repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
MrEditor97/CommandVoter | src/main/java/Me/MrEditor97/CommandVoter/Messages/Message.java | 3134 | package Me.MrEditor97.CommandVoter.Messages;
import java.util.Map;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import Me.MrEditor97.CommandVoter.CommandVoter;
import Me.MrEditor97.CommandVoter.Util.Util;
public class Message {
CommandVoter plugin;
public Message(CommandVoter instance) {
this.plugin = instance;
}
//Used on the vote command
public void vote(CommandSender sender, String message, int voted) {
Util util = new Util(plugin);
sender.sendMessage(util.colorize(util.playerize(util.voterize(message, voted), (Player) sender)));
}
//Used on the topvoters command
public void top(CommandSender sender, Map<String, Integer> timesVoted, String message, int topVotersLength) {
Util util = new Util(plugin);
int topPlayers = plugin.getConfig().getInt("listTopVoters") -1;
int i = 0;
for (Map.Entry<String, Integer> entry : util.sortByValues(timesVoted).entrySet()) {
if (i <= topPlayers) {
i++;
sender.sendMessage(util.colorize(util.stringPlayerize(util.voterize(message, entry.getValue()), entry.getKey())));
}
}
}
//Used on player join event
public void join(Player player, String message, int timesVoted) {
Util util = new Util(plugin);
if (!message.equalsIgnoreCase("false")) {
player.sendMessage(util.colorize(util.playerize(util.voterize(message, timesVoted), player)));
}
}
//Used on player voted event
public void voted(String player, String message, int timesVoted) {
Util util = new Util(plugin);
if (!message.equalsIgnoreCase("false")) {
plugin.getServer().broadcastMessage(util.colorize(util.stringPlayerize(util.voterize(message, timesVoted), plugin.getConfig().getString("players." + player.toLowerCase() + ".username"))));
}
}
//Used on player online event
public void online(Player player, String message, String name) {
Util util = new Util(plugin);
player.sendMessage(util.colorize(util.stringPlayerize(message, name)));
}
//Used on player permission event
public void permission(CommandSender sender, String message) {
Util util = new Util(plugin);
sender.sendMessage(util.colorize(message));
}
//Used on player reward even
public void reward(boolean reward, CommandSender sender, Player target, String message) {
Util util = new Util(plugin);
if (!reward == true) {
sender.sendMessage(util.colorize(util.playerize(message, target)));
} else {
}
}
//Used on player reward target
public void rewardTarget(Player sender, Player target, String messageTarget, String messageSender) {
Util util = new Util(plugin);
target.sendMessage(util.colorize(util.playerize(messageTarget, target)));
rewardPlayer(sender, messageSender);
}
//Used on player reward player (sender)
public void rewardPlayer(Player player, String message) {
Util util = new Util(plugin);
player.sendMessage(util.colorize(util.stringPlayerize(message, player.getName())));
}
//Used on message send
public void send(Player player, String message) {
Util util = new Util(plugin);
player.sendMessage(util.colorize(util.playerize(message, player)));
}
}
| gpl-2.0 |
derekhe/goos-learning | src/test/java/com/april1985/goos/SingleMessageListener.java | 1023 | package com.april1985.goos;
import org.hamcrest.Matcher;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* Created by sche on 9/17/14.
*/
public class SingleMessageListener implements MessageListener {
private final ArrayBlockingQueue<Message> messages = new ArrayBlockingQueue<Message>(1);
@Override
public void processMessage(Chat chat, Message message) {
messages.add(message);
}
public void receivesAMessage(Matcher<? super String> messageMatcher) throws InterruptedException {
final Message message = messages.poll(20, TimeUnit.SECONDS);
assertThat("Message", message, is(notNullValue()));
assertThat(message.getBody(), messageMatcher);
}
}
| gpl-2.0 |
Prasad1337/Scavenger-Hunt | src/csci567/scavengerhunt/services/QueryService.java | 2639 | package csci567.scavengerhunt.services;
import java.util.Map;
import java.util.Map.Entry;
import csci567.scavengerhunt.model.PersistentEntity;
/**
* @author ccubukcu
* */
public class QueryService {
public static String createInsertQuery(PersistentEntity entity) {
String query = null;
Map<String, Object> colValueMap = entity.getColumnValueMap();
if(entity.getTableName() != null && !entity.getTableName().equals("")
&& colValueMap != null && colValueMap.size() > 0) {
query = "INSERT INTO " + entity.getTableName() + "(";
String values = " VALUES(";
int i = 0;
for (Entry<String, Object> mapEntry : colValueMap.entrySet()) {
if(mapEntry.getKey().equals(PersistentEntity.ID_KEY))
continue;
Object val = mapEntry.getValue();
if(val == null) {
i++;
continue;
}
if(val instanceof Integer || val instanceof Double) {
values += val.toString();
} else if (val instanceof String){
values += "'" + val.toString() + "'";
} else if (val instanceof Boolean) {
values += ((Boolean)val == true ? "TRUE" : "FALSE");
} else {
i++;
continue;
}
query += mapEntry.getKey();
if(i < colValueMap.size() - 1) {
query += ", ";
values += ", ";
}
i++;
}
query = query + ") " + values + ")";
}
return query;
}
public static String createUpdateQuery(PersistentEntity entity) {
String query = null;
Map<String, Object> colValueMap = entity.getColumnValueMap();
if(entity.getTableName() != null && !entity.getTableName().equals("")
&& colValueMap != null && colValueMap.size() > 0
&& entity.getId() != null && entity.getId() > 0) {
query = "UPDATE " + entity.getTableName() + " SET ";
int i = 0;
for (Entry<String, Object> mapEntry : colValueMap.entrySet()) {
if(mapEntry.getKey().equals(PersistentEntity.ID_KEY))
continue;
Object val = mapEntry.getValue();
if(val == null) {
i++;
continue;
}
query += mapEntry.getKey() + "=";
if(val instanceof Integer || val instanceof Double) {
query += val.toString();
} else if (val instanceof String){
query += "'" + val.toString() + "'";
} else if (val instanceof Boolean) {
query += ((Boolean)val == true ? "1" : "0");
} else {
continue;
}
if(i < colValueMap.size() - 1) {
query += ", ";
}
i++;
}
String str = query.substring(query.length()-2);
if(str.equals(", ")) {
query = query.substring(0, query.length() -2);
}
query = query + " WHERE ID = " + entity.getId();
}
return query;
}
}
| gpl-2.0 |
langmo/youscope | core/server/src/main/java/org/youscope/server/MeasurementRMI.java | 7910 | /*******************************************************************************
* Copyright (c) 2017 Moritz Lang.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Moritz Lang - initial API and implementation
******************************************************************************/
/**
*
*/
package org.youscope.server;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.UUID;
import org.youscope.common.ComponentRunningException;
import org.youscope.common.MessageListener;
import org.youscope.common.PositionInformation;
import org.youscope.common.measurement.Measurement;
import org.youscope.common.measurement.MeasurementException;
import org.youscope.common.measurement.MeasurementListener;
import org.youscope.common.measurement.MeasurementMetadata;
import org.youscope.common.measurement.MeasurementState;
import org.youscope.common.microscope.DeviceSetting;
import org.youscope.common.saving.MeasurementSaver;
import org.youscope.common.task.Task;
/**
* @author Moritz Lang
*/
class MeasurementRMI extends UnicastRemoteObject implements Measurement
{
/**
* Serial Version UID.
*/
private static final long serialVersionUID = -8611665286420613463L;
private final MeasurementImpl measurement;
private final MeasurementManager measurementManager;
private final MeasurementSaver measurementSaver;
/**
* Constructor.
*
* @throws RemoteException
*/
protected MeasurementRMI(MeasurementImpl measurement, MeasurementManager measurementManager) throws RemoteException
{
this.measurement = measurement;
this.measurementManager = measurementManager;
this.measurementSaver = new MeasurementSaverImpl(measurement);
}
@Override
public void addMeasurementListener(MeasurementListener listener)
{
measurement.addMeasurementListener(listener);
}
@Override
public void startMeasurement() throws MeasurementException
{
MeasurementState state = measurement.getState();
if(state != MeasurementState.READY && state != MeasurementState.UNINITIALIZED && state != MeasurementState.PAUSED)
throw new MeasurementException("Measurement must be in state Ready, Uninitialized or Paused to be started. Current state: "+state.toString()+".");
measurementManager.addMeasurement(measurement);
}
@Override
public void stopMeasurement(boolean processJobQueue) throws MeasurementException
{
measurement.stopMeasurement(processJobQueue);
measurementManager.removeMeasurement(measurement);
}
@Override
public void pauseMeasurement() throws MeasurementException
{
measurement.pauseMeasurement();
measurementManager.removeMeasurement(measurement);
}
@Override
public void interruptMeasurement()
{
measurementManager.interruptMeasurement(measurement);
}
@Override
public void setMaxRuntime(long measurementRuntime) throws ComponentRunningException
{
measurement.setMaxRuntime(measurementRuntime);
}
@Override
public String getName()
{
return measurement.getName();
}
@Override
public void setName(String name) throws ComponentRunningException
{
measurement.setName(name);
}
@Override
public void removeMeasurementListener(MeasurementListener listener)
{
measurement.removeMeasurementListener(listener);
}
@Override
public long getMaxRuntime()
{
return measurement.getMaxRuntime();
}
@Override
public void setLockMicroscopeWhileRunning(boolean lock) throws ComponentRunningException
{
measurement.setLockMicroscopeWhileRunning(lock);
}
@Override
public boolean isLockMicroscopeWhileRunning()
{
return measurement.isLockMicroscopeWhileRunning();
}
@Override
public void setTypeIdentifier(String type) throws ComponentRunningException
{
measurement.setTypeIdentifier(type);
}
@Override
public String getTypeIdentifier()
{
return measurement.getTypeIdentifier();
}
@Override
public MeasurementState getState()
{
return measurement.getState();
}
@Override
public MeasurementSaver getSaver()
{
return measurementSaver;
}
@Override
public Task addTask(long period, boolean fixedTimes, long startTime, long numExecutions)
throws ComponentRunningException, RemoteException
{
return measurement.addTask(period, fixedTimes, startTime, numExecutions);
}
@Override
public Task addMultiplePeriodTask(long[] periods, long startTime,
long numExecutions) throws ComponentRunningException, RemoteException
{
return measurement.addMultiplePeriodTask(periods, startTime, numExecutions);
}
@Override
public Task addTask(long period, boolean fixedTimes, long startTime)
throws ComponentRunningException, RemoteException
{
return measurement.addTask(period, fixedTimes, startTime);
}
@Override
public Task addMultiplePeriodTask(long[] periods, long startTime)
throws ComponentRunningException, RemoteException
{
return measurement.addMultiplePeriodTask(periods, startTime);
}
@Override
public void setFinishDeviceSettings(DeviceSetting[] settings)
throws ComponentRunningException
{
measurement.setFinishDeviceSettings(settings);
}
@Override
public void setStartupDeviceSettings(DeviceSetting[] settings)
throws ComponentRunningException
{
measurement.setStartupDeviceSettings(settings);
}
@Override
public Task[] getTasks()
{
return measurement.getTasks();
}
@Override
public long getStartTime()
{
return measurement.getStartTime();
}
@Override
public long getStopTime()
{
return measurement.getStopTime();
}
@Override
public void addStartupDeviceSetting(DeviceSetting setting) throws ComponentRunningException
{
measurement.addStartupDeviceSetting(setting);
}
@Override
public void addFinishDeviceSetting(DeviceSetting setting) throws ComponentRunningException
{
measurement.addFinishDeviceSetting(setting);
}
@Override
public void addMessageListener(MessageListener writer)
{
measurement.addMessageListener(writer);
}
@Override
public void removeMessageListener(MessageListener writer)
{
measurement.removeMessageListener(writer);
}
@Override
public PositionInformation getPositionInformation()
{
return new PositionInformation();
}
@Override
public void setInitialMeasurementContextProperty(String identifier, Serializable property) throws ComponentRunningException
{
measurement.setInitialMeasurementContextProperty(identifier, property);
}
@Override
public UUID getUUID()
{
return measurement.getUUID();
}
@Override
public long getPauseTime()
{
return measurement.getPauseTime();
}
@Override
public long getPauseDuration()
{
return measurement.getPauseDuration();
}
@Override
public long getRuntime()
{
return measurement.getRuntime();
}
@Override
public MeasurementMetadata getMetadata() throws RemoteException {
return measurement.getMetadata();
}
@Override
public void setInitialRuntime(long initialRuntime)
throws RemoteException, ComponentRunningException, IllegalArgumentException {
measurement.setInitialRuntime(initialRuntime);
}
@Override
public long getInitialRuntime() throws RemoteException {
return measurement.getInitialRuntime();
}
}
| gpl-2.0 |
eyetrackingDB/GazeTrackingFramework | src/de/vion/eyetracking/gazedetection/gazetracker/GazeTrackerAbstract.java | 1749 | package de.vion.eyetracking.gazedetection.gazetracker;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.opencv.core.Mat;
import android.content.Context;
/**
*
* The Abstract class that defines the methods for each gaze tracker that we
* want to implement.
*
* @author André Pomp
*
*/
public abstract class GazeTrackerAbstract {
protected Context context;
protected long nativeObjectAddress;
public GazeTrackerAbstract(Context context) {
super();
this.context = context;
}
/**
* Handles the initilization of the gaze tracking approach
*
* @param settings
*/
public abstract void init(GazeTrackerSettingsAbstract settings);
/**
* Handles the detection of the gaze based on a frame
*
* @param colorFrame
* @return
*/
public abstract int[] detect(Mat colorFrame);
/**
* Releases all resources
*/
public abstract void release();
/**
* Loads a single file from the resources
*
* @param dir
* @param res
* @param filename
*/
protected File loadHaarFile(File dir, int res, String filename) {
try {
InputStream is = this.context.getResources().openRawResource(res);
File target = new File(dir, filename);
FileOutputStream os = new FileOutputStream(target);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
return target;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
} | gpl-2.0 |
manojgudalakumar/middleware-service-testing-tool | service-virtualization/src/main/java/com/github/tomakehurst/wiremock/admin/ShutdownServerTask.java | 423 | package com.github.tomakehurst.wiremock.admin;
import com.github.tomakehurst.wiremock.core.Admin;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
public class ShutdownServerTask implements AdminTask {
public ResponseDefinition execute(final Admin admin, final Request request) {
admin.shutdownServer();
return ResponseDefinition.ok();
}
}
| gpl-2.0 |
BigBoss424/JSS | Twisted/SecuritySystem/Java/objects/GUI/GUI.java | 530 | /**
* Created by: Aaron Jones
* Date: 4/3/2015
* Last Modified: 4/3/2015
* Description: This class will be the main point from which the GUI side of the application will be run from.
* I don't believe I will be doing much work in this class until everything else is finished but might as well
* create something to be the placeholder for the time being until I get to that stage in development.
*
*
* Bugs:
*
*
*
* Fixes:
*
*
*
*
*/
package GUI;
/**
* @author bigboss424
*
*/
public class GUI {
}
| gpl-2.0 |
OpenRedu/mobile-deprecated | code/src/br/com/redu/redumobile/adapters/PopupAdapter.java | 4413 | package br.com.redu.redumobile.adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import br.com.developer.redu.models.Space;
import br.com.developer.redu.models.Subject;
import br.com.redu.redumobile.R;
import br.com.redu.redumobile.activities.lecture.NewFolderActivity;
import br.com.redu.redumobile.activities.lecture.UploadStep1Activity;
import br.com.redu.redumobile.activities.lecture.UploadStep2Activity;
public class PopupAdapter extends BaseAdapter {
final private LayoutInflater mInflater;
final private Context mContext;
private Space space;
private Subject mSubject;
private String id;
private String[] values;
public PopupAdapter(Context context, String[] values, String id, Space space) {
mContext = context;
mInflater = LayoutInflater.from(context);
this.values = values;
this.id = id;
this.space = space;
}
public PopupAdapter(Context context, String[] values, Space space, Subject subject) {
mContext = context;
mInflater = LayoutInflater.from(context);
this.mSubject = subject;
this.values = values;
this.space = space;
}
@Override
public int getCount() {
return values.length;
}
@Override
public Object getItem(int position) {
return values[position];
}
@Override
public long getItemId(int position) {
return 0;
}
// public void add(TextView status) {
// listMaterials.add(status);
// }
//
// public void add(List<TextView> statuses) {
// listMaterials.addAll(statuses);
// }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout ll = (LinearLayout) mInflater.inflate(R.layout.popup_listview_row, null);
ImageView iv = (ImageView)ll.findViewById(R.id.iv_insert_file_folder);
TextView tv = (TextView)ll.findViewById(R.id.tv_insert_file_folder);
tv.setText(values[position]);
if (values[position].equals("Arquivo de Apoio")){
iv.setImageResource(R.drawable.ic_file_mini);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(mContext, UploadStep1Activity.class);
it.putExtra(Space.class.getName(), space);
it.putExtra("id", id);
mContext.startActivity(it);
}
});
}
if (values[position].equals("Pasta")){
iv.setImageResource(R.drawable.ic_folder);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(mContext, NewFolderActivity.class);
it.putExtra(Space.class.getName(), space);
it.putExtra("id", id);
mContext.startActivity(it);
}
});
}
if (values[position].equals("Vídeo")){
iv.setImageResource(R.drawable.ic_midia);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(mContext, UploadStep2Activity.class);
it.putExtra(Space.class.getName(), space);
it.putExtra(Subject.class.getName(), mSubject);
it.putExtra("id", id);
it.putExtra("type", "video");
mContext.startActivity(it);
}
});
}
if (values[position].equals("Foto")){
iv.setImageResource(R.drawable.ic_photo);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(mContext, UploadStep2Activity.class);
it.putExtra(Space.class.getName(), space);
it.putExtra(Subject.class.getName(), mSubject);
it.putExtra("id", id);
it.putExtra("type", "foto");
mContext.startActivity(it);
}
});
}
if (values[position].equals("Áudio")){
iv.setImageResource(R.drawable.ic_midia);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(mContext, UploadStep2Activity.class);
it.putExtra(Space.class.getName(), space);
it.putExtra("id", id);
it.putExtra("type", "audio");
mContext.startActivity(it);
}
});
}
if (values[position].equals("Camera")){
iv.setImageResource(R.drawable.ic_midia);
}
if (values[position].equals("Escolher da Galeria")){
iv.setImageResource(R.drawable.ic_galery);
}
return ll;
}
}
| gpl-2.0 |
goetzmaster13/McGourmetGoetze | McGoetzeGourmet/src/main/java/at/irian/jsfatwork/gui/jsf/DebugPhaseListener.java | 815 | package at.irian.jsfatwork.gui.jsf;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* PhaseListener that logs a short message before and after every phase.
*
* @author Michael Kurz
*/
public class DebugPhaseListener implements PhaseListener {
private static final long serialVersionUID = 28697126271609506L;
private static Log log = LogFactory.getLog(DebugPhaseListener.class);
public void afterPhase(PhaseEvent event) {
log.debug("After phase: " + event.getPhaseId());
}
public void beforePhase(PhaseEvent event) {
log.debug("Before phase: " + event.getPhaseId());
}
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
}
| gpl-2.0 |
OpenRedu/mobile | OpenRedu/app/src/main/java/br/ufpe/cin/openredu/ReduApplication.java | 1374 | package br.ufpe.cin.openredu;
import org.scribe.exceptions.OAuthConnectionException;
import org.scribe.exceptions.OAuthException;
import android.app.Application;
import android.content.Context;
import br.com.developer.redu.DefaultReduClient;
import br.com.developer.redu.models.User;
import br.ufpe.cin.openredu.util.PinCodeHelper;
public class ReduApplication extends Application {
static private DefaultReduClient reduClientInitialized;
static private User user;
static public DefaultReduClient getReduClient(Context context) throws OAuthConnectionException, OAuthException {
if(reduClientInitialized != null) {
return reduClientInitialized;
}
String consumerKey = context.getString(R.string.CONSUMER_KEY);
String consumerSecretKey = context.getString(R.string.CONSUMER_SECRET_KEY);
DefaultReduClient reduClient = new DefaultReduClient(consumerKey, consumerSecretKey);
String pinCode = PinCodeHelper.get(context);
if(pinCode != null) {
reduClient.initClient(pinCode);
reduClientInitialized = reduClient;
}
return reduClient;
}
static public User getUser(Context context) throws OAuthConnectionException {
if(user == null) {
user = getReduClient(context).getMe();
}
return user;
}
static public void clear(Context context) {
PinCodeHelper.clear(context);
reduClientInitialized = null;
user = null;
}
}
| gpl-2.0 |
utds3lab/SMVHunter | dynamic/src/com/android/ddmlib/Device.java | 26864 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ddmlib;
import java.io.File;
import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.android.ddmlib.log.LogReceiver;
/**
* A Device. It can be a physical device or an emulator.
*/
final class Device implements IDevice {
private static final String DEVICE_MODEL_PROPERTY = "ro.product.model"; //$NON-NLS-1$
private static final String DEVICE_MANUFACTURER_PROPERTY = "ro.product.manufacturer"; //$NON-NLS-1$
private final static int INSTALL_TIMEOUT = 2*60*1000; //2min
private static final int BATTERY_TIMEOUT = 2*1000; //2 seconds
private static final int GETPROP_TIMEOUT = 2*1000; //2 seconds
/** Emulator Serial Number regexp. */
final static String RE_EMULATOR_SN = "emulator-(\\d+)"; //$NON-NLS-1$
/** Serial number of the device */
private String mSerialNumber = null;
/** Name of the AVD */
private String mAvdName = null;
/** State of the device. */
private DeviceState mState = null;
/** Device properties. */
private final Map<String, String> mProperties = new HashMap<String, String>();
private final Map<String, String> mMountPoints = new HashMap<String, String>();
private final ArrayList<Client> mClients = new ArrayList<Client>();
private DeviceMonitor mMonitor;
private static final String LOG_TAG = "Device";
private static final char SEPARATOR = '-';
/**
* Socket for the connection monitoring client connection/disconnection.
*/
private SocketChannel mSocketChannel;
private boolean mArePropertiesSet = false;
private Integer mLastBatteryLevel = null;
private long mLastBatteryCheckTime = 0;
private String mName;
/**
* Output receiver for "pm install package.apk" command line.
*/
private static final class InstallReceiver extends MultiLineReceiver {
private static final String SUCCESS_OUTPUT = "Success"; //$NON-NLS-1$
private static final Pattern FAILURE_PATTERN = Pattern.compile("Failure\\s+\\[(.*)\\]"); //$NON-NLS-1$
private String mErrorMessage = null;
public InstallReceiver() {
}
@Override
public void processNewLines(String[] lines) {
for (String line : lines) {
if (line.length() > 0) {
if (line.startsWith(SUCCESS_OUTPUT)) {
mErrorMessage = null;
} else {
Matcher m = FAILURE_PATTERN.matcher(line);
if (m.matches()) {
mErrorMessage = m.group(1);
}
}
}
}
}
@Override
public boolean isCancelled() {
return false;
}
public String getErrorMessage() {
return mErrorMessage;
}
}
/**
* Output receiver for "dumpsys battery" command line.
*/
private static final class BatteryReceiver extends MultiLineReceiver {
private static final Pattern BATTERY_LEVEL = Pattern.compile("\\s*level: (\\d+)");
private static final Pattern SCALE = Pattern.compile("\\s*scale: (\\d+)");
private Integer mBatteryLevel = null;
private Integer mBatteryScale = null;
/**
* Get the parsed percent battery level.
* @return
*/
public Integer getBatteryLevel() {
if (mBatteryLevel != null && mBatteryScale != null) {
return (mBatteryLevel * 100) / mBatteryScale;
}
return null;
}
@Override
public void processNewLines(String[] lines) {
for (String line : lines) {
Matcher batteryMatch = BATTERY_LEVEL.matcher(line);
if (batteryMatch.matches()) {
try {
mBatteryLevel = Integer.parseInt(batteryMatch.group(1));
} catch (NumberFormatException e) {
Log.w(LOG_TAG, String.format("Failed to parse %s as an integer",
batteryMatch.group(1)));
}
}
Matcher scaleMatch = SCALE.matcher(line);
if (scaleMatch.matches()) {
try {
mBatteryScale = Integer.parseInt(scaleMatch.group(1));
} catch (NumberFormatException e) {
Log.w(LOG_TAG, String.format("Failed to parse %s as an integer",
batteryMatch.group(1)));
}
}
}
}
@Override
public boolean isCancelled() {
return false;
}
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getSerialNumber()
*/
@Override
public String getSerialNumber() {
return mSerialNumber;
}
/** {@inheritDoc} */
@Override
public String getAvdName() {
return mAvdName;
}
/**
* Sets the name of the AVD
*/
void setAvdName(String avdName) {
if (isEmulator() == false) {
throw new IllegalArgumentException(
"Cannot set the AVD name of the device is not an emulator");
}
mAvdName = avdName;
}
@Override
public String getName() {
if (mName == null) {
mName = constructName();
}
return mName;
}
private String constructName() {
if (isEmulator()) {
String avdName = getAvdName();
if (avdName != null) {
return String.format("%s [%s]", avdName, getSerialNumber());
} else {
return getSerialNumber();
}
} else {
String manufacturer = cleanupStringForDisplay(
getProperty(DEVICE_MANUFACTURER_PROPERTY));
String model = cleanupStringForDisplay(
getProperty(DEVICE_MODEL_PROPERTY));
StringBuilder sb = new StringBuilder(20);
if (manufacturer != null) {
sb.append(manufacturer);
sb.append(SEPARATOR);
}
if (model != null) {
sb.append(model);
sb.append(SEPARATOR);
}
sb.append(getSerialNumber());
return sb.toString();
}
}
private String cleanupStringForDisplay(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isLetterOrDigit(c)) {
sb.append(Character.toLowerCase(c));
} else {
sb.append('_');
}
}
return sb.toString();
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getState()
*/
@Override
public DeviceState getState() {
return mState;
}
/**
* Changes the state of the device.
*/
void setState(DeviceState state) {
mState = state;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getProperties()
*/
@Override
public Map<String, String> getProperties() {
return Collections.unmodifiableMap(mProperties);
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getPropertyCount()
*/
@Override
public int getPropertyCount() {
return mProperties.size();
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getProperty(java.lang.String)
*/
@Override
public String getProperty(String name) {
return mProperties.get(name);
}
/**
* {@inheritDoc}
*/
@Override
public boolean arePropertiesSet() {
return mArePropertiesSet;
}
/**
* {@inheritDoc}
*/
@Override
public String getPropertyCacheOrSync(String name) throws TimeoutException,
AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
if (mArePropertiesSet) {
return getProperty(name);
} else {
return getPropertySync(name);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getPropertySync(String name) throws TimeoutException,
AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
CollectingOutputReceiver receiver = new CollectingOutputReceiver();
executeShellCommand(String.format("getprop '%s'", name), receiver, GETPROP_TIMEOUT);
String value = receiver.getOutput().trim();
if (value.isEmpty()) {
return null;
}
return value;
}
@Override
public String getMountPoint(String name) {
return mMountPoints.get(name);
}
@Override
public String toString() {
return mSerialNumber;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#isOnline()
*/
@Override
public boolean isOnline() {
return mState == DeviceState.ONLINE;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#isEmulator()
*/
@Override
public boolean isEmulator() {
return mSerialNumber.matches(RE_EMULATOR_SN);
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#isOffline()
*/
@Override
public boolean isOffline() {
return mState == DeviceState.OFFLINE;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#isBootLoader()
*/
@Override
public boolean isBootLoader() {
return mState == DeviceState.BOOTLOADER;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#hasClients()
*/
@Override
public boolean hasClients() {
return mClients.size() > 0;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getClients()
*/
@Override
public Client[] getClients() {
synchronized (mClients) {
return mClients.toArray(new Client[mClients.size()]);
}
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getClient(java.lang.String)
*/
@Override
public Client getClient(String applicationName) {
synchronized (mClients) {
for (Client c : mClients) {
if (applicationName.equals(c.getClientData().getClientDescription())) {
return c;
}
}
}
return null;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getSyncService()
*/
@Override
public SyncService getSyncService()
throws TimeoutException, AdbCommandRejectedException, IOException {
SyncService syncService = new SyncService(AndroidDebugBridge.getSocketAddress(), this);
if (syncService.openSync()) {
return syncService;
}
return null;
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getFileListingService()
*/
@Override
public FileListingService getFileListingService() {
return new FileListingService(this);
}
@Override
public RawImage getScreenshot()
throws TimeoutException, AdbCommandRejectedException, IOException {
return AdbHelper.getFrameBuffer(AndroidDebugBridge.getSocketAddress(), this);
}
@Override
public void executeShellCommand(String command, IShellOutputReceiver receiver)
throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
IOException {
AdbHelper.executeRemoteCommand(AndroidDebugBridge.getSocketAddress(), command, this,
receiver, DdmPreferences.getTimeOut());
}
@Override
public void executeShellCommand(String command, IShellOutputReceiver receiver,
int maxTimeToOutputResponse)
throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
IOException {
AdbHelper.executeRemoteCommand(AndroidDebugBridge.getSocketAddress(), command, this,
receiver, maxTimeToOutputResponse);
}
@Override
public void runEventLogService(LogReceiver receiver)
throws TimeoutException, AdbCommandRejectedException, IOException {
AdbHelper.runEventLogService(AndroidDebugBridge.getSocketAddress(), this, receiver);
}
@Override
public void runLogService(String logname, LogReceiver receiver)
throws TimeoutException, AdbCommandRejectedException, IOException {
AdbHelper.runLogService(AndroidDebugBridge.getSocketAddress(), this, logname, receiver);
}
@Override
public void createForward(int localPort, int remotePort)
throws TimeoutException, AdbCommandRejectedException, IOException {
AdbHelper.createForward(AndroidDebugBridge.getSocketAddress(), this,
String.format("tcp:%d", localPort), //$NON-NLS-1$
String.format("tcp:%d", remotePort)); //$NON-NLS-1$
}
@Override
public void createForward(int localPort, String remoteSocketName,
DeviceUnixSocketNamespace namespace) throws TimeoutException,
AdbCommandRejectedException, IOException {
AdbHelper.createForward(AndroidDebugBridge.getSocketAddress(), this,
String.format("tcp:%d", localPort), //$NON-NLS-1$
String.format("%s:%s", namespace.getType(), remoteSocketName)); //$NON-NLS-1$
}
@Override
public void removeForward(int localPort, int remotePort)
throws TimeoutException, AdbCommandRejectedException, IOException {
AdbHelper.removeForward(AndroidDebugBridge.getSocketAddress(), this,
String.format("tcp:%d", localPort), //$NON-NLS-1$
String.format("tcp:%d", remotePort)); //$NON-NLS-1$
}
@Override
public void removeForward(int localPort, String remoteSocketName,
DeviceUnixSocketNamespace namespace) throws TimeoutException,
AdbCommandRejectedException, IOException {
AdbHelper.removeForward(AndroidDebugBridge.getSocketAddress(), this,
String.format("tcp:%d", localPort), //$NON-NLS-1$
String.format("%s:%s", namespace.getType(), remoteSocketName)); //$NON-NLS-1$
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#getClientName(int)
*/
@Override
public String getClientName(int pid) {
synchronized (mClients) {
for (Client c : mClients) {
if (c.getClientData().getPid() == pid) {
return c.getClientData().getClientDescription();
}
}
}
return null;
}
Device(DeviceMonitor monitor, String serialNumber, DeviceState deviceState) {
mMonitor = monitor;
mSerialNumber = serialNumber;
mState = deviceState;
}
DeviceMonitor getMonitor() {
return mMonitor;
}
void addClient(Client client) {
synchronized (mClients) {
mClients.add(client);
}
}
List<Client> getClientList() {
return mClients;
}
boolean hasClient(int pid) {
synchronized (mClients) {
for (Client client : mClients) {
if (client.getClientData().getPid() == pid) {
return true;
}
}
}
return false;
}
void clearClientList() {
synchronized (mClients) {
mClients.clear();
}
}
/**
* Sets the client monitoring socket.
* @param socketChannel the sockets
*/
void setClientMonitoringSocket(SocketChannel socketChannel) {
mSocketChannel = socketChannel;
}
/**
* Returns the client monitoring socket.
*/
SocketChannel getClientMonitoringSocket() {
return mSocketChannel;
}
/**
* Removes a {@link Client} from the list.
* @param client the client to remove.
* @param notify Whether or not to notify the listeners of a change.
*/
void removeClient(Client client, boolean notify) {
mMonitor.addPortToAvailableList(client.getDebuggerListenPort());
synchronized (mClients) {
mClients.remove(client);
}
if (notify) {
mMonitor.getServer().deviceChanged(this, CHANGE_CLIENT_LIST);
}
}
void update(int changeMask) {
if ((changeMask & CHANGE_BUILD_INFO) != 0) {
mArePropertiesSet = true;
}
mMonitor.getServer().deviceChanged(this, changeMask);
}
void update(Client client, int changeMask) {
mMonitor.getServer().clientChanged(client, changeMask);
}
void addProperty(String label, String value) {
mProperties.put(label, value);
}
void setMountingPoint(String name, String value) {
mMountPoints.put(name, value);
}
@Override
public void pushFile(String local, String remote)
throws IOException, AdbCommandRejectedException, TimeoutException, SyncException {
SyncService sync = null;
try {
String targetFileName = getFileName(local);
Log.d(targetFileName, String.format("Uploading %1$s onto device '%2$s'",
targetFileName, getSerialNumber()));
sync = getSyncService();
if (sync != null) {
String message = String.format("Uploading file onto device '%1$s'",
getSerialNumber());
Log.d(LOG_TAG, message);
sync.pushFile(local, remote, SyncService.getNullProgressMonitor());
} else {
throw new IOException("Unable to open sync connection!");
}
} catch (TimeoutException e) {
Log.e(LOG_TAG, "Error during Sync: timeout.");
throw e;
} catch (SyncException e) {
Log.e(LOG_TAG, String.format("Error during Sync: %1$s", e.getMessage()));
throw e;
} catch (IOException e) {
Log.e(LOG_TAG, String.format("Error during Sync: %1$s", e.getMessage()));
throw e;
} finally {
if (sync != null) {
sync.close();
}
}
}
@Override
public void pullFile(String remote, String local)
throws IOException, AdbCommandRejectedException, TimeoutException, SyncException {
SyncService sync = null;
try {
String targetFileName = getFileName(remote);
Log.d(targetFileName, String.format("Downloading %1$s from device '%2$s'",
targetFileName, getSerialNumber()));
sync = getSyncService();
if (sync != null) {
String message = String.format("Downloding file from device '%1$s'",
getSerialNumber());
Log.d(LOG_TAG, message);
sync.pullFile(remote, local, SyncService.getNullProgressMonitor());
} else {
throw new IOException("Unable to open sync connection!");
}
} catch (TimeoutException e) {
Log.e(LOG_TAG, "Error during Sync: timeout.");
throw e;
} catch (SyncException e) {
Log.e(LOG_TAG, String.format("Error during Sync: %1$s", e.getMessage()));
throw e;
} catch (IOException e) {
Log.e(LOG_TAG, String.format("Error during Sync: %1$s", e.getMessage()));
throw e;
} finally {
if (sync != null) {
sync.close();
}
}
}
@Override
public String installPackage(String packageFilePath, boolean reinstall, String... extraArgs)
throws InstallException {
try {
String remoteFilePath = syncPackageToDevice(packageFilePath);
String result = installRemotePackage(remoteFilePath, reinstall, extraArgs);
removeRemotePackage(remoteFilePath);
return result;
} catch (IOException e) {
throw new InstallException(e);
} catch (AdbCommandRejectedException e) {
throw new InstallException(e);
} catch (TimeoutException e) {
throw new InstallException(e);
} catch (SyncException e) {
throw new InstallException(e);
}
}
@Override
public String syncPackageToDevice(String localFilePath)
throws IOException, AdbCommandRejectedException, TimeoutException, SyncException {
SyncService sync = null;
try {
String packageFileName = getFileName(localFilePath);
String remoteFilePath = String.format("/data/local/tmp/%1$s", packageFileName); //$NON-NLS-1$
Log.d(packageFileName, String.format("Uploading %1$s onto device '%2$s'",
packageFileName, getSerialNumber()));
sync = getSyncService();
if (sync != null) {
String message = String.format("Uploading file onto device '%1$s'",
getSerialNumber());
Log.d(LOG_TAG, message);
sync.pushFile(localFilePath, remoteFilePath, SyncService.getNullProgressMonitor());
} else {
throw new IOException("Unable to open sync connection!");
}
return remoteFilePath;
} catch (TimeoutException e) {
Log.e(LOG_TAG, "Error during Sync: timeout.");
throw e;
} catch (SyncException e) {
Log.e(LOG_TAG, String.format("Error during Sync: %1$s", e.getMessage()));
throw e;
} catch (IOException e) {
Log.e(LOG_TAG, String.format("Error during Sync: %1$s", e.getMessage()));
throw e;
} finally {
if (sync != null) {
sync.close();
}
}
}
/**
* Helper method to retrieve the file name given a local file path
* @param filePath full directory path to file
* @return {@link String} file name
*/
private String getFileName(String filePath) {
return new File(filePath).getName();
}
@Override
public String installRemotePackage(String remoteFilePath, boolean reinstall,
String... extraArgs) throws InstallException {
try {
InstallReceiver receiver = new InstallReceiver();
StringBuilder optionString = new StringBuilder();
if (reinstall) {
optionString.append("-r ");
}
for (String arg : extraArgs) {
optionString.append(arg);
optionString.append(' ');
}
String cmd = String.format("pm install %1$s \"%2$s\"", optionString.toString(),
remoteFilePath);
executeShellCommand(cmd, receiver, INSTALL_TIMEOUT);
return receiver.getErrorMessage();
} catch (TimeoutException e) {
throw new InstallException(e);
} catch (AdbCommandRejectedException e) {
throw new InstallException(e);
} catch (ShellCommandUnresponsiveException e) {
throw new InstallException(e);
} catch (IOException e) {
throw new InstallException(e);
}
}
@Override
public void removeRemotePackage(String remoteFilePath) throws InstallException {
try {
executeShellCommand("rm " + remoteFilePath, new NullOutputReceiver(), INSTALL_TIMEOUT);
} catch (IOException e) {
throw new InstallException(e);
} catch (TimeoutException e) {
throw new InstallException(e);
} catch (AdbCommandRejectedException e) {
throw new InstallException(e);
} catch (ShellCommandUnresponsiveException e) {
throw new InstallException(e);
}
}
@Override
public String uninstallPackage(String packageName) throws InstallException {
try {
InstallReceiver receiver = new InstallReceiver();
executeShellCommand("pm uninstall " + packageName, receiver, INSTALL_TIMEOUT);
return receiver.getErrorMessage();
} catch (TimeoutException e) {
throw new InstallException(e);
} catch (AdbCommandRejectedException e) {
throw new InstallException(e);
} catch (ShellCommandUnresponsiveException e) {
throw new InstallException(e);
} catch (IOException e) {
throw new InstallException(e);
}
}
/*
* (non-Javadoc)
* @see com.android.ddmlib.IDevice#reboot()
*/
@Override
public void reboot(String into)
throws TimeoutException, AdbCommandRejectedException, IOException {
AdbHelper.reboot(into, AndroidDebugBridge.getSocketAddress(), this);
}
@Override
public Integer getBatteryLevel() throws TimeoutException, AdbCommandRejectedException,
IOException, ShellCommandUnresponsiveException {
// use default of 5 minutes
return getBatteryLevel(5 * 60 * 1000);
}
@Override
public Integer getBatteryLevel(long freshnessMs) throws TimeoutException,
AdbCommandRejectedException, IOException, ShellCommandUnresponsiveException {
if (mLastBatteryLevel != null
&& mLastBatteryCheckTime > (System.currentTimeMillis() - freshnessMs)) {
return mLastBatteryLevel;
}
BatteryReceiver receiver = new BatteryReceiver();
executeShellCommand("dumpsys battery", receiver, BATTERY_TIMEOUT);
mLastBatteryLevel = receiver.getBatteryLevel();
mLastBatteryCheckTime = System.currentTimeMillis();
return mLastBatteryLevel;
}
}
| gpl-2.0 |
jurkov/j-algo-mod | src/org/jalgo/module/ebnf/model/syndia/TerminalSymbol.java | 2602 | /*
* j-Algo - j-Algo is an algorithm visualization tool, especially useful for
* students and lecturers of computer science. It is written in Java and platform
* independent. j-Algo is developed with the help of Dresden University of
* Technology.
*
* Copyright (C) 2004-2005 j-Algo-Team, j-algo-development@lists.sourceforge.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 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jalgo.module.ebnf.model.syndia;
import org.jalgo.main.util.*;
/**
* A <code>TerminalSymbol</code> has a label.
*
* @author Michael Thiele
*/
public class TerminalSymbol extends SynDiaElem {
private static final long serialVersionUID = 1L;
private String label;
/**
* Constructs a terminal Symbol.
*
* @param parent
* parent of the element
* @param label
* label of the terminal symbol
* @param mySyntaxDiagram
* the syntax diagram this element belongs to
*/
public TerminalSymbol(SynDiaElem parent, String label,
SyntaxDiagram mySyntaxDiagram) {
super(parent, mySyntaxDiagram);
if (label == null || label.trim().equals(""))
throw new IllegalArgumentException(Messages.getString("ebnf",
"SynDiaModel.EmptyNameException"));
this.label = label;
}
/**
* @return Returns the label of the terminal symbol.
*/
public String getLabel() {
return label;
}
/**
* Sets the label name.
*
* @param label
* label of the terminal symbol
*/
public void setLabel(String label) {
if (label == null || label.trim().equals(""))
throw new IllegalArgumentException(Messages.getString("ebnf",
"SynDiaModel.EmptyNameException"));
this.getMySyntaxDiagram().getMySynDiaSystem().removeTerminal(this.label);
this.label = label;
this.getMySyntaxDiagram().getMySynDiaSystem().addTerminal(this.label);
this.getMySyntaxDiagram().getMySynDiaSystem().changed();
}
public String toString() {
return "Terminal: " + label;
}
}
| gpl-2.0 |
cmackie/Unsignedness-Study-jake2 | src/jake2/sound/lwjgl/Channel.java | 12067 | /*
* Created on Jun 19, 2004
*
* Copyright (C) 2003
*
* $Id: Channel.java,v 1.12 2006-11-23 13:31:58 cawe Exp $
*/
/*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package jake2.sound.lwjgl;
import jake2.Defines;
import jake2.Globals;
import jake2.client.CL_ents;
import jake2.game.entity_state_t;
import jake2.qcommon.Com;
import jake2.sound.*;
import jake2.util.Lib;
import jake2.util.Math3D;
import java.nio.*;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import org.checkerframework.checker.signedness.qual.Constant;
import org.lwjgl.openal.AL10;
import org.lwjgl.openal.OpenALException;
/**
* Channel
*
* @author dsanders/cwei
*/
public class Channel {
final static @Constant int LISTENER = 0;
final static @Constant int FIXED = 1;
final static @Constant int DYNAMIC = 2;
final static @Constant int MAX_CHANNELS = 32;
private final static FloatBuffer NULLVECTOR = Lib.newFloatBuffer(3);
private static Channel[] channels = new Channel[MAX_CHANNELS];
private static IntBuffer sources = Lib.newIntBuffer(MAX_CHANNELS);
// a reference of L:WJGLSoundImpl.buffers
private static IntBuffer buffers;
private static Map looptable = new Hashtable(MAX_CHANNELS);
private static int numChannels;
// stream handling
private static boolean streamingEnabled = false;
private static int streamQueue = 0;
// sound attributes
private int type;
private int entnum;
private int entchannel;
private int bufferId;
private int sourceId;
private float volume;
private float rolloff;
private float[] origin = {0, 0, 0};
// update flags
private boolean autosound;
private boolean active;
private boolean modified;
private boolean bufferChanged;
private boolean volumeChanged;
private Channel(int sourceId) {
this.sourceId = sourceId;
clear();
volumeChanged = false;
volume = 1.0f;
}
private void clear() {
entnum = entchannel = bufferId = -1;
bufferChanged = false;
rolloff = 0;
autosound = false;
active = false;
modified = false;
}
private static IntBuffer tmp = Lib.newIntBuffer(1);
static int init(IntBuffer buffers) {
Channel.buffers = buffers;
// create channels
int sourceId;
numChannels = 0;
for (int i = 0; i < MAX_CHANNELS; i++) {
try {
AL10.alGenSources(tmp);
sourceId = tmp.get(0);
// can't generate more sources
if (sourceId <= 0) break;
} catch (OpenALException e) {
// can't generate more sources
break;
}
sources.put(i, sourceId);
channels[i] = new Channel(sourceId);
numChannels++;
// set default values for AL sources
AL10.alSourcef (sourceId, AL10.AL_GAIN, 1.0f);
AL10.alSourcef (sourceId, AL10.AL_PITCH, 1.0f);
AL10.alSourcei (sourceId, AL10.AL_SOURCE_RELATIVE, AL10.AL_FALSE);
AL10.alSource(sourceId, AL10.AL_VELOCITY, NULLVECTOR);
AL10.alSourcei (sourceId, AL10.AL_LOOPING, AL10.AL_FALSE);
AL10.alSourcef (sourceId, AL10.AL_REFERENCE_DISTANCE, 200.0f);
AL10.alSourcef (sourceId, AL10.AL_MIN_GAIN, 0.0005f);
AL10.alSourcef (sourceId, AL10.AL_MAX_GAIN, 1.0f);
}
sources.limit(numChannels);
return numChannels;
}
static void reset() {
for (int i = 0; i < numChannels; i++) {
AL10.alSourceStop(sources.get(i));
AL10.alSourcei(sources.get(i), AL10.AL_BUFFER, 0);
channels[i].clear();
}
}
static void shutdown() {
AL10.alDeleteSources(sources);
numChannels = 0;
}
static void enableStreaming() {
if (streamingEnabled) return;
// use the last source
numChannels--;
streamingEnabled = true;
streamQueue = 0;
int source = channels[numChannels].sourceId;
AL10.alSourcei (source, AL10.AL_SOURCE_RELATIVE, AL10.AL_TRUE);
AL10.alSourcef(source, AL10.AL_GAIN, 1.0f);
channels[numChannels].volumeChanged = true;
Com.DPrintf("streaming enabled\n");
}
static void disableStreaming() {
if (!streamingEnabled) return;
unqueueStreams();
int source = channels[numChannels].sourceId;
AL10.alSourcei (source, AL10.AL_SOURCE_RELATIVE, AL10.AL_FALSE);
// free the last source
numChannels++;
streamingEnabled = false;
Com.DPrintf("streaming disabled\n");
}
static void unqueueStreams() {
if (!streamingEnabled) return;
int source = channels[numChannels].sourceId;
// stop streaming
AL10.alSourceStop(source);
int count = AL10.alGetSourcei(source, AL10.AL_BUFFERS_QUEUED);
Com.DPrintf("unqueue " + count + " buffers\n");
while (count-- > 0) {
AL10.alSourceUnqueueBuffers(source, tmp);
}
streamQueue = 0;
}
static void updateStream(ByteBuffer samples, int count, int format, int rate) {
enableStreaming();
int source = channels[numChannels].sourceId;
int processed = AL10.alGetSourcei(source, AL10.AL_BUFFERS_PROCESSED);
boolean playing = (AL10.alGetSourcei(source, AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING);
boolean interupted = !playing && streamQueue > 2;
IntBuffer buffer = tmp;
if (interupted) {
unqueueStreams();
buffer.put(0, buffers.get(Sound.MAX_SFX + streamQueue++));
Com.DPrintf("queue " + (streamQueue - 1) + '\n');
} else if (processed < 2) {
// check queue overrun
if (streamQueue >= Sound.STREAM_QUEUE) return;
buffer.put(0, buffers.get(Sound.MAX_SFX + streamQueue++));
Com.DPrintf("queue " + (streamQueue - 1) + '\n');
} else {
// reuse the buffer
AL10.alSourceUnqueueBuffers(source, buffer);
}
samples.position(0);
samples.limit(count);
AL10.alBufferData(buffer.get(0), format, samples, rate);
AL10.alSourceQueueBuffers(source, buffer);
if (streamQueue > 1 && !playing) {
Com.DPrintf("start sound\n");
AL10.alSourcePlay(source);
}
}
static void addPlaySounds() {
while (Channel.assign(PlaySound.nextPlayableSound()));
}
private static boolean assign(PlaySound ps) {
if (ps == null) return false;
Channel ch = null;
int i;
for (i = 0; i < numChannels; i++) {
ch = channels[i];
if (ps.entchannel != 0 && ch.entnum == ps.entnum && ch.entchannel == ps.entchannel) {
// always override sound from same entity
if (ch.bufferId != ps.bufferId) {
AL10.alSourceStop(ch.sourceId);
}
break;
}
// don't let monster sounds override player sounds
if ((ch.entnum == Globals.cl.playernum+1) && (ps.entnum != Globals.cl.playernum+1) && ch.bufferId != -1)
continue;
// looking for a free AL source
if (!ch.active) {
break;
}
}
if (i == numChannels)
return false;
ch.type = ps.type;
if (ps.type == Channel.FIXED)
Math3D.VectorCopy(ps.origin, ch.origin);
ch.entnum = ps.entnum;
ch.entchannel = ps.entchannel;
ch.bufferChanged = (ch.bufferId != ps.bufferId);
ch.bufferId = ps.bufferId;
ch.rolloff = ps.attenuation * 2;
ch.volumeChanged = (ch.volume != ps.volume);
ch.volume = ps.volume;
ch.active = true;
ch.modified = true;
return true;
}
private static Channel pickForLoop(int bufferId, float attenuation) {
Channel ch;
for (int i = 0; i < numChannels; i++) {
ch = channels[i];
// looking for a free AL source
if (!ch.active) {
ch.entnum = 0;
ch.entchannel = 0;
ch.bufferChanged = (ch.bufferId != bufferId);
ch.bufferId = bufferId;
ch.volumeChanged = (ch.volume != 1.0f);
ch.volume = 1.0f;
ch.rolloff = attenuation * 2;
ch.active = true;
ch.modified = true;
return ch;
}
}
return null;
}
private static FloatBuffer sourceOriginBuffer = Lib.newFloatBuffer(3);
//stack variable
private static float[] entityOrigin = {0, 0, 0};
static void playAllSounds(FloatBuffer listenerOrigin) {
FloatBuffer sourceOrigin = sourceOriginBuffer;
Channel ch;
int sourceId;
int state;
for (int i = 0; i < numChannels; i++) {
ch = channels[i];
if (ch.active) {
sourceId = ch.sourceId;
switch (ch.type) {
case Channel.LISTENER:
sourceOrigin.put(0, listenerOrigin.get(0));
sourceOrigin.put(1, listenerOrigin.get(1));
sourceOrigin.put(2, listenerOrigin.get(2));
break;
case Channel.DYNAMIC:
CL_ents.GetEntitySoundOrigin(ch.entnum, entityOrigin);
convertVector(entityOrigin, sourceOrigin);
break;
case Channel.FIXED:
convertVector(ch.origin, sourceOrigin);
break;
}
if (ch.modified) {
if (ch.bufferChanged) {
try {
AL10.alSourcei(sourceId, AL10.AL_BUFFER, ch.bufferId);
} catch (OpenALException e) {
// fallback for buffer changing
AL10.alSourceStop(sourceId);
AL10.alSourcei(sourceId, AL10.AL_BUFFER, ch.bufferId);
}
}
if (ch.volumeChanged) {
AL10.alSourcef (sourceId, AL10.AL_GAIN, ch.volume);
}
AL10.alSourcef (sourceId, AL10.AL_ROLLOFF_FACTOR, ch.rolloff);
AL10.alSource(sourceId, AL10.AL_POSITION, sourceOrigin);
AL10.alSourcePlay(sourceId);
ch.modified = false;
} else {
state = AL10.alGetSourcei(sourceId, AL10.AL_SOURCE_STATE);
if (state == AL10.AL_PLAYING) {
AL10.alSource(sourceId, AL10.AL_POSITION, sourceOrigin);
} else {
ch.clear();
}
}
ch.autosound = false;
}
}
}
/*
* adddLoopSounds
* Entities with a ->sound field will generated looped sounds
* that are automatically started, stopped, and merged together
* as the entities are sent to the client
*/
static void addLoopSounds() {
if ((Globals.cl_paused.value != 0.0f) || (Globals.cls.state != Globals.ca_active) || !Globals.cl.sound_prepped) {
removeUnusedLoopSounds();
return;
}
Channel ch;
sfx_t sfx;
sfxcache_t sc;
int num;
entity_state_t ent;
Object key;
int sound = 0;
for (int i=0 ; i<Globals.cl.frame.num_entities ; i++) {
num = (Globals.cl.frame.parse_entities + i)&(Defines.MAX_PARSE_ENTITIES-1);
ent = Globals.cl_parse_entities[num];
sound = ent.sound;
if (sound == 0) continue;
key = new Integer(ent.number);
ch = (Channel)looptable.get(key);
if (ch != null) {
// keep on looping
ch.autosound = true;
Math3D.VectorCopy(ent.origin, ch.origin);
continue;
}
sfx = Globals.cl.sound_precache[sound];
if (sfx == null)
continue; // bad sound effect
sc = sfx.cache;
if (sc == null)
continue;
// allocate a channel
ch = Channel.pickForLoop(buffers.get(sfx.bufferId), 6);
if (ch == null)
break;
ch.type = FIXED;
Math3D.VectorCopy(ent.origin, ch.origin);
ch.autosound = true;
looptable.put(key, ch);
AL10.alSourcei(ch.sourceId, AL10.AL_LOOPING, AL10.AL_TRUE);
}
removeUnusedLoopSounds();
}
private static void removeUnusedLoopSounds() {
Channel ch;
// stop unused loopsounds
for (Iterator iter = looptable.values().iterator(); iter.hasNext();) {
ch = (Channel)iter.next();
if (!ch.autosound) {
AL10.alSourceStop(ch.sourceId);
AL10.alSourcei(ch.sourceId, AL10.AL_LOOPING, AL10.AL_FALSE);
iter.remove();
ch.clear();
}
}
}
static void convertVector(float[] from, FloatBuffer to) {
to.put(0, from[0]);
to.put(1, from[2]);
to.put(2, -from[1]);
}
static void convertOrientation(float[] forward, float[] up, FloatBuffer orientation) {
orientation.put(0, forward[0]);
orientation.put(1, forward[2]);
orientation.put(2, -forward[1]);
orientation.put(3, up[0]);
orientation.put(4, up[2]);
orientation.put(5, -up[1]);
}
}
| gpl-2.0 |
belyabl9/teammates | src/main/java/teammates/storage/api/CoursesDb.java | 6171 | package teammates.storage.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.jdo.JDOHelper;
import javax.jdo.Query;
import teammates.common.datatransfer.CourseAttributes;
import teammates.common.datatransfer.EntityAttributes;
import teammates.common.exception.EntityDoesNotExistException;
import teammates.common.exception.InvalidParametersException;
import teammates.common.util.Assumption;
import teammates.common.util.Const;
import teammates.storage.entity.Course;
/**
* Handles CRUD Operations for course entities.
* The API uses data transfer classes (i.e. *Attributes) instead of presistable classes.
*/
public class CoursesDb extends EntitiesDb {
/*
* Explanation: Based on our policies for the storage component, this class does not handle cascading.
* It treats invalid values as an exception.
*/
public static final String ERROR_UPDATE_NON_EXISTENT_COURSE = "Trying to update a Course that doesn't exist: ";
public void createCourses(Collection<CourseAttributes> coursesToAdd) throws InvalidParametersException {
List<EntityAttributes> coursesToUpdate = createEntities(coursesToAdd);
for (EntityAttributes entity : coursesToUpdate) {
CourseAttributes course = (CourseAttributes) entity;
try {
updateCourse(course);
} catch (EntityDoesNotExistException e) {
// This situation is not tested as replicating such a situation is
// difficult during testing
Assumption.fail("Entity found be already existing and not existing simultaneously");
}
}
}
/**
* Preconditions: <br>
* * All parameters are non-null.
* @return Null if not found.
*/
public CourseAttributes getCourse(String courseId) {
Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId);
Course c = getCourseEntity(courseId);
if (c == null) {
return null;
}
return new CourseAttributes(c);
}
public List<CourseAttributes> getCourses(List<String> courseIds) {
Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseIds);
List<Course> courses = getCourseEntities(courseIds);
List<CourseAttributes> courseAttributes = new ArrayList<CourseAttributes>();
// TODO add method to get List<CourseAttributes> from List<Course>
for (Course c : courses) {
if (!JDOHelper.isDeleted(c)) {
courseAttributes.add(new CourseAttributes(c));
}
}
return courseAttributes;
}
/**
* @deprecated Not scalable. Use only in admin features.
*/
@Deprecated
public List<CourseAttributes> getAllCourses() {
Query q = getPm().newQuery(Course.class);
@SuppressWarnings("unchecked")
List<Course> courseList = (List<Course>) q.execute();
List<CourseAttributes> courseDataList = new ArrayList<CourseAttributes>();
for (Course c : courseList) {
if (!JDOHelper.isDeleted(c)) {
courseDataList.add(new CourseAttributes(c));
}
}
return courseDataList;
}
/**
* Updates the course.<br>
* Updates only name and course archive status.<br>
* Preconditions: <br>
* * {@code courseToUpdate} is non-null.<br>
* @throws InvalidParametersException, EntityDoesNotExistException
*/
public void updateCourse(CourseAttributes courseToUpdate) throws InvalidParametersException,
EntityDoesNotExistException {
Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseToUpdate);
courseToUpdate.sanitizeForSaving();
if (!courseToUpdate.isValid()) {
throw new InvalidParametersException(courseToUpdate.getInvalidityInfo());
}
Course courseEntityToUpdate = getCourseEntity(courseToUpdate.getId());
if (courseEntityToUpdate == null) {
throw new EntityDoesNotExistException(ERROR_UPDATE_NON_EXISTENT_COURSE);
}
courseEntityToUpdate.setName(courseToUpdate.getName());
courseEntityToUpdate.setTimeZone(courseToUpdate.getTimeZone());
log.info(courseToUpdate.getBackupIdentifier());
getPm().close();
}
/**
* Note: This is a non-cascade delete.<br>
* <br> Fails silently if there is no such object.
* <br> Preconditions:
* <br> * {@code courseId} is not null.
*/
public void deleteCourse(String courseId) {
Assumption.assertNotNull(Const.StatusCodes.DBLEVEL_NULL_INPUT, courseId);
// only the courseId is important here, everything else are placeholders
CourseAttributes entityToDelete = new CourseAttributes(courseId, "Non-existent course", "UTC");
deleteEntity(entityToDelete);
}
@Override
protected Object getEntity(EntityAttributes attributes) {
return getCourseEntity(((CourseAttributes) attributes).getId());
}
private Course getCourseEntity(String courseId) {
Query q = getPm().newQuery(Course.class);
q.declareParameters("String courseIdParam");
q.setFilter("ID == courseIdParam");
@SuppressWarnings("unchecked")
List<Course> courseList = (List<Course>) q.execute(courseId);
if (courseList.isEmpty() || JDOHelper.isDeleted(courseList.get(0))) {
return null;
}
return courseList.get(0);
}
private List<Course> getCourseEntities(List<String> courseIds) {
if (courseIds.isEmpty()) {
return new ArrayList<Course>();
}
Query q = getPm().newQuery(Course.class);
q.setFilter(":p.contains(ID)");
@SuppressWarnings("unchecked")
List<Course> courses = (List<Course>) q.execute(courseIds);
return courses;
}
}
| gpl-2.0 |
trueg/virtuoso-opensource | libsrc/JDBCDriverType4/testsuite_4.0/TestMoreRes.java | 5936 | /*
* This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
* project.
*
* Copyright (C) 1998-2012 OpenLink Software
*
* This project 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; only version 2 of the License, dated June 1991.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package testsuite;
import java.sql.*;
import virtuoso.jdbc4.*;
public class TestMoreRes
{
public static void main(String args[])
{
try
{
String url;
if(args.length == 0)
url = "jdbc:virtuoso://localhost:1111";
else
url = args[0];
Class.forName("virtuoso.jdbc4.Driver");
System.out.println("--------------------- Test of scrollable cursor -------------------");
System.out.print("Establish connection at " + url);
Connection connection = DriverManager.getConnection(url,"dba","dba");
if(connection instanceof virtuoso.jdbc4.VirtuosoConnection)
System.out.println(" PASSED");
else
{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.print("Create a Statement class attached to this connection");
Statement stmt = ((VirtuosoConnection)connection).createStatement(VirtuosoResultSet.TYPE_SCROLL_INSENSITIVE,VirtuosoResultSet.CONCUR_READ_ONLY);
if(stmt instanceof virtuoso.jdbc4.VirtuosoStatement)
System.out.println(" PASSED");
else
{
System.out.println(" FAILED");
System.exit(-1);
}
try{
stmt.executeUpdate("drop procedure ex..pdemo");
}catch(Exception e) {}
System.out.print("Execute CREATE PROCEDURE");
if(stmt.executeUpdate("create procedure ex..pdemo () { result_names('a1'); result(1); end_result(); result_names('b1','b2'); result(2,3); end_result(); }") == 0)
System.out.println(" PASSED");
else
{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.print("Execute procedure");
stmt.executeQuery("{call ex..pdemo()}");
System.out.println(" PASSED");
System.out.print("Get the result set");
ResultSet rs = stmt.getResultSet();
if(rs instanceof virtuoso.jdbc4.VirtuosoResultSet)
{
System.out.println(" PASSED");
}
else
{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.println("Get Data");
System.out.print("Execute the resultset.next()");
if(rs.next())
{
if(rs.getInt(1) != 1)
{
System.out.println(" FAILED");
System.exit(-1);
}
}else{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.println(" PASSED");
System.out.print("Execute the getMoreResults()");
if (!stmt.getMoreResults())
{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.println(" PASSED");
System.out.print("Get the result set");
rs = stmt.getResultSet();
if(rs instanceof virtuoso.jdbc4.VirtuosoResultSet)
{
System.out.println(" PASSED");
}
else
{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.print("Get Data");
System.out.print("Execute the resultset.next()");
if(rs.next()){
if(rs.getInt(1) != 2)
{
System.out.println(" FAILED");
System.exit(-1);
}
if(rs.getInt(2) != 3)
{
System.out.println(" FAILED");
System.exit(-1);
}
}else{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.println(" PASSED");
System.out.print("Execute the getMoreResults()");
if (!stmt.getMoreResults())
{
System.out.println(" FAILED");
System.exit(-1);
}
if (stmt.getMoreResults())
{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.println(" PASSED");
stmt.close();
stmt = connection.createStatement();
System.out.print("Execute DROP PROCEDURE");
if(stmt.executeUpdate("DROP PROCEDURE ex..pdemo") == 0)
System.out.println(" PASSED");
else
{
System.out.println(" FAILED");
System.exit(-1);
}
System.out.print("Close statement at " + url);
stmt.close();
System.out.println(" PASSED");
System.out.print("Close connection at " + url);
connection.close();
System.out.println(" PASSED");
System.out.println("-------------------------------------------------------------------");
System.exit(0);
}
catch(Exception e)
{
System.out.println(" FAILED");
e.printStackTrace();
System.exit(-1);
}
}
}
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/ironjacamar/org/jboss/jca/core/connectionmanager/pool/strategy/PoolByCri.java | 2974 | /*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2008-2009, Red Hat Inc, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jca.core.connectionmanager.pool.strategy;
import org.jboss.jca.core.CoreLogger;
import org.jboss.jca.core.api.connectionmanager.pool.PoolConfiguration;
import org.jboss.jca.core.connectionmanager.pool.AbstractPool;
import javax.resource.ResourceException;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnectionFactory;
import javax.security.auth.Subject;
import org.jboss.logging.Logger;
/**
* Pool implementation that uses subject.
*
* @author <a href="mailto:gurkanerdogdu@yahoo.com">Gurkan Erdogdu</a>
* @author <a href="mailto:jesper.pedersen@ironjacamar.org">Jesper Pedersen</a>
*/
public class PoolByCri extends AbstractPool
{
/** The logger */
private static CoreLogger log = Logger.getMessageLogger(CoreLogger.class, PoolByCri.class.getName());
/**
* Creates a new instance.
* @param mcf managed connection factory
* @param pc pool configuration
* @param noTxSeparatePools notx seperate pool
* @param sharable Are the connections sharable
* @param mcp mcp
*/
public PoolByCri(final ManagedConnectionFactory mcf, final PoolConfiguration pc,
final boolean noTxSeparatePools, final boolean sharable,
final String mcp)
{
super(mcf, pc, noTxSeparatePools, sharable, mcp);
}
/**
* {@inheritDoc}
*/
@Override
protected Object getKey(Subject subject, ConnectionRequestInfo cri, boolean separateNoTx) throws ResourceException
{
return new CriKey(cri, separateNoTx);
}
/**
* {@inheritDoc}
*/
public boolean testConnection()
{
return false;
}
/**
* {@inheritDoc}
*/
public boolean testConnection(ConnectionRequestInfo cri, Subject subject)
{
return internalTestConnection(cri, null);
}
/**
* {@inheritDoc}
*/
public CoreLogger getLogger()
{
return log;
}
}
| gpl-2.0 |
mountain/dajoo | dev/frame/src/org/dajoo/frame/TraceableFrameServlet.java | 2115 | package org.dajoo.frame;
import java.io.CharArrayWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.dajoo.httpd.Content;
import org.dajoo.httpd.HttpRequest;
import org.dajoo.httpd.HttpResponse;
import org.dajoo.httpd.Servlet;
import org.dajoo.httpd.ServletException;
import org.dajoo.httpd.StringContent;
import freemarker.template.Template;
public abstract class TraceableFrameServlet implements Servlet, Traceable {
protected freemarker.template.Configuration templateCfg;
protected ToolbarManager tlbMgr;
protected TraceManager traceMgr;
public TraceableFrameServlet(freemarker.template.Configuration tc, ToolbarManager tlbm, TraceManager trcm) {
templateCfg = tc;
tlbMgr = tlbm;
traceMgr = trcm;
}
public void service(HttpRequest req, HttpResponse resp) throws ServletException {
traceMgr.addTrace(getTrace(req));
resp.setContent(getContent(req));
resp.sendNormally();
}
protected Content getContent(HttpRequest req) {
Map<String, Object> root = new HashMap<String, Object>();
root.put("title", getTitle(req));
root.put("path", getPath(req));
root.put("toolbar", tlbMgr.getButtonsForPath(req.getPath()));
root.put("traces", traceMgr.getTraces());
setBody(req, root);
Writer out = new CharArrayWriter(500);
try {
Template template = templateCfg.getTemplate(getTemplate(), "utf-8");
template.process(root, out);
out.flush();
} catch(Exception e) {
e.printStackTrace();
}
return new StringContent(out.toString(), "text/html");
}
protected abstract String getTemplate();
protected abstract String getTitle(HttpRequest req);
protected abstract String getPath(HttpRequest req);
protected abstract void setBody(HttpRequest req, Map<String, Object> root);
public Trace getTrace(HttpRequest req) {
return new Trace(getTitle(req), req.getPath());
}
}
| gpl-2.0 |
OceanAtlas/JOA | gov/noaa/pmel/sgt/beans/DataTargetMismatchException.java | 1109 | /*
* $Id: DataTargetMismatchException.java,v 1.2 2003/08/22 23:02:34 dwd Exp $
*
* This software is provided by NOAA for full, free and open release. It is
* understood by the recipient/user that NOAA assumes no liability for any
* errors contained in the code. Although this software is released without
* conditions or restrictions in its use, it is expected that appropriate
* credit be given to its author and to the National Oceanic and Atmospheric
* Administration should the software be included by the recipient as an
* element in other product development.
*/
package gov.noaa.pmel.sgt.beans;
/**
* <code>SGTData</code> does not match the target of <code>Panel</code> and
* <code>DataGroup</code> or <code>Legend</code> type.
*
* @author Donald Denbo
* @version $Revision: 1.2 $, $Date: 2003/08/22 23:02:34 $
* @since 3.0
* @stereotype bean
**/
public class DataTargetMismatchException extends Exception {
public DataTargetMismatchException() {
super();
}
public DataTargetMismatchException(String message) {
super(message);
}
} | gpl-2.0 |
phantamanta44/OpenAargon | src/main/java/io/github/phantamanta44/openar/game/map/MovementHandler.java | 4956 | package io.github.phantamanta44.openar.game.map;
import io.github.phantamanta44.openar.audio.AudioManager;
import io.github.phantamanta44.openar.game.beam.BeamTile;
import io.github.phantamanta44.openar.game.piece.IGamePiece;
import io.github.phantamanta44.openar.game.piece.PieceRegistry;
import io.github.phantamanta44.openar.game.piece.impl.PieceAir;
import io.github.phantamanta44.openar.render.Quad8I;
import io.github.phantamanta44.openar.render.RenderManager;
import io.github.phantamanta44.openar.util.math.IntVector;
public class MovementHandler {
private volatile SingletonPieceWrapper held;
private volatile IntVector heldCoords;
private volatile IntVector mouseCoords;
private volatile boolean hasMoved;
private volatile GameField heldField;
public MovementHandler() {
mouseCoords = new IntVector();
hasMoved = false;
}
public boolean holdingPiece() {
return held != null;
}
public void clearHand() {
held = null;
}
public boolean grab(GameField field, IntVector coords, int dir) {
IGamePiece piece = field.getPiece(coords);
if (piece != null && !(piece instanceof PieceAir) && !holdingPiece()) {
if (!Mutability.forMask(field.getMutability(coords)).canMove()) {
if (Mutability.forMask(field.getMutability(coords)).canRotate()) {
field.setRotation(coords, modulo(field.getRotation(coords) + dir));
AudioManager.play("audio/rotate.wav");
field.updateBeams();
return true;
} else
return false;
}
held = new SingletonPieceWrapper(piece, field.getRotation(coords), field.getMeta(coords), field.getMutability(coords));
heldCoords = coords;
heldField = field;
return true;
}
return false;
}
public boolean drop(GameField field, IntVector coords, int dir) {
if (holdingPiece()) {
if (!hasMoved) {
field.setPiece(heldCoords, held.piece);
field.setMeta(heldCoords, held.meta);
field.setMutability(heldCoords, held.muta);
if (Mutability.forMask(field.getMutability(coords)).canRotate() && !hasMoved) {
field.setRotation(heldCoords, modulo(held.rot + dir));
AudioManager.play("audio/rotate.wav");
}
else
field.setRotation(heldCoords, held.rot);
held = null;
hasMoved = false;
field.updateBeams();
return true;
}
IGamePiece endPt = field.getPiece(coords);
if (endPt != null && !(endPt instanceof PieceAir)) {
if (!Mutability.forMask(field.getMutability(coords)).canMove()) {
field.setPiece(heldCoords, held.piece);
field.setRotation(heldCoords, held.rot);
field.setMeta(heldCoords, held.meta);
field.setMutability(heldCoords, held.muta);
held = null;
hasMoved = false;
field.updateBeams();
AudioManager.play("audio/fail.wav");
return false;
}
field.setPiece(heldCoords, endPt);
field.setRotation(heldCoords, field.getRotation(coords));
field.setMeta(heldCoords, field.getMeta(coords));
field.setMutability(heldCoords, field.getMutability(coords));
}
field.setPiece(coords, held.piece);
field.setRotation(coords, held.rot);
field.setMeta(coords, held.meta);
field.setMutability(coords, held.muta);
held = null;
hasMoved = false;
field.updateBeams();
AudioManager.play("audio/drop.wav");
return true;
}
return false;
}
public void updatePos(int mX, int mY, int cX, int cY) {
mouseCoords.setX(mX).setY(mY);
if (holdingPiece()) {
if (!hasMoved && (heldCoords.getX() != cX || heldCoords.getY() != cY)) {
heldField.setPiece(heldCoords, PieceRegistry.EMPTY);
heldField.updateBeams();
hasMoved = true;
AudioManager.play("audio/grab.wav");
}
}
}
public synchronized void bufferRenders(float xSize, float ySize, float ratio) {
if (holdingPiece() && hasMoved) {
String path = held.piece.getTexturePath(held, IntVector.ZERO, held.rot, held.meta);
IntVector offset = held.piece.getTextureOffset(held, IntVector.ZERO, held.rot, held.meta);
RenderManager.bufferQuad(new Quad8I(path, (int) ((float) mouseCoords.getX() * 1.965F - xSize - 52F),
(int) ((ySize / ratio) - (float) mouseCoords.getY() * 1.965F - 52F),
103, 103, offset.getX(), offset.getY(), 32, 32));
}
}
private static int modulo(int rot) {
return (rot + 8) % 8;
}
public static class SingletonPieceWrapper implements IGameField {
private final IGamePiece piece;
private final int rot, meta, muta;
private SingletonPieceWrapper(IGamePiece piece, int rot, int meta, int muta) {
this.piece = piece;
this.rot = rot;
this.meta = meta;
this.muta = muta;
}
@Override
public IGamePiece getPiece(IntVector coords) {
return piece;
}
@Override
public int getRotation(IntVector coords) {
return rot;
}
@Override
public int getMeta(IntVector coords) {
return meta;
}
@Override
public BeamTile getBeams(IntVector coords) {
return BeamTile.EMPTY;
}
@Override
public int getMutability(IntVector coords) {
return muta;
}
}
}
| gpl-2.0 |
takaki/jdip | src/main/java/dip/gui/swing/XJTextField.java | 3784 | //
// @(#)XJTextPane.java 3/2003
//
// Copyright 2003 Zachary DelProposto. All rights reserved.
// Use is subject to license terms.
//
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
// Or from http://www.gnu.org/
//
package dip.gui.swing;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;
import java.awt.*;
/**
* eXtended JTextField.
* <p>
* Converts unicode arrows (\u2192) to "->" arrows,
* if the component font is not Unicode-aware.
*/
public class XJTextField extends JTextField {
private boolean isUnicodeArrowAware = false;
public XJTextField() {
this(null, 0);
}
public XJTextField(final int columns) {
this(null, columns);
}
public XJTextField(final String text) {
this(text, 0);
}
public XJTextField(final String text, final int columns) {
super(null, columns);
final AbstractDocument doc = (AbstractDocument) getDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(final FilterBypass fb, final int offset,
final String text,
final AttributeSet attr) throws BadLocationException {
replace(fb, offset, 0, text, attr);
}// insertString()
@Override
public void replace(final FilterBypass fb, final int offset,
final int length, final String text,
final AttributeSet attr) throws BadLocationException {
if (!isUnicodeAware()) {
fb.replace(offset, length, getFixedString(text), attr);
} else {
super.replace(fb, offset, length, text, attr);
}
}// replace()
private String getFixedString(final String in) {
final StringBuffer buffer = new StringBuffer(in == null ? "" : in);
for (int i = buffer.length() - 1; i >= 0; i--) {
final char c = buffer.charAt(i);
if (c == '\u2192') {
buffer.deleteCharAt(i);
buffer.insert(i, "->");
}
}
return buffer.toString();
}// getValidURLString()
});
setText(text);
if (text != null) {
setText(text);
}
}
@Override
public void setFont(final Font f) {
super.setFont(f);
detectUnicode();
}// setFont()
/**
* Detect if font is unicode-aware
*/
private void detectUnicode() {
isUnicodeArrowAware = getFont().canDisplay('\u2192');
}// detectUnicode()
/**
* Returns if parent is unicode-aware
*/
private boolean isUnicodeAware() {
return isUnicodeArrowAware;
}// isUnicodeAware()
}// class XJTextField
| gpl-2.0 |
tnsingle/logmypain | app/src/main/java/com/logmypain/utils/CalendarUtil.java | 3265 | package com.logmypain.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.os.Bundle;
public class CalendarUtil {
public static String getDateDisplay(Calendar cal){
return cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US)+" " + cal.get(Calendar.DATE) + ", " + cal.get(Calendar.YEAR);
}
public static String getShortDateDisplay(Calendar cal){
return cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US)+" " + cal.get(Calendar.DATE);
}
public static String getShortMonthYearDisplay(Calendar cal){
return cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US)+" " + cal.get(Calendar.YEAR);
}
public static String getTimeDisplay(Calendar cal){
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa", Locale.getDefault());
return dateFormat.format(cal.getTime());
}
/*public static String getDuration(Calendar start, Calendar end){
Date startDate = start.getTime();
Date endDate = end.getTime();
long difference = endDate.getTime() - startDate.getTime();
int days = (int) (difference / (1000*60*60*24));
int hours = (int) (difference / (1000*60*60)); //(1000*60*60*24*days)) / (1000*60*60));
int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
return hours + " hours and " + min + " minutes";
}*/
public static String getShortDuration(Calendar startDate, Calendar endDate)
{
long startTime = startDate.getTimeInMillis();
long endTime = endDate.getTimeInMillis();
long milliseconds = endTime - startTime;
int days = (int) (milliseconds / (1000*60*60*24));
int hours = (int) (milliseconds / (1000*60*60));
int min = (int) (milliseconds - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
if (hours < 1) {
return min + " min";
}else{
StringBuilder durationText = new StringBuilder();
if (hours == 1) {
durationText.append(hours + " hr");
}else{
durationText.append(hours + " hrs");
}
if(min > 30){
durationText.append(" " + min + " min");
}
return durationText.toString();
}
}
public static Bundle bundleCalendar(Calendar cal){
Bundle args = new Bundle();
if (cal == null)
cal = Calendar.getInstance(Locale.getDefault());;
args.putInt("year", cal.get(Calendar.YEAR));
args.putInt("month", cal.get(Calendar.MONTH));
args.putInt("day", cal.get(Calendar.DAY_OF_MONTH));
args.putInt("hour", cal.get(Calendar.HOUR_OF_DAY));
args.putInt("minute", cal.get(Calendar.MINUTE));
return args;
}
public static Bundle bundleCalendar(Calendar cal, long minDate){
Bundle args = new Bundle();
if (cal == null)
cal = Calendar.getInstance(Locale.getDefault());;
args.putInt("year", cal.get(Calendar.YEAR));
args.putInt("month", cal.get(Calendar.MONTH));
args.putInt("day", cal.get(Calendar.DAY_OF_MONTH));
args.putInt("hour", cal.get(Calendar.HOUR_OF_DAY));
args.putInt("minute", cal.get(Calendar.MINUTE));
args.putLong("minDate", minDate);
return args;
}
}
| gpl-2.0 |
seb0uil/tportal | src/net/tinyportal/tools/CommitBufferedOutputStream.java | 4586 | /*
This file is part of tPortal.
tPortal 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.
tPortal 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 tPortal. If not, see <http://www.gnu.org/licenses/>.
The original code was written by Sebastien Bettinger <sebastien.bettinger@gmail.com>
*/
package net.tinyportal.tools;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
public class CommitBufferedOutputStream extends BufferedOutputStream implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4828002484747518385L;
/**
* Flag indiquant si le buffer a été commité ou non
*/
protected boolean commit = false;
/**
* Creates a new buffered output stream to write data to the
* specified underlying output stream.
*
* @param out the underlying output stream.
*/
public CommitBufferedOutputStream(OutputStream out) {
this(out, 8192);
}
/**
* Creates a new buffered output stream to write data to the
* specified underlying output stream with the specified buffer
* size.
*
* @param out the underlying output stream.
* @param size the buffer size.
* @exception IllegalArgumentException if size <= 0.
*/
public CommitBufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
/** Flush the internal buffer */
private void flushBuffer() throws IOException {
commit = true;
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
/**
* Writes the specified byte to this buffered output stream.
*
* @param b the byte to be written.
* @exception IOException if an I/O error occurs.
*/
public synchronized void write(int b) throws IOException {
if (count >= buf.length) {
flushBuffer();
}
buf[count++] = (byte)b;
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this buffered output stream.
*
* <p> Ordinarily this method stores bytes from the given array into this
* stream's buffer, flushing the buffer to the underlying output stream as
* needed. If the requested length is at least as large as this stream's
* buffer, however, then this method will flush the buffer and write the
* bytes directly to the underlying output stream. Thus redundant
* <code>BufferedOutputStream</code>s will not copy data unnecessarily.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
public synchronized void write(byte b[], int off, int len) throws IOException {
if (len >= buf.length) {
/* If the request length exceeds the size of the output buffer,
flush the output buffer and then write the data directly.
In this way buffered streams will cascade harmlessly. */
flushBuffer();
out.write(b, off, len);
return;
}
if (len > buf.length - count) {
flushBuffer();
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
/**
* Flushes this buffered output stream. This forces any buffered
* output bytes to be written out to the underlying output stream.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public synchronized void flush() throws IOException {
flushBuffer();
out.flush();
}
public boolean isCommitted() {
return commit;
}
public String toString() {
return this.out.toString();
}
public int getBufferSize() {
return buf.length;
}
/**
* Positionne la taille du buffer
* @param size taille en byte
* @throws IllegalStateException Si une écriture a déjà été réalisée
* une IllegalStateException est levé
*/
public void setBufferSize(int size) {
if (commit || count > 0) throw new IllegalStateException();
// flush();
buf = new byte[size];
count = 0;
commit = false;
}
}
| gpl-2.0 |
Jorl17/universe-25 | project/core/src/universe25/GameLogic/Movement/deprecated/SteerableImage/Scene2dSteeringUtils.java | 1271 | /*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* 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 universe25.GameLogic.Movement.deprecated.SteerableImage;
import com.badlogic.gdx.math.Vector2;
public final class Scene2dSteeringUtils {
private Scene2dSteeringUtils () {
}
public static float vectorToAngle (Vector2 vector) {
return (float)Math.atan2(-vector.x, vector.y);
}
public static Vector2 angleToVector (Vector2 outVector, float angle) {
outVector.x = -(float)Math.sin(angle);
outVector.y = (float)Math.cos(angle);
return outVector;
}
}
| gpl-2.0 |
luigivieira/ImagMAS | imagmas/ontology/CConclusionInformation.java | 1254 | /*
* Copyright (C) 2009 Luiz Carlos Vieira
* http://www.luiz.vieira.nom.br
*
* This file is part of the ImagMAS (A Multiagent System to Estimate
* the Coverage of Alluminum Alloy Plates Submitted to Peen Forming Process).
*
* ImagMAS 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.
*
* ImagMAS 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 imagmas.ontology;
public class CConclusionInformation
{
private boolean m_bConcluded;
public CConclusionInformation()
{
setConcluded(false);
}
public CConclusionInformation(boolean bConcluded)
{
setConcluded(bConcluded);
}
public boolean isConcluded()
{
return m_bConcluded;
}
public void setConcluded(boolean bValue)
{
m_bConcluded = bValue;
}
} | gpl-2.0 |
tomaszbabiuk/geekhome-asymptote | asymptote/src/main/java/eu/geekhome/asymptote/utils/UdpUtils.java | 376 | package eu.geekhome.asymptote.utils;
import java.net.DatagramPacket;
import java.util.Arrays;
public class UdpUtils {
public static String datagramToString(DatagramPacket datagram) {
byte[] data = Arrays.copyOf(datagram.getData(), datagram.getLength());
return String.format("[%s] from: [%s]", ByteUtils.bytesToHex(data), datagram.getAddress());
}
}
| gpl-2.0 |
marylinh/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01284.java | 3839 | /**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01284")
public class BenchmarkTest01284 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = request.getParameter("vector");
if (param == null) param = "";
String bar = new Test().doSomething(param);
org.owasp.benchmark.helpers.LDAPManager ads = new org.owasp.benchmark.helpers.LDAPManager();
try {
response.setContentType("text/html");
String base = "ou=users,ou=system";
javax.naming.directory.SearchControls sc = new javax.naming.directory.SearchControls();
sc.setSearchScope(javax.naming.directory.SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectclass=person)(uid=" + bar
+ "))";
javax.naming.directory.DirContext ctx = ads.getDirContext();
javax.naming.directory.InitialDirContext idc = (javax.naming.directory.InitialDirContext) ctx;
javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
idc.search(base, filter, sc);
while (results.hasMore()) {
javax.naming.directory.SearchResult sr = (javax.naming.directory.SearchResult) results.next();
javax.naming.directory.Attributes attrs = sr.getAttributes();
javax.naming.directory.Attribute attr = attrs.get("uid");
javax.naming.directory.Attribute attr2 = attrs.get("street");
if (attr != null){
response.getWriter().write("LDAP query results:<br>"
+ " Record found with name " + attr.get() + "<br>"
+ "Address: " + attr2.get()+ "<br>");
System.out.println("record found " + attr.get());
}
}
} catch (javax.naming.NamingException e) {
throw new ServletException(e);
}finally{
try {
ads.closeDirContext();
} catch (Exception e) {
throw new ServletException(e);
}
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = "safe!";
java.util.HashMap<String,Object> map11065 = new java.util.HashMap<String,Object>();
map11065.put("keyA-11065", "a_Value"); // put some stuff in the collection
map11065.put("keyB-11065", param); // put it in a collection
map11065.put("keyC", "another_Value"); // put some stuff in the collection
bar = (String)map11065.get("keyB-11065"); // get it back out
bar = (String)map11065.get("keyA-11065"); // get safe value back out
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
langmo/youscope | plugins/microscopeaccess/src/main/java/org/json/JSONException.java | 698 | package org.json;
/**
* The JSONException is thrown by the JSON.org classes then things are amiss.
* @author JSON.org
* @version 2
*/
public class JSONException extends Exception {
private static final long serialVersionUID = 5894276831604379907L;
private Throwable cause;
/**
* Constructs a JSONException with an explanatory message.
* @param message Detail about the reason for the exception.
*/
public JSONException(String message) {
super(message);
}
public JSONException(Throwable t) {
super(t.getMessage());
this.cause = t;
}
@Override
public synchronized Throwable getCause() {
return this.cause;
}
}
| gpl-2.0 |
saalejo/medico | Logistico/src/logistico/db/dao/interfaz/BarrioDao.java | 611 | package logistico.db.dao.interfaz;
import java.util.List;
import logistico.db.dto.modelo.Barrio;
/**
* Descripción de la interfaz:contrato que contiene todos los métodos (servicios)
* ofrecidos por la capa de acceso a datos correspondiente a la entidad Barrio.
* @author Yedinzon Toro Gil
*
*/
public interface BarrioDao {
List<Barrio> obtener(int municipioId) throws Exception;
List<Barrio> obtener() throws Exception;
void actualizar(Barrio barrio) throws Exception;
void guardar(Barrio barrio) throws Exception;
void borrar(Barrio barrio) throws Exception;
} | gpl-2.0 |
micwing/onekr-www | cardservice/src/main/java/onekr/cardservice/card/impl/CardBizImpl.java | 2761 | package onekr.cardservice.card.impl;
import java.util.Date;
import onekr.cardservice.card.dao.CardDao;
import onekr.cardservice.card.intf.CardBiz;
import onekr.cardservice.model.Card;
import onekr.cardservice.model.CardType;
import onekr.commonservice.model.Status;
import onekr.framework.exception.AppException;
import onekr.framework.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
public class CardBizImpl implements CardBiz {
@Autowired
private CardDao cardDao;
@Override
public Card findById(Long cardId) {
return cardDao.findOne(cardId);
}
@Override
public Page<Card> listCard(CardType cardType,
Pageable pageable) {
return cardDao.findByCardTypeOrderByCreateAtDesc(cardType,
pageable);
}
@Override
public Page<Card> listCard(CardType cardType, Long uid,
Pageable pageable) {
return cardDao.findByCardTypeAndCreateByOrderByCreateAtDesc(cardType,
uid, pageable);
}
@Override
public Card saveCard(Card card, Long uid) {
Date now = new Date();
Card entity = new Card();
if (card.getId() != null) {
entity = cardDao.findOne(card.getId());
if (entity == null)
throw new AppException(ErrorCode.ENTITY_NOT_FOUND);
} else {
entity.setPeople1Name(card.getPeople1Name());
entity.setPeople2Name(card.getPeople2Name());
entity.setCreateAt(now);
entity.setCreateBy(uid);
// 默认值
if (card.getCardType() == null) {
card.setCardType(CardType.WED_CARD);
}
if (card.getStatus() == null) {
card.setStatus(Status.NORMAL);
}
}
entity.setCardType(card.getCardType());
entity.setAddress(card.getAddress());
entity.setAfterInfo(card.getAfterInfo());
entity.setBeforeInfo(card.getBeforeInfo());
entity.setPartyTime(card.getPartyTime());
entity.setPeople1Mobile(card.getPeople1Mobile());
entity.setPeople2Mobile(card.getPeople2Mobile());
entity.setRemark(card.getRemark());
entity.setRemind(card.getRemind());
entity.setRestaurant(card.getRestaurant());
entity.setStatus(card.getStatus());
entity.setTempletId(card.getTempletId());
entity.setTitle(card.getTitle());
entity.setTraffic(card.getTraffic());
entity.setUpdateAt(now);
entity.setUpdateBy(uid);
return cardDao.save(entity);
}
@Override
public Card updateCardMap(Long cardId, String mapPicUrl, String mapUrl, Long uid) {
Card card = cardDao.findOne(cardId);
if (card == null)
throw new AppException(ErrorCode.ENTITY_NOT_FOUND);
card.setMapPicUrl(mapPicUrl);
card.setMapUrl(mapUrl);
card.setUpdateAt(new Date());
card.setUpdateBy(uid);
return cardDao.save(card);
}
}
| gpl-2.0 |
lamsfoundation/lams | lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/model/VoteQueUsr.java | 5092 | /***************************************************************************
* Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org)
* =============================================================
* License Information: http://lamsfoundation.org/licensing/lams/2.0/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2.0
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*
* http://www.gnu.org/licenses/gpl.txt
* ***********************************************************************/
package org.lamsfoundation.lams.tool.vote.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* <p>
* Persistent object/bean that defines the user for the Voting tool.
* Provides accessors and mutators to get/set attributes
* It maps to database table: tl_lavote11_que_usr
* </p>
*
* @author Ozgur Demirtas
*/
@Entity
@Table(name = "tl_lavote11_usr")
public class VoteQueUsr implements Serializable, Comparable<VoteQueUsr> {
private static final long serialVersionUID = 7303944502340276133L;
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long uid;
@Column(name = "user_id")
private Long queUsrId;
@Column
private String username;
@Column
private String fullname;
@Column
private boolean responseFinalised;
@Column
private boolean finalScreenRequested;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "vote_session_id")
private VoteSession voteSession;
@OneToMany(mappedBy = "voteQueUsr", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<VoteUsrAttempt> voteUsrAttempts;
public VoteQueUsr(Long queUsrId, String username, String fullname, VoteSession voteSession,
Set<VoteUsrAttempt> voteUsrAttempts) {
this.queUsrId = queUsrId;
this.username = username;
this.fullname = fullname;
this.voteSession = voteSession;
this.voteUsrAttempts = voteUsrAttempts;
}
public VoteQueUsr() {
}
public VoteQueUsr(Long queUsrId, Set<VoteUsrAttempt> voteUsrAttempts) {
this.queUsrId = queUsrId;
this.voteUsrAttempts = voteUsrAttempts;
}
public Long getUid() {
return this.uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public Long getQueUsrId() {
return this.queUsrId;
}
public void setQueUsrId(Long queUsrId) {
this.queUsrId = queUsrId;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullname() {
return this.fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public Set<VoteUsrAttempt> getVoteUsrAttempts() {
if (this.voteUsrAttempts == null) {
setVoteUsrAttempts(new HashSet<VoteUsrAttempt>());
}
return this.voteUsrAttempts;
}
public void setMcUsrAttempts(Set<VoteUsrAttempt> voteUsrAttempts) {
this.voteUsrAttempts = voteUsrAttempts;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("uid", getUid()).toString();
}
public VoteSession getVoteSession() {
return voteSession;
}
public void setVoteSession(VoteSession voteSession) {
this.voteSession = voteSession;
}
public void setVoteUsrAttempts(Set<VoteUsrAttempt> voteUsrAttempts) {
this.voteUsrAttempts = voteUsrAttempts;
}
public boolean isResponseFinalised() {
return responseFinalised;
}
public void setResponseFinalised(boolean responseFinalised) {
this.responseFinalised = responseFinalised;
}
public boolean isFinalScreenRequested() {
return finalScreenRequested;
}
public void setFinalScreenRequested(boolean finalScreenRequested) {
this.finalScreenRequested = finalScreenRequested;
}
@Override
public int compareTo(VoteQueUsr other) {
// if the object does not exist yet, then just return any one of 0, -1, 1. Should not make a difference.
if (uid == null) {
return 1;
} else {
return (int) (uid.longValue() - other.uid.longValue());
}
}
} | gpl-2.0 |
LuckyStars/nbc | function-teachersignup/java/function-teacherSignup/src/main/com/nbcedu/function/teachersignup/core/pager/SimplePager.java | 3651 | package com.nbcedu.function.teachersignup.core.pager;
import java.util.List;
/**
* <p>
* 简单分页模型
* </p>
*
* @author Du Haiying Create at:2011-10-24 下午04:11:31
*/
public class SimplePager<T> {
/**
* 分页数据列表
*/
private List<T> datas;
/**
* 每页显示数据个数
*/
private int pageSize = 1;
/**
* 当前页码
*/
private int pageNo = 1;
/**
* 最大页码(总的页面个数)
*/
private int maxPageNo;
/**
* 数据总的个数
*/
private int count;
/**
* default
*/
public SimplePager() {
}
/**
* 指定 要查找的当前页码与页面显示数据个数
*
* @param pageNo 当前页码
* @param pageSize 每页显示数据个数
*/
public SimplePager(int pageNo, int pageSize) {
if (pageNo <= 0) {
this.pageNo = 1;
} else {
this.pageNo = pageNo;
}
if (pageSize <= 0) {
this.pageSize = 1;
} else {
this.pageSize = pageSize;
}
}
/**
* 指定 要查找的当前页码与页面显示数据个数
*
* @param pageNo 当前页码
* @param pageSize 每页显示数据个数
*/
public SimplePager(String pageNo, int pageSize) {
int t = 0;
try {
t = Integer.parseInt(pageNo);
} catch (NumberFormatException e) {
t = 1;
}
if (t <= 0) {
this.pageNo = 1;
} else {
this.pageNo = t;
}
if (pageSize <= 0) {
this.pageSize = 1;
} else {
this.pageSize = pageSize;
}
}
/**
* @param pageSize the pageSize to set
*/
public void setPageSize(int pageSize) {
if (pageSize <= 0) {
this.pageSize = 1;
} else {
this.pageSize = pageSize;
}
}
/**
* @param pageNo the pageNo to set
*/
public void setPageNo(int pageNo) {
if (pageNo <= 0) {
this.pageNo = 1;
} else {
this.pageNo = pageNo;
}
}
/**
* 设置总的数据个数
*
* @author Du Haiying
* @param count 总的数据个数
*/
public void setCount(int count) {
if (count <= 0) {
this.count = 0;
this.maxPageNo = 1;
this.pageNo = 1;
} else {
this.count = count;
this.maxPageNo = this.count % this.pageSize == 0 ? this.count / this.pageSize : this.count
/ this.pageSize + 1;
}
}
/**
* @return the datas
*/
public List<T> getDatas() {
return datas;
}
/**
* @param datas the datas to set
*/
public void setDatas(List<T> datas) {
this.datas = datas;
}
/**
* @return the pageNo
*/
public int getPageNo() {
return pageNo;
}
/**
* @return the nextPageNo
*/
public int getNextPageNo() {
if (pageNo == maxPageNo) {
return pageNo;
} else {
return pageNo + 1;
}
}
/**
* @return the lastPageNo
*/
public int getLastPageNo() {
if (pageNo == 1) {
return 1;
} else {
return pageNo - 1;
}
}
/**
* 得到分页的第一个序列值
*
* @author dhy
* @return
*/
public int getFirstIndex() {
return (this.pageNo - 1) * pageSize;
}
/**
* @return the maxPageNo
*/
public int getMaxPageNo() {
return maxPageNo;
}
/**
* @return the count
*/
public int getCount() {
return count;
}
/**
* @return the pageSize
*/
public int getPageSize() {
return pageSize;
}
/**
* 是否还有上一页.
*/
public boolean isHasLast() {
return (pageNo - 1 >= 1);
}
/**
* 是否还有上一页.
*/
public boolean isHasNext() {
return (pageNo + 1 <= maxPageNo);
}
/**
* 得到所有页码序列数组
*
* @author Du Haiying
* @return
*/
public int[] getPageNos() {
if(count <=0){
return new int[0];
}
int[] pageNos = new int[this.maxPageNo];
for (int i = 0; i < this.maxPageNo; i++) {
pageNos[i] = i + 1;
}
return pageNos;
}
}
| gpl-2.0 |
XinyueZ/playground-notification | app/src/main/java/com/playground/notification/app/activities/SplashActivity.java | 4411 | package com.playground.notification.app.activities;
import android.Manifest.permission;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import com.playground.notification.R;
import java.util.List;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import static pub.devrel.easypermissions.AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE;
public final class SplashActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
private static final int RC_PERMISSIONS = 123;
private void gotPermissions() {
MapActivity.showInstance(this);
ActivityCompat.finishAfterTransition(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
requirePermissions();
}
@SuppressLint("InlinedApi")
private boolean hasPermissions() {
return EasyPermissions.hasPermissions(this, permission.READ_PHONE_STATE, permission.WRITE_EXTERNAL_STORAGE);
}
@SuppressLint("InlinedApi")
@AfterPermissionGranted(RC_PERMISSIONS)
private void requirePermissions() {
if (hasPermissions()) {
gotPermissions();
} else {
// Ask for one permission
EasyPermissions.requestPermissions(this, getString(R.string.rationale_permissions_phone_state_storage), RC_PERMISSIONS, permission.READ_PHONE_STATE, permission.WRITE_EXTERNAL_STORAGE);
}
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
gotPermissions();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
permissionsDeniedOpenSetting();
}
private void permissionsDeniedOpenSetting() {
if (!hasPermissions()) {
new AppSettingsDialog.Builder(this, getString(R.string.app_settings_dialog_rationale_ask_again)).setTitle(getString(R.string.app_settings_dialog_title_settings_dialog))
.setPositiveButton(getString(R.string.app_settings_dialog_setting))
.setNegativeButton(getString(R.string.app_settings_dialog_cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.finishAffinity(SplashActivity.this);
}
})
.build()
.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case DEFAULT_SETTINGS_REQ_CODE:
permissionsDeniedOpenSetting();
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| gpl-2.0 |
openflexo-team/diana | diana-core/src/main/java/org/openflexo/diana/connectors/rpc/AdjustableMiddleControlPoint.java | 12644 | /**
*
* Copyright (c) 2013-2014, Openflexo
* Copyright (c) 2011-2012, AgileBirds
*
* This file is part of Diana-core, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* This software is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* See http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo (openflexo-contacts@openflexo.org)
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.diana.connectors.rpc;
import java.awt.event.MouseEvent;
import java.util.Vector;
import java.util.logging.Logger;
import org.openflexo.diana.DianaUtils;
import org.openflexo.diana.connectors.impl.RectPolylinConnector;
import org.openflexo.diana.geom.DianaGeometricObject;
import org.openflexo.diana.geom.DianaPoint;
import org.openflexo.diana.geom.DianaRectPolylin;
import org.openflexo.diana.geom.DianaGeometricObject.SimplifiedCardinalDirection;
import org.openflexo.diana.geom.area.DianaArea;
import org.openflexo.diana.geom.area.DianaPlane;
public class AdjustableMiddleControlPoint extends RectPolylinAdjustableControlPoint {
static final Logger LOGGER = Logger.getLogger(AdjustableMiddleControlPoint.class.getPackage().getName());
public AdjustableMiddleControlPoint(DianaPoint point, RectPolylinConnector connector) {
super(point, connector);
}
@Override
public DianaArea getDraggingAuthorizedArea() {
return new DianaPlane();
}
@Override
public boolean dragToPoint(DianaPoint newRelativePoint, DianaPoint pointRelativeToInitialConfiguration, DianaPoint newAbsolutePoint,
DianaPoint initialPoint, MouseEvent event) {
DianaPoint pt = getNearestPointOnAuthorizedArea(newRelativePoint);
if (pt == null) {
LOGGER.warning("Cannot nearest point for point " + newRelativePoint + " and area " + getDraggingAuthorizedArea());
return false;
}
// Following little hack is used here to prevent some equalities that may
// lead to inconsistent orientations
pt.x += DianaGeometricObject.EPSILON;
pt.y += DianaGeometricObject.EPSILON;
setPoint(pt);
getPolylin().updatePointAt(1, pt);
movedMiddleCP();
getConnector()._connectorChanged(true);
getNode().notifyConnectorModified();
return true;
}
private void movedMiddleCP() {
DianaArea startArea = getConnector().retrieveAllowedStartArea(false);
Vector<SimplifiedCardinalDirection> allowedStartOrientations = getConnector().getPrimitiveAllowedStartOrientations();
Vector<SimplifiedCardinalDirection> allowedEndOrientations = getConnector().getPrimitiveAllowedEndOrientations();
if (getConnectorSpecification().getIsStartingLocationFixed() && !getConnectorSpecification().getIsStartingLocationDraggable()) {
// If starting location is fixed and not draggable,
// Then retrieve start area itself (which is here a single point)
startArea = getConnector().retrieveStartArea();
allowedStartOrientations = getConnector().getAllowedStartOrientations();
}
DianaArea endArea = getConnector().retrieveAllowedEndArea(false);
if (getConnectorSpecification().getIsEndingLocationFixed() && !getConnectorSpecification().getIsEndingLocationDraggable()) {
// If starting location is fixed and not draggable,
// Then retrieve start area itself (which is here a single point)
endArea = getConnector().retrieveEndArea();
allowedEndOrientations = getConnector().getAllowedEndOrientations();
}
/*System.out.println("startArea="+startArea);
System.out.println("endArea="+endArea);
System.out.println("allowedStartOrientations="+allowedStartOrientations);
System.out.println("allowedEndOrientations="+allowedEndOrientations);*/
DianaRectPolylin newPolylin;
DianaPoint middleCPLocation = getPoint();
newPolylin = DianaRectPolylin.makeRectPolylinCrossingPoint(startArea, endArea, middleCPLocation, true, getConnector()
.getOverlapXResultingFromPixelOverlap(), getConnector().getOverlapYResultingFromPixelOverlap(), SimplifiedCardinalDirection
.allDirectionsExcept(allowedStartOrientations), SimplifiedCardinalDirection.allDirectionsExcept(allowedEndOrientations));
if (newPolylin == null) {
LOGGER.warning("Obtained null polylin allowedStartOrientations=" + allowedStartOrientations);
return;
}
if (getConnectorSpecification().getIsStartingLocationFixed()) { // Don't forget this !!!
getConnector().setFixedStartLocation(
DianaUtils.convertNormalizedPoint(getNode(), newPolylin.getFirstPoint(), getNode().getStartNode()));
}
if (getConnectorSpecification().getIsEndingLocationFixed()) { // Don't forget this !!!
getConnector().setFixedEndLocation(
DianaUtils.convertNormalizedPoint(getNode(), newPolylin.getLastPoint(), getNode().getEndNode()));
}
if (newPolylin.isNormalized()) {
getConnector().updateWithNewPolylin(newPolylin, true, false);
} else {
LOGGER.warning("Computed layout returned a non-normalized polylin. Please investigate");
getConnector().updateWithNewPolylin(newPolylin, false, false);
}
}
/**
* This method is internally called when first control point has been detected to be moved.
*
*/
/*private void movedMiddleCP()
{
DianaArea startArea = getConnector().retrieveAllowedStartArea(false);
if (getConnector().getIsStartingLocationFixed()
&& !getConnector().getIsStartingLocationDraggable()) {
// If starting location is fixed and not draggable,
// Then retrieve start area itself (which is here a single point)
startArea = getConnector().retrieveStartArea();
}
DianaArea endArea = getConnector().retrieveAllowedEndArea(false);
if (getConnector().getIsEndingLocationFixed()
&& !getConnector().getIsEndingLocationDraggable()) {
// If starting location is fixed and not draggable,
// Then retrieve start area itself (which is here a single point)
endArea = getConnector().retrieveEndArea();
}
DianaPoint middleCPLocation = getPoint();
//SimplifiedCardinalDirection initialStartOrientation = initialPolylin.getApproximatedOrientationOfSegment(0);
//SimplifiedCardinalDirection initialEndOrientation = initialPolylin.getApproximatedOrientationOfSegment(1).getOpposite();
// Try to find a cardinal direction in which it is possible to project
// dragged control point
SimplifiedCardinalDirection startOrientation = null;
SimplifiedCardinalDirection altStartOrientation = null;
for (SimplifiedCardinalDirection o : SimplifiedCardinalDirection.values()) {
if (startArea.getOrthogonalPerspectiveArea(o).containsPoint(middleCPLocation)) {
startOrientation = o;
}
}
if (startOrientation == null) {
CardinalQuadrant quadrant = DianaPoint.getCardinalQuadrant(getPolylin().getFirstPoint(),middleCPLocation);
startOrientation = quadrant.getHorizonalComponent();
altStartOrientation = quadrant.getVerticalComponent();
}
// Try to find a cardinal direction in which it is possible to project
// dragged control point
SimplifiedCardinalDirection endOrientation = null;
SimplifiedCardinalDirection altEndOrientation = null;
for (SimplifiedCardinalDirection o : SimplifiedCardinalDirection.values()) {
if (endArea.getOrthogonalPerspectiveArea(o).containsPoint(middleCPLocation)) {
endOrientation = o;
}
}
if (endOrientation == null) {
CardinalQuadrant quadrant = DianaPoint.getCardinalQuadrant(middleCPLocation, getPolylin().getLastPoint());
endOrientation = quadrant.getHorizonalComponent().getOpposite();
altEndOrientation = quadrant.getVerticalComponent().getOpposite();
}
if (startArea.getOrthogonalPerspectiveArea(startOrientation).containsPoint(middleCPLocation)) {
// OK, the new location will not modify general structure of connector
DianaPoint newPoint = new DianaPoint(getPolylin().getFirstPoint());
if (startOrientation.isHorizontal()) {
newPoint.setY(middleCPLocation.y);
}
else if (startOrientation.isVertical()) {
newPoint.setX(middleCPLocation.x);
}
getPolylin().updatePointAt(0, newPoint);
getConnector().getStartControlPoint().setPoint(newPoint);
if (getConnector().getIsStartingLocationFixed()) { // Don't forget this !!!
getConnector().setFixedStartLocation(
GraphicalRepresentation.convertNormalizedPoint(getGraphicalRepresentation(), newPoint, getGraphicalRepresentation().getStartObject()));
}
}
if (endArea.getOrthogonalPerspectiveArea(endOrientation).containsPoint(middleCPLocation)) {
// OK, the new location will not modify general structure of connector
DianaPoint newPoint = new DianaPoint(getPolylin().getLastPoint());
if (endOrientation.isHorizontal()) {
newPoint.setY(middleCPLocation.y);
}
else if (endOrientation.isVertical()) {
newPoint.setX(middleCPLocation.x);
}
getPolylin().updatePointAt(getPolylin().getPointsNb()-1, newPoint);
getConnector().getEndControlPoint().setPoint(newPoint);
if (getConnector().getIsEndingLocationFixed()) { // Don't forget this !!!
getConnector().setFixedEndLocation(
GraphicalRepresentation.convertNormalizedPoint(getGraphicalRepresentation(), newPoint, getGraphicalRepresentation().getEndObject()));
}
}
System.out.println("Tiens, je sais pas quoi faire...");
int alternatives = 1;
if (altStartOrientation != null) alternatives=alternatives*2;
if (altEndOrientation != null) alternatives=alternatives*2;
DianaRectPolylin[] newPolylins = new DianaRectPolylin[alternatives];
int n=0;
newPolylins[n++]
= DianaRectPolylin.makeRectPolylinCrossingPoint(
getPolylin().getFirstPoint(),
getPolylin().getLastPoint(),
middleCPLocation,
startOrientation,
endOrientation,
true, getConnector().getOverlapXResultingFromPixelOverlap(), getConnector().getOverlapYResultingFromPixelOverlap());
if (altStartOrientation != null) {
newPolylins[n++]
= DianaRectPolylin.makeRectPolylinCrossingPoint(
getPolylin().getFirstPoint(),
getPolylin().getLastPoint(),
middleCPLocation,
altStartOrientation,
endOrientation,
true, getConnector().getOverlapXResultingFromPixelOverlap(), getConnector().getOverlapYResultingFromPixelOverlap());
if (altEndOrientation != null) {
newPolylins[n++]
= DianaRectPolylin.makeRectPolylinCrossingPoint(
getPolylin().getFirstPoint(),
getPolylin().getLastPoint(),
middleCPLocation,
altStartOrientation,
altEndOrientation,
true, getConnector().getOverlapXResultingFromPixelOverlap(), getConnector().getOverlapYResultingFromPixelOverlap());
}
}
if (altEndOrientation != null) {
newPolylins[n++]
= DianaRectPolylin.makeRectPolylinCrossingPoint(
getPolylin().getFirstPoint(),
getPolylin().getLastPoint(),
middleCPLocation,
startOrientation,
altEndOrientation,
true, getConnector().getOverlapXResultingFromPixelOverlap(), getConnector().getOverlapYResultingFromPixelOverlap());
}
DianaRectPolylin newPolylin = null;
for (int i=0; i<alternatives; i++) {
if (!newPolylins[i].crossedItSelf() && newPolylin == null)
newPolylin = newPolylins[i];
}
if (newPolylin == null) newPolylin = newPolylins[0];
getConnector().updateWithNewPolylin(newPolylin,true);
}
*/
}
| gpl-3.0 |
martinmladenov/SoftUni-Solutions | Software Technologies/12. Java Basics - Exercises/src/Ex10_Index_of_Letters.java | 308 | import java.util.Scanner;
public class Ex10_Index_of_Letters {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
for (char c : str.toCharArray())
System.out.printf("%s -> %d\r\n", c, c - 'a');
}
}
| gpl-3.0 |
lyind/base | src/main/java/net/talpidae/base/insect/exchange/BaseMessage.java | 1994 | /*
* Copyright (C) 2017 Jonas Zeiger <jonas.zeiger@talpidae.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/>.
*/
package net.talpidae.base.insect.exchange;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import lombok.AccessLevel;
import lombok.Getter;
public class BaseMessage
{
@Getter(AccessLevel.PROTECTED)
private final ByteBuffer buffer;
@Getter
private InetSocketAddress remoteAddress;
protected BaseMessage(int maximumSize)
{
buffer = ByteBuffer.allocateDirect(maximumSize);
}
/**
* Override this to perform additional cleanup.
*/
protected void clear()
{
}
boolean receiveFrom(DatagramChannel channel) throws IOException
{
remoteAddress = (InetSocketAddress) channel.receive(buffer);
if (remoteAddress != null)
{
buffer.flip();
return true;
}
return false;
}
void setRemoteAddress(InetSocketAddress remoteAddress)
{
this.remoteAddress = remoteAddress;
}
boolean sendTo(DatagramChannel channel) throws IOException
{
return channel.send(buffer, remoteAddress) != 0;
}
void passivate()
{
clear(); // may be overridden
buffer.clear();
remoteAddress = null;
}
}
| gpl-3.0 |
gg-net/dwoss | ui/receipt/src/main/java/eu/ggnet/dwoss/receipt/ui/cap/ReportRefurbishmentMenuItem.java | 1889 | /*
* Copyright (C) 2021 GG-Net GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.ggnet.dwoss.receipt.ui.cap;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javafx.scene.control.MenuItem;
import eu.ggnet.dwoss.core.widget.FileUtil;
import eu.ggnet.dwoss.core.widget.Progressor;
import eu.ggnet.dwoss.core.widget.dl.RemoteDl;
import eu.ggnet.dwoss.receipt.ee.reporting.RefurbishmentReporter;
import eu.ggnet.dwoss.receipt.ui.ReportRefurbishmentController;
import eu.ggnet.saft.core.Saft;
/**
*
* @author mirko.schulze
*/
public class ReportRefurbishmentMenuItem extends MenuItem {
@Inject
private Saft saft;
@Inject
private RemoteDl remote;
@Inject
private Progressor progressor;
public ReportRefurbishmentMenuItem() {
super("Refurbishmentreport");
}
@PostConstruct
private void init() {
setOnAction(e -> saft.build().fxml().eval(ReportRefurbishmentController.class).cf()
.thenApply(r -> progressor.run("Refurbishmentreporter", () -> remote.lookup(RefurbishmentReporter.class).toXls(r.getTradeName(), r.getStart(), r.getEnd()).toTemporaryFile()))
.thenAccept(f -> FileUtil.osOpen(f))
.handle(saft.handler())
);
}
}
| gpl-3.0 |
FernandoPucci/controleArmarios | codificacao/ControleArmarios/src/testers/TesterApachePOI.java | 11429 | /*
* Copyright (C) 2016 fernando-pucci
*
* 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 testers;
import br.com.etefgarcia.armarios.dao.AlunoDAO;
import br.com.etefgarcia.armarios.dao.impl.AlunoDAOImpl;
import br.com.etefgarcia.armarios.exceptions.NegocioException;
import br.com.etefgarcia.armarios.exceptions.SistemaException;
import br.com.etefgarcia.armarios.model.Aluno;
import br.com.etefgarcia.armarios.service.AlunoService;
import br.com.etefgarcia.armarios.util.ServiceUtils;
import br.com.etefgarcia.armarios.util.TelaUtils;
import br.com.etefgarcia.armarios.util.constantes.ConstantesExcelHeaders;
import br.com.etefgarcia.armarios.view.BarraProgresso;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @author fernando-pucci
*/
public class TesterApachePOI {
private final String CAMINHO_ARQUIVO = "/home/fernando-pucci/Projetos/ETEC/Diversos/base_xls/banco_alunos.xlsx";
private Map<String, Integer> mapaColunas;
private Double totalLinhas = 0.0;
private Double linhasAtualizadas = 0.0;
public void inicia() {
try {
System.out.println("TESTE APACHE POI");
List<Aluno> listaAlunos = null;
listaAlunos = carregaListaAlunos(CAMINHO_ARQUIVO, 4);
totalLinhas = Double.parseDouble(listaAlunos.size()+"");
//TESTE - mostra mapa de colunas
// for (Map.Entry m : mapaColunas.entrySet()) {
//
// System.out.println(m.getKey() + " - " + m.getValue());
//
// }
AlunoDAO dao = new AlunoDAOImpl();
Long initTime = System.nanoTime();
System.out.println("AGUARDE...");
for (Aluno a : listaAlunos) {
System.out.println(a);
if (a.getTelefone() == null && a.getEmail() == null) {
throw new NegocioException("Aluno " + a.getIdAluno() + ", possui dados de contato inválidos");
}
if (a.getEmail() != null) {
if (!TelaUtils.validaEmail(a.getEmail())) {
throw new NegocioException("Aluno " + a.getIdAluno() + ", possui dados de e-mail inválidos");
}
}
if (a.getTelefone() != null) {
if (!TelaUtils.validaTelefone(a.getTelefone())) {
throw new NegocioException("Aluno " + a.getIdAluno() + ", possui dados de Telefone inválidos");
}
}
try {
AlunoService service = new AlunoService(dao);
service.cadastrarAluno(a);
linhasAtualizadas++;
} catch (Exception e) {
throw new SistemaException(e.getMessage());
}
}
Long finalTime = System.nanoTime() - initTime;
double tempoSegundos = (double) finalTime / 1000000000.0;
System.out.println(listaAlunos.size() + " registros em " + tempoSegundos / 60 + " minutos");
} catch (SistemaException | NegocioException | IOException ex) {
System.out.println(ex.getMessage());
} finally {
System.exit(0);
}
}
private List<Aluno> carregaListaAlunos(String arquivo, int linhaInicio) throws NegocioException, IOException {
List<Aluno> listaAlunos = null;
try {
int linhaInicioReal = linhaInicio - 1;
listaAlunos = new ArrayList<>();
mapaColunas = new HashMap<>();
FileInputStream fis = new FileInputStream(arquivo);
Workbook workbook = null;
if (arquivo.toLowerCase().endsWith("xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (arquivo.toLowerCase().endsWith("xls")) {
workbook = new HSSFWorkbook(fis);
}
int totalPaginas = workbook.getNumberOfSheets();
for (int i = 0; i < totalPaginas; i++) {
//Iterator de planilha
Sheet sheet = workbook.getSheetAt(i);
//Iterator de linha
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
if (row.getRowNum() < linhaInicio) {
continue;
}
Aluno a = new Aluno();
//Iterator de celula
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (row.getRowNum() == linhaInicioReal) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
populaMapaColunas(cell);
if (!validaCampos()) {
throw new NegocioException("Arquivo Inválido! - Formatação de Colunas Incorreta.");
}
} else {
throw new NegocioException("Arquivo Inválido!");
}
}
String valor = null;
//verifica o tipo do valor da celula
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
valor = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
valor = cell.getNumericCellValue() + "";
break;
}
switch (cell.getColumnIndex()) {
case ConstantesExcelHeaders.COLUNA_RM:
a.setIdAluno(new Long(valor));
break;
case ConstantesExcelHeaders.COLUNA_NOME:
a.setNome(valor);
break;
case ConstantesExcelHeaders.COLUNA_E_MAIL:
a.setEmail(valor);
break;
case ConstantesExcelHeaders.COLUNA_CELULAR:
if (a.getTelefone() == null || !TelaUtils.validaTelefone(a.getTelefone())) {//se nao tiver telefone grava celular
a.setTelefone(ServiceUtils.limpaTelefone(valor));
}
break;
case ConstantesExcelHeaders.COLUNA_TELEFONE:
a.setTelefone(ServiceUtils.limpaTelefone(valor));
break;
case ConstantesExcelHeaders.COLUNA_SEXO:
a.setSexo(valor);
break;
}
}
listaAlunos.add(a);
}
}
fis.close();
} catch (IOException e) {
throw e;
}
return listaAlunos;
}
private boolean validaCampos() {
for (Map.Entry m : mapaColunas.entrySet()) {
switch ((int) m.getValue()) {
case ConstantesExcelHeaders.COLUNA_RM:
if (!m.getKey().equals(ConstantesExcelHeaders.RM)) {
return false;
}
break;
case ConstantesExcelHeaders.COLUNA_NOME:
if (!m.getKey().equals(ConstantesExcelHeaders.NOME)) {
return false;
}
break;
case ConstantesExcelHeaders.COLUNA_TELEFONE:
if (!m.getKey().equals(ConstantesExcelHeaders.TELEFONE)) {
return false;
}
break;
case ConstantesExcelHeaders.COLUNA_CELULAR:
if (!m.getKey().equals(ConstantesExcelHeaders.CELULAR)) {
return false;
}
break;
case ConstantesExcelHeaders.COLUNA_E_MAIL:
if (!m.getKey().equals(ConstantesExcelHeaders.EMAIL)) {
return false;
}
break;
case ConstantesExcelHeaders.COLUNA_SEXO:
if (!m.getKey().equals(ConstantesExcelHeaders.SEXO)) {
return false;
}
break;
}
}
return true;
}
private void populaMapaColunas(Cell cell) throws NegocioException {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
switch (cell.getStringCellValue()) {
case ConstantesExcelHeaders.RM:
mapaColunas.put(ConstantesExcelHeaders.RM, cell.getColumnIndex());
break;
case ConstantesExcelHeaders.NOME:
mapaColunas.put(ConstantesExcelHeaders.NOME, cell.getColumnIndex());
break;
case ConstantesExcelHeaders.TELEFONE:
mapaColunas.put(ConstantesExcelHeaders.TELEFONE, cell.getColumnIndex());
break;
case ConstantesExcelHeaders.CELULAR:
mapaColunas.put(ConstantesExcelHeaders.CELULAR, cell.getColumnIndex());
break;
case ConstantesExcelHeaders.EMAIL:
mapaColunas.put(ConstantesExcelHeaders.EMAIL, cell.getColumnIndex());
break;
case ConstantesExcelHeaders.SEXO:
mapaColunas.put(ConstantesExcelHeaders.SEXO, cell.getColumnIndex());
break;
default:
break;
}
} else {
throw new NegocioException("Arquivo fora do padrão de colunas.");
}
}
public Double getTotalLinhas() {
return totalLinhas;
}
public Double getTotalLinhasAtualizadas() {
return linhasAtualizadas;
}
}
| gpl-3.0 |
Jude95/Fishing | app/src/main/java/com/jude/fishing/module/setting/MsgSetActivity.java | 1707 | package com.jude.fishing.module.setting;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import com.jude.beam.bijection.RequiresPresenter;
import com.jude.beam.expansion.data.BeamDataActivity;
import com.jude.fishing.R;
import com.jude.fishing.model.entities.PushSetting;
import butterknife.ButterKnife;
import butterknife.InjectView;
@RequiresPresenter(MsgSetPresenter.class)
public class MsgSetActivity extends BeamDataActivity<MsgSetPresenter,PushSetting> {
public static final String CHAT_NOTIFY = "chatNotify";
@InjectView(R.id.toolbar)
Toolbar toolbar;
@InjectView(R.id.switch_praise)
SwitchCompat switchPraise;
@InjectView(R.id.switch_comment)
SwitchCompat switchComment;
@InjectView(R.id.switch_care)
SwitchCompat switchCare;
@InjectView(R.id.switch_address)
SwitchCompat switchAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_activity_msg_set);
ButterKnife.inject(this);
switchPraise.setOnCheckedChangeListener(getPresenter());
switchComment.setOnCheckedChangeListener(getPresenter());
switchCare.setOnCheckedChangeListener(getPresenter());
switchAddress.setOnCheckedChangeListener(getPresenter());
}
@Override
public void setData(PushSetting data) {
super.setData(data);
switchPraise.setChecked(data.isPraiseNotify());
switchComment.setChecked(data.isCommentNotify());
switchAddress.setChecked(data.isPlaceNotify());
switchCare.setChecked(data.isCareNotify());
}
}
| gpl-3.0 |
gigaSproule/jacqueline | src/main/java/uk/co/bensproule/jacqueline/GCMRegisterWithServer.java | 2521 | package uk.co.bensproule.jacqueline;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.provider.Settings.Secure;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class GCMRegisterWithServer extends Service {
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Context context = getApplicationContext();
Log.d("GCMRegisterWithServer.onStart", "Sending registration ID to my application server");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"http://www.britintel.co.uk/gcm/register.php");
SharedPreferences preferences = context.getSharedPreferences("preferences", 0);
String registrationID = preferences.getString("registrationID", "");
String deviceID = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// Get the deviceID
Log.i("GCMRegisterWithServer.onStart", "Registration ID: " + registrationID);
Log.i("GCMRegisterWithServer.onStart", "Device ID: " + deviceID);
nameValuePairs.add(new BasicNameValuePair("deviceid", deviceID));
nameValuePairs.add(new BasicNameValuePair("registrationid", registrationID));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
| gpl-3.0 |
tianyuan168326/nono-android | app/src/main/java/com/seki/noteasklite/Fragment/Ask/RegisterAccountFragment.java | 3150 | package com.seki.noteasklite.Fragment.Ask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.seki.noteasklite.R;
import com.seki.noteasklite.Util.VerifyInput;
/**
* Created by yuan-tian01 on 2016/2/27.
*/
public class RegisterAccountFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_register_account,container,false);
}
public static RegisterAccountFragment newInstance(){
return new RegisterAccountFragment();
}
public AccountInfo getAccountInfo(){
String username=((TextView)getView().findViewById(R.id.register_username))
.getText().toString();
String useremail=((TextView)getView().findViewById(R.id.register_email))
.getText().toString();
String password=((TextView)getView().findViewById(R.id.register_password))
.getText().toString();
String passwordagin=((TextView)getView().findViewById(R.id.register_password_again))
.getText().toString();
AccountInfo accountInfo = new AccountInfo();
if(!VerifyInput.isUserName(username))
{
accountInfo.errorInfo = "用户名要为3-15的数字/字母组合哦~";
return accountInfo;
}
if(!VerifyInput.isEmail(useremail))
{
accountInfo.errorInfo = "邮箱格式不正确哦~";
return accountInfo;
}
if(!VerifyInput.isPassword(password))
{
accountInfo.errorInfo = "密码要为6-12位哦~";
return accountInfo;
}
if(!(password.equals(passwordagin) ))
{
accountInfo.errorInfo = "两个密码不一致哦~";
return accountInfo;
}
accountInfo = new AccountInfo(useremail,password,passwordagin,username);
return accountInfo;
}
public static class BaseInfo{
public String errorInfo = null;
}
public static class AccountInfo extends BaseInfo{
public String register_username;
public String register_email;
public String register_password;
public String register_password_again;
public AccountInfo(String register_email, String register_password, String register_password_again, String register_username) {
this.register_email = register_email;
this.register_password = register_password;
this.register_password_again = register_password_again;
this.register_username = register_username;
}
public AccountInfo(){
}
}
}
| gpl-3.0 |
TheMurderer/keel | src/keel/Algorithms/Decision_Trees/C45/C45.java | 20839 | /***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
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 keel.Algorithms.Decision_Trees.C45;
import java.io.*;
/**
* Class to implement the C4.5 algorithm
*
* @author Cristóbal Romero Morales (UCO) (30-03-06)
* @author modified by Alberto Fernandez (UGR)
* @version 1.2 (29-04-10)
* @since JDK 1.5
*</p>
**/
public class C45 extends Algorithm {
/** Decision tree. */
private Tree root;
/** Is the tree pruned or not. */
private boolean prune = true;
/** Confidence level. */
private float confidence = 0.25f;
/** Minimum number of itemsets per leaf. */
private int minItemsets = 2;
/** The prior probabilities of the classes. */
private double[] priorsProbabilities;
/** Resolution of the margin histogram. */
private static int marginResolution = 500;
/** Cumulative margin classification. */
private double marginCounts[];
/** The sum of counts for priors. */
private double classPriorsSum;
/** Constructor.
*
* @param paramFile The parameters file.
*
* @throws Exception If the algorithm cannot be executed.
*/
public C45(String paramFile) throws Exception {
try {
// starts the time
long startTime = System.currentTimeMillis();
/* Sets the options of the execution from text file*/
StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new
FileReader(paramFile)));
initTokenizer(tokenizer);
setOptions(tokenizer);
/* Sets the options from XML file */
/** para commons.configuration
XMLConfiguration config = new XMLConfiguration(paramFile);
setOptions( config );
*/
/* Initializes the dataset. */
modelDataset = new Dataset(modelFileName, true);
trainDataset = new Dataset(trainFileName, false);
testDataset = new Dataset(testFileName, false);
priorsProbabilities = new double[modelDataset.numClasses()];
priorsProbabilities();
marginCounts = new double[marginResolution + 1];
// generate the tree
generateTree(modelDataset);
printTrain();
printTest();
printResult();
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit( -1);
}
}
/** Function to read the options from the xml parameter file and assign the values to the corresponding member variables of C45 class:
* modelFileName, trainFileName, testFileName, trainOutputFileName, testOutputFileName, resultFileName, prune, confidence, minItemsets.
*
* @param config The XMLObject with the parameters.
*
* @throws Exception If there is any problem with the xml file
*/
/** para commons.configuration
protected void setOptions( XMLConfiguration config ) throws Exception
{
String algorithm = config.getString("algorithm");
if (!algorithm.equalsIgnoreCase( "C4.5" ) )
throw new Exception( "The name of the algorithm is not correct." );
modelFileName = config.getString("inputData.inputData1");
trainFileName = config.getString("inputData.inputData2");
testFileName = config.getString("inputData.inputData3");
trainOutputFileName = config.getString("outputData.outputData1");
testOutputFileName = config.getString("outputData.outputData2");
resultFileName = config.getString("outputData.outputData3");
prune = config.getBoolean("parameter.pruned");
confidence = config.getFloat("parameter.confidence");
minItemsets = config.getInt("parameter.instancesPerLeaf");
}
*/
/** Function to read the options from the execution file and assign the values to the parameters.
*
* @param options The StreamTokenizer that reads the parameters file.
*
* @throws Exception If the format of the file is not correct.
*/
protected void setOptions(StreamTokenizer options) throws Exception {
options.nextToken();
/* Checks that the file starts with the token algorithm */
if (options.sval.equalsIgnoreCase("algorithm")) {
options.nextToken();
options.nextToken();
//if (!options.sval.equalsIgnoreCase( "C4.5" ) )
// throw new Exception( "The name of the algorithm is not correct." );
options.nextToken();
options.nextToken();
options.nextToken();
options.nextToken();
/* Reads the names of the input files*/
if (options.sval.equalsIgnoreCase("inputData")) {
options.nextToken();
options.nextToken();
modelFileName = options.sval;
if (options.nextToken() != StreamTokenizer.TT_EOL) {
trainFileName = options.sval;
options.nextToken();
testFileName = options.sval;
if (options.nextToken() != StreamTokenizer.TT_EOL) {
trainFileName = modelFileName;
options.nextToken();
}
}
} else {
throw new Exception("No file test provided.");
}
/* Reads the names of the output files*/
while (true) {
if (options.nextToken() == StreamTokenizer.TT_EOF) {
throw new Exception("No output file provided.");
}
if (options.sval == null) {
continue;
} else if (options.sval.equalsIgnoreCase("outputData")) {
break;
}
}
options.nextToken();
options.nextToken();
trainOutputFileName = options.sval;
options.nextToken();
testOutputFileName = options.sval;
options.nextToken();
resultFileName = options.sval;
if (!getNextToken(options)) {
return;
}
while (options.ttype != StreamTokenizer.TT_EOF) {
/* Reads the prune parameter */
if (options.sval.equalsIgnoreCase("pruned")) {
options.nextToken();
options.nextToken();
if (options.sval.equalsIgnoreCase("TRUE")) {
prune = true;
} else {
//prune = false;
prune = true;
}
}
/* Reads the confidence parameter */
if (options.sval.equalsIgnoreCase("confidence")) {
if (!prune) {
throw new Exception(
"Doesn't make sense to change confidence for prune "
+ "tree!");
}
options.nextToken();
options.nextToken();
/* Checks that the confidence threshold is between 0 and 1. */
float cf = Float.parseFloat(options.sval);
if (cf <= 1 || cf >= 0) {
confidence = Float.parseFloat(options.sval);
}
}
/* Reads the itemsets per leaf parameter */
if (options.sval.equalsIgnoreCase("itemsetsPerLeaf")) {
options.nextToken();
options.nextToken();
if (Integer.parseInt(options.sval) > 0) {
minItemsets = Integer.parseInt(options.sval);
}
}
getNextToken(options);
}
}
}
/** Generates the tree.
*
* @param itemsets The dataset used to build the tree.
*
* @throws Exception If the tree cannot be built.
*/
public void generateTree(Dataset itemsets) throws Exception {
SelectCut selectCut;
selectCut = new SelectCut(minItemsets, itemsets);
root = new Tree(selectCut, prune, confidence);
root.buildTree(itemsets);
}
/** Function to evaluate the class which the itemset must have according to the classification of the tree.
*
* @param itemset The itemset to evaluate.
*
* @return The index of the class index predicted.
*/
public double evaluateItemset(Itemset itemset) throws Exception {
Itemset classMissing = (Itemset) itemset.copy();
double prediction = 0;
classMissing.setDataset(itemset.getDataset());
classMissing.setClassMissing();
double[] classification = classificationForItemset(classMissing);
prediction = maxIndex(classification);
updateStats(classification, itemset, itemset.numClasses());
//itemset.setPredictedValue( prediction );
return prediction;
}
/** Updates all the statistics for the current itemset.
*
* @param predictedClassification Distribution of class values predicted for the itemset.
* @param itemset The itemset.
* @param nClasses The number of classes.
*
*/
private void updateStats(double[] predictedClassification, Itemset itemset,
int nClasses) {
int actualClass = (int) itemset.getClassValue();
if (!itemset.classIsMissing()) {
updateMargins(predictedClassification, actualClass, nClasses);
// Determine the predicted class (doesn't detect multiple classifications)
int predictedClass = -1;
double bestProb = 0.0;
for (int i = 0; i < nClasses; i++) {
if (predictedClassification[i] > bestProb) {
predictedClass = i;
bestProb = predictedClassification[i];
}
}
// Update counts when no class was predicted
if (predictedClass < 0) {
return;
}
double predictedProb = Math.max(Double.MIN_VALUE,
predictedClassification[actualClass]);
double priorProb = Math.max(Double.MIN_VALUE,
priorsProbabilities[actualClass] /
classPriorsSum);
}
}
/** Returns class probabilities for an itemset.
*
* @param itemset The itemset.
*
* @throws Exception If cannot compute the classification.
*/
public final double[] classificationForItemset(Itemset itemset) throws
Exception {
return root.classificationForItemset(itemset);
}
/** Update the cumulative record of classification margins.
*
* @param predictedClassification Distribution of class values predicted for the itemset.
* @param actualClass The class value.
* @param nClasses Number of classes.
*/
private void updateMargins(double[] predictedClassification,
int actualClass, int nClasses) {
double probActual = predictedClassification[actualClass];
double probNext = 0;
for (int i = 0; i < nClasses; i++) {
if ((i != actualClass) && ( //Comparators.isGreater( predictedClassification[i], probNext ) ) )
predictedClassification[i] > probNext)) {
probNext = predictedClassification[i];
}
}
double margin = probActual - probNext;
int bin = (int) ((margin + 1.0) / 2.0 * marginResolution);
marginCounts[bin]++;
}
/** Evaluates if a string is a boolean value.
*
* @param value The string to evaluate.
*
* @return True if value is a boolean value. False otherwise.
*/
private boolean isBoolean(String value) {
if (value.equalsIgnoreCase("TRUE") || value.equalsIgnoreCase("FALSE")) {
return true;
} else {
return false;
}
}
/** Returns index of maximum element in a given array of doubles. First maximum is returned.
*
* @param doubles The array of elements.
*
*/
public static int maxIndex(double[] doubles) {
double maximum = 0;
int maxIndex = 0;
for (int i = 0; i < doubles.length; i++) {
if ((i == 0) || //
doubles[i] > maximum) {
maxIndex = i;
maximum = doubles[i];
}
}
return maxIndex;
}
/** Sets the class prior probabilities.
*
* @throws Exception If cannot compute the probabilities.
*/
public void priorsProbabilities() throws Exception {
for (int i = 0; i < modelDataset.numClasses(); i++) {
priorsProbabilities[i] = 1;
}
classPriorsSum = modelDataset.numClasses();
for (int i = 0; i < modelDataset.numItemsets(); i++) {
if (!modelDataset.itemset(i).classIsMissing()) {
try {
priorsProbabilities[(int) modelDataset.itemset(i).
getClassValue()] += modelDataset.itemset(i).
getWeight();
classPriorsSum += modelDataset.itemset(i).getWeight();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
}
/** Writes the tree and the results of the training and the test in the file.
*
* @exception If the file cannot be written.
*/
public void printResult() throws IOException {
long totalTime = (System.currentTimeMillis() - startTime) / 1000;
long seconds = totalTime % 60;
long minutes = ((totalTime - seconds) % 3600) / 60;
String tree = "";
PrintWriter resultPrint;
tree += toString();
tree += "\n@TotalNumberOfNodes " + root.NumberOfNodes;
tree += "\n@NumberOfLeafs " + root.NumberOfLeafs;
tree += "\n@TotalNumberOfNodes " + root.NumberOfNodes;
int atts = root.getAttributesPerRule();
if (atts > 0){
tree += "\n@NumberOfAntecedentsByRule "+(1.0*atts)/root.NumberOfLeafs;
}else{
tree += "\n@NumberOfAntecedentsByRule 0";
}
tree += "\n\n@NumberOfItemsetsTraining " + trainDataset.numItemsets();
tree += "\n@NumberOfCorrectlyClassifiedTraining " + correct;
tree += "\n@PercentageOfCorrectlyClassifiedTraining " +
(float) (correct * 100.0) / (float) trainDataset.numItemsets() +
"%";
tree += "\n@NumberOfInCorrectlyClassifiedTraining " +
(trainDataset.numItemsets() - correct);
tree += "\n@PercentageOfInCorrectlyClassifiedTraining " +
(float) ((trainDataset.numItemsets() - correct) * 100.0) /
(float) trainDataset.numItemsets() + "%";
tree += "\n\n@NumberOfItemsetsTest " + testDataset.numItemsets();
tree += "\n@NumberOfCorrectlyClassifiedTest " + testCorrect;
tree += "\n@PercentageOfCorrectlyClassifiedTest " +
(float) (testCorrect * 100.0) / (float) testDataset.numItemsets() +
"%";
tree += "\n@NumberOfInCorrectlyClassifiedTest " +
(testDataset.numItemsets() - testCorrect);
tree += "\n@PercentageOfInCorrectlyClassifiedTest " +
(float) ((testDataset.numItemsets() - testCorrect) * 100.0) /
(float) testDataset.numItemsets() + "%";
tree += "\n\n@ElapsedTime " +
(totalTime - minutes * 60 - seconds) / 3600 + ":" +
minutes / 60 + ":" + seconds;
resultPrint = new PrintWriter(new FileWriter(resultFileName));
resultPrint.print(getHeader() + "\n@decisiontree\n\n" + tree);
resultPrint.close();
}
/** Evaluates the training dataset and writes the results in the file.
*
* @exception If the file cannot be written.
*/
public void printTrain() {
String text = getHeader();
for (int i = 0; i < trainDataset.numItemsets(); i++) {
try {
Itemset itemset = trainDataset.itemset(i);
int cl = (int) evaluateItemset(itemset);
if (cl == (int) itemset.getValue(trainDataset.getClassIndex())) {
correct++;
}
text += trainDataset.getClassAttribute().value(((int) itemset.
getClassValue())) + " " + trainDataset.getClassAttribute().value(cl)
+ "\n";
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
try {
PrintWriter print = new PrintWriter(new FileWriter(
trainOutputFileName));
print.print(text);
print.close();
} catch (IOException e) {
System.err.println("Can not open the training output file: " +
e.getMessage());
}
}
/** Evaluates the test dataset and writes the results in the file.
*
* @exception If the file cannot be written.
*/
public void printTest() {
String text = getHeader();
for (int i = 0; i < testDataset.numItemsets(); i++) {
try {
int cl = (int) evaluateItemset(testDataset.itemset(i));
Itemset itemset = testDataset.itemset(i);
if (cl == (int) itemset.getValue(testDataset.getClassIndex())) {
testCorrect++;
}
text += testDataset.getClassAttribute().value(((int) itemset.
getClassValue())) + " " + testDataset.getClassAttribute().value(cl)
+ "\n";
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
try {
PrintWriter print = new PrintWriter(new FileWriter(
testOutputFileName));
print.print(text);
print.close();
} catch (IOException e) {
System.err.println("Can not open the training output file.");
}
}
/** Function to print the tree.
*
*/
public String toString() {
return root.toString();
}
/** Main function.
*
* @param args The parameters file.
*
* @throws Exception If the algorithm cannot been executed properly.
*/
public static void main(String[] args) {
try {
if (args.length != 1) {
throw new Exception("\nError: you have to specify the parameters file\n\tusage: java -jar C45.java parameterfile.txt");
} else {
C45 classifier = new C45(args[0]);
}
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit( -1);
}
}
}
| gpl-3.0 |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/preferences/SeekBarPreferenceCompat.java | 9892 | /*
* Copyright (c) 2021 David Allison <davidallisongithub@gmail.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/>.
*
*
* The following code was written by Matthew Wiggins
* and is released under the APACHE 2.0 license
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* adjusted by Norbert Nagold 2011 <norbert.nagold@gmail.com>
* adjusted by David Allison 2021 <davidallisongithub@gmail.com>
* * Converted to androidx.preference.DialogPreference
* * Split into SeekBarPreferenceCompat and SeekBarDialogFragmentCompat
*/
package com.ichi2.preferences;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import com.ichi2.anki.AnkiDroidApp;
import com.ichi2.ui.FixedTextView;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.preference.PreferenceDialogFragmentCompat;
public class SeekBarPreferenceCompat extends androidx.preference.DialogPreference {
private static final String androidns = "http://schemas.android.com/apk/res/android";
private String mSuffix;
private int mDefault;
private int mMax;
private int mMin;
private int mInterval;
private int mValue = 0;
@StringRes
private int mXLabel;
@StringRes
private int mYLabel;
public SeekBarPreferenceCompat(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setupVariables(attrs);
}
public SeekBarPreferenceCompat(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setupVariables(attrs);
}
public SeekBarPreferenceCompat(Context context, AttributeSet attrs) {
super(context, attrs);
setupVariables(attrs);
}
public SeekBarPreferenceCompat(Context context) {
super(context);
}
private void setupVariables(AttributeSet attrs) {
mSuffix = attrs.getAttributeValue(androidns, "text");
mDefault = attrs.getAttributeIntValue(androidns, "defaultValue", 0);
mMax = attrs.getAttributeIntValue(androidns, "max", 100);
mMin = attrs.getAttributeIntValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "min", 0);
mInterval = attrs.getAttributeIntValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "interval", 1);
mXLabel = attrs.getAttributeResourceValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "xlabel", 0);
mYLabel = attrs.getAttributeResourceValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "ylabel", 0);
}
@SuppressWarnings("deprecation") // 5019 - onSetInitialValue
@Override
protected void onSetInitialValue(boolean restore, Object defaultValue) {
super.onSetInitialValue(restore, defaultValue);
mValue = getPersistedInt(mDefault);
if (restore) {
mValue = shouldPersist() ? getPersistedInt(mDefault) : 0;
} else {
mValue = (Integer) defaultValue;
}
}
public int getValue() {
if (mValue == 0) {
return getPersistedInt(mDefault);
} else {
return mValue;
}
}
public void setValue(int value) {
mValue = value;
persistInt(value);
}
private void onValueUpdated() {
if (shouldPersist()) {
persistInt(mValue);
}
callChangeListener(mValue);
}
private String getValueText() {
String t = String.valueOf(mValue);
return mSuffix == null ? t : t + mSuffix;
}
// TODO: These could do with some thought as to either documentation, or defining the coupling between here and
// SeekBarDialogFragmentCompat
private void setRelativeValue(int value) {
mValue = (value * mInterval) + mMin;
}
private int getRelativeMax() {
return (mMax - mMin) / mInterval;
}
private int getRelativeProgress() {
return (mValue - mMin) / mInterval;
}
private void setupTempValue() {
if (!shouldPersist()) {
return;
}
mValue = getPersistedInt(mDefault);
}
public static class SeekBarDialogFragmentCompat extends PreferenceDialogFragmentCompat
implements SeekBar.OnSeekBarChangeListener {
public static SeekBarDialogFragmentCompat newInstance(@NonNull String key) {
SeekBarDialogFragmentCompat fragment = new SeekBarDialogFragmentCompat();
Bundle b = new Bundle(1);
b.putString(ARG_KEY, key);
fragment.setArguments(b);
return fragment;
}
private LinearLayout mSeekLine;
private SeekBar mSeekBar;
private TextView mValueText;
@Override
public SeekBarPreferenceCompat getPreference() {
return (SeekBarPreferenceCompat) super.getPreference();
}
@Override
public void onProgressChanged(SeekBar seekBar, int value, boolean fromUser) {
if (fromUser) {
getPreference().setRelativeValue(value);
getPreference().onValueUpdated();
onValueUpdated();
}
}
protected void onValueUpdated() {
mValueText.setText(getPreference().getValueText());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// intentionally left blank
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
this.getDialog().dismiss();
}
@Override
public void onDialogClosed(boolean positiveResult) {
// nothing needed - see onStopTrackingTouch
}
@Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
mSeekBar.setMax(getPreference().getRelativeMax());
mSeekBar.setProgress(getPreference().getRelativeProgress());
}
@Override
protected void onPrepareDialogBuilder(androidx.appcompat.app.AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
builder.setNegativeButton(null, null);
builder.setPositiveButton(null, null);
builder.setTitle(null);
}
@Override
protected View onCreateDialogView(Context context) {
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(6, 6, 6, 6);
mValueText = new FixedTextView(context);
mValueText.setGravity(Gravity.CENTER_HORIZONTAL);
mValueText.setTextSize(32);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layout.addView(mValueText, params);
mSeekBar = new SeekBar(context);
mSeekBar.setOnSeekBarChangeListener(this);
layout.addView(mSeekBar, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
SeekBarPreferenceCompat preference = getPreference();
if (preference.mXLabel != 0 && preference.mYLabel != 0) {
LinearLayout.LayoutParams params_seekbar = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params_seekbar.setMargins(0, 12, 0, 0);
mSeekLine = new LinearLayout(context);
mSeekLine.setOrientation(LinearLayout.HORIZONTAL);
mSeekLine.setPadding(6, 6, 6, 6);
addLabelsBelowSeekBar(context);
layout.addView(mSeekLine, params_seekbar);
}
preference.setupTempValue();
mSeekBar.setMax(preference.getRelativeMax());
mSeekBar.setProgress(preference.getRelativeProgress());
onValueUpdated();
return layout;
}
private void addLabelsBelowSeekBar(Context context) {
int[] labels = { getPreference().mXLabel, getPreference().mYLabel };
for (int count = 0; count < 2; count++) {
TextView textView = new FixedTextView(context);
textView.setText(context.getString(labels[count]));
textView.setGravity(Gravity.START);
mSeekLine.addView(textView);
if(context.getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_LTR)
textView.setLayoutParams((count == 1) ? getLayoutParams(0.0f) : getLayoutParams(1.0f));
else
textView.setLayoutParams((count == 0) ? getLayoutParams(0.0f) : getLayoutParams(1.0f));
}
}
LinearLayout.LayoutParams getLayoutParams(float weight) {
return new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, weight);
}
}
}
| gpl-3.0 |
elan-ev/StudIPAndroidApp | app/src/main/java/de/elanev/studip/android/app/courses/presentation/model/CourseUserModel.java | 861 | /*
* Copyright (c) 2016 ELAN e.V.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package de.elanev.studip.android.app.courses.presentation.model;
/**
* @author joern
*/
public class CourseUserModel {
private String userId;
private String name;
private String avatarUrl;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
}
| gpl-3.0 |
T-800/DenkiBlocks | src/gui/MenuGame.java | 1839 | package gui;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.*;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class MenuGame extends BasicGameState {
public static final int ID = 3;
private Titre titre;
private Button button[] = new Button[4];
@Override
public int getID() {
return ID;
}
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
titre = new Titre("",(container.getWidth()/2)-200/2,50);
for (int i = 0;i<button.length;i++){
button[i] = new Button("",(container.getWidth()/2)-200/2,150+(i*(75+15)));
}
button[1].setName("Choix Niveau");
button[2].setName("HighScore");
button[3].setName("Quiter");
}
@Override
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
Fenetre.image_bg.draw(0,0,container.getWidth(),container.getHeight());
titre.setName("Hello "+ Fenetre.profilActif.getName()+"!");
titre.render(g);
for (Button aButton : button) {
aButton.render(g);
}
button[0].setName("Level n°" + Fenetre.profilActif.getCurrent_Level());
}
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
Input input = container.getInput();
for (Button aButton : button) {
aButton.update(container);
}
if (button[0].isClicked()) {
Fenetre.profilActif.setLevel(Fenetre.profilActif.getCurrent_Level());
game.enterState(PlayLevel.ID);
}
else if(button[1].isClicked()) {
game.enterState(ChoixNiveau.ID);
}
else if(button[2].isClicked()) {
game.enterState(HighScore.ID);
}
else if(button[3].isClicked()) {
System.out.println("Quit Game");
System.exit(0);
}
else if (input.isKeyPressed(Keyboard.KEY_ESCAPE)) {
game.enterState(StartGame.ID);
}
}
} | gpl-3.0 |
zhilianxinke/SchoolInHand | app/src/main/java/com/zhilianxinke/schoolinhand/domain/AttendanceClass.java | 775 | package com.zhilianxinke.schoolinhand.domain;
/**
* Created by Ldb on 2015/9/28.
*/
public class AttendanceClass {
private String id;
private String name;
private String ru_time;
private String chu_time;
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setRu_time(String ru_time) {
this.ru_time = ru_time;
}
public void setChu_time(String chu_time) {
this.chu_time = chu_time;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getRu_time() {
return ru_time;
}
public String getChu_time() {
return chu_time;
}
}
| gpl-3.0 |
getconverge/converge-1.x | modules/converge-core/src/main/java/dk/i2m/converge/core/annotations/WorkflowValidator.java | 1093 | /*
* Copyright (C) 2011 Interactive Media Management
*
* 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 dk.i2m.converge.core.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WorkflowValidator {
} | gpl-3.0 |
openflexo-team/diana | diana-geomedit/src/main/java/org/openflexo/diana/geomedit/model/SegmentReference.java | 3580 | /**
*
* Copyright (c) 2013-2014, Openflexo
* Copyright (c) 2011-2012, AgileBirds
*
* This file is part of Diana-geomedit, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* This software is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* See http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo (openflexo-contacts@openflexo.org)
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.diana.geomedit.model;
import org.openflexo.diana.BackgroundStyle;
import org.openflexo.diana.ForegroundStyle;
import org.openflexo.diana.geom.DianaSegment;
import org.openflexo.diana.geomedit.model.SegmentReference.SegmentReferenceImpl;
import org.openflexo.pamela.annotations.ImplementationClass;
import org.openflexo.pamela.annotations.ModelEntity;
import org.openflexo.pamela.annotations.XMLElement;
@ModelEntity
@ImplementationClass(SegmentReferenceImpl.class)
@XMLElement
public interface SegmentReference extends SegmentConstruction {
public SegmentConstruction getReference();
public void setReference(SegmentConstruction reference);
public abstract class SegmentReferenceImpl extends SegmentConstructionImpl implements SegmentReference {
public SegmentConstruction reference;
@Override
public SegmentConstruction getReference() {
return reference;
}
@Override
public void setReference(SegmentConstruction reference) {
if ((reference == null && this.reference != null) || (reference != null && !reference.equals(this.reference))) {
SegmentConstruction oldValue = this.reference;
this.reference = reference;
getPropertyChangeSupport().firePropertyChange("reference", oldValue, reference);
}
}
@Override
public BackgroundStyle getBackground() {
if (getReference() != null) {
return getReference().getBackground();
}
return null;
}
@Override
public ForegroundStyle getForeground() {
if (getReference() != null) {
return getReference().getForeground();
}
return null;
}
@Override
protected DianaSegment computeData() {
if (getReference() != null) {
return getReference().getData();
}
return null;
}
@Override
public String toString() {
return "SegmentReference[" + reference.toString() + "]";
}
@Override
public GeometricConstruction[] getDepends() {
GeometricConstruction[] returned = { getReference() };
return returned;
}
}
}
| gpl-3.0 |
jdubois/responses | src/main/java/org/owasp/validator/html/util/ErrorMessageUtil.java | 4666 | /*
* Copyright (c) 2007-2008, Arshan Dabirsiaghi, Jason Li
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of OWASP nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.owasp.validator.html.util;
import java.text.MessageFormat;
import java.util.ResourceBundle;
public final class ErrorMessageUtil {
public static final String ERROR_TAG_NOT_IN_POLICY = "error.tag.notfound";
public static final String ERROR_TAG_DISALLOWED = "error.tag.removed";
public static final String ERROR_TAG_FILTERED = "error.tag.filtered";
public static final String ERROR_TAG_ENCODED = "error.tag.encoded";
public static final String ERROR_ATTRIBUTE_CAUSE_FILTER = "error.attribute.invalid.filtered";
public static final String ERROR_ATTRIBUTE_CAUSE_ENCODE = "error.attribute.invalid.encoded";
public static final String ERROR_ATTRIBUTE_INVALID_FILTERED = "error.attribute.invalid.filtered";
public static final String ERROR_ATTRIBUTE_INVALID_REMOVED = "error.attribute.invalid.removed";
public static final String ERROR_ATTRIBUTE_NOT_IN_POLICY = "error.attribute.notfound";
public static final String ERROR_ATTRIBUTE_INVALID = "error.attribute.invalid";
public static final String ERROR_COMMENT_REMOVED = "error.comment.removed";
public static final String ERROR_INPUT_SIZE = "error.size.toolarge";
public static final String ERROR_CSS_ATTRIBUTE_MALFORMED = "error.css.attribute.malformed";
public static final String ERROR_CSS_TAG_MALFORMED = "error.css.tag.malformed";
public static final String ERROR_STYLESHEET_NOT_ALLOWED = "error.css.disallowed";
public static final String ERROR_CSS_IMPORT_DISABLED = "error.css.import.disabled";
public static final String ERROR_CSS_IMPORT_EXCEEDED = "error.css.import.exceeded";
public static final String ERROR_CSS_IMPORT_FAILURE = "error.css.import.failure";
public static final String ERROR_CSS_IMPORT_INPUT_SIZE = "error.css.import.toolarge";
public static final String ERROR_CSS_IMPORT_URL_INVALID = "error.css.import.url.invalid";
public static final String ERROR_STYLESHEET_RELATIVE = "error.css.stylesheet.relative";
public static final String ERROR_CSS_TAG_RELATIVE = "error.css.tag.relative";
public static final String ERROR_STYLESHEET_RULE_NOTFOUND = "error.css.stylesheet.rule.notfound";
public static final String ERROR_CSS_TAG_RULE_NOTFOUND = "error.css.tag.rule.notfound";
public static final String ERROR_STYLESHEET_SELECTOR_NOTFOUND = "error.css.stylesheet.selector.notfound";
public static final String ERROR_CSS_TAG_SELECTOR_NOTFOUND = "error.css.tag.selector.notfound";
public static final String ERROR_STYLESHEET_SELECTOR_DISALLOWED = "error.css.stylesheet.selector.disallowed";
public static final String ERROR_CSS_TAG_SELECTOR_DISALLOWED = "error.css.tag.selector.disallowed";
public static final String ERROR_STYLESHEET_PROPERTY_INVALID = "error.css.stylesheet.property.invalid";
public static final String ERROR_CSS_TAG_PROPERTY_INVALID = "error.css.tag.property.invalid";
private ErrorMessageUtil() {
}
public static String getMessage(ResourceBundle messages, String msgKey, Object[] arguments) {
return MessageFormat.format(messages.getString(msgKey), arguments);
}
}
| gpl-3.0 |
iterate-ch/cyberduck | webdav/src/test/java/ch/cyberduck/core/dav/DAVUploadFeatureTest.java | 4716 | package ch.cyberduck.core.dav;
/*
* Copyright (c) 2002-2013 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Bug fixes, suggestions and comments should be sent to feedback@cyberduck.ch
*/
import ch.cyberduck.core.AlphanumericRandomStringService;
import ch.cyberduck.core.DisabledConnectionCallback;
import ch.cyberduck.core.DisabledLoginCallback;
import ch.cyberduck.core.Local;
import ch.cyberduck.core.Path;
import ch.cyberduck.core.exception.AccessDeniedException;
import ch.cyberduck.core.features.Delete;
import ch.cyberduck.core.io.BandwidthThrottle;
import ch.cyberduck.core.io.DisabledStreamListener;
import ch.cyberduck.core.local.DefaultLocalTouchFeature;
import ch.cyberduck.core.shared.DefaultHomeFinderService;
import ch.cyberduck.core.transfer.TransferStatus;
import ch.cyberduck.test.IntegrationTest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.EnumSet;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@Category(IntegrationTest.class)
public class DAVUploadFeatureTest extends AbstractDAVTest {
@Test(expected = AccessDeniedException.class)
@Ignore
public void testAccessDenied() throws Exception {
final TransferStatus status = new TransferStatus();
final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
new DefaultLocalTouchFeature().touch(local);
final Path test = new Path(new Path("/dav/accessdenied", EnumSet.of(Path.Type.directory)), "nosuchname", EnumSet.of(Path.Type.file));
try {
new DAVUploadFeature(new DAVWriteFeature(session)).upload(
test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
status,
new DisabledConnectionCallback());
}
catch(AccessDeniedException e) {
assertEquals("Unexpected response (403 Forbidden). Please contact your web hosting service provider for assistance.", e.getDetail());
throw e;
}
finally {
local.delete();
}
}
@Test
public void testAppend() throws Exception {
final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
final int length = 32770;
final byte[] content = RandomUtils.nextBytes(length);
final OutputStream out = local.getOutputStream(false);
IOUtils.write(content, out);
out.close();
final Path test = new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
{
final TransferStatus status = new TransferStatus().withLength(content.length / 2);
new DAVUploadFeature(new DAVWriteFeature(session)).upload(
test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
status,
new DisabledConnectionCallback());
}
{
final TransferStatus status = new TransferStatus().withLength(content.length / 2).withOffset(content.length / 2).append(true);
new DAVUploadFeature(new DAVWriteFeature(session)).upload(
test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
status,
new DisabledConnectionCallback());
}
final byte[] buffer = new byte[content.length];
final InputStream in = new DAVReadFeature(session).read(test, new TransferStatus().withLength(content.length), new DisabledConnectionCallback());
IOUtils.readFully(in, buffer);
in.close();
assertArrayEquals(content, buffer);
new DAVDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
local.delete();
}
}
| gpl-3.0 |
pantelis60/L2Scripts_Underground | gameserver/src/main/java/ru/akumu/smartguard/utils/log/GuardLog.java | 1671 | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package ru.akumu.smartguard.utils.log;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import l2s.gameserver.network.l2.GameClient;
import ru.akumu.smartguard.GuardConfig;
import ru.akumu.smartguard.manager.session.model.ClientData;
import ru.akumu.smartguard.utils.log.LogFormatter;
public class GuardLog {
private static final Logger _log = Logger.getLogger("GENERAL");
private static final Logger _logAuth = Logger.getLogger("AUTH");
private static final LogFormatter _format = new LogFormatter();
public GuardLog() {
}
public static Logger getLogger() {
return _log;
}
public static void logAuth(ClientData cd, GameClient client) {
if(GuardConfig.LogToFile) {
_logAuth.info(String.format("Account \'%s\' logged in with HWID \'%s\' and IP \'%s\'", new Object[]{cd.account, cd.hwid.plain, client.getIpAddr()}));
}
}
public static void logException(Exception e) {
_log.log(Level.SEVERE, "Exception occurred:", e);
}
static {
try {
FileHandler e = new FileHandler(GuardConfig.SMART_GUARD_DIR + "log/general.log", true);
e.setFormatter(_format);
_log.addHandler(e);
FileHandler auth = new FileHandler(GuardConfig.SMART_GUARD_DIR + "log/auth.log", true);
auth.setFormatter(_format);
_logAuth.addHandler(auth);
} catch (Exception var2) {
_log.severe("Error! Log handler could not be created!");
}
}
}
| gpl-3.0 |
afodor/clusterstuff | src/kw_jobinGA/MakeQiimeMap.java | 1110 | /**
* generate mapping file for QIIME (run1)
*/
package kw_jobinGA;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class MakeQiimeMap {
public static String DIR = "/nobackup/afodor_research/kwinglee/jobin/ga-stool/";
public static String FASTA_FOLDER = DIR + "sequences/";
public static void main(String[] args) throws IOException {
String[] files = new File(FASTA_FOLDER).list();
Arrays.sort(files);
BufferedWriter out = new BufferedWriter(new FileWriter(new File(DIR + "qiime/qiimeMap.txt")));
out.write("#SampleID\tBarcodeSequence\tLinkerPrimerSequence\tInputFileName\tDescription\n");
for(String name : files) {
if(name.contains("_R1_") && name.endsWith(".fasta")) {
//String id = name.split("_")[2].replace(".fasta", "");
String id = name.replace(".fasta", "").replace("_", ".");
if(!id.startsWith("S")) {//include controls and gastric aspirate but not stool
out.write(id + "\tX\tX\t" + name + "\n");
}
}
}
out.close();
}
}
| gpl-3.0 |
Eliosoft/elios | src/main/java/net/eliosoft/elios/gui/controllers/DMXController.java | 1959 | /*
* This file is part of Elios.
*
* Copyright 2010 Jeremie GASTON-RAOUL & Alexandre COLLIGNON
*
* Elios 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.
*
* Elios 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 Elios. If not, see <http://www.gnu.org/licenses/>.
*/
package net.eliosoft.elios.gui.controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import net.eliosoft.elios.gui.models.DMXTableModel;
import net.eliosoft.elios.gui.views.DMXView;
/**
* The controller of the cues view.
*
* @author Jeremie GASTON-RAOUL
*/
public class DMXController {
private final DMXTableModel dmxTableModel;
private final DMXView dmxView;
/**
* The constructor of the DMXController class.
*
* @param dmxTableModel
* the dmx table model associated with this Controller
* @param dmxView
* the view associated with this Controller
*/
public DMXController(final DMXTableModel dmxTableModel,
final DMXView dmxView) {
this.dmxTableModel = dmxTableModel;
this.dmxView = dmxView;
this.initListeners();
}
private void initListeners() {
this.dmxView.addInOutRadioActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent actionEvent) {
dmxTableModel.setInputEnabled(actionEvent.getActionCommand()
.equals("input"));
}
});
}
}
| gpl-3.0 |
dennisfischer/simplejavayoutubeuploader | src/main/java/de/chaosfisch/uploader/Directories.java | 2350 | /*
* Copyright (c) 2014 Dennis Fischer.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0+
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors: Dennis Fischer
*/
package de.chaosfisch.uploader;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
public final class Directories {
private Directories() {
}
/**
* Copies a directory.
* <p/>
* NOTE: This method is not thread-safe.
* <p/>
*
* @param source the directory to copy from
* @param target the directory to copy into
* @throws IOException if an I/O error occurs
*/
public static void copyDirectory(final Path source, final Path target) throws IOException {
Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
if (null != exc) {
throw exc;
}
return FileVisitResult.CONTINUE;
}
});
}
public static void delete(final Path directory) throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
if (null == exc) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw exc;
}
}
});
}
}
| gpl-3.0 |
Alpha-Trader/AlphaTraderJavaRestApiLib | src/test/java/com/alphatrader/rest/CompanyTest.java | 8132 | package com.alphatrader.rest;
import com.alphatrader.rest.util.PropertyGson;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import static org.junit.Assert.*;
/**
* Test case for the {@link Company} class.
*
* @author Christopher Guckes (christopher.guckes@torq-dev.de)
* @version 1.0
*/
public class CompanyTest {
private static HttpResponder httpResponder = HttpResponder.getInstance();
private static final Gson gson = new PropertyGson().create();
private static final String JSON = "{\n" +
" \"securitiesAccountId\": \"57875cf3-de0a-48e4-a3bc-314d4550df12\",\n" +
" \"securityIdentifier\": \"STK0F513\",\n" +
" \"ceo\": {\n" +
" \"gravatarHash\": \"7b7f03e2a716b0efaf4ff8728ad070c3\",\n" +
" \"userCapabilities\": {\n" +
" \"level2UserEndDate\": null,\n" +
" \"premiumEndDate\": null,\n" +
" \"level2User\": false,\n" +
" \"partner\": true,\n" +
" \"premium\": false,\n" +
" \"locale\": null\n" +
" },\n" +
" \"username\": \"FauserneEist\",\n" +
" \"id\": \"43986f13-edde-486c-9ef0-718b100a1949\"\n" +
" },\n" +
" \"listing\": {\n" +
" \"startDate\": 1469951698361,\n" +
" \"endDate\": null,\n" +
" \"securityIdentifier\": \"STK0F513\",\n" +
" \"name\": \"Katholische Kirche AG\",\n" +
" \"type\": \"STOCK\"\n" +
" }," +
" \"name\": \"Katholische Kirche AG\",\n" +
" \"id\": \"81dcf5a1-b0b6-462a-a40c-e374619edc2f\"\n" +
"}";
private Company toTest;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Http.setInstance(httpResponder.getMock());
}
@Before
public void setUp() throws Exception {
toTest = gson.fromJson(JSON, Company.class);
}
@Test
public void getAllUserCompanies() throws Exception {
List<Company> reference = gson.fromJson(httpResponder.getJsonForRequest("/api/companies/"),
new TypeToken<ArrayList<Company>>() { }.getType());
List<Company> testObject = Company.getAllUserCompanies();
assertNotEquals(0, testObject.size());
assertEquals(new HashSet<>(reference), new HashSet<>(testObject));
}
@Test
public void getAllUserCompaniesByUsername() throws Exception {
List<Company> reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/companies/ceo/username/FauserneEist"),
new TypeToken<ArrayList<Company>>() { }.getType());
List<Company> testObject = Company.getAllUserCompaniesByUsername("FauserneEist");
assertNotEquals(0, testObject.size());
assertEquals(new HashSet<>(reference), new HashSet<>(testObject));
}
@Test
public void getAllUserCompanies1() throws Exception {
User user = gson.fromJson("{" +
"\"id\": \"43986f13-edde-486c-9ef0-718b100a1949\"" +
"}", User.class);
List<Company> reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/companies/ceo/userid/43986f13-edde-486c-9ef0-718b100a1949"),
new TypeToken<ArrayList<Company>>() { }.getType());
List<Company> testObject = Company.getAllUserCompanies(user);
assertNotEquals(0, testObject.size());
assertEquals(new HashSet<>(reference), new HashSet<>(testObject));
}
@Test
public void getAllCompanies() throws Exception {
List<Company> reference = gson.fromJson(httpResponder.getJsonForRequest("/api/companies/all/"),
new TypeToken<ArrayList<Company>>() { }.getType());
List<Company> testObject = Company.getAllCompanies();
assertNotEquals(0, testObject.size());
assertEquals(new HashSet<>(reference), new HashSet<>(testObject));
}
@Test
public void getBySecuritiesAccountId() throws Exception {
Company reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/companies/securitiesaccount/57875cf3-de0a-48e4-a3bc-314d4550df12"), Company.class);
Company testObject = Company.getBySecuritiesAccountId("57875cf3-de0a-48e4-a3bc-314d4550df12");
assertNotNull(testObject);
assertEquals(reference, testObject);
}
@Test
public void getBySecurityIdentifier() throws Exception {
Company reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/companies/securityIdentifier/STK0F513"), Company.class);
Company testObject = Company.getBySecurityIdentifier("STK0F513");
assertNotNull(testObject);
assertEquals(reference, testObject);
}
@Test
public void getById() throws Exception {
Company reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/companies/81dcf5a1-b0b6-462a-a40c-e374619edc2f"), Company.class);
Company testObject = Company.getById("81dcf5a1-b0b6-462a-a40c-e374619edc2f");
assertNotNull(testObject);
assertEquals(reference, testObject);
}
@Test
public void searchByName() throws Exception {
List<Company> reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/search/companies/Katholische"), new TypeToken<ArrayList<Company>>() { }.getType());
List<Company> testObject = Company.searchByName("Katholische");
assertNotEquals(0, testObject.size());
assertEquals(new HashSet<>(reference), new HashSet<>(testObject));
}
@Test
public void testGetName() throws Exception {
assertEquals("Katholische Kirche AG", toTest.getName());
}
@Test
public void testGetSecuritiesAccountId() throws Exception {
assertEquals("57875cf3-de0a-48e4-a3bc-314d4550df12", toTest.getSecuritiesAccountId());
}
@Test
public void testGetId() throws Exception {
assertEquals("81dcf5a1-b0b6-462a-a40c-e374619edc2f", toTest.getId());
}
@Test
public void testGetListing() throws Exception {
Listing reference = gson.fromJson("{\n" +
" \"startDate\": 1469951698361,\n" +
" \"endDate\": null,\n" +
" \"securityIdentifier\": \"STK0F513\",\n" +
" \"name\": \"Katholische Kirche AG\",\n" +
" \"type\": \"STOCK\"\n" +
"}", Listing.class);
assertEquals(reference, toTest.getListing());
}
@Test
public void testGetProfile() throws Exception {
CompanyProfile reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/companyprofiles/81dcf5a1-b0b6-462a-a40c-e374619edc2f"), CompanyProfile.class);
assertEquals(reference, toTest.getProfile());
assertEquals(reference, toTest.getProfile());
assertNotNull(toTest.getProfile());
}
@Test
public void testGetPortfolio() throws Exception {
Portfolio reference = gson.fromJson(httpResponder.getJsonForRequest(
"/api/portfolios/57875cf3-de0a-48e4-a3bc-314d4550df12"), Portfolio.class);
assertEquals(reference, toTest.getPortfolio());
assertEquals(reference, toTest.getPortfolio());
assertNotNull(toTest.getPortfolio());
}
@Test
public void testToString() throws Exception {
assertTrue(toTest.toString().startsWith(toTest.getClass().getSimpleName()));
}
@Test
public void testEquals() throws Exception {
assertTrue(toTest.equals(toTest));
assertFalse(toTest.equals(null));
assertFalse(toTest.equals("Test"));
Company other = gson.fromJson("{\n" +
" \"id\": \"12345\"\n" +
"}", Company.class);
assertFalse(toTest.equals(other));
}
@Test
public void testHashCode() throws Exception {
Company reference = gson.fromJson(JSON, Company.class);
assertEquals(reference.hashCode(), toTest.hashCode());
}
} | gpl-3.0 |
xsystems/xsystems-backend | xsystems-backend-api/src/main/java/org/xsystems/backend/entity/FileType.java | 1258 | /*
* The API of the backend of the xSystems web-application.
* Copyright (C) 2015-2016 xSystems
*
* 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.xsystems.backend.entity;
public enum FileType {
IMAGE(Values.IMAGE);
private String value;
FileType(final String value) {
if (!this.name().equals(value)) {
throw new IllegalStateException(
"The value parameter must be the same as the Enum name, i.e.: " + this.name());
}
this.value = value;
}
@Override
public String toString() {
return this.value;
}
public static class Values {
public static final String IMAGE = "IMAGE";
}
}
| gpl-3.0 |
miracatici/MakamBox | src/backEnd/TemplateCreate.java | 9932 | /** This file is part of MakamBox.
MakamBox 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.
MakamBox 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 MakamBox. If not, see <http://www.gnu.org/licenses/>.
*
* MakamBox is an implementation of MakamToolBox Turkish Makam music analysis tool which is developed by Baris Bozkurt
* This is the project of music tuition system that is a tool that helps users to improve their skills to perform music.
* This thesis aims at developing a computer based interactive tuition system specifically for Turkish music.
*
* Designed and implemented by @author Bilge Mirac Atici
* Supervised by @supervisor Baris Bozkurt
* Bahcesehir University, 2014-2015
*/
package backEnd;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.math3.util.FastMath;
import applied.HistogramExtractor;
import datas.Makam;
import utilities.Plot;
public class TemplateCreate {
private int maxFiles;
private File mainDirectory, theoryFile;
private String[] fileExtension;
private BufferedReader buffReader;
private Thread eThread;
private float histogramDifference=1;
private float[] referenceHistogram = new float[3272],
songHistogram = new float[636],
distanceArray = new float[3272-636+1],
makamAverageHistogram = new float[3272];
private File entryCollection;
private Iterator<File> iterateCollection;
private Collection<File> filesCollection;
private Map.Entry<File,float[]> entrySong;
private Iterator<Entry<File,float[]>> iterateSong;
private TreeMap<File,float[]> listedSong = new TreeMap<File,float[]>();
private Map.Entry<String,Makam> entryMakam;
private Iterator<Entry<String, Makam>> iterateMakam;
private TreeMap<String,Makam> makamsMap = new TreeMap<String,Makam>();
/***************Constructors******************************/
public TemplateCreate(String folderPath, String dataPath){
this(new File(folderPath),new File(dataPath));
}
public TemplateCreate(File directory, File data){
mainDirectory = directory;
theoryFile = data;
fileExtension = new String[]{"wav","mp3"};
}
/************************************ Methods ******************************************************/
public void createTemplates(){
eThread = new Thread(new Runnable(){
@Override
public void run() {
listFiles();
if(isConfirmed()){
HistogramExtractor.lblProgress.setText(0 + "/" + maxFiles);
readTheory();
searchFilesName();
createTheoryTemplate();
createSongHistogram();
allignFileHistogram();
HistogramExtractor.lblProgress.setText("Done !!! :) ");
}
}
});
eThread.start();
}
private void listFiles(){
filesCollection = FileUtils.listFiles(mainDirectory, fileExtension, true);
iterateCollection = filesCollection.iterator();
while(iterateCollection.hasNext()) {
entryCollection = iterateCollection.next();
listedSong.put(entryCollection, null);
}
maxFiles = filesCollection.size();
HistogramExtractor.progressBar.setMaximum(maxFiles);
}
private void readTheory(){
try {
String line;
buffReader = new BufferedReader (new FileReader(theoryFile));
while((line = buffReader.readLine())!=null){
String[] temp = line.split("\\t");
float[] interval = new float[temp.length-1];
for (int i = 1; i < temp.length; i++) {
interval[i-1] = Float.valueOf(temp[i]);
}
makamsMap.put(temp[0], new Makam(temp[0],interval));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void searchFilesName(){
iterateSong = listedSong.entrySet().iterator();
while(iterateSong.hasNext()) {
entrySong = iterateSong.next();
String nameFile = entrySong.getKey().getName();
nameFile = nameFile.toLowerCase();
iterateMakam = makamsMap.entrySet().iterator();
while(iterateMakam.hasNext()) {
entryMakam = iterateMakam.next();
String nameMakam = entryMakam.getValue().getName();
nameMakam = nameMakam.toLowerCase();
if(nameFile.contains("_"+nameMakam)){
entryMakam.getValue().songList.add(entrySong.getKey());
}
}
}
}
private void createTheoryTemplate(){
iterateMakam = makamsMap.entrySet().iterator();
while(iterateMakam.hasNext()) {
entryMakam = iterateMakam.next();
if(entryMakam.getValue().songList.size()>0){
entryMakam.getValue().distribute();
Plot.plot(entryMakam.getValue().getHistogramData());
}
}
}
private void createSongHistogram(){
iterateSong = listedSong.entrySet().iterator();
int currFile = 0;
while(iterateSong.hasNext()) {
try {
entrySong = iterateSong.next();
MakamBox box = new MakamBox(entrySong.getKey(),null);
listedSong.put(entrySong.getKey(),box.getHistogramData());
Plot.plot(box.getHistogramData());
System.gc();
++currFile;
HistogramExtractor.progressBar.setValue(currFile);
HistogramExtractor.lblProgress.setText(currFile + "/" + maxFiles);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void allignFileHistogram(){
HistogramExtractor.lblProgress.setText("Alligning Histograms");
iterateMakam = makamsMap.entrySet().iterator();
while(iterateMakam.hasNext()) {
referenceHistogram = new float[3272];
songHistogram = new float[636];
distanceArray = new float[3272-636+1];
entryMakam = iterateMakam.next();
if(entryMakam.getValue().songList.size()>0){
int count = 0;
while(histogramDifference>0.1){
makamAverageHistogram = new float[3272];
referenceHistogram = entryMakam.getValue().getHistogramData();
for (int i = 0; i < entryMakam.getValue().songList.size(); i++) {
songHistogram = listedSong.get(entryMakam.getValue().songList.get(i));
allign(songHistogram,referenceHistogram);
}
normalize(makamAverageHistogram,entryMakam.getValue().songList.size());
histogramDifference = L1distance(referenceHistogram,makamAverageHistogram);
entryMakam.getValue().setHistogramData(makamAverageHistogram);
count++;
}
System.out.println(count);
histogramDifference = 1f;
Plot.plot(makamAverageHistogram);
HistogramExtractor.lblProgress.setText("Saving Templates");
saveTemplate(entryMakam);
}
}
}
private void allign(float[] a, float[] b){
float[] c = a.clone();
createDistanceArray(a,b);
int shiftAmount = sortAndPick(distanceArray);
int indis = 1636 - shiftAmount;
indis = reCompute(c,indis,5);
shiftAmount = 1636 - indis;
sumHistograms(a,shiftAmount);
}
private void createDistanceArray(float[] song, float[] ref){
for (int pos = 0; pos <3272-636+1; pos++) {
float[] temp = reFill(song,pos);
distanceArray[pos] = L1distance(temp,ref);
}
}
private float[] reFill(float[] song , int t){
float[] longHistogram = new float[3272];
for(int i = 0;i<song.length;i++){
longHistogram[t+i] = song[i];
}
return longHistogram;
}
private float L1distance(float[] p1, float[] p2) {
float sum = 0f;
for (int i = 0; i < p1.length; i++) {
sum += FastMath.abs(p1[i] - p2[i]);
}
return sum;
}
private int sortAndPick(float[] distArray){
List<Float> b = Arrays.asList(ArrayUtils.toObject(distArray));
int tonicPoint = ArrayUtils.indexOf(distArray, Collections.min(b));
return tonicPoint;
}
private void sumHistograms(float[] hist, int point){
float[] longHisto = reFill(hist, point);
for (int i = 0; i < longHisto.length; i++) {
makamAverageHistogram[i]+=longHisto[i];
}
}
private int reCompute(float[] arr,int tonInd,int offset){
float[] sub = ArrayUtils.subarray(arr, tonInd - offset, tonInd + offset);
int add=-1; float max=-1;
for (int i = 0; i < sub.length; i++) {
if(sub[i]>max){
max=sub[i];
add=i;
}
}
int newT = (tonInd+add-offset);
return newT;
}
private void normalize(float[] array, float k){
for (int i = 0; i < array.length; i++) {
array[i] = array[i]/k;
}
}
private void saveTemplate(Entry<String, Makam> ent){
try {
new File(mainDirectory.getAbsolutePath()+"/Templates/").mkdir();
BufferedWriter wr = new BufferedWriter(new FileWriter(mainDirectory.getAbsolutePath()
+"/Templates/"+ent.getValue().getName()+".txt"));
for (int i = 0; i < makamAverageHistogram.length; i++) {
wr.write(new DecimalFormat("0.0000000000000000").format((makamAverageHistogram[i])));
wr.write("\n");
}
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isConfirmed(){
int reply = JOptionPane.showConfirmDialog(null, String.valueOf(maxFiles)+
" files found. Extraction might takes long time. Are you sure?", "Confirmation"
, JOptionPane.YES_NO_OPTION);
if (reply ==JOptionPane.YES_OPTION){
return true;
} else {
return false;
}
}
@Override
public void finalize(){
System.out.println("object is garbage collected");
}
}
| gpl-3.0 |
Lux-Vacuos/LightEngine | lightengine-client/src/main/java/net/luxvacuos/lightengine/client/ui/Root.java | 1012 | /*
* This file is part of Light Engine
*
* Copyright (C) 2016-2019 Lux Vacuos
*
* 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 net.luxvacuos.lightengine.client.ui;
public class Root {
public float rootX, rootY, rootW, rootH;
public Root(float rootX, float rootY, float rootW, float rootH) {
this.rootX = rootX;
this.rootY = rootY;
this.rootW = rootW;
this.rootH = rootH;
}
}
| gpl-3.0 |
tghoward/geopaparazzi | geopaparazzispatialitelibrary/src/com/vividsolutions/jts/simplify/LineSegmentIndex.java | 1925 | package com.vividsolutions.jts.simplify;
import java.util.*;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.index.*;
import com.vividsolutions.jts.index.quadtree.Quadtree;
/**
* An spatial index on a set of {@link LineSegment}s.
* Supports adding and removing items.
*
* @author Martin Davis
*/
class LineSegmentIndex
{
private Quadtree index = new Quadtree();
public LineSegmentIndex()
{
}
public void add(TaggedLineString line) {
TaggedLineSegment[] segs = line.getSegments();
for (int i = 0; i < segs.length; i++) {
TaggedLineSegment seg = segs[i];
add(seg);
}
}
public void add(LineSegment seg)
{
index.insert(new Envelope(seg.p0, seg.p1), seg);
}
public void remove(LineSegment seg)
{
index.remove(new Envelope(seg.p0, seg.p1), seg);
}
public List query(LineSegment querySeg)
{
Envelope env = new Envelope(querySeg.p0, querySeg.p1);
LineSegmentVisitor visitor = new LineSegmentVisitor(querySeg);
index.query(env, visitor);
List itemsFound = visitor.getItems();
// List listQueryItems = index.query(env);
// System.out.println("visitor size = " + itemsFound.size()
// + " query size = " + listQueryItems.size());
// List itemsFound = index.query(env);
return itemsFound;
}
}
/**
* ItemVisitor subclass to reduce volume of query results.
*/
class LineSegmentVisitor
implements ItemVisitor
{
// MD - only seems to make fragment_about a 10% difference in overall time.
private LineSegment querySeg;
private ArrayList items = new ArrayList();
public LineSegmentVisitor(LineSegment querySeg) {
this.querySeg = querySeg;
}
public void visitItem(Object item)
{
LineSegment seg = (LineSegment) item;
if (Envelope.intersects(seg.p0, seg.p1, querySeg.p0, querySeg.p1))
items.add(item);
}
public ArrayList getItems() { return items; }
}
| gpl-3.0 |
johnalexandergreene/Geom_Kisrhombille | GK.java | 44752 | package org.fleen.geom_Kisrhombille;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.fleen.geom_2D.GD;
/*
* KISRHOMBILLE GEOMETRY
*
* General kisrhombille coordinate system constants and methods.
*
* Directions are integers. We have 12, like a clock.
* Vertex has 4 coordinates. TODO reduce to 3
*
*
*
* o V12
* |\
* | \
* | \
* | \ hawk
* goat | \
* | \
* | \
* | \
* V4 o--------o V6
* fish
*
*/
public class GK{
public static final double SQRT3=Math.sqrt(3.0);
public static final int AXISCOUNT=6;
/*
* ################################
* BASIC DIAMOND CONSTANTS AND METRICS
* ################################
*/
public static final boolean
TWIST_POSITIVE=true,
TWIST_NEGATIVE=false;
public static enum Orbit{
CLOCKWISE,
COUNTERCLOCKWISE}
/*
* ++++++++++++++++++++++++++++++++
* VERTEX TYPES
* type values corrospond to dog values
* name index corrosponds to the number of segs that connect at a vertex of that type
* eg : VERTEX12 has 12 connections, VERTEX4A has 4 connections, etc
*/
public static final int
VERTEX_NULL=-1,
VERTEX_12=0,
VERTEX_4A=1,
VERTEX_6A=2,
VERTEX_4B=3,
VERTEX_6B=4,
VERTEX_4C=5;
/*
* ++++++++++++++++++++++++++++++++
* VERTEX GENERAL TYPES
* general type is 4,6 or 12
* it is also the number of edges at the vertex
*/
public static final int
VERTEX_GTYPE_4=0,
VERTEX_GTYPE_6=1,
VERTEX_GTYPE_12=2;
/*
* ++++++++++++++++++++++++++++++++
* EDGE TYPES
* "edge" as in a graph edge
* that is, the connecting lines between vertices
*/
public static final int
EDGE_NULL=-1,EDGE_FISH=0,EDGE_GOAT=1,EDGE_HAWK=2;
/*
* ++++++++++++++++++++++++++++++++
* EDGE STANDARD LENGTH VALUES
* these can be scaled however, of course
*/
public static final double
EDGESLV_FISH=1.0,
EDGESLV_GOAT=Math.sqrt(3.0),
EDGESLV_HAWK=2.0;
/*
* ++++++++++++++++++++++++++++++++
* DIRECTIONS
* For standard grid spin (spin==true) DIRECTION_0 is north and
* they are addressed clockwise.
*/
public static final int
DIRECTION_NULL=-1,
DIRECTION_0=0,
DIRECTION_1=1,
DIRECTION_2=2,
DIRECTION_3=3,
DIRECTION_4=4,
DIRECTION_5=5,
DIRECTION_6=6,
DIRECTION_7=7,
DIRECTION_8=8,
DIRECTION_9=9,
DIRECTION_10=10,
DIRECTION_11=11;
/*
* ++++++++++++++++++++++++++++++++
* 2D VALUES FOR OUR 12 DIRECTIONS
*/
public static final double[] DIRECTION_2D={
(0.0/12.0)*(GD.PI*2.0),
(1.0/12.0)*(GD.PI*2.0),
(2.0/12.0)*(GD.PI*2.0),
(3.0/12.0)*(GD.PI*2.0),
(4.0/12.0)*(GD.PI*2.0),
(5.0/12.0)*(GD.PI*2.0),
(6.0/12.0)*(GD.PI*2.0),
(7.0/12.0)*(GD.PI*2.0),
(8.0/12.0)*(GD.PI*2.0),
(9.0/12.0)*(GD.PI*2.0),
(10.0/12.0)*(GD.PI*2.0),
(11.0/12.0)*(GD.PI*2.0)};
/*
* convert diamond direction to real 2d direciton
*/
public static final double getDirection2D(int d){
if(d<0||d>11)return -1;
return DIRECTION_2D[d];}
/*
* Direction axis types
*/
public static final boolean
DIRECTION_AXIS_HAWK=true,
DIRECTION_AXIS_GOAT=false;
/*
*
*/
public static final boolean getAxisType(int d){
return d%2==0;}
public static final boolean directionAxisIsHawky(int d){
return d%2==0;}
public static final boolean directionAxisIsGoaty(int d){
return d%2==1;}
/*
* normalize arbitrary integer value to range [0,11]
*/
public static final int normalizeDirection(int d){
d=d%12;
if(d<0)d+=12;
return d;}
/*
* ################################
* VERTEX LIBERTIES
* each vertex is connected to the diamond graph via 4, 6 or 12 directions.
* We refer to each of directions as a "liberty".
* herein we describe the set of liberties for each vertex type (indicated by the "dog" coordinate)
* ################################
*/
public static final int[][] VERTEX_LIBERTIES={
{0,1,2,3,4,5,6,7,8,9,10,11},//V12
{2,5,8,11},//V4A
{0,2,4,6,8,10},//V6A
{1,4,7,10},//V4B
{0,2,4,6,8,10},//V6B
{0,3,6,9}};//V4C
public static final int[] getLiberties(int vdog){
return VERTEX_LIBERTIES[vdog];}
/*
* return true if a vertex of the specified type (vdog)
* has liberty in the specified direction.
* false otherwise.
*/
public static final boolean hasLiberty(int vdog,int dir){
for(int i=0;i<VERTEX_LIBERTIES[vdog].length;i++){
if(VERTEX_LIBERTIES[vdog][i]==dir)
return true;}
return false;}
/*
* ################################
* ADJACENT VERTEX
* ################################
*/
/*
* returns null if the specified vertex has no such adjacent in the specified direction
*/
public static final KPoint getVertex_Adjacent(KPoint v,int dir){
int[] v1=new int[4];
getVertex_Adjacent(
v.coors[0],
v.coors[1],
v.coors[2],
v.coors[3],
dir,
v1);
if(v1[3]==VERTEX_NULL)return null;
return new KPoint(v1);}
/*
* Given the specified vertex (v0a,v0b,v0c,v0d) and a direction (dir), return
* the coordinates of the implied adjacent vertex in the v1 array
* if the specified direction indicates an invalid liberty for v0
* then we return VERTEX_NULL in v1[3]
*/
public static final void getVertex_Adjacent(int v0a,int v0b,int v0c,int v0d,int dir,int[] v1){
switch(v0d){
case VERTEX_12:
switch(dir){
case DIRECTION_0:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=2;
return;
case DIRECTION_1:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=3;
return;
case DIRECTION_2:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_3:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=5;
return;
case DIRECTION_4:
v1[0]=v0a+1;
v1[1]=v0b;
v1[2]=v0c-1;
v1[3]=2;
return;
case DIRECTION_5:
v1[0]=v0a+1;
v1[1]=v0b;
v1[2]=v0c-1;
v1[3]=1;
return;
case DIRECTION_6:
v1[0]=v0a;
v1[1]=v0b-1;
v1[2]=v0c-1;
v1[3]=4;
return;
case DIRECTION_7:
v1[0]=v0a;
v1[1]=v0b-1;
v1[2]=v0c-1;
v1[3]=3;
return;
case DIRECTION_8:
v1[0]=v0a;
v1[1]=v0b-1;
v1[2]=v0c-1;
v1[3]=2;
return;
case DIRECTION_9:
v1[0]=v0a-1;
v1[1]=v0b-1;
v1[2]=v0c;
v1[3]=5;
return;
case DIRECTION_10:
v1[0]=v0a-1;
v1[1]=v0b-1;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_11:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=1;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_4A:
switch(dir){
case DIRECTION_2:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=2;
return;
case DIRECTION_5:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_8:
v1[0]=v0a-1;
v1[1]=v0b-1;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_11:
v1[0]=v0a-1;
v1[1]=v0b;
v1[2]=v0c+1;
v1[3]=0;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_6A:
switch(dir){
case DIRECTION_0:
v1[0]=v0a-1;
v1[1]=v0b;
v1[2]=v0c+1;
v1[3]=5;
return;
case DIRECTION_2:
v1[0]=v0a;
v1[1]=v0b+1;
v1[2]=v0c+1;
v1[3]=0;
return;
case DIRECTION_4:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=3;
return;
case DIRECTION_6:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_8:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=1;
return;
case DIRECTION_10:
v1[0]=v0a-1;
v1[1]=v0b;
v1[2]=v0c+1;
v1[3]=0;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_4B:
switch(dir){
case DIRECTION_1:
v1[0]=v0a;
v1[1]=v0b+1;
v1[2]=v0c+1;
v1[3]=0;
return;
case DIRECTION_4:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_7:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_10:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=2;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_6B:
switch(dir){
case DIRECTION_0:
v1[0]=v0a;
v1[1]=v0b+1;
v1[2]=v0c+1;
v1[3]=0;
return;
case DIRECTION_2:
v1[0]=v0a+1;
v1[1]=v0b+1;
v1[2]=v0c;
v1[3]=1;
return;
case DIRECTION_4:
v1[0]=v0a+1;
v1[1]=v0b+1;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_6:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=5;
return;
case DIRECTION_8:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_10:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=3;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_4C:
switch(dir){
case DIRECTION_0:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_3:
v1[0]=v0a+1;
v1[1]=v0b+1;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_6:
v1[0]=v0a+1;
v1[1]=v0b;
v1[2]=v0c-1;
v1[3]=2;
return;
case DIRECTION_9:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
default:
v1[3]=VERTEX_NULL;
return;}
default:
v1[3]=VERTEX_NULL;
return;}}
/*
* ################################
* VERTEX EDGE TYPES BY DIRECTION
* ################################
*/
/*
* Given a vertex type (vdog) and a direction (dir), get the edge type therein
*/
public static final int getEdgeType(int vdog,int dir){
switch(vdog){
case VERTEX_12:
switch(dir){
case DIRECTION_0:
return EDGE_HAWK;
case DIRECTION_1:
return EDGE_GOAT;
case DIRECTION_2:
return EDGE_HAWK;
case DIRECTION_3:
return EDGE_GOAT;
case DIRECTION_4:
return EDGE_HAWK;
case DIRECTION_5:
return EDGE_GOAT;
case DIRECTION_6:
return EDGE_HAWK;
case DIRECTION_7:
return EDGE_GOAT;
case DIRECTION_8:
return EDGE_HAWK;
case DIRECTION_9:
return EDGE_GOAT;
case DIRECTION_10:
return EDGE_HAWK;
case DIRECTION_11:
return EDGE_GOAT;
default:
return EDGE_NULL;}
case VERTEX_4A:
switch(dir){
case DIRECTION_2:
return EDGE_FISH;
case DIRECTION_5:
return EDGE_GOAT;
case DIRECTION_8:
return EDGE_FISH;
case DIRECTION_11:
return EDGE_GOAT;
default:
return EDGE_NULL;}
case VERTEX_6A:
switch(dir){
case DIRECTION_0:
return EDGE_FISH;
case DIRECTION_2:
return EDGE_HAWK;
case DIRECTION_4:
return EDGE_FISH;
case DIRECTION_6:
return EDGE_HAWK;
case DIRECTION_8:
return EDGE_FISH;
case DIRECTION_10:
return EDGE_HAWK;
default:
return EDGE_NULL;}
case VERTEX_4B:
switch(dir){
case DIRECTION_1:
return EDGE_GOAT;
case DIRECTION_4:
return EDGE_FISH;
case DIRECTION_7:
return EDGE_GOAT;
case DIRECTION_10:
return EDGE_FISH;
default:
return EDGE_NULL;}
case VERTEX_6B:
switch(dir){
case DIRECTION_0:
return EDGE_HAWK;
case DIRECTION_2:
return EDGE_FISH;
case DIRECTION_4:
return EDGE_HAWK;
case DIRECTION_6:
return EDGE_FISH;
case DIRECTION_8:
return EDGE_HAWK;
case DIRECTION_10:
return EDGE_FISH;
default:
return EDGE_NULL;}
case VERTEX_4C:
switch(dir){
case DIRECTION_0:
return EDGE_FISH;
case DIRECTION_3:
return EDGE_GOAT;
case DIRECTION_6:
return EDGE_FISH;
case DIRECTION_9:
return EDGE_GOAT;
default:
return EDGE_NULL;}
default:
return EDGE_NULL;}}
/*
* ################################
* VERTEX, VECTOR, DISTANCE, DIRECTION OPS
* NOTE We don't have to be really optimal or efficient, so we arent. We brute it.
* We will be dealing with distances in the range of 1..20 at most.
* More likely maxing at 5. We do it the easy way. Prolly the faster way too.
* Look at the old code for our old bloated complex universally applicable methods.
* ################################
*/
/**
* Given 2 directions, get the direction of d0 relative to d1
* returns value in range [-5,5]
* throws exception on direction reversal
* TODO just return the -6?
*/
public static final int getDirectionDelta(int d0,int d1){
int delta;
if(d0==d1){//same direction
delta=0;
}else{
//pretend that d0 is 0
int w=(d1+12-d0)%12;
if(w<6){
delta=w;
}else if(w>6){
delta=w-12;
}else{
throw new IllegalArgumentException("BAD GEOMETRY : direction reversal : d0="+d0+" d1="+d1);}}
return delta;}
/*
* ++++++++++++++++++++++++++++++++
* GET DIRECTION VERTEX VERTEX
* ++++++++++++++++++++++++++++++++
*/
private static final double
GETDIRVV_ERROR=1.0/(65596.0*2.0*GD.PI),
DIRECTION_2D_0_ALTERNATE=GD.PI*2.0;
private static final double[][] GETDIRVV_RANGES={
{DIRECTION_2D_0_ALTERNATE-GETDIRVV_ERROR,GETDIRVV_ERROR},
{DIRECTION_2D[1]-GETDIRVV_ERROR,DIRECTION_2D[1]+GETDIRVV_ERROR},
{DIRECTION_2D[2]-GETDIRVV_ERROR,DIRECTION_2D[2]+GETDIRVV_ERROR},
{DIRECTION_2D[3]-GETDIRVV_ERROR,DIRECTION_2D[3]+GETDIRVV_ERROR},
{DIRECTION_2D[4]-GETDIRVV_ERROR,DIRECTION_2D[4]+GETDIRVV_ERROR},
{DIRECTION_2D[5]-GETDIRVV_ERROR,DIRECTION_2D[5]+GETDIRVV_ERROR},
{DIRECTION_2D[6]-GETDIRVV_ERROR,DIRECTION_2D[6]+GETDIRVV_ERROR},
{DIRECTION_2D[7]-GETDIRVV_ERROR,DIRECTION_2D[7]+GETDIRVV_ERROR},
{DIRECTION_2D[8]-GETDIRVV_ERROR,DIRECTION_2D[8]+GETDIRVV_ERROR},
{DIRECTION_2D[9]-GETDIRVV_ERROR,DIRECTION_2D[9]+GETDIRVV_ERROR},
{DIRECTION_2D[10]-GETDIRVV_ERROR,DIRECTION_2D[10]+GETDIRVV_ERROR},
{DIRECTION_2D[11]-GETDIRVV_ERROR,DIRECTION_2D[11]+GETDIRVV_ERROR}};
/*
* Given 2 vertices : v0,v1
* get the direction from v0 to v1
* If the direction is invalid because the 2 vertices are not colinar (coaxial)
* (not one of our 12, within error) then we return DIRECTION_NULL
*/
public static final int getDirection_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
//get the direction 2dwise
double[] p0=new double[2],p1=new double[2];
getBasicPoint2D_Vertex(v0a,v0b,v0c,v0d,p0);
getBasicPoint2D_Vertex(v1a,v1b,v1c,v1d,p1);
double d2d=GD.getDirection_PointPoint(p0[0],p0[1],p1[0],p1[1]);
double[] range;
//filter the 2d direction value for gkis direction 0
if(d2d>GETDIRVV_RANGES[0][0]||d2d<GETDIRVV_RANGES[0][1])
return 0;
//filter the 2d direction value for our other 11 gkis directions
for(int i=1;i<12;i++){
range=GETDIRVV_RANGES[i];
if(d2d>range[0]&&d2d<range[1])
return i;}
return DIRECTION_NULL;}
public static final int getDirection_VertexVertex(KPoint v0,KPoint v1){
return getDirection_VertexVertex(
v0.getAnt(),v0.getBat(),v0.getCat(),v0.getDog(),
v1.getAnt(),v1.getBat(),v1.getCat(),v1.getDog());}
// public static final void main(String[] a){
// KVertex v0=new KVertex(-1,2,3,0),v1=new KVertex(-1,1,2,2);
// int dir=getDirection_VertexVertex(v0,v1);
// System.out.println("dir="+dir);
// }
/*
* COLINEARITY TEST
* If the direction from v0 to v1 is a valid one for that particular
* pair of vertex types then v0 and v1 are colinear.
*/
public static final boolean getColinear_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
int d=getDirection_VertexVertex(v0a,v0b,v0c,v0d,v1a,v1b,v1c,v1d);
//if null direction then noncolinear
if(d==DIRECTION_NULL)return false;
//we have a valid direction, is it valid for this pair of vertex types?
//that is, is it a shared liberty?
return hasLiberty(v0d,d)&&hasLiberty(v1d,d);}
/*
* ++++++++++++++++++++++++++++++++
* GET DISTANCE VERTEX VERTEX
* simply convert to basic 2d points and use 2d distance
* ++++++++++++++++++++++++++++++++
*/
public static final double getDistance_VertexVertex(
KPoint v0,KPoint v1){
return getDistance_VertexVertex(
v0.getAnt(),v0.getBat(),v0.getCat(),v0.getDog(),
v1.getAnt(),v1.getBat(),v1.getCat(),v1.getDog());}
public static final double getDistance_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
double[] p0=new double[2],p1=new double[2];
getBasicPoint2D_Vertex(v0a,v0b,v0c,v0d,p0);
getBasicPoint2D_Vertex(v1a,v1b,v1c,v1d,p1);
return GD.getDistance_PointPoint(p0[0],p0[1],p1[0],p1[1]);}
/*
* ++++++++++++++++++++++++++++++++
* GET VECTOR FROM 2 VERTICES
* ++++++++++++++++++++++++++++++++
*/
public static final KVector getVector_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
int dir=getDirection_VertexVertex(v0a,v0b,v0c,v0d,v1a,v1b,v1c,v1d);
//if it's a null direction then bad vector
if(dir==DIRECTION_NULL)return null;
//if the direction is one where either of the vertices has no such liberty then bad vector
if(!(hasLiberty(v0d,dir))&&(hasLiberty(v1d,dir)))return null;
//get distance and that's that
double dis=getDistance_VertexVertex(v0a,v0b,v0c,v0d,v1a,v1b,v1c,v1d);
return new KVector(dir,dis);}
/*
* ++++++++++++++++++++++++++++++++
* GET VERTEX FROM VERTEX AND VECTOR
* Crawl from the specified vertex one adjacent neighbor at a time in
* the specified direction over the specified distance until distance is within error of zero
* if it falls beneath negative error then fail.
* ++++++++++++++++++++++++++++++++
*/
private static final double
GETVERTEXVV_TRAVERSALERRORCEILING=1.0/65536.0,
GETVERTEXVV_TRAVERSALERRORFLOOR=-GETVERTEXVV_TRAVERSALERRORCEILING;
public static final KPoint getVertex_VertexVector(KPoint v,KVector t){
int[] v1=new int[4];
getVertex_VertexVector(v.getAnt(),v.getBat(),v.getCat(),v.getDog(),t.direction,t.distance,v1);
if(v1[3]==VERTEX_NULL)return null;
KPoint vertex=new KPoint(v1);
return vertex;}
public static final int[] getVertex_VertexVector(int[] v0,int tdir,double tdis){
int[] v1=new int[4];
getVertex_VertexVector(v0[0],v0[1],v0[2],v0[3],tdir,tdis,v1);
return v1;}
/*
* return the vertex in v1 as an int[4] of coordinates
* return VERTEX_NULL at dog on fail
*/
public static final void getVertex_VertexVector(
int v0a,int v0b,int v0c,int v0d,int tdir,double tdis,int[] v1){
double remaining=tdis;
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=v0d;
while(remaining>GETVERTEXVV_TRAVERSALERRORCEILING){
remaining-=getAdjacentDistance(v1[3],tdir);
if(remaining<GETVERTEXVV_TRAVERSALERRORFLOOR){
v1[3]=VERTEX_NULL;
return;}
getVertex_Adjacent(v1[0],v1[1],v1[2],v1[3],tdir,v1);
if(v1[3]==VERTEX_NULL){
return;}}}
/*
* given the specified vertex type and direction, get the distance to the vertex adjacent to
* that vertex in that direction.
* we DO NOT check that a vertex with the specified vdog does indeed have a liberty at the specified direction
* so if the specified vertex type does not have a liberty at the specified direction then an ambiguous value
* will be returned
*/
public static final double getAdjacentDistance(int vdog,int dir){
if(dir%2==1)return EDGESLV_GOAT;
switch(vdog){
case VERTEX_12:
return EDGESLV_HAWK;
case VERTEX_4A:
return EDGESLV_FISH;
case VERTEX_6A:
if(dir%4==0){
return EDGESLV_FISH;
}else{
return EDGESLV_HAWK;}
case VERTEX_4B:
return EDGESLV_FISH;
case VERTEX_6B:
if(dir%4==0){
return EDGESLV_HAWK;
}else{
return EDGESLV_FISH;}
case VERTEX_4C:
return EDGESLV_FISH;
default:
throw new IllegalArgumentException("invalid value for vdog : "+vdog);}}
/*
* ++++++++++++++++++++++++++++++++
* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
* TEST
* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
* ++++++++++++++++++++++++++++++++
*/
private static final int TEST_CYCLES_COUNT=10000;
/*
* get a random vertex v0
* get a random vector t
* derive v1 via sequential adjacent process
* derive v1 via getVertex_VertexVector method
* if they match then good
* if they don't then fail
* run it 10000 times or so
* time it too
*/
public static final void TEST_getVertex_VertexVector(){
int[] v0,v1a,v1b,vector;
int failurecount=0;
for(int i=0;i<TEST_CYCLES_COUNT;i++){
v0=getRandomVertex();
vector=getRandomVector(v0);
v1a=new int[4];
v1b=new int[4];
getVertex_VertexVector_AdjProcessForTest(v0[0],v0[1],v0[2],v0[3],vector[0],vector[1],v1a);
getVertex_VertexVector(v0[0],v0[1],v0[2],v0[3],vector[0],vector[1],v1b);
//our derived vertices can match in 2 ways :
// 1) they both express failure (dog==VERTEX_NULL therefor invalid vertex, due to bad distance)
// 2) all of the coordinates match
if(
(v1a[3]==VERTEX_NULL&&v1b[3]==VERTEX_NULL)||
(v1a[0]==v1b[0]&&
v1a[1]==v1b[1]&&
v1a[2]==v1b[2]&&
v1a[3]==v1b[3])){
System.out.println("TEST INDEX : "+i+" : --- SUCCEESS ---");
}else{
failurecount++;
System.out.println("TEST INDEX : "+i+" : ##>> FAIL <<##");
System.out.println("v0 : "+v0[0]+","+v0[1]+","+v0[2]+","+v0[3]);
System.out.println("vector dir : "+vector[0]);
System.out.println("vector dis : "+vector[1]);
System.out.println("v1a : "+v1a[0]+","+v1a[1]+","+v1a[2]+","+v1a[3]);
System.out.println("v1b : "+v1b[0]+","+v1b[1]+","+v1b[2]+","+v1b[3]);
System.out.println("#><##><##><##><##><##><##><##><#");}}
//
if(failurecount==0){
System.out.println("^^^^^^^^^^^^^^");
System.out.println("TEST SUCCEEDED");
System.out.println("TEST CYCLES : "+TEST_CYCLES_COUNT);
System.out.println("^^^^^^^^^^^^^^");
}else{
System.out.println("#><##><##><##><##><##><##><##><#");
System.out.println("TEST FAILED");
System.out.println("TEST CYCLES : "+TEST_CYCLES_COUNT);
System.out.println("FAILURE COUNT : "+failurecount);
System.out.println("#><##><##><##><##><##><##><##><#");}}
/*
* consider our vertex and vector
* traverse adjacent vertices from v0 in direction vector.direction until total distance >= vector.distance
* if 0 was skipped and total distance reached is > vector.distance then we have arrived in the middle of a hawk
* edge. Therefor fail because distances must work out perfectly.
*/
private static final void getVertex_VertexVector_AdjProcessForTest(
int v0a,int v0b,int v0c,int v0d,int tdir,int tdis,int[] v1){
int distancetraversed=0,edgelength;
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=v0d;
while(distancetraversed<tdis){
edgelength=(getEdgeType(v1[3],tdir)==EDGE_HAWK)?2:1;
getVertex_Adjacent(v1[0],v1[1],v1[2],v1[3],tdir,v1);
distancetraversed+=edgelength;}
//if we have overrun our vector distance then the vertex is invalid
if(distancetraversed>tdis){
v1[3]=VERTEX_NULL;}}
private static final int[] getRandomVertex(){
Random r=new Random();
int
a=r.nextInt(21)-10,
b=r.nextInt(21)-10,
c=b-a,
d=r.nextInt(6);
return new int[]{a,b,c,d};}
private static final int[] getRandomVector(int[] v){
Random r=new Random();
int
dir=VERTEX_LIBERTIES[v[3]][r.nextInt(VERTEX_LIBERTIES[v[3]].length)],
dis=r.nextInt(33)+1;
return new int[]{dir,dis};}
/*
* ################################
* POINT 2D FROM VERTEX
* Given a basic diamond coordinate system (origin=(0,0), twist=true, foreward=0, fish=1),
* translate the specified diamond vertex coordinates into 2d point coordinates
* ################################
*/
private static final double
UINT_1=1.0,
UINT_2=2.0,
UINT_SQRT3=Math.sqrt(3.0),
P2D_G=UINT_SQRT3/2.0,
P2D_H=3.0/2.0;
public static final double[] getBasicPoint2D_Vertex(int[] p){
double[] p2=new double[2];
getBasicPoint2D_Vertex(p[0],p[1],p[2],p[3],p2);
return p2;}
/*
* return the 2d point assuming a standard diamond grid where
* foreward == 0/2PI, fish=1.0 and direction indexing is clockwise.
*/
public static final void getBasicPoint2D_Vertex(int ant,int bat,int cat,int dog,double[] p2d){
//start with coordinates of the v12 at the center of the flower
p2d[0]=(ant+bat)*UINT_SQRT3;
p2d[1]=cat*(UINT_1+UINT_2);
//the other 5 vertices are relative to the V12
switch(dog){
case 0: //V12
break;
case 1: //V4A
p2d[0]-=P2D_G;
p2d[1]+=P2D_H;
break;
case 2: //V6A
p2d[1]+=UINT_2;
break;
case 3: //V4B
p2d[0]+=P2D_G;
p2d[1]+=P2D_H;
break;
case 4: //V6B
p2d[0]+=UINT_SQRT3;
p2d[1]+=UINT_1;
break;
case 5: //V4C
p2d[0]+=UINT_SQRT3;
break;
default:throw new IllegalArgumentException("dog out of range [0,5]. dog=="+dog);}}
/*
* ################################
* GET VERTEX TRANSITIONWISE
* Use an integer transitions count instead of real distance
* ################################
*/
/*
* ++++++++++++++++++++++++++++++++
* get vertex via vertex, direction and transitions
* ++++++++++++++++++++++++++++++++
*/
//dog patterns by direction
private static final int[]
DOGPATTERN0={0,2,5,4},
DOGPATTERN1={0,3,0,3},
DOGPATTERN2={0,4,1,2},
DOGPATTERN3={0,5,0,5},
DOGPATTERN4={0,2,3,4},
DOGPATTERN5={0,1,0,1},
DOGPATTERN6={0,4,5,2},
DOGPATTERN7={0,3,0,3},
DOGPATTERN8={0,2,1,4},
DOGPATTERN9={0,5,0,5},
DOGPATTERN10={0,4,3,2},
DOGPATTERN11={0,1,0,1};
/*
* given a vertex (v0a,v0b,v0c,v0d) a direction (dir) and a transitions count (trans), return the
* implied vertex coordinates in v1.
*/
public static final void getVertex_Transitionswise(
int v0a,int v0b,int v0c,int v0d,int dir,int trans,int[] v1){
//if transitions is 0 then we return the original vertex
if(trans==0){
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=v0d;}
//
switch(v0d){
//++++++++++++++++
case VERTEX_12:
switch(dir){
case 0:
v1[0]=v0a-(trans+2)/4;
v1[1]=v0b+trans/4;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN0[trans%4];
return;
case 1:
v1[0]=v0a;
v1[1]=v0b+trans/2;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN1[trans%4];
return;
case 2:
v1[0]=v0a+(trans+2)/4;
v1[1]=v0b+trans/2;
v1[2]=v0c+trans/4;
v1[3]=DOGPATTERN2[trans%4];
return;
case 3:
v1[0]=v0a+trans/2;
v1[1]=v0b+trans/2;
v1[2]=v0c;
v1[3]=DOGPATTERN3[trans%4];
return;
case 4:
v1[0]=v0a+trans/2;
if(trans%4==1)v1[0]++;
v1[1]=v0b+trans/4;
v1[2]=v0c-(trans+3)/4;
v1[3]=DOGPATTERN4[trans%4];
return;
case 5:
v1[0]=v0a+(trans+1)/2;
v1[1]=v0b;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN5[trans%4];
return;
case 6:
v1[0]=v0a+(trans+1)/4;
v1[1]=v0b-(trans+3)/4;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN6[trans%4];
return;
case 7:
v1[0]=v0a;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN7[trans%4];
return;
case 8:
v1[0]=v0a-(trans+1)/4;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c-(trans+3)/4;
v1[3]=DOGPATTERN8[trans%4];
return;
case 9:
v1[0]=v0a-(trans+1)/2;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c;
v1[3]=DOGPATTERN9[trans%4];
return;
case 10:
v1[0]=v0a-trans/2;
if(trans%4==1)v1[0]--;
v1[1]=v0b-(trans+3)/4;
v1[2]=v0c+trans/4;
v1[3]=DOGPATTERN10[trans%4];
return;
case 11:
v1[0]=v0a-trans/2;
v1[1]=v0b;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN11[trans%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_4A:
switch(dir){
case 2:
v1[0]=v0a+trans/4;
v1[1]=v0b+trans/2;
v1[2]=v0c+(trans+2)/4;
v1[3]=DOGPATTERN2[(trans+2)%4];
return;
case 5:
v1[0]=v0a+trans/2;
v1[1]=v0b;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN5[(trans+1)%4];
return;
case 8:
v1[0]=v0a-(trans+3)/4;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c-(trans+1)/4;
v1[3]=DOGPATTERN8[(trans+2)%4];
return;
case 11:
v1[0]=v0a-(trans+1)/2;
v1[1]=v0b;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN5[(trans+1)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_6A:
switch(dir){
case 0:
v1[0]=v0a-(trans+3)/4;
v1[1]=v0b+(trans+1)/4;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN0[(trans+1)%4];
return;
case 2:
v1[0]=v0a+(trans+1)/4;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c+(trans+3)/4;
v1[3]=DOGPATTERN2[(trans+3)%4];
return;
case 4:
v1[0]=v0a+trans/2;
if(trans%4==2)v1[0]--;
v1[1]=v0b+(trans+1)/4;
v1[2]=v0c-trans/4;
v1[3]=DOGPATTERN4[(trans+1)%4];
return;
case 6:
v1[0]=v0a+trans/4;
v1[1]=v0b-(trans+2)/4;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN6[(trans+3)%4];
return;
case 8:
v1[0]=v0a-(trans+2)/4;
v1[1]=v0b-trans/2;
v1[2]=v0c-trans/4;
v1[3]=DOGPATTERN8[(trans+1)%4];
return;
case 10:
v1[0]=v0a-(trans+1)/2;
if(trans%4==2)v1[0]--;
v1[1]=v0b-(trans+2)/4;
v1[2]=v0c+(trans+3)/4;
v1[3]=DOGPATTERN10[(trans+3)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_4B:
switch(dir){
case 1:
v1[0]=v0a;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN1[(trans+1)%4];
return;
case 4:
v1[0]=v0a+(trans+1)/2;
if(trans%4==1)v1[0]--;
v1[1]=v0b+(trans+2)/4;
v1[2]=v0c-(trans+1)/4;
v1[3]=DOGPATTERN4[(trans+2)%4];
return;
case 7:
v1[0]=v0a;
v1[1]=v0b-trans/2;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN7[(trans+1)%4];
return;
case 10:
v1[0]=v0a-trans/2;
if(trans%4==3)v1[0]--;
v1[1]=v0b-(trans+1)/4;
v1[2]=v0c+(trans+2)/4;
v1[3]=DOGPATTERN10[(trans+2)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_6B:
switch(dir){
case 0:
v1[0]=v0a-(trans+1)/4;
v1[1]=v0b+(trans+3)/4;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN0[(trans+3)%4];
return;
case 2:
v1[0]=v0a+(trans+3)/4;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c+(trans+1)/4;
v1[3]=DOGPATTERN2[(trans+1)%4];
return;
case 4:
v1[0]=v0a+(trans+1)/2;
if(trans%4==2)v1[0]++;
v1[1]=v0b+(trans+3)/4;
v1[2]=v0c-(trans+2)/4;
v1[3]=DOGPATTERN4[(trans+3)%4];
return;
case 6:
v1[0]=v0a+(trans+2)/4;
v1[1]=v0b-trans/4;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN6[(trans+1)%4];
return;
case 8:
v1[0]=v0a-trans/4;
v1[1]=v0b-trans/2;
v1[2]=v0c-(trans+2)/4;
v1[3]=DOGPATTERN8[(trans+3)%4];
return;
case 10:
v1[0]=v0a-trans/2;
if(trans%4==2)v1[0]++;
v1[1]=v0b-trans/4;
v1[2]=v0c+(trans+1)/4;
v1[3]=DOGPATTERN10[(trans+1)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_4C:
switch(dir){
case 0:
v1[0]=v0a-trans/4;
v1[1]=v0b+(trans+2)/4;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN0[(trans+2)%4];
return;
case 3:
v1[0]=v0a+(trans+1)/2;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c;
v1[3]=DOGPATTERN3[(trans+1)%4];
return;
case 6:
v1[0]=v0a+(trans+3)/4;
v1[1]=v0b-(trans+1)/4;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN6[(trans+2)%4];
return;
case 9:
v1[0]=v0a-trans/2;
v1[1]=v0b-trans/2;
v1[2]=v0c;
v1[3]=DOGPATTERN9[(trans+1)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
//INVALID VERTEX INDEX(?)
default:
return;}}
public static final KPoint getVertex_Transitionswise(KPoint v0,int dir,int transitions){
int[] a=new int[4];
getVertex_Transitionswise(v0.getAnt(),v0.getBat(),v0.getCat(),v0.getDog(),dir,transitions,a);
return new KPoint(a);}
/*
* ################################
* CONVERT 2D COORDINATES TO GRID COORDINATES FOR STANDARD GRID
* Given a point, get the closest vertex within the specified margin
* It chops the space up into boxes and delivers us the closest point, excluding a small degenerate space.
* It's fast.
* we're working with a standard grid here: foreward=0, twist=clockwise, fish=1.0
* If we're too far from any vertices then null is returned
* ################################
*/
private static final double
GRIDCELLBOXWIDTH=Math.sqrt(3.0),
GRIDCELLBOXHEIGHT=3.0;
public static final KPoint getStandardVertex(double[] p,double margin){
return getStandardVertex(p[0],p[1],margin);}
public static final KPoint getStandardVertex(double px,double py,double margin){
//get the box coordinates
int
bx=(int)Math.floor(px/GRIDCELLBOXWIDTH),
by=(int)Math.floor(py/GRIDCELLBOXHEIGHT);
//get the intra-box coordinates
int
ibx=(int)((px-(bx*GRIDCELLBOXWIDTH))/(GRIDCELLBOXWIDTH/4)),
iby=(int)((py-(by*GRIDCELLBOXHEIGHT))/(GRIDCELLBOXHEIGHT/12));
//we have 2 kinds of boxes
//get the actual vertex coordinates
int ka,kb,kc,kd;
//GET COORDINATES FOR BOX TYPE A
SEEK:if(Math.abs(bx%2)==Math.abs(by%2)){
//get the key v12 vertex coors
ka=(bx-by)/2;//beware those rounding integers. bx/2 - by/2 is not what we want
kc=by;
kb=ka+kc;
//analyze position within box grid : (ibx,iby)
if(ibx==0){//0 (see notes)
if(iby==0||iby==1){
kd=0;
break SEEK;
}else if(iby==6||iby==7||iby==8||iby==9){//4
kd=2;
break SEEK;
}else if(iby==10||iby==11){//5
ka=ka-1;
kc=kc+1;
kd=5;
break SEEK;
}else{//ambiguous
return null;}
}else if(ibx==1||ibx==2){
if(iby==4||iby==5||iby==6||iby==7){//3
kd=3;
break SEEK;
}else{//ambiguous
return null;}
}else{//ibx==3
if(iby==0||iby==1){//1
kd=5;
break SEEK;
}else if(iby==2||iby==3||iby==4||iby==5){//2
kd=4;
break SEEK;
}else if(iby==10||iby==11){//6
kb=kb+1;
kc=kc+1;
kd=0;
break SEEK;
}else{//ambiguous
return null;}}
//GET COORDINATES FOR BOX TYPE B
}else{
//get the key v12 vertex coors
ka=(bx-by+1)/2;
kc=by;
kb=ka+kc;
//analyze position within box grid : (ibx,iby)
if(ibx==0){
if(iby==0||iby==1){//1
ka=ka-1;
kb=kb-1;
kd=5;
break SEEK;
}else if(iby==2||iby==3||iby==4||iby==5){//2
ka=ka-1;
kb=kb-1;
kd=4;
break SEEK;
}else if(iby==10||iby==11){//6
ka=ka-1;
kc=kc+1;
kd=0;
break SEEK;
}else{//ambiguous
return null;}
}else if(ibx==1||ibx==2){
if(iby==4||iby==5||iby==6||iby==7){//3
kd=1;
break SEEK;
}else{//ambiguous
return null;}
}else{//ibx==3
if(iby==0||iby==1){//0
kd=0;
break SEEK;
}else if(iby==6||iby==7||iby==8||iby==9){//4
kd=2;
break SEEK;
}else if(iby==10||iby==11){//5
ka=ka-1;
kc=kc+1;
kd=5;
break SEEK;
}else{//ambiguous
return null;}}}
//now we have our most likely suspect
//are we close enough?
KPoint v=new KPoint(ka,kb,kc,kd);
double[] precisepoint=v.getBasicPointCoor();
if(Math.abs(px-precisepoint[0])<margin&&Math.abs(py-precisepoint[1])<margin){
return v;
}else{
return null;}}
/*
* ################################
* ANGLES
* ################################
*/
/**
* given 3 different vertices, v0,v1,v2
* return the angle formed on the right
*
* v2 o
* |
* |
* |
* v1 o <--this angle
* \
* \
* v0 o
*
*/
public static final int getRightAngle(KPoint v0,KPoint v1,KPoint v2){
int
d0=getDirection_VertexVertex(v0,v1),
d1=getDirection_VertexVertex(v1,v2);
int d=getDirectionDelta(d0,d1);
return 6-d;}
/**
* given 3 different vertices, v0,v1,v2
* return the angle formed on the left
*
* o v2
* |
* |
* |
* this angle--> o v1
* /
* /
* o v0
*
*/
public static final int getLeftAngle(KPoint v0,KPoint v1,KPoint v2){
int
d0=getDirection_VertexVertex(v0,v1),
d1=getDirection_VertexVertex(v1,v2);
int d=getDirectionDelta(d0,d1);
return 6+d;}
/**
* Get the counterclockwise offset of d1 relative to d0
* We assume that d0 and d1 have been normalized to range {0,11}
*
* o---------> d1
* | .
* | .
* | . offset angle
* |.
* |
* V
* d0
*
* @param d0 a direction
* @param d1 another direction
* @return the counterclockwise offset from d0 to d1
*/
// public static final int getCCWOffset(int d0,int d1){
// d0%=12;
// d1%=12;
// d0+=12;
// d1+=12;
// if(d1>d0)return 12-(d1-d0);
// return d0-d1;}
/*
* returns true is direction d is "between right" of the directions d0 and d1
* TODO TEST
*
* ^ d1
* |
* |
* |
* o ------> right
* |
* |
* |
* V d0
*/
public static final boolean isBetweenRight(int d0,int d1,int d){
int
d0cw=getCWOffset(d,d0),
d1ccw=getCCWOffset(d,d1);
return (d0cw+d1ccw)<11;}
/*
* returns true is direction d is "between right" of the directions d0 and d1
* TODO TEST
*
* ^ d1
* |
* |
* left |
* <------ o
* |
* |
* |
* V d0
*/
public static final boolean isBetweenLeft(int d0,int d1,int d){
int
d0ccw=getCCWOffset(d,d0),
d1cw=getCWOffset(d,d1);
return (d0ccw+d1cw)<11;}
/*
*
* returns the clockwise offset of direction d1 relative to direction d0
* ex0 : the clockwise offset of 6 relative to 2 is 4
* ex1 : the clockwise offset of 0 relative to 4 is 8
*
*
* d0
* ^
* | . .
* | . + clockwise offset
* | .
* | V
* o-----------> d1
*
*/
public static final int getCWOffset(int d0,int d1){
if(d1>=d0)
return d1-d0;
else
return 12-d0+d1;}
public static final int getCCWOffset(int d0,int d1){
int f=12-getCWOffset(d0,d1);
if(f==12)f=0;
return f;}
//TEST
public static final void main(String[] a){
Random r=new Random();
int a0,a1,cwoff;
for(int i=0;i<10;i++){
a0=r.nextInt(12);
a1=r.nextInt(12);
cwoff=getCCWOffset(a0,a1);
System.out.println("a0="+a0+" : a1="+a1+" : cwoff="+cwoff);
}}
/*
* ################################
* METAGON ANCHOR CONGRUENT POLYGON PERMUTATIONS
* Given a metagon and an anchor, we can derive a polygon
* however, implicit are 0..n other anchors that would also deliver the same polygon geometry
* The specific point location and index+ traversal direction may vary, but the same basic polygon will result.
* for example :
*
* These 3 polygons are congruent, yet they do the points differently
*
* 0 1 1 0 3 2
* o--------o o--------o o--------o
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* o--------o o--------o o--------o
* 3 2 2 3 0 1
*
* Some metagon anchor systems will have several permutations, some will have just 1
* ################################
*/
/*
* Given a metagon and an anchor, producing polygon P.
* return a list of all anchors that, with this metagon, also describe polygons congruent to P.
* This list includes the original parameter anchor.
* These anchors are alternatives to the specified anchor.
* Other ways to generate the same basic polygon but with different orientation and twist.
*
* Create a polygon from params metagon and anchor : porg
* Get every pair of adjacent vertices in the polygon : va,vb
* Create 4 anchors from each of those pairs.
* That is, the vertices in foreward and reverse order, with positive and negative twist.
* ie : va,vb,pos; va,vb,neg; vb,va,pos; vb,va,neg
*
* now we have a list of prospective anchors : pa
* for every anchor in pa, create a polygon : pp
* if pp is valid, and congruent to porg, then it passes the test. Add that anchor to the list
*/
public static final List<KAnchor> getMetagonAnchorOptions(KMetagon metagon,KAnchor anchor){
KPolygon sample=metagon.getPolygon(anchor),test;
List<KAnchor> prospects=getProspectiveAnchorsForMAA(sample);
List<KAnchor> validprospects=new ArrayList<KAnchor>();
for(KAnchor a:prospects){
test=metagon.getPolygon(a);
if(test!=null&&test.isCongruent(sample))
validprospects.add(a);}
System.out.println("VALID PROSPECTS COUNT : "+validprospects.size());
return validprospects;}
private static final List<KAnchor> getProspectiveAnchorsForMAA(KPolygon p){
List<KAnchor> anchors=new ArrayList<KAnchor>();
int i0,i1,s=p.size();
KPoint v0,v1;
for(i0=0;i0<s;i0++){
i1=i0+1;
if(i1==s)i1=0;
v0=p.get(i0);
v1=p.get(i1);
anchors.add(new KAnchor(v0,v1,true));
anchors.add(new KAnchor(v0,v1,false));
anchors.add(new KAnchor(v1,v0,true));
anchors.add(new KAnchor(v1,v0,false));}
return anchors;}
}
| gpl-3.0 |
KromatikSolutions/dasshy | dasshy-server/src/main/java/com/kromatik/dasshy/server/event/PolicyBatchCancelled.java | 1396 | /**
* Dasshy - Real time and Batch Analytics Open Source System
* Copyright (C) 2016 Kromatik Solutions (http://kromatiksolutions.com)
*
* This file is part of Dasshy
*
* Dasshy 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.
*
* Dasshy 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 Dasshy. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kromatik.dasshy.server.event;
/**
* Batch cancelled event
*/
public class PolicyBatchCancelled extends JobEvent
{
private final String batchId;
/***
* New batch cancelled event
*
* @param id event id
* @param jobId job id
* @param timestamp creation timestamp
* @param batchId batch id
*/
public PolicyBatchCancelled(String id, String jobId, Long timestamp, String batchId)
{
super(id, jobId, timestamp, JobEventType.BATCH_CANCELLED);
this.batchId = batchId;
}
public String getBatchId()
{
return batchId;
}
}
| gpl-3.0 |
BackgammonHT16/Backgammon3 | backgammon3/src/main/java/bg/backgammon3/view/helper/Position.java | 392 | /**
*
*/
package bg.backgammon3.view.helper;
/**
*
*
*/
public class Position {
public double x;
public double y;
public double rotation;
public Position()
{
}
public Position(double x, double y)
{
this.x = x;
this.y = y;
this.rotation = 0;
}
public Position(double x, double y, double rotation)
{
this.x = x;
this.y = y;
this.rotation = rotation;
}
}
| gpl-3.0 |
cleberecht/singa | singa-simulation/src/test/java/bio/singa/simulation/model/sections/CellRegionTest.java | 3439 | package bio.singa.simulation.model.sections;
import bio.singa.features.units.UnitRegistry;
import bio.singa.simulation.entities.ChemicalEntity;
import bio.singa.simulation.entities.SimpleEntity;
import org.junit.jupiter.api.Test;
import tech.units.indriya.quantity.Quantities;
import static bio.singa.features.units.UnitProvider.MOLE_PER_LITRE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static tech.units.indriya.unit.MetricPrefix.MICRO;
import static tech.units.indriya.unit.Units.METRE;
/**
* @author cl
*/
class CellRegionTest {
private final ChemicalEntity entityA = SimpleEntity.create("A").build();
private final ChemicalEntity entityB = SimpleEntity.create("B").build();
private final ChemicalEntity entityC = SimpleEntity.create("C").build();
@Test
void resembleSingleContainer() {
// set environment
UnitRegistry.setSpace(Quantities.getQuantity(1.0, MICRO(METRE)));
// create region
CellRegion region = new CellRegion("Cytoplasm");
region.addSubsection(CellTopology.INNER, CellSubsections.CYTOPLASM);
ConcentrationContainer concentrationContainer = region.setUpConcentrationContainer();
// set concentration
concentrationContainer.initialize(CellSubsections.CYTOPLASM, entityA, Quantities.getQuantity(1.0, MOLE_PER_LITRE));
// retrieve values
assertEquals(1.0, UnitRegistry.concentration(concentrationContainer.get(CellSubsections.CYTOPLASM, entityA)).to(MOLE_PER_LITRE).getValue().doubleValue());
assertEquals(0.0, UnitRegistry.concentration(concentrationContainer.get(CellSubsections.EXTRACELLULAR_REGION, entityA)).to(MOLE_PER_LITRE).getValue().doubleValue());
assertEquals(0.0, UnitRegistry.concentration(concentrationContainer.get(CellSubsections.CYTOPLASM, entityB)).to(MOLE_PER_LITRE).getValue().doubleValue());
}
@Test
void resembleMembraneContainer() {
// set environment
UnitRegistry.setSpace(Quantities.getQuantity(1.0, MICRO(METRE)));
// create region
CellRegion region = new CellRegion("Lateral membrane");
region.addSubsection(CellTopology.INNER, CellSubsections.CYTOPLASM);
region.addSubsection(CellTopology.MEMBRANE, CellSubsections.CELL_OUTER_MEMBRANE);
region.addSubsection(CellTopology.OUTER, CellSubsections.EXTRACELLULAR_REGION);
ConcentrationContainer concentrationContainer = region.setUpConcentrationContainer();
// set concentration
concentrationContainer.initialize(CellSubsections.CYTOPLASM, entityA, Quantities.getQuantity(1.0, MOLE_PER_LITRE));
concentrationContainer.initialize(CellSubsections.EXTRACELLULAR_REGION, entityB, Quantities.getQuantity(0.5, MOLE_PER_LITRE));
concentrationContainer.initialize(CellSubsections.CELL_OUTER_MEMBRANE, entityC, Quantities.getQuantity(1.0, MOLE_PER_LITRE));
// retrieve values
assertEquals(1.0, UnitRegistry.concentration(concentrationContainer.get(CellSubsections.CYTOPLASM, entityA)).to(MOLE_PER_LITRE).getValue().doubleValue());
assertEquals(0.5, UnitRegistry.concentration(concentrationContainer.get(CellSubsections.EXTRACELLULAR_REGION, entityB)).to(MOLE_PER_LITRE).getValue().doubleValue());
assertEquals(0.0, UnitRegistry.concentration(concentrationContainer.get(CellSubsections.CELL_OUTER_MEMBRANE, entityB)).to(MOLE_PER_LITRE).getValue().doubleValue());
}
} | gpl-3.0 |
codepilotde/AdServing | ad.db/src/main/java/net/mad/ads/db/definition/condition/DayConditionDefinition.java | 1311 | /**
* Mad-Advertisement
* Copyright (C) 2011 Thorsten Marx <thmarx@gmx.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/>.
*/
package net.mad.ads.db.definition.condition;
import java.util.ArrayList;
import java.util.List;
import net.mad.ads.db.definition.ConditionDefinition;
import net.mad.ads.db.enums.Day;
/**
* Steuerung an welchen Wochentagen (Montag - Sonntag) das Banner angezeigt werden soll
*
* @author tmarx
*
*/
public class DayConditionDefinition implements ConditionDefinition {
private List<Day> days = new ArrayList<Day>();
public DayConditionDefinition () {
}
public List<Day> getDays() {
return this.days;
}
public void addDay(Day day) {
this.days.add(day);
}
}
| gpl-3.0 |
xiaoaowanghu/MJServer | MJServer/nettysrc/io/netty/handler/ssl/JdkSslClientContext.java | 16342 | /*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you 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 io.netty.handler.ssl;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.File;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
/**
* A client-side {@link SslContext} which uses JDK's SSL/TLS implementation.
*
* @deprecated Use {@link SslContextBuilder} to create {@link JdkSslContext} instances and only
* use {@link JdkSslContext} in your code.
*/
@Deprecated
public final class JdkSslClientContext extends JdkSslContext {
/**
* Creates a new instance.
*
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext() throws SSLException {
this(null, null);
}
/**
* Creates a new instance.
*
* @param certChainFile an X.509 certificate chain file in PEM format.
* {@code null} to use the system default
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(File certChainFile) throws SSLException {
this(certChainFile, null);
}
/**
* Creates a new instance.
*
* @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
* that verifies the certificates sent from servers.
* {@code null} to use the default.
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(TrustManagerFactory trustManagerFactory) throws SSLException {
this(null, trustManagerFactory);
}
/**
* Creates a new instance.
*
* @param certChainFile an X.509 certificate chain file in PEM format.
* {@code null} to use the system default
* @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
* that verifies the certificates sent from servers.
* {@code null} to use the default.
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException {
this(certChainFile, trustManagerFactory, null, IdentityCipherSuiteFilter.INSTANCE,
JdkDefaultApplicationProtocolNegotiator.INSTANCE, 0, 0);
}
/**
* Creates a new instance.
*
* @param certChainFile an X.509 certificate chain file in PEM format.
* {@code null} to use the system default
* @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
* that verifies the certificates sent from servers.
* {@code null} to use the default.
* @param ciphers the cipher suites to enable, in the order of preference.
* {@code null} to use the default cipher suites.
* @param nextProtocols the application layer protocols to accept, in the order of preference.
* {@code null} to disable TLS NPN/ALPN extension.
* @param sessionCacheSize the size of the cache used for storing SSL session objects.
* {@code 0} to use the default value.
* @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
* {@code 0} to use the default value.
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(
File certChainFile, TrustManagerFactory trustManagerFactory,
Iterable<String> ciphers, Iterable<String> nextProtocols,
long sessionCacheSize, long sessionTimeout) throws SSLException {
this(certChainFile, trustManagerFactory, ciphers, IdentityCipherSuiteFilter.INSTANCE,
toNegotiator(toApplicationProtocolConfig(nextProtocols), false), sessionCacheSize, sessionTimeout);
}
/**
* Creates a new instance.
*
* @param certChainFile an X.509 certificate chain file in PEM format.
* {@code null} to use the system default
* @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
* that verifies the certificates sent from servers.
* {@code null} to use the default.
* @param ciphers the cipher suites to enable, in the order of preference.
* {@code null} to use the default cipher suites.
* @param cipherFilter a filter to apply over the supplied list of ciphers
* @param apn Provides a means to configure parameters related to application protocol negotiation.
* @param sessionCacheSize the size of the cache used for storing SSL session objects.
* {@code 0} to use the default value.
* @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
* {@code 0} to use the default value.
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(
File certChainFile, TrustManagerFactory trustManagerFactory,
Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
long sessionCacheSize, long sessionTimeout) throws SSLException {
this(certChainFile, trustManagerFactory, ciphers, cipherFilter,
toNegotiator(apn, false), sessionCacheSize, sessionTimeout);
}
/**
* Creates a new instance.
*
* @param certChainFile an X.509 certificate chain file in PEM format.
* {@code null} to use the system default
* @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
* that verifies the certificates sent from servers.
* {@code null} to use the default.
* @param ciphers the cipher suites to enable, in the order of preference.
* {@code null} to use the default cipher suites.
* @param cipherFilter a filter to apply over the supplied list of ciphers
* @param apn Application Protocol Negotiator object.
* @param sessionCacheSize the size of the cache used for storing SSL session objects.
* {@code 0} to use the default value.
* @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
* {@code 0} to use the default value.
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(
File certChainFile, TrustManagerFactory trustManagerFactory,
Iterable<String> ciphers, CipherSuiteFilter cipherFilter, JdkApplicationProtocolNegotiator apn,
long sessionCacheSize, long sessionTimeout) throws SSLException {
this(certChainFile, trustManagerFactory, null, null, null, null,
ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout);
}
/**
* Creates a new instance.
* @param trustCertCollectionFile an X.509 certificate collection file in PEM format.
* {@code null} to use the system default
* @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
* that verifies the certificates sent from servers.
* {@code null} to use the default or the results of parsing
* {@code trustCertCollectionFile}
* @param keyCertChainFile an X.509 certificate chain file in PEM format.
* This provides the public key for mutual authentication.
* {@code null} to use the system default
* @param keyFile a PKCS#8 private key file in PEM format.
* This provides the private key for mutual authentication.
* {@code null} for no mutual authentication.
* @param keyPassword the password of the {@code keyFile}.
* {@code null} if it's not password-protected.
* Ignored if {@code keyFile} is {@code null}.
* @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s
* that is used to encrypt data being sent to servers.
* {@code null} to use the default or the results of parsing
* {@code keyCertChainFile} and {@code keyFile}.
* @param ciphers the cipher suites to enable, in the order of preference.
* {@code null} to use the default cipher suites.
* @param cipherFilter a filter to apply over the supplied list of ciphers
* @param apn Provides a means to configure parameters related to application protocol negotiation.
* @param sessionCacheSize the size of the cache used for storing SSL session objects.
* {@code 0} to use the default value.
* @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
* {@code 0} to use the default value.
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(File trustCertCollectionFile, TrustManagerFactory trustManagerFactory,
File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory,
Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn,
long sessionCacheSize, long sessionTimeout) throws SSLException {
this(trustCertCollectionFile, trustManagerFactory, keyCertChainFile, keyFile, keyPassword, keyManagerFactory,
ciphers, cipherFilter, toNegotiator(apn, false), sessionCacheSize, sessionTimeout);
}
/**
* Creates a new instance.
* @param trustCertCollectionFile an X.509 certificate collection file in PEM format.
* {@code null} to use the system default
* @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
* that verifies the certificates sent from servers.
* {@code null} to use the default or the results of parsing
* {@code trustCertCollectionFile}
* @param keyCertChainFile an X.509 certificate chain file in PEM format.
* This provides the public key for mutual authentication.
* {@code null} to use the system default
* @param keyFile a PKCS#8 private key file in PEM format.
* This provides the private key for mutual authentication.
* {@code null} for no mutual authentication.
* @param keyPassword the password of the {@code keyFile}.
* {@code null} if it's not password-protected.
* Ignored if {@code keyFile} is {@code null}.
* @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s
* that is used to encrypt data being sent to servers.
* {@code null} to use the default or the results of parsing
* {@code keyCertChainFile} and {@code keyFile}.
* @param ciphers the cipher suites to enable, in the order of preference.
* {@code null} to use the default cipher suites.
* @param cipherFilter a filter to apply over the supplied list of ciphers
* @param apn Application Protocol Negotiator object.
* @param sessionCacheSize the size of the cache used for storing SSL session objects.
* {@code 0} to use the default value.
* @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
* {@code 0} to use the default value.
* @deprecated use {@link SslContextBuilder}
*/
@Deprecated
public JdkSslClientContext(File trustCertCollectionFile, TrustManagerFactory trustManagerFactory,
File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory,
Iterable<String> ciphers, CipherSuiteFilter cipherFilter, JdkApplicationProtocolNegotiator apn,
long sessionCacheSize, long sessionTimeout) throws SSLException {
super(newSSLContext(toX509CertificatesInternal(
trustCertCollectionFile), trustManagerFactory,
toX509CertificatesInternal(keyCertChainFile), toPrivateKeyInternal(keyFile, keyPassword),
keyPassword, keyManagerFactory, sessionCacheSize, sessionTimeout), true,
ciphers, cipherFilter, apn, ClientAuth.NONE, null, false);
}
JdkSslClientContext(X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
X509Certificate[] keyCertChain, PrivateKey key, String keyPassword,
KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter,
ApplicationProtocolConfig apn, String[] protocols, long sessionCacheSize, long sessionTimeout)
throws SSLException {
super(newSSLContext(trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword,
keyManagerFactory, sessionCacheSize, sessionTimeout), true,
ciphers, cipherFilter, toNegotiator(apn, false), ClientAuth.NONE, protocols, false);
}
private static SSLContext newSSLContext(X509Certificate[] trustCertCollection,
TrustManagerFactory trustManagerFactory, X509Certificate[] keyCertChain,
PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
long sessionCacheSize, long sessionTimeout) throws SSLException {
try {
if (trustCertCollection != null) {
trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory);
}
if (keyCertChain != null) {
keyManagerFactory = buildKeyManagerFactory(keyCertChain, key, keyPassword, keyManagerFactory);
}
SSLContext ctx = SSLContext.getInstance(PROTOCOL);
ctx.init(keyManagerFactory == null ? null : keyManagerFactory.getKeyManagers(),
trustManagerFactory == null ? null : trustManagerFactory.getTrustManagers(),
null);
SSLSessionContext sessCtx = ctx.getClientSessionContext();
if (sessionCacheSize > 0) {
sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
}
if (sessionTimeout > 0) {
sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
}
return ctx;
} catch (Exception e) {
if (e instanceof SSLException) {
throw (SSLException) e;
}
throw new SSLException("failed to initialize the client-side SSL context", e);
}
}
}
| gpl-3.0 |
TinyGroup/tiny | db/org.tinygroup.dbrouterjdbc3/src/test/java/org/tinygroup/dbrouterjdbc3/jdbc/sample/TestRouterSelectPrimarySlave.java | 1638 | /**
* Copyright (c) 1997-2013, www.tinygroup.org (luo_guo@icloud.com).
*
* Licensed under the GPL, Version 3.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.gnu.org/licenses/gpl.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinygroup.dbrouterjdbc3.jdbc.sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import org.tinygroup.dbrouter.RouterManager;
import org.tinygroup.dbrouter.config.Router;
import org.tinygroup.dbrouter.factory.RouterManagerBeanFactory;
public class TestRouterSelectPrimarySlave {
public static void main(String[] args) throws Throwable {
RouterManager routerManager = RouterManagerBeanFactory.getManager();
Router router = TestRouterUtil.getPrimarySlaveRouter();
routerManager.addRouter(router);
Class.forName("org.tinygroup.dbrouterjdbc3.jdbc.TinyDriver");
Connection conn =
DriverManager.getConnection("jdbc:dbrouter://router1", "luog", "123456");
Statement stmt = conn.createStatement();
String sql;
//插入100条数据
for (int i = 1; i <= 100; i++) {
sql = "select * from aaa";
boolean result = stmt.execute(sql);
}
}
}
| gpl-3.0 |
DanielMalmgren/HAndroid | HAndroid/src/main/java/se/kolefors/handroid/PopulateGroupFragment.java | 624 | package se.kolefors.handroid;
import android.view.View;
import java.util.List;
/**
* Created by damal08 on 2014-01-11.
*/
public class PopulateGroupFragment extends PopulateFragment{
public PopulateGroupFragment(View rootView) {
super(rootView);
super.setStartTag("groups");
super.setItemTag("group");
super.setApiFunctions("groups");
super.setApiIdSpecifier("groupid");
}
public void updateObjects(List items) {
updateOnOffObjects(items);
}
public void drawObjects(List items) {
drawOnOffObjects(items);
}
}
| gpl-3.0 |
wjaneal/liastem | Tank Drive/src/org/usfirst/frc/team6162/robot/Robot.java | 1572 | package org.usfirst.frc.team6162.robot;
import edu.wpi.first.wpilibj.SampleRobot;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Timer;
/**
* This is a demo program showing the use of the RobotDrive class, specifically
* it contains the code necessary to operate a robot with tank drive.
*
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SampleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*
* WARNING: While it may look like a good choice to use for your code if you're
* inexperienced, don't. Unless you know what you are doing, complex code will
* be much more difficult under this system. Use IterativeRobot or Command-Based
* instead if you're new.
*/
public class Robot extends SampleRobot {
RobotDrive myRobot = new RobotDrive(0, 1); // class that handles basic drive
// operations
Joystick leftStick = new Joystick(0); // set to ID 1 in DriverStation
Joystick rightStick = new Joystick(1); // set to ID 2 in DriverStation
public Robot() {
myRobot.setExpiration(0.1);
}
/**
* Runs the motors with tank steering.
*/
@Override
public void operatorControl() {
myRobot.setSafetyEnabled(true);
while (isOperatorControl() && isEnabled()) {
myRobot.tankDrive(leftStick, rightStick);
Timer.delay(0.005); // wait for a motor update time
}
}
}
| gpl-3.0 |
sapia-oss/corus | modules/client/src/test/java/org/sapia/corus/client/rest/resources/DistributionWriteResourceTest.java | 7055 | package org.sapia.corus.client.rest.resources;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.sapia.corus.client.ClusterInfo;
import org.sapia.corus.client.common.rest.RestRequest;
import org.sapia.corus.client.common.rest.Value;
import org.sapia.corus.client.facade.CorusConnectionContext;
import org.sapia.corus.client.facade.CorusConnector;
import org.sapia.corus.client.facade.DeployerFacade;
import org.sapia.corus.client.rest.ConnectorPool;
import org.sapia.corus.client.rest.PartitionService;
import org.sapia.corus.client.rest.RequestContext;
import org.sapia.corus.client.rest.async.AsyncTask;
import org.sapia.corus.client.rest.async.AsynchronousCompletionService;
import org.sapia.corus.client.rest.resources.DistributionWriteResource;
import org.sapia.corus.client.services.deployer.DeployPreferences;
import org.sapia.corus.client.services.deployer.DistributionCriteria;
import org.sapia.corus.client.services.deployer.UndeployPreferences;
@RunWith(MockitoJUnitRunner.class)
public class DistributionWriteResourceTest {
@Mock
private CorusConnector connector;
@Mock
private ConnectorPool connectors;
@Mock
private CorusConnectionContext connection;
@Mock
private AsynchronousCompletionService async;
@Mock
private PartitionService partitions;
@Mock
private RestRequest request;
@Mock
private DeployerFacade deployer;
private DistributionWriteResource resource;
private RequestContext context;
@Before
public void setUp() {
resource = new DistributionWriteResource() {
@Override
protected File transfer(RequestContext ctx, String extension) throws IOException {
File toReturn = mock(File.class);
when(toReturn.getAbsolutePath()).thenReturn("test");
return toReturn;
}
};
context = new RequestContext(request, connector, async, partitions, connectors);
when(connectors.acquire()).thenReturn(connector);
when(connector.getContext()).thenReturn(connection);
when(connector.getDeployerFacade()).thenReturn(deployer);
when(request.getValue("corus:host")).thenReturn(new Value("corus:host", "localhost:33000"));
when(request.getValue("d")).thenReturn(new Value("d", "dist"));
when(request.getValue("v")).thenReturn(new Value("v", "version"));
when(request.getValue("backup", "0")).thenReturn(new Value("backup", "0"));
when(request.getValue("checksum-md5")).thenReturn(new Value("checksum-md5", "test-checksum"));
when(request.getValue("runScripts", "false")).thenReturn(new Value("backup", "0"));
when(request.getValue(eq("batchSize"), anyString())).thenReturn(new Value("batchSize", "0"));
when(request.getValue(eq("async"), anyString())).thenReturn(new Value("async", "false"));
when(request.getValue("minHosts", "1")).thenReturn(new Value("minHosts", "1"));
when(request.getValue("corus:name")).thenReturn(new Value("corus:name", "dist"));
when(request.getValue("corus:version")).thenReturn(new Value("corus:version", "1.0"));
when(request.getValue("rev")).thenReturn(new Value("rev", "previous"));
when(request.getValue("maxErrors", "0")).thenReturn(new Value("maxErrors", "0"));
when(request.getValue("async", "false")).thenReturn(new Value("async", "false"));
when(request.getValue("runDiagnostic", "false")).thenReturn(new Value("runDiagnostic", "false"));
when(request.getValue("diagnosticInterval", "false")).thenReturn(new Value("diagnosticInterval", "10"));
}
@Test
public void testDeployDistributionForCluster() throws Exception {
resource.deployDistributionForCluster(context);
verify(deployer).deployDistribution(eq("test"), any(DeployPreferences.class), any(ClusterInfo.class));
}
@Test
public void testDeployDistributionForCluster_async() throws Exception {
when(request.getValue(eq("async"), anyString())).thenReturn(new Value("async", "true"));
resource.deployDistributionForCluster(context);
verify(deployer, never()).deployDistribution(eq("test"), any(DeployPreferences.class), any(ClusterInfo.class));
verify(async).registerForExecution(any(AsyncTask.class));
}
@Test
public void testDeployDistributionForHost() throws Exception {
resource.deployDistributionForHost(context);
verify(deployer).deployDistribution(eq("test"), any(DeployPreferences.class), any(ClusterInfo.class));
}
@Test
public void testDeployDistributionForHost_async() throws Exception {
when(request.getValue(eq("async"), anyString())).thenReturn(new Value("async", "true"));
resource.deployDistributionForHost(context);
verify(deployer, never()).deployDistribution(eq("test"), any(DeployPreferences.class), any(ClusterInfo.class));
verify(async).registerForExecution(any(AsyncTask.class));
}
@Test
public void testUndeployDistributionForCluster() throws Exception {
resource.undeployDistributionForCluster(context);
verify(deployer).undeployDistribution(any(DistributionCriteria.class), any(UndeployPreferences.class), any(ClusterInfo.class));
}
@Test
public void testUndeployDistributionForHost() throws Exception {
resource.undeployDistributionForCluster(context);
verify(deployer).undeployDistribution(any(DistributionCriteria.class), any(UndeployPreferences.class), any(ClusterInfo.class));
}
@Test
public void testRollbackDistributionForCluster() throws Exception {
resource.rollbackDistributionForCluster(context);
verify(deployer).rollbackDistribution(eq("dist"), eq("1.0"), any(ClusterInfo.class));
}
@Test
public void testRollbackDistributionForCluster_async() throws Exception {
when(request.getValue(eq("async"), anyString())).thenReturn(new Value("async", "true"));
resource.rollbackDistributionForCluster(context);
verify(deployer, never()).rollbackDistribution(eq("dist"), eq("1.0"), any(ClusterInfo.class));
verify(async).registerForExecution(any(AsyncTask.class));
}
@Test
public void testRollbackDistributionForHost() throws Exception {
resource.rollbackDistributionForCluster(context);
verify(deployer).rollbackDistribution(eq("dist"), eq("1.0"), any(ClusterInfo.class));
}
@Test
public void testRollbackDistributionForHost_async() throws Exception {
when(request.getValue(eq("async"), anyString())).thenReturn(new Value("async", "true"));
resource.rollbackDistributionForCluster(context);
verify(deployer, never()).rollbackDistribution(eq("dist"), eq("1.0"), any(ClusterInfo.class));
verify(async).registerForExecution(any(AsyncTask.class));
}
}
| gpl-3.0 |
DarkSeraphim/FreeAutoMessage | src/com/j0ach1mmall3/freeautomessage/api/internal/storage/yaml/Config.java | 1837 | package com.j0ach1mmall3.freeautomessage.api.internal.storage.yaml;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Created by j0ach1mmall3 on 8:55 29/06/2015 using IntelliJ IDEA.
*/
public class Config {
private JavaPlugin plugin;
private String name;
public Config(String name, JavaPlugin plugin){
this.plugin = plugin;
this.name = name;
}
public FileConfiguration getConfig() {
return YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), name));
}
public void saveConfig(FileConfiguration config) {
try {
config.save(new File(plugin.getDataFolder(), name));
} catch(Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
public void reloadConfig() {
if(plugin.getResource(name) != null){
FileConfiguration config = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), name));
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(plugin.getResource(name));
config.setDefaults(defConfig);
}
}
public void saveDefaultConfig(){
File configfile = new File(plugin.getDataFolder(), name);
if (!configfile.exists()) {
plugin.saveResource(name, false);
}
}
public List<String> getKeys(String section){
List<String> keysList = new ArrayList<>();
Set<String> keys = getConfig().getConfigurationSection(section).getKeys(false);
for(String key : keys){
keysList.add(key);
}
return keysList;
}
}
| gpl-3.0 |
adofsauron/KEEL | src/keel/Algorithms/Discretizers/OneR/Opt.java | 2845 | /***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
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 keel.Algorithms.Discretizers.OneR;
import java.util.Arrays;
/**
* <p>
* This class represents the optimum class for a given explanatory value
* </p>
*
* <p>
* @author Written by Julián Luengo Martín 28/10/2008
* @version 0.1
* @since JDK 1.5
* </p>
*/
public class Opt {
double _value;
int count[];
int prior[];
boolean clean;
int max;
public Opt(){
_value = Double.NaN;
count = null;
clean = false;
max = -1;
}
/**
* Creates a new object with the given elements
* @param value the explanatory value
* @param numClasses the total number of different classes
*/
public Opt(double value,int numClasses){
_value = value;
count = new int[numClasses];
clean = false;
prior = new int[numClasses];
}
/**
* Sets the priority of the classes associated to this explanatory value (the less, the more priority)
* @param p array with the priority associated to each class
*/
public void setPrior(int p[]){
prior = Arrays.copyOf(p, p.length);
}
/**
* Increases the count for the class indicated
* @param index the class for which the count will be incremented by one
*/
public void countClass(int index){
count[index]++;
clean = false;
}
/**
* Computes the optimum class for the explanatory value
* @return the optimum class found
*/
public int getOptClass(){
if(!clean){
max = 0;
for(int i=1;i<count.length;i++){
if(count[i]>max)
max = i;
else if(prior[i]<prior[max])
max = i;
}
clean = true;
}
return max;
}
/**
* Gets the explanatory value associated
* @return the explanatory value associated
*/
public double getValue(){
return _value;
}
}
| gpl-3.0 |
LuoXiao-Wing/Tea-ALongStory | src/main/java/cloud/lemonslice/teastory/common/block/CatapultBoardBlock.java | 5664 | package cloud.lemonslice.teastory.common.block;
import cloud.lemonslice.silveroak.helper.VoxelShapeHelper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.SoundType;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particles.RedstoneParticleData;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.Random;
public class CatapultBoardBlock extends NormalHorizontalBlock
{
private static final VoxelShape SHAPE = VoxelShapeHelper.createVoxelShape(0, 0, 0, 16, 2, 16);
private static final BooleanProperty ENABLED = BlockStateProperties.ENABLED;
private final float motion;
public CatapultBoardBlock(float motion, String name, Properties properties)
{
super(properties, name);
this.setDefaultState(this.getStateContainer().getBaseState().with(HORIZONTAL_FACING, Direction.NORTH).with(ENABLED, false));
this.motion = motion;
}
@Override
public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos)
{
return true;
}
@Override
@SuppressWarnings("deprecation")
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context)
{
return SHAPE;
}
@Override
@SuppressWarnings("deprecation")
public boolean isValidPosition(BlockState state, IWorldReader worldIn, BlockPos pos)
{
return hasSolidSideOnTop(worldIn, pos.down());
}
@Override
@SuppressWarnings("deprecation")
public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos)
{
return !stateIn.isValidPosition(worldIn, currentPos) ? Blocks.AIR.getDefaultState() : super.updatePostPlacement(stateIn, facing, facingState, worldIn, currentPos, facingPos);
}
@Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder)
{
builder.add(HORIZONTAL_FACING, ENABLED);
}
@Override
@SuppressWarnings("deprecation")
public void tick(BlockState state, ServerWorld worldIn, BlockPos pos, Random random)
{
worldIn.setBlockState(pos, state.with(ENABLED, false), 2);
}
@OnlyIn(Dist.CLIENT)
public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand)
{
if (worldIn.isBlockPowered(pos))
{
double d0 = (double) pos.getX() + 0.5D + (rand.nextDouble() - 0.5D);
double d1 = (double) pos.getY() + 0.125D + (rand.nextDouble() - 0.5D) * 0.2D;
double d2 = (double) pos.getZ() + 0.5D + (rand.nextDouble() - 0.5D);
worldIn.addParticle(RedstoneParticleData.REDSTONE_DUST, d0, d1, d2, 0.0D, 0.0D, 0.0D);
}
}
@Override
@SuppressWarnings("deprecation")
public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit)
{
if (player.getHeldItem(handIn).getItem() == BlocksRegistry.BAMBOO_TRAY.asItem())
{
worldIn.setBlockState(pos, BlocksRegistry.STONE_CATAPULT_BOARD_WITH_TRAY.getDefaultState().with(HORIZONTAL_FACING, state.get(HORIZONTAL_FACING)));
SoundType soundtype = BlocksRegistry.BAMBOO_TRAY.getDefaultState().getSoundType(worldIn, pos, player);
worldIn.playSound(player, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F);
return ActionResultType.SUCCESS;
}
else
return ActionResultType.FAIL;
}
@Override
@SuppressWarnings("deprecation")
public void onEntityCollision(BlockState state, World worldIn, BlockPos pos, Entity entityIn)
{
if (worldIn.isBlockPowered(pos))
{
worldIn.setBlockState(pos, state.with(ENABLED, true), 2);
worldIn.getPendingBlockTicks().scheduleTick(pos, this, 5);
Vector3d vec3d;
switch (state.get(HORIZONTAL_FACING))
{
case SOUTH:
{
vec3d = new Vector3d(0, motion, -motion);
break;
}
case EAST:
{
vec3d = new Vector3d(-motion, motion, 0);
break;
}
case WEST:
{
vec3d = new Vector3d(motion, motion, 0);
break;
}
default:
vec3d = new Vector3d(0, motion, motion);
}
entityIn.fallDistance = 0.0F;
entityIn.setMotion(vec3d);
}
}
}
| gpl-3.0 |
huangxianyuan/hxyFrame | frame-activiti/src/main/java/com/hxy/activiti/service/ExtendActTasklogService.java | 1056 | package com.hxy.activiti.service;
import com.hxy.activiti.entity.ExtendActTasklogEntity;
import java.util.List;
import java.util.Map;
/**
*
*
* @author hxy
* @email huangxianyuan@gmail.com
* @date 2017-08-04 11:46:48
*/
public interface ExtendActTasklogService {
ExtendActTasklogEntity queryObject(String id);
List<ExtendActTasklogEntity> queryList(Map<String, Object> map);
int queryTotal(Map<String, Object> map);
void save(ExtendActTasklogEntity extendActTasklog);
void update(ExtendActTasklogEntity extendActTasklog);
void delete(String id);
void deleteBatch(String[] ids);
/**
* 根据任务id 更改日志
* @param extendActTasklogEntity
* @return
*/
int updateByTaskId(ExtendActTasklogEntity extendActTasklogEntity);
/**
* 转办任务时更新任务日志,有可能会存在多次转办,就会产生多条任务日志,所有这里用 taskId+appAction为空 作唯一
* @param extendActTasklogEntity
* @return
*/
int updateByTaskIdOpinion(ExtendActTasklogEntity extendActTasklogEntity);
}
| gpl-3.0 |
MythicTeam/Mythical-Mobs | mythology/proxy/CommonProxy.java | 279 | package mythology.proxy;
import mythology.handlers.KeyHandler;
import net.minecraft.client.model.ModelBiped;
public class CommonProxy {
public KeyHandler keyHandler;
public void RenderEntity(){
}
public static ModelBiped getArmorModel(int id) {
return null;
}
}
| gpl-3.0 |
PrepETNA2015/OSCL-Reload | Sources/checker-src/checker/matching/DiffAnalysis.java | 14172 | /**
*
* Copyright (C) 2007 Lauri Koponen
*
* This program is free software; you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*/
package checker.matching;
import java.util.ArrayList;
import java.util.HashMap;
import checker.Log;
import checker.LogEntry;
import checker.license.Tag;
/**
* License match analysis. This class analyzes the results of matching comments
* to a license template with the Diff class.
*
* @author Lauri Koponen
*/
public class DiffAnalysis {
protected static final int MAX_TAG_LENGTH = 20;
/**
* The Diff that is being analyzed.
*/
private Diff diff;
/**
* Words from the license template.
*/
private WordList templatewords;
/**
* Words from the comments that are being matched.
*/
private WordList textwords;
/**
* List of tags from license.
*/
private ArrayList<Tag> licenseTags;
/**
* Match percentage, in range 0.0 .. 1.0.
*/
private float match;
ArrayList<MatchPosition> foundPositions = null;
/**
* Get the match percentage.
*
* @return match percentage, in range 0.0 .. 1.0.
*/
public float getMatchPr() {
return match;
}
/**
* Get the found matches.
*
* @return list of found matches
*/
public ArrayList<MatchPosition> getPositions() {
return foundPositions;
}
/**
* List of found tags.
*/
public HashMap<String, String> tags;
/**
* List of tag starting word indices.
*/
public HashMap<String, Integer> tagStart;
/**
* Class constructor that analyzes the Diff result. Results are stored in
* the DiffAnalysis instance and can be retrieved with member methods.
*
* @param diff
* Diff to be analysed
* @param template
* license template used in matching
* @param text
* comments used in matching
* @param minMatch
* Minimum matched substring length,
* percentage of total length in range 0.0 .. 1.0
*/
public DiffAnalysis(Diff diff, WordList template, WordList text,
double minMatch, ArrayList<Tag> tags) {
this.diff = diff;
this.templatewords = template;
this.textwords = text;
this.licenseTags = tags;
this.tags = new HashMap<String, String>();
this.tagStart = new HashMap<String, Integer>();
analysis(minMatch);
}
/**
* Save tag in tag list.
*
* @param tag Name of tag
* @param value Value of tag
* @param i Index of first tag word
*/
private void storeTag(String tag, String value, int i) {
tags.put(tag, value);
tagStart.put(tag, new Integer(i));
Log.log(LogEntry.DEBUG, "Found tag '" + tag + "': " + value);
}
/**
* Scan text backwards to the beginning of a tag.
*
* @param i Position in source text
* @param oi Position in license template
* @return New position in source text or -1 if no tag was found
*/
private int scanTagBackward(int i, int oi)
{
/* diff.O[oi] is the "<tag>" and diff.N[i] is the last word of the tag value */
String tag = diff.O[oi];
StringBuffer sb = new StringBuffer();
int length = 0;
/* check for overflow */
if(oi - 1 < 0) return -1;
while((i >= 0) && (length < MAX_TAG_LENGTH)) {
if (diff.N[i].equals(diff.O[oi - 1])) {
storeTag(tag, sb.toString(), i + 1);
/* scanned one too far in loop */
return i + 1;
}
/* add this word to the tag */
if(length != 0)
sb.insert(0, ' '); /* words separated by spaces */
sb.insert(0, diff.N[i]);
i--;
length++;
}
/* could not find tag start */
return -1;
}
/**
* Scan text forwards to the end of a tag.
*
* @param i Position in source text
* @param oi Position in license template
* @return New position in source text or -1 if no tag was found
*/
private int scanTagForward(int i, int oi)
{
/* diff.O[oi] is the "<tag>" and diff.N[i] is the first word of the tag value */
int si = i; /* tag start index */
String tag = diff.O[oi];
StringBuffer sb = new StringBuffer();
int length = 0;
/* check for overflow */
if(oi + 1 >= diff.O.length) return -1;
while((i < diff.N.length) && (length < MAX_TAG_LENGTH)) {
if (diff.N[i].equals(diff.O[oi + 1])) {
storeTag(tag, sb.toString(), si);
/* scanned one too far in loop */
return i - 1;
}
/* add this word to the tag */
if(length != 0)
sb.append(' '); /* words separated by spaces */
sb.append(diff.N[i]);
i++;
length++;
}
/* could not find tag end */
return -1;
}
/**
* Scan backwards from a found it at diff.N[i] and locate the real
* start of the matching substring.
*
* @param i Found location of a match. diff.NA[i] must be an Integer
* @param oi Index in diff.O[] that matches diff.NA[i]
* @return
*/
private int[] scanBackwards(int i, int oi) {
boolean dobreak = false;
/* index in diff.O[] */
//int oi = ((Integer) diff.NA[i]).intValue();
do {
/* check we're not going out of bounds */
if((i == 0) || (oi == 0)) break;
if(isTag(diff.O[oi - 1])) {
int tag_start = scanTagBackward(i - 1, oi - 1);
if(tag_start < 0) {
/* tag scan failed */
break;
}
/* go backwards past the tag */
i = tag_start - 1;
oi -= 2;
} else {
dobreak = true;
}
/* check again we're not going out of bounds */
if((i == 0) || (oi == 0)) break;
/* scan as long as words match */
while (diff.O[oi - 1].equals(diff.N[i - 1])) {
/* scan backwards */
oi--;
i--;
dobreak = false;
if((oi == 0) || (i == 0)) {
/* can't go past beginning of text */
dobreak = true;
break;
}
}
} while(!dobreak);
int result[] = new int[2];
result[0] = i;
result[1] = oi;
return result;
}
/**
* Check if a word is a tag. If the word starts with a "<" and ends
* with ">", it is assumed to be a tag.
*
* @param word Word to check
* @return True if the word is a tag, false otherwise
*/
private boolean isTag(String word) {
/* TODO: add tag checking from license info */
if (word.startsWith("<") && word.endsWith(">")) {
for (Tag t : licenseTags) {
if (t.getId().equals(word)) {
return true;
}
}
return true;
}
return false;
}
/**
* Find match positions, fill foundPositions.
*
* @param minMatch Minimum match percentage, in range 0..1
*/
private void findPositions(double minMatch) {
int i;
ArrayList<MatchPosition> pos = new ArrayList<MatchPosition>();
/* position in source code */
int start_row = -1, start_col = 0;
int end_row = 0, end_col = 0;
/* position in template */
int t_start_row = -1, t_start_col = 0;
int t_end_row = 0, t_end_col = 0;
/* found match length in words */
int match_length = 0;
int best_length = 0;
int total_length = 0; /* total number of matched words */
MatchPosition bestMatch = null;
boolean continuous = false;
int oi = 0; /* found index in diff.O[] */
for (i = 0; i < diff.N.length - 1; i++) {
/* if two sequential words are indices to sequential
* word in template, found a match.
*/
if (diff.NA[i] instanceof Integer
&& (diff.NA[i + 1] instanceof Integer)) {
int oi1 = ((Integer) diff.NA[i]).intValue();
int oi2 = ((Integer) diff.NA[i + 1]).intValue();
if ((oi1 + 1) == oi2) {
/* words are sequential in template */
if (start_row == -1) {
int start[] = scanBackwards(i, oi1);
/* start a new match */
start_row = textwords.row.get(start[0]);
start_col = textwords.col.get(start[0]);
t_start_row = templatewords.row.get(start[1]);
t_start_col = templatewords.col.get(start[1]);
/* count the words already found in new match */
/* using the template is safer for counting words */
match_length = (oi1 + 1 - start[1]);
}
/* current found match ends at the next word */
match_length++;
continuous = true;
oi = oi2;
} else {
/* this and next word not sequential in template,
* match ends.
*/
continuous = false;
}
}
/* or if foundNoneUnique is set, also consider first instance of each word */
else if (diff.foundNoneUnique
&& ((diff.NA[i] instanceof Diff.SymbolTableEntry)
&& (((Diff.SymbolTableEntry)diff.NA[i]).nwno == i)
&& (diff.NA[i + 1] instanceof Diff.SymbolTableEntry)
&& (((Diff.SymbolTableEntry)diff.NA[i + 1])).nwno == i + 1)) {
int oi1 =((Diff.SymbolTableEntry)diff.NA[i]).olno;
int oi2 =((Diff.SymbolTableEntry)diff.NA[i + 1]).olno;
if ((oi1 + 1) == oi2) {
/* words are sequential in template */
if (start_row == -1) {
int start[] = scanBackwards(i, oi1);
/* start a new match */
start_row = textwords.row.get(start[0]);
start_col = textwords.col.get(start[0]);
t_start_row = templatewords.row.get(start[1]);
t_start_col = templatewords.col.get(start[1]);
/* count the words already found in new match */
/* using the template is safer for counting words */
match_length = (oi1 + 1 - start[1]);
}
/* current found match ends at the next word */
match_length++;
continuous = true;
oi = oi2;
} else {
/* this and next word not sequential in template,
* match ends.
*/
continuous = false;
}
} else if(continuous && (oi + 1 < diff.O.length) && isTag(diff.O[oi + 1])) {
/* continous match and the template expects a tag */
int new_i = scanTagForward(i + 1, oi + 1);
if(new_i == -1) {
/* tag search failed, match ends */
continuous = false;
} else {
i = new_i;
oi += 2;
/* current found match ends at the next word */
match_length += 2;
continuous = true;
}
} else if(continuous && (diff.NA[i + 1] instanceof Diff.SymbolTableEntry)) {
/* found a word that has more than one hit in either the
* source text or the template.
*/
/* if the words match, continue found hit */
if((oi + 1 < diff.O.length) && diff.N[i + 1].equals(diff.O[oi + 1])) {
/* words match */
oi++;
match_length++;
} else {
/* words don't match */
continuous = false;
}
}
if(!continuous) {
if (start_row != -1) {
/* found match ends */
end_row = textwords.row.get(i);
end_col = textwords.col.get(i)
+ textwords.len.get(i) - 1;
t_end_row = templatewords.row.get(oi);
t_end_col = templatewords.col.get(oi)
+ templatewords.len.get(oi) - 1;
total_length += match_length;
if (((double)match_length / (double)diff.O.length)
>= minMatch) {
int findInd = -1;
int ii = 0;
for (MatchPosition m : pos) {
if (m.getStartLine() == start_row &&
m.getStartCol() == start_col) {
findInd = ii;
}
ii++;
}
if (findInd != -1) {
total_length -= pos.get(findInd).getNumWords();
pos.set(findInd, new MatchPosition(start_row, start_col,
end_row, end_col, t_start_row, t_start_col,
t_end_row, t_end_col, 0, match_length));
}
else {
pos.add(new MatchPosition(start_row, start_col,
end_row, end_col, t_start_row, t_start_col,
t_end_row, t_end_col, 0, match_length));
}
}
if(match_length > best_length) {
best_length = match_length;
bestMatch = new MatchPosition(start_row, start_col,
end_row, end_col, t_start_row, t_start_col,
t_end_row, t_end_col, 0, match_length);
}
start_row = -1;
}
}
}
/* check if a match is still open */
if (start_row != -1) {
end_row = textwords.row.get(i);
end_col = textwords.col.get(i)
+ textwords.len.get(i) - 1;
t_end_row = templatewords.row.get(oi);
t_end_col = templatewords.col.get(oi)
+ templatewords.len.get(oi) - 1;
if (((double)match_length / (double)diff.O.length)
>= minMatch) {
int findInd = -1;
int ii = 0;
for (MatchPosition m : pos) {
if (m.getStartLine() == start_row &&
m.getStartCol() == start_col) {
findInd = ii;
}
ii++;
}
if (findInd != -1) {
total_length -= pos.get(findInd).getNumWords();
pos.set(findInd, new MatchPosition(start_row, start_col,
end_row, end_col, t_start_row, t_start_col,
t_end_row, t_end_col, 0, match_length));
}
else {
pos.add(new MatchPosition(start_row, start_col,
end_row, end_col, t_start_row, t_start_col,
t_end_row, t_end_col, 0, match_length));
}
}
total_length += match_length;
if(match_length > best_length)
best_length = match_length;
}
foundPositions = pos;
}
/**
* Perform analysis on the produced diff. This function calculates the
* results of the matching.
*
* @param minMatch Minimum match percentage in range 0..1.
*/
private void analysis(double minMatch) {
findPositions(minMatch);
/* Calculate match% = (length of longest match) / (length of template) */
int maxpts = diff.O.length;
int best = 0;
int total_length = 0;
for (MatchPosition pos : foundPositions) {
if(pos.getNumWords() > best)
best = pos.getNumWords();
total_length += pos.getNumWords();
pos.setOrigMatchLength(pos.getNumWords());
}
/* match% is the length of the best match compared to maximum length */
match = (float) best / (float) maxpts;
}
}
| gpl-3.0 |
spdeepak/docgen | src/main/java/com/docgen/crypt/DecryptDocument.java | 2631 | package com.docgen.crypt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import org.apache.commons.io.IOUtils;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Deepak
*
*/
public class DecryptDocument {
private static final Logger logger = LoggerFactory.getLogger(DecryptDocument.class);
/**
* @param docxFileStream
* docx File or any XML Based file
* @param password
* Password
* @return {@link InputStream} of the decrypted file
*/
public InputStream docxIn(InputStream docxFileStream, String password) {
try {
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(docxFileStream);
EncryptionInfo encryptionInfo = new EncryptionInfo(poifsFileSystem);
Decryptor decryptor = Decryptor.getInstance(encryptionInfo);
if (!decryptor.verifyPassword(password)) {
logger.error("Wrong Password");
return null;
}
InputStream inputStream = decryptor.getDataStream(poifsFileSystem);
return inputStream;
} catch (IOException e) {
logger.error("Error with the input file" + e);
} catch (GeneralSecurityException e) {
logger.error("Wrong Password: " + e);
}
return null;
}
/**
* @param docxFileStream docx File or any XML Based file
* @param password Password
* @return {@link OutputStream} of the decrypted file
*/
public OutputStream docxOut(InputStream docxFileStream, String password) {
try {
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(docxFileStream);
EncryptionInfo encryptionInfo = new EncryptionInfo(poifsFileSystem);
Decryptor decryptor = Decryptor.getInstance(encryptionInfo);
if (!decryptor.verifyPassword(password)) {
logger.error("Wrong Password");
return null;
}
InputStream inputStream = decryptor.getDataStream(poifsFileSystem);
String extension = URLConnection.guessContentTypeFromStream(inputStream);
File outputFile = new File(inputStream.toString() + extension);
IOUtils.copyLarge(inputStream, new FileOutputStream(outputFile));
inputStream.close();
extension = null;
outputFile.deleteOnExit();
return new FileOutputStream(outputFile);
} catch (IOException e) {
logger.error("Error with the input file" + e);
} catch (GeneralSecurityException e) {
logger.error("Wrong Password: " + e);
}
return null;
}
}
| gpl-3.0 |
Boukefalos/jlibitunes | src/main/java/com/dt/iTunesController/ITSource.java | 1596 | package com.dt.iTunesController;
import com.jacob.com.Dispatch;
/**
* Represents an entry in the Source list (music library, CD, device, etc.).
* You can retrieve all the sources using <code>iTunes.getSources()</code>.
* @author <a href="mailto:steve@dot-totally.co.uk">Steve Eyre</a>
* @version 0.2
*/
public class ITSource extends ITObject {
public ITSource(Dispatch d) {
super(d);
}
/**
* Returns the kind of the source.
* @return Returns the kind of the source.
*/
public ITSourceKind getKind() {
return ITSourceKind.values()[Dispatch.get(object, "Kind").getInt()];
}
/**
* Returns the total size of the source, if it has a fixed size.
* @return Returns the total size of the source, if it has a fixed size.
*/
public double getCapacity() {
return Dispatch.get(object, "Capacity").getDouble();
}
/**
* Returns the free space on the source, if it has a fixed size.
* @return Returns the free space on the source, if it has a fixed size.
*/
public double getFreespace() {
return Dispatch.get(object, "Freespace").getDouble();
}
/**
* Returns a collection containing the playlists in this source.
* The source's primary playlist is always the first playlist in the
* collection.
* @return Collection of IITPlaylist objects.
*/
public ITPlaylistCollection getPlaylists() {
Dispatch playlists = Dispatch.get(object, "Playlists").toDispatch();
return new ITPlaylistCollection(playlists);
}
}
| gpl-3.0 |
Elhuyar/Bilakit | src/elhuyar/bilakit/EustaggerLemmatizer.java | 4761 |
/*
* Copyright 2015 Elhuyar Fundazioa
This file is part of Bilakit.
Bilakit 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.
Bilakit 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 Bilakit. If not, see <http://www.gnu.org/licenses/>.
*/
package elhuyar.bilakit;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.Normalizer;
import java.util.regex.Pattern;
import java.io.File;
import java.io.FileWriter;
/**
* This class implements a socket based client for using Eustagger Basque POS tagger.
*/
public class EustaggerLemmatizer {
class FreelingSocketClient {
private static final String ENCODING = "UTF8";
private final static int BUF_SIZE = 2048;
Socket socket;
DataInputStream bufferEntrada;
DataOutputStream bufferSalida;
FreelingSocketClient(String host,int port) {
try
{
socket = new Socket (host, port);
socket.setSoLinger (true, 10);
socket.setKeepAlive(true);
socket.setSoTimeout(0);
bufferEntrada = new DataInputStream (socket.getInputStream());
bufferSalida = new DataOutputStream (socket.getOutputStream());
}
catch (Exception e){
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {}
}
}
public String processSegment(String text) throws IOException {
writeMessage(bufferSalida, text,ENCODING);
StringBuffer sb = readMessage(bufferEntrada);
return sb.toString().trim();
}
void writeMessage(java.io.DataOutputStream out, String message, String encoding)
throws IOException
{
out.write(message.getBytes(encoding));
out.write(0);
out.flush();
}
void close() throws IOException {
socket.close();
}
private synchronized StringBuffer readMessage(DataInputStream bufferEntrada)
throws IOException {
byte[] buffer = new byte[BUF_SIZE];
int bl = 0;
StringBuffer sb = new StringBuffer();
//messages ends with
do {
bl = bufferEntrada.read(buffer, 0, BUF_SIZE);
if(bl>0) sb.append(new String (buffer,0,bl));
}while (bl>0 && buffer[bl-1]!=0);
return sb;
}
}
public EustaggerLemmatizer(){}
public String getLemmatizedText(String text){
text = Normalizer.normalize(text, Normalizer.Form.NFD);
text = text.replaceAll("\n", " ").trim();
Pattern pattern = Pattern.compile("[^a-zA-Z0-9 .,;:\\-_()\"\'¿?¡!]+");
text = pattern.matcher(text).replaceAll("");
if ((text.length() > 0) && (text.substring(text.length()-1).equals("-"))){
if (text.length() > 1){
text = text.substring(0, text.length()-2);
}
else{
text = "";
}
}
if (text.length() > 0){
System.out.println("### Eustagger text IN length =>[" + text.length() + "]");
String text_lemmatized="";
FreelingSocketClient server = null;
try {
File tempFile = File.createTempFile("BasqueLemmatizer",null);
BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
out.write(text);
out.close();
server = new FreelingSocketClient("localhost", 50010);
text_lemmatized = server.processSegment(tempFile.getAbsolutePath());
tempFile.delete();
server.close();
}
catch(IOException e) {
try {
server.close();
} catch (IOException e1) {}
}
//retrieve only lemmas
String text_lemmatizedpost="";
//split \n
String lines[] = text_lemmatized.split("\\n");
//for
for (int i = 0; i < lines.length; i++)
{
// split and get lemma
if (lines[i].contentEquals(""))
{
text_lemmatizedpost=text_lemmatizedpost+"\n";
}
else
{
String fields[] = lines[i].split(" ");
text_lemmatizedpost=text_lemmatizedpost+" "+fields[1];
}
}
text_lemmatizedpost=text_lemmatizedpost.replaceAll("Hiru~", " ");
text_lemmatizedpost=text_lemmatizedpost.replaceAll("\\*edun", " ");
text_lemmatizedpost=text_lemmatizedpost.replaceAll("\\*ezan", " ");
//System.out.println("### Eustagger OUT: " + text_lemmatizedpost + "\n");
//System.out.println("### Eustagger text OUT length =>[" + text_lemmatized.length() + "]");
return text_lemmatizedpost;
}
return "";
}
} | gpl-3.0 |
buddystudio/BuddyPP | src/util/io/BDCodeReader.java | 1296 | /*
* 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 util.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author gsh
*/
public class BDCodeReader
{
public BDCodeReader()
{
}
/**
* Read file by lines.s
*/
public static String readFileByLines(String fileName) throws UnsupportedEncodingException, FileNotFoundException, IOException
{
String CodeTxt = "";
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
String line = null;
while ((line = br.readLine()) != null)
{
lines.add(line);
CodeTxt += (line + "\\n");
}
br.close();
return CodeTxt;
}
}
| gpl-3.0 |
Cubiccl/Command-Generator | src/fr/cubiccl/generator/gui/component/panel/advancement/PanelAdvancementSelection.java | 4210 | package fr.cubiccl.generator.gui.component.panel.advancement;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.SwingConstants;
import fr.cubi.cubigui.CTextArea;
import fr.cubiccl.generator.CommandGenerator;
import fr.cubiccl.generator.gameobject.advancements.Advancement;
import fr.cubiccl.generator.gameobject.registries.ObjectSaver;
import fr.cubiccl.generator.gui.Dialogs;
import fr.cubiccl.generator.gui.component.CScrollPane;
import fr.cubiccl.generator.gui.component.button.CGButton;
import fr.cubiccl.generator.gui.component.label.CGLabel;
import fr.cubiccl.generator.gui.component.panel.CGPanel;
import fr.cubiccl.generator.gui.component.panel.utils.ListListener;
import fr.cubiccl.generator.gui.component.panel.utils.PanelObjectList;
import fr.cubiccl.generator.utils.FileUtils;
import fr.cubiccl.generator.utils.Settings;
public class PanelAdvancementSelection extends CGPanel implements ActionListener, ListListener<Advancement>
{
private static final long serialVersionUID = 458787504307263140L;
private CGButton buttonGenerate, buttonLoad, buttonImport;
public PanelObjectList<Advancement> list;
public PanelAdvancementSelection()
{
super();
this.setBorder(BorderFactory.createLoweredSoftBevelBorder());
CGLabel l = new CGLabel("advancement.list");
l.setHorizontalAlignment(SwingConstants.CENTER);
l.setFont(l.getFont().deriveFont(Font.BOLD, 30));
GridBagConstraints gbc = this.createGridBagLayout();
gbc.gridwidth = 3;
gbc.anchor = GridBagConstraints.CENTER;
this.add(l, gbc);
++gbc.gridy;
this.add(this.list = new PanelObjectList<Advancement>(null, (String) null, Advancement.class), gbc);
++gbc.gridy;
gbc.gridwidth = 1;
this.add(this.buttonGenerate = new CGButton("command.generate"), gbc);
++gbc.gridx;
this.add(this.buttonLoad = new CGButton("advancement.load"), gbc);
++gbc.gridx;
this.add(this.buttonImport = new CGButton("command.import"), gbc);
this.buttonGenerate.setFont(this.buttonGenerate.getFont().deriveFont(Font.BOLD, 20));
this.buttonGenerate.addActionListener(this);
this.buttonLoad.addActionListener(this);
this.buttonImport.addActionListener(this);
this.list.setValues(ObjectSaver.advancements.list());
this.list.addListListener(this);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (this.list.selectedIndex() != -1 && e.getSource() == this.buttonGenerate) CommandGenerator.generateAdvancement();
else if (e.getSource() == this.buttonLoad)
{
CGPanel p = new CGPanel();
p.setLayout(new BorderLayout());
p.add(new CGLabel("advancement.load.description"), BorderLayout.NORTH);
CTextArea area = new CTextArea("");
area.setEditable(true);
CScrollPane sc = new CScrollPane(area);
sc.setPreferredSize(new Dimension(400, 200));
p.add(sc, BorderLayout.CENTER);
if (!Dialogs.showConfirmDialog(p)) return;
CommandGenerator.parseAdvancement(area.getText());
} else if (e.getSource() == this.buttonImport)
{
JFileChooser fileChooser = new JFileChooser(Settings.getSetting(Settings.LAST_FOLDER));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION)
{
File f = fileChooser.getSelectedFile();
Settings.setSetting(Settings.LAST_FOLDER, f.getParentFile().getPath());
CommandGenerator.parseAdvancement(FileUtils.readFile(f));
}
}
}
@Override
public void onAddition(int index, Advancement object)
{
ObjectSaver.advancements.addObject(object);
}
@Override
public void onChange(int index, Advancement object)
{}
@Override
public void onDeletion(int index, Advancement object)
{
ObjectSaver.advancements.remove(object);
}
public Advancement selectedAdvancement()
{
return ObjectSaver.advancements.find(this.list.getSelectedValue());
}
@Override
public void setEnabled(boolean enabled)
{
super.setEnabled(enabled);
this.buttonGenerate.setEnabled(enabled);
this.buttonLoad.setEnabled(enabled);
this.list.setEnabled(enabled);
}
}
| gpl-3.0 |
aiQon/crowdshare | src/org/servalproject/ui/help/AboutScreen.java | 1589 | /* Copyright (C) 2012 The Serval Project
*
* This file is part of Serval Software (http://www.servalproject.org)
*
* Serval Software 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 source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.servalproject.ui.help;
import org.servalproject.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* help screens - main interface guide
*/
public class AboutScreen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutview);
// Donate Screen
Button btnDonate = (Button) this.findViewById(R.id.btnDonate);
btnDonate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
AboutScreen.this.startActivity(new Intent(AboutScreen.this,
DonateScreen.class));
}
});
}
}
| gpl-3.0 |
TerrenceMiao/camel-spring | src/main/java/org/paradise/itext/qrcode/MatrixUtil.java | 22186 | /*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.paradise.itext.qrcode;
/**
* @author satorux@google.com (Satoru Takabayashi) - creator
* @author dswitkin@google.com (Daniel Switkin) - ported from C++
* @since 5.0.2
*/
public final class MatrixUtil {
private MatrixUtil() {
// do nothing
}
private static final int[][] POSITION_DETECTION_PATTERN = {
{1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 1},
{1, 0, 1, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1},
};
private static final int[][] HORIZONTAL_SEPARATION_PATTERN = {
{0, 0, 0, 0, 0, 0, 0, 0},
};
private static final int[][] VERTICAL_SEPARATION_PATTERN = {
{0}, {0}, {0}, {0}, {0}, {0}, {0},
};
private static final int[][] POSITION_ADJUSTMENT_PATTERN = {
{1, 1, 1, 1, 1},
{1, 0, 0, 0, 1},
{1, 0, 1, 0, 1},
{1, 0, 0, 0, 1},
{1, 1, 1, 1, 1},
};
// From Appendix E. Table 1, JIS0510X:2004 (p 71). The table was double-checked by komatsu.
private static final int[][] POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE = {
{-1, -1, -1, -1, -1, -1, -1}, // Version 1
{6, 18, -1, -1, -1, -1, -1}, // Version 2
{6, 22, -1, -1, -1, -1, -1}, // Version 3
{6, 26, -1, -1, -1, -1, -1}, // Version 4
{6, 30, -1, -1, -1, -1, -1}, // Version 5
{6, 34, -1, -1, -1, -1, -1}, // Version 6
{6, 22, 38, -1, -1, -1, -1}, // Version 7
{6, 24, 42, -1, -1, -1, -1}, // Version 8
{6, 26, 46, -1, -1, -1, -1}, // Version 9
{6, 28, 50, -1, -1, -1, -1}, // Version 10
{6, 30, 54, -1, -1, -1, -1}, // Version 11
{6, 32, 58, -1, -1, -1, -1}, // Version 12
{6, 34, 62, -1, -1, -1, -1}, // Version 13
{6, 26, 46, 66, -1, -1, -1}, // Version 14
{6, 26, 48, 70, -1, -1, -1}, // Version 15
{6, 26, 50, 74, -1, -1, -1}, // Version 16
{6, 30, 54, 78, -1, -1, -1}, // Version 17
{6, 30, 56, 82, -1, -1, -1}, // Version 18
{6, 30, 58, 86, -1, -1, -1}, // Version 19
{6, 34, 62, 90, -1, -1, -1}, // Version 20
{6, 28, 50, 72, 94, -1, -1}, // Version 21
{6, 26, 50, 74, 98, -1, -1}, // Version 22
{6, 30, 54, 78, 102, -1, -1}, // Version 23
{6, 28, 54, 80, 106, -1, -1}, // Version 24
{6, 32, 58, 84, 110, -1, -1}, // Version 25
{6, 30, 58, 86, 114, -1, -1}, // Version 26
{6, 34, 62, 90, 118, -1, -1}, // Version 27
{6, 26, 50, 74, 98, 122, -1}, // Version 28
{6, 30, 54, 78, 102, 126, -1}, // Version 29
{6, 26, 52, 78, 104, 130, -1}, // Version 30
{6, 30, 56, 82, 108, 134, -1}, // Version 31
{6, 34, 60, 86, 112, 138, -1}, // Version 32
{6, 30, 58, 86, 114, 142, -1}, // Version 33
{6, 34, 62, 90, 118, 146, -1}, // Version 34
{6, 30, 54, 78, 102, 126, 150}, // Version 35
{6, 24, 50, 76, 102, 128, 154}, // Version 36
{6, 28, 54, 80, 106, 132, 158}, // Version 37
{6, 32, 58, 84, 110, 136, 162}, // Version 38
{6, 26, 54, 82, 110, 138, 166}, // Version 39
{6, 30, 58, 86, 114, 142, 170}, // Version 40
};
// Type info cells at the left top corner.
private static final int[][] TYPE_INFO_COORDINATES = {
{8, 0},
{8, 1},
{8, 2},
{8, 3},
{8, 4},
{8, 5},
{8, 7},
{8, 8},
{7, 8},
{5, 8},
{4, 8},
{3, 8},
{2, 8},
{1, 8},
{0, 8},
};
// From Appendix D in JISX0510:2004 (p. 67)
private static final int VERSION_INFO_POLY = 0x1f25; // 1 1111 0010 0101
// From Appendix C in JISX0510:2004 (p.65).
private static final int TYPE_INFO_POLY = 0x537;
private static final int TYPE_INFO_MASK_PATTERN = 0x5412;
// Set all cells to -1. -1 means that the cell is empty (not set yet).
//
// JAVAPORT: We shouldn't need to do this at all. The code should be rewritten to begin encoding
// with the ByteMatrix initialized all to zero.
public static void clearMatrix(ByteMatrix matrix) {
matrix.clear((byte) -1);
}
// Build 2D matrix of QR Code from "dataBits" with "ecLevel", "version" and "getMaskPattern". On
// success, store the result in "matrix" and return true.
public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version,
int maskPattern, ByteMatrix matrix) throws WriterException {
clearMatrix(matrix);
embedBasicPatterns(version, matrix);
// Type information appear with any version.
embedTypeInfo(ecLevel, maskPattern, matrix);
// Version info appear if version >= 7.
maybeEmbedVersionInfo(version, matrix);
// Data should be embedded at end.
embedDataBits(dataBits, maskPattern, matrix);
}
// Embed basic patterns. On success, modify the matrix and return true.
// The basic patterns are:
// - Position detection patterns
// - Timing patterns
// - Dark dot at the left bottom corner
// - Position adjustment patterns, if need be
public static void embedBasicPatterns(int version, ByteMatrix matrix) throws WriterException {
// Let's get started with embedding big squares at corners.
embedPositionDetectionPatternsAndSeparators(matrix);
// Then, embed the dark dot at the left bottom corner.
embedDarkDotAtLeftBottomCorner(matrix);
// Position adjustment patterns appear if version >= 2.
maybeEmbedPositionAdjustmentPatterns(version, matrix);
// Timing patterns should be embedded after position adj. patterns.
embedTimingPatterns(matrix);
}
// Embed type information. On success, modify the matrix.
public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix)
throws WriterException {
BitVector typeInfoBits = new BitVector();
makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits);
for (int i = 0; i < typeInfoBits.size(); ++i) {
// Place bits in LSB to MSB order. LSB (least significant bit) is the last value in
// "typeInfoBits".
int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i);
// Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46).
int x1 = TYPE_INFO_COORDINATES[i][0];
int y1 = TYPE_INFO_COORDINATES[i][1];
matrix.set(x1, y1, bit);
if (i < 8) {
// Right top corner.
int x2 = matrix.getWidth() - i - 1;
int y2 = 8;
matrix.set(x2, y2, bit);
} else {
// Left bottom corner.
int x2 = 8;
int y2 = matrix.getHeight() - 7 + (i - 8);
matrix.set(x2, y2, bit);
}
}
}
// Embed version information if need be. On success, modify the matrix and return true.
// See 8.10 of JISX0510:2004 (p.47) for how to embed version information.
public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix) throws WriterException {
if (version < 7) { // Version info is necessary if version >= 7.
return; // Don't need version info.
}
BitVector versionInfoBits = new BitVector();
makeVersionInfoBits(version, versionInfoBits);
int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0.
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 3; ++j) {
// Place bits in LSB (least significant bit) to MSB order.
int bit = versionInfoBits.at(bitIndex);
bitIndex--;
// Left bottom corner.
matrix.set(i, matrix.getHeight() - 11 + j, bit);
// Right bottom corner.
matrix.set(matrix.getHeight() - 11 + j, i, bit);
}
}
}
// Embed "dataBits" using "getMaskPattern". On success, modify the matrix and return true.
// For debugging purposes, it skips masking process if "getMaskPattern" is -1.
// See 8.7 of JISX0510:2004 (p.38) for how to embed data bits.
public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix)
throws WriterException {
int bitIndex = 0;
int direction = -1;
// Start from the right bottom cell.
int x = matrix.getWidth() - 1;
int y = matrix.getHeight() - 1;
while (x > 0) {
// Skip the vertical timing pattern.
if (x == 6) {
x -= 1;
}
while (y >= 0 && y < matrix.getHeight()) {
for (int i = 0; i < 2; ++i) {
int xx = x - i;
// Skip the cell if it's not empty.
if (!isEmpty(matrix.get(xx, y))) {
continue;
}
int bit;
if (bitIndex < dataBits.size()) {
bit = dataBits.at(bitIndex);
++bitIndex;
} else {
// Padding bit. If there is no bit left, we'll fill the left cells with 0, as described
// in 8.4.9 of JISX0510:2004 (p. 24).
bit = 0;
}
// Skip masking if mask_pattern is -1.
if (maskPattern != -1) {
if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) {
bit ^= 0x1;
}
}
matrix.set(xx, y, bit);
}
y += direction;
}
direction = -direction; // Reverse the direction.
y += direction;
x -= 2; // Move to the left.
}
// All bits should be consumed.
if (bitIndex != dataBits.size()) {
throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size());
}
}
// Return the position of the most significant bit set (to one) in the "value". The most
// significant bit is position 32. If there is no bit set, return 0. Examples:
// - findMSBSet(0) => 0
// - findMSBSet(1) => 1
// - findMSBSet(255) => 8
public static int findMSBSet(int value) {
int numDigits = 0;
while (value != 0) {
value >>>= 1;
++numDigits;
}
return numDigits;
}
// Calculate BCH (Bose-Chaudhuri-Hocquenghem) code for "value" using polynomial "poly". The BCH
// code is used for encoding type information and version information.
// Example: Calculation of version information of 7.
// f(x) is created from 7.
// - 7 = 000111 in 6 bits
// - f(x) = x^2 + x^2 + x^1
// g(x) is given by the standard (p. 67)
// - g(x) = x^12 + x^11 + x^10 + x^9 + x^8 + x^5 + x^2 + 1
// Multiply f(x) by x^(18 - 6)
// - f'(x) = f(x) * x^(18 - 6)
// - f'(x) = x^14 + x^13 + x^12
// Calculate the remainder of f'(x) / g(x)
// x^2
// __________________________________________________
// g(x) )x^14 + x^13 + x^12
// x^14 + x^13 + x^12 + x^11 + x^10 + x^7 + x^4 + x^2
// --------------------------------------------------
// x^11 + x^10 + x^7 + x^4 + x^2
//
// The remainder is x^11 + x^10 + x^7 + x^4 + x^2
// Encode it in binary: 110010010100
// The return value is 0xc94 (1100 1001 0100)
//
// Since all coefficients in the polynomials are 1 or 0, we can do the calculation by bit
// operations. We don't care if cofficients are positive or negative.
public static int calculateBCHCode(int value, int poly) {
// If poly is "1 1111 0010 0101" (version info poly), msbSetInPoly is 13. We'll subtract 1
// from 13 to make it 12.
int msbSetInPoly = findMSBSet(poly);
value <<= msbSetInPoly - 1;
// Do the division business using exclusive-or operations.
while (findMSBSet(value) >= msbSetInPoly) {
value ^= poly << (findMSBSet(value) - msbSetInPoly);
}
// Now the "value" is the remainder (i.e. the BCH code)
return value;
}
// Make bit vector of type information. On success, store the result in "bits" and return true.
// Encode error correction level and mask pattern. See 8.9 of
// JISX0510:2004 (p.45) for details.
public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits)
throws WriterException {
if (!QRCode.isValidMaskPattern(maskPattern)) {
throw new WriterException("Invalid mask pattern");
}
int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
bits.appendBits(typeInfo, 5);
int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY);
bits.appendBits(bchCode, 10);
BitVector maskBits = new BitVector();
maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15);
bits.xor(maskBits);
if (bits.size() != 15) { // Just in case.
throw new WriterException("should not happen but we got: " + bits.size());
}
}
// Make bit vector of version information. On success, store the result in "bits" and return true.
// See 8.10 of JISX0510:2004 (p.45) for details.
public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException {
bits.appendBits(version, 6);
int bchCode = calculateBCHCode(version, VERSION_INFO_POLY);
bits.appendBits(bchCode, 12);
if (bits.size() != 18) { // Just in case.
throw new WriterException("should not happen but we got: " + bits.size());
}
}
// Check if "value" is empty.
private static boolean isEmpty(int value) {
return value == -1;
}
// Check if "value" is valid.
private static boolean isValidValue(int value) {
return (value == -1 || // Empty.
value == 0 || // Light (white).
value == 1); // Dark (black).
}
private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException {
// -8 is for skipping position detection patterns (size 7), and two horizontal/vertical
// separation patterns (size 1). Thus, 8 = 7 + 1.
for (int i = 8; i < matrix.getWidth() - 8; ++i) {
int bit = (i + 1) % 2;
// Horizontal line.
if (!isValidValue(matrix.get(i, 6))) {
throw new WriterException();
}
if (isEmpty(matrix.get(i, 6))) {
matrix.set(i, 6, bit);
}
// Vertical line.
if (!isValidValue(matrix.get(6, i))) {
throw new WriterException();
}
if (isEmpty(matrix.get(6, i))) {
matrix.set(6, i, bit);
}
}
}
// Embed the lonely dark dot at left bottom corner. JISX0510:2004 (p.46)
private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException {
if (matrix.get(8, matrix.getHeight() - 8) == 0) {
throw new WriterException();
}
matrix.set(8, matrix.getHeight() - 8, 1);
}
private static void embedHorizontalSeparationPattern(int xStart, int yStart,
ByteMatrix matrix) throws WriterException {
// We know the width and height.
if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) {
throw new WriterException("Bad horizontal separation pattern");
}
for (int x = 0; x < 8; ++x) {
if (!isEmpty(matrix.get(xStart + x, yStart))) {
throw new WriterException();
}
matrix.set(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]);
}
}
private static void embedVerticalSeparationPattern(int xStart, int yStart,
ByteMatrix matrix) throws WriterException {
// We know the width and height.
if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) {
throw new WriterException("Bad vertical separation pattern");
}
for (int y = 0; y < 7; ++y) {
if (!isEmpty(matrix.get(xStart, yStart + y))) {
throw new WriterException();
}
matrix.set(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]);
}
}
// Note that we cannot unify the function with embedPositionDetectionPattern() despite they are
// almost identical, since we cannot write a function that takes 2D arrays in different sizes in
// C/C++. We should live with the fact.
private static void embedPositionAdjustmentPattern(int xStart, int yStart,
ByteMatrix matrix) throws WriterException {
// We know the width and height.
if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) {
throw new WriterException("Bad position adjustment");
}
for (int y = 0; y < 5; ++y) {
for (int x = 0; x < 5; ++x) {
if (!isEmpty(matrix.get(xStart + x, yStart + y))) {
throw new WriterException();
}
matrix.set(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]);
}
}
}
private static void embedPositionDetectionPattern(int xStart, int yStart,
ByteMatrix matrix) throws WriterException {
// We know the width and height.
if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) {
throw new WriterException("Bad position detection pattern");
}
for (int y = 0; y < 7; ++y) {
for (int x = 0; x < 7; ++x) {
if (!isEmpty(matrix.get(xStart + x, yStart + y))) {
throw new WriterException();
}
matrix.set(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]);
}
}
}
// Embed position detection patterns and surrounding vertical/horizontal separators.
private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException {
// Embed three big squares at corners.
int pdpWidth = POSITION_DETECTION_PATTERN[0].length;
// Left top corner.
embedPositionDetectionPattern(0, 0, matrix);
// Right top corner.
embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix);
// Left bottom corner.
embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix);
// Embed horizontal separation patterns around the squares.
int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].length;
// Left top corner.
embedHorizontalSeparationPattern(0, hspWidth - 1, matrix);
// Right top corner.
embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth,
hspWidth - 1, matrix);
// Left bottom corner.
embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix);
// Embed vertical separation patterns around the squares.
int vspSize = VERTICAL_SEPARATION_PATTERN.length;
// Left top corner.
embedVerticalSeparationPattern(vspSize, 0, matrix);
// Right top corner.
embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix);
// Left bottom corner.
embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize,
matrix);
}
// Embed position adjustment patterns if need be.
private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix)
throws WriterException {
if (version < 2) { // The patterns appear if version >= 2
return;
}
int index = version - 1;
int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index];
int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].length;
for (int i = 0; i < numCoordinates; ++i) {
for (int j = 0; j < numCoordinates; ++j) {
int y = coordinates[i];
int x = coordinates[j];
if (x == -1 || y == -1) {
continue;
}
// If the cell is unset, we embed the position adjustment pattern here.
if (isEmpty(matrix.get(x, y))) {
// -2 is necessary since the x/y coordinates point to the center of the pattern, not the
// left top corner.
embedPositionAdjustmentPattern(x - 2, y - 2, matrix);
}
}
}
}
}
| gpl-3.0 |
ErhardSiegl/jboss-examples | call-ejb-between-deployments/call-ejb/src/main/java/at/gepardec/ejbtest/remote_ejb/ConverterBean.java | 546 | package at.gepardec.ejbtest.remote_ejb;
import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.ejb.Remote;
import javax.ejb.Stateless;
@Resources( {
@Resource(name="java:/services/StringConverter", lookup="java:module/ConverterBean"),
})
@Stateless
@Remote(StringConverter.class)
public class ConverterBean implements StringConverter{
@Override
public String toLowerCase(String input) {
return input.toLowerCase();
}
@Override
public String toUpperCase(String input) {
return input.toUpperCase();
}
}
| gpl-3.0 |
cuong0906/test | app/src/org/runnerup/export/format/GoogleFitData.java | 22410 | /*
* Copyright (C) 2014 paradix@10g.pl
*
* 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.runnerup.export.format;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Pair;
import org.runnerup.R;
import org.runnerup.export.GoogleFitSynchronizer;
import org.runnerup.export.util.SyncHelper;
import org.runnerup.util.JsonWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.runnerup.common.util.Constants.DB;
public class GoogleFitData {
public static final int SECONDS_TO_MILLIS = 1000;
public static final int MICRO_TO_NANOS = 1000000;
public static final int SECONDS_TO_NANOS = 1000000000;
private static final Map<Integer, Integer> ACTIVITY_TYPE;
static {
Map<Integer, Integer> aMap = new HashMap<Integer, Integer>();
aMap.put(DB.ACTIVITY.SPORT_RUNNING, 8);
aMap.put(DB.ACTIVITY.SPORT_BIKING, 1);
ACTIVITY_TYPE = Collections.unmodifiableMap(aMap);
}
private static final Map<DataSourceType, List<DataTypeField>> DATA_TYPE_FIELDS;
static {
Map<DataSourceType, List<DataTypeField>> fieldsMap = new HashMap<DataSourceType, List<DataTypeField>>();
List<DataTypeField> fields = new ArrayList<DataTypeField>();
Pair<String, String> floatPoint = Pair.create("floatPoint", "fpVal");
Pair<String, String> integer = Pair.create("integer", "intVal");
fields.add(new DataTypeField("activity", integer, DB.ACTIVITY.SPORT));
fieldsMap.put(DataSourceType.ACTIVITY_SEGMENT, fields);
fields = new ArrayList<DataTypeField>();
fields.add(new DataTypeField("bpm", floatPoint, DB.LOCATION.HR));
fieldsMap.put(DataSourceType.ACTIVITY_HEARTRATE, fields);
fields = new ArrayList<DataTypeField>();
fields.add(new DataTypeField("latitude", floatPoint, DB.LOCATION.LATITUDE));
fields.add(new DataTypeField("longitude", floatPoint, DB.LOCATION.LONGITUDE));
fields.add(new DataTypeField("accuracy", floatPoint, DB.LOCATION.ACCURANCY));
fields.add(new DataTypeField("altitude", floatPoint, DB.LOCATION.ALTITUDE));
fieldsMap.put(DataSourceType.ACTIVITY_LOCATION, fields);
fields = new ArrayList<DataTypeField>();
fields.add(new DataTypeField("speed", floatPoint, DB.LOCATION.SPEED));
fieldsMap.put(DataSourceType.ACTIVITY_SPEED, fields);
fields = new ArrayList<DataTypeField>();
fields.add(new DataTypeField("activity", integer, DB.ACTIVITY.SPORT));
fields.add(new DataTypeField("duration", integer, DB.ACTIVITY.TIME));
fields.add(new DataTypeField("num_segments", integer, "1"));
fieldsMap.put(DataSourceType.ACTIVITY_SUMMARY, fields);
fields = new ArrayList<DataTypeField>();
fields.add(new DataTypeField("average", floatPoint, "AVG(" + DB.LOCATION.HR + ")"));
fields.add(new DataTypeField("max", floatPoint, "MAX(" + DB.LOCATION.HR + ")"));
fields.add(new DataTypeField("min", floatPoint, "MIN(" + DB.LOCATION.HR + ")"));
fieldsMap.put(DataSourceType.HEARTRATE_SUMMARY, fields);
fields = new ArrayList<DataTypeField>();
fields.add(new DataTypeField("low_latitude", floatPoint, "MIN(" + DB.LOCATION.LATITUDE + ")"));
fields.add(new DataTypeField("high_latitude", floatPoint, "MAX(" + DB.LOCATION.LATITUDE + ")"));
fields.add(new DataTypeField("low_longitude", floatPoint, "MIN(" + DB.LOCATION.LONGITUDE + ")"));
fields.add(new DataTypeField("high_longitude", floatPoint, "MAX(" + DB.LOCATION.LONGITUDE + ")"));
fieldsMap.put(DataSourceType.LOCATION_SUMMARY, fields);
fields = new ArrayList<DataTypeField>();
fields.add(new DataTypeField("average", floatPoint, "AVG(" + DB.LOCATION.SPEED + ")"));
fields.add(new DataTypeField("max", floatPoint, "MAX(" + DB.LOCATION.SPEED + ")"));
fields.add(new DataTypeField("min", floatPoint, "MIN(" + DB.LOCATION.SPEED + ")"));
fieldsMap.put(DataSourceType.SPEED_SUMMARY, fields);
DATA_TYPE_FIELDS = Collections.unmodifiableMap(fieldsMap);
}
private final Context mContext;
private final String mProjectId;
private SQLiteDatabase mDB = null;
public GoogleFitData(final SQLiteDatabase db, String project, Context ctx) {
this.mDB = db;
this.mProjectId = project;
this.mContext = ctx;
}
public final String getProjectId() {
return mProjectId;
}
public final SQLiteDatabase getDB() {
return mDB;
}
public final List<DataSourceType> getActivityDataSourceTypes(long activityId) {
List<DataSourceType> neededSources = new ArrayList<DataSourceType>();
String[] pColumns = {DB.LOCATION.TIME};
// First we export the location
Cursor cursor = getDB().query(DB.LOCATION.TABLE, pColumns,
DB.LOCATION.ACTIVITY + " = " + activityId + " AND " + DB.LOCATION.LATITUDE + " IS NOT NULL", null, null, null,
null);
if (cursor.getCount() > 0) {
neededSources.add(DataSourceType.ACTIVITY_LOCATION);
neededSources.add(DataSourceType.LOCATION_SUMMARY);
}
// Than if present the heart rate
cursor = getDB().query(DB.LOCATION.TABLE, pColumns,
DB.LOCATION.ACTIVITY + " = " + activityId + " AND " + DB.LOCATION.HR + " IS NOT NULL", null, null, null,
null);
if (cursor.getCount() > 0) {
neededSources.add(DataSourceType.ACTIVITY_HEARTRATE);
neededSources.add(DataSourceType.HEARTRATE_SUMMARY);
}
// Next will be the speed
cursor = getDB().query(DB.LOCATION.TABLE, pColumns,
DB.LOCATION.ACTIVITY + " = " + activityId + " AND " + DB.LOCATION.SPEED + " IS NOT NULL", null, null, null,
null);
if (cursor.getCount() > 0) {
neededSources.add(DataSourceType.ACTIVITY_SPEED);
neededSources.add(DataSourceType.SPEED_SUMMARY);
}
// At last the segments and summary
neededSources.add(DataSourceType.ACTIVITY_SEGMENT);
neededSources.add(DataSourceType.ACTIVITY_SUMMARY);
return neededSources;
}
public final void exportDataSource(DataSourceType type, Writer writer) {
JsonWriter w = new JsonWriter(writer);
try {
w.beginObject();
w.name("dataStreamId").value(type.getDataStreamId(this));
w.name("dataStreamName").value(type.getDataName());
w.name("type").value(type.SOURCE_TYPE);
w.name("dataType");
w.beginObject();
w.name("name").value(type.getDataType());
w.name("field");
w.beginArray();
fillFieldArray(type, w);
w.endArray();
w.endObject();
w.name("application");
addApplicationObject(w);
w.endObject();
System.out.println("Creating new dataSource: " + type.getDataStreamId(this));
} catch (IOException e) {
e.printStackTrace();
}
}
public final String exportTypeData(DataSourceType source, long activityId, StringWriter w) {
String requestUrl = "";
switch (source) {
case ACTIVITY_SEGMENT:
requestUrl = exportActivitySegments(source, activityId, w);
return requestUrl;
case ACTIVITY_SUMMARY:
requestUrl = exportActivitySummary(source, activityId, w);
return requestUrl;
case ACTIVITY_LOCATION:
case ACTIVITY_HEARTRATE:
case ACTIVITY_SPEED:
case LOCATION_SUMMARY:
case HEARTRATE_SUMMARY:
case SPEED_SUMMARY:
requestUrl = exportSourceDataPoints(source, activityId, w);
return requestUrl;
}
return requestUrl;
}
private String exportActivitySegments(DataSourceType source, long activityId, StringWriter writer) {
String[] pColumns = {
DB.ACTIVITY.START_TIME, DB.ACTIVITY.TIME, DB.ACTIVITY.SPORT
};
Cursor cursor = getDB().query(DB.ACTIVITY.TABLE, pColumns, "_id = " + activityId, null, null, null, null);
cursor.moveToFirst();
//time as nanos
long startTime = cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.START_TIME)) * SECONDS_TO_NANOS;
long endTime = (cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.START_TIME)) + cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.TIME))) * SECONDS_TO_NANOS;
JsonWriter w = new JsonWriter(writer);
try {
w.beginObject();
w.name("minStartTimeNs").value(startTime);
w.name("maxEndTimeNs").value(endTime);
w.name("dataSourceId").value(source.getDataStreamId(this));
w.name("point");
w.beginArray();
//export points
w.beginObject();
w.name("startTimeNanos").value(startTime);
w.name("endTimeNanos").value(endTime);
w.name("dataTypeName").value(source.getDataType());
w.name("originDataSourceId").value(source.getDataStreamId(this));
w.name("value");
w.beginArray();
w.beginObject();
w.name("intVal").value(ACTIVITY_TYPE.get(cursor.getInt(2)));
w.endObject();
w.endArray();
w.name("rawTimestampNanos").value(startTime);
w.name("computationTimeMillis").value(System.currentTimeMillis());
w.endObject();
//end export points
w.endArray();
w.endObject();
} catch (IOException e) {
e.printStackTrace();
}
return getDataSetURLSuffix(source, startTime, endTime);
}
private String exportSourceDataPoints(DataSourceType source, long activityId, StringWriter writer) {
ArrayList<String> pColumns = new ArrayList<String>();
pColumns.add("MIN(" + DB.LOCATION.TIME + ") AS MIN");
pColumns.add("MAX(" + DB.LOCATION.TIME + ")");
Cursor minMaxTime = getDB().query(DB.LOCATION.TABLE, pColumns.toArray(new String[pColumns.size()]), DB.LOCATION.ACTIVITY + " = " + activityId, null, null, null, null);
minMaxTime.moveToFirst();
pColumns = new ArrayList<String>();
pColumns.add(DB.LOCATION.TIME);
List<DataTypeField> fields = DATA_TYPE_FIELDS.get(source);
for (DataTypeField field : fields) {
pColumns.add(field.getColumn());
}
Cursor cursor = getDB().query(DB.LOCATION.TABLE, pColumns.toArray(new String[pColumns.size()]), DB.LOCATION.ACTIVITY + " = " + activityId, null, null, null, null);
cursor.moveToFirst();
long startTime = minMaxTime.getLong(0) * MICRO_TO_NANOS;
long endTime = minMaxTime.getLong(1) * MICRO_TO_NANOS;
JsonWriter w = new JsonWriter(writer);
try {
w.beginObject();
w.name("minStartTimeNs").value(startTime);
w.name("maxEndTimeNs").value(endTime);
w.name("dataSourceId").value(source.getDataStreamId(this));
w.name("point");
w.beginArray();
//export points
do {
w.beginObject();
w.name("startTimeNanos").value(cursor.getLong(cursor.getColumnIndex(DB.LOCATION.TIME)) * MICRO_TO_NANOS);
if (!cursor.isLast()) {
cursor.moveToNext();
w.name("endTimeNanos").value(cursor.getLong(cursor.getColumnIndex(DB.LOCATION.TIME)) * MICRO_TO_NANOS);
cursor.moveToPrevious();
} else {
w.name("endTimeNanos").value(endTime);
}
w.name("originDataSourceId").value(source.getDataStreamId(this)
);
w.name("dataTypeName").value(source.getDataType());
w.name("value");
w.beginArray();
writeDataPointValues(fields, cursor, w);
w.endArray();
w.name("rawTimestampNanos").value(cursor.getLong(cursor.getColumnIndex(DB.LOCATION.TIME)) * MICRO_TO_NANOS);
w.name("computationTimeMillis").value(System.currentTimeMillis());
w.endObject();
} while (cursor.moveToNext());
//end export points
w.endArray();
w.endObject();
} catch (IOException e) {
e.printStackTrace();
}
return getDataSetURLSuffix(source, startTime, endTime);
}
private String exportActivitySummary(DataSourceType source, long activityId, StringWriter writer) {
ArrayList<String> pColumns = new ArrayList<String>();
pColumns.add(DB.ACTIVITY.START_TIME);
pColumns.add(DB.ACTIVITY.TIME);
List<DataTypeField> fields = DATA_TYPE_FIELDS.get(source);
for (DataTypeField field : fields) {
pColumns.add(field.getColumn());
}
Cursor cursor = getDB().query(DB.ACTIVITY.TABLE, pColumns.toArray(new String[pColumns.size()]), "_id = " + activityId, null, null, null, null);
cursor.moveToFirst();
//time as nanos
long startTime = cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.START_TIME)) * SECONDS_TO_NANOS;
long endTime = (cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.START_TIME)) + cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.TIME))) * SECONDS_TO_NANOS;
JsonWriter w = new JsonWriter(writer);
try {
w.beginObject();
w.name("minStartTimeNs").value(startTime);
w.name("maxEndTimeNs").value(endTime);
w.name("dataSourceId").value(source.getDataStreamId(this));
w.name("point");
w.beginArray();
//export points
w.beginObject();
w.name("startTimeNanos").value(startTime);
w.name("endTimeNanos").value(endTime);
w.name("dataTypeName").value(source.getDataType());
w.name("originDataSourceId").value(source.getDataStreamId(this));
w.name("value");
w.beginArray();
writeDataPointValues(fields, cursor, w);
w.endArray();
w.name("rawTimestampNanos").value(startTime);
w.name("computationTimeMillis").value(System.currentTimeMillis());
w.endObject();
//end export points
w.endArray();
w.endObject();
} catch (IOException e) {
e.printStackTrace();
}
return getDataSetURLSuffix(source, startTime, endTime);
}
private void addApplicationObject(JsonWriter w) throws IOException {
w.beginObject();
w.name("name").value(mContext.getString(R.string.app_name));
w.endObject();
}
private void fillFieldArray(DataSourceType type, JsonWriter w) throws IOException {
for (DataTypeField field : DATA_TYPE_FIELDS.get(type)) {
w.beginObject();
w.name(field.getNameValue().first).value(field.getNameValue().second);
w.name(field.getFormatSourceValue().first).value(field.getFormatSourceValue().second);
w.endObject();
}
}
private void writeDataPointValues(List<DataTypeField> fields, Cursor cursor, JsonWriter w) throws IOException {
for (DataTypeField field : fields) {
w.beginObject();
w.name(field.getFormatDataPointValue());
if (field.getFormatDataPointValue().equals("intVal")) {
w.value(cursor.getInt(cursor.getColumnIndex(field.getColumn())));
} else if (field.getFormatDataPointValue().equals("fpVal")) {
w.value(cursor.getDouble(cursor.getColumnIndex(field.getColumn())));
}
w.endObject();
}
}
public final String exportSession(long activityId, Writer writer) {
String[] pColumns = {
DB.ACTIVITY.START_TIME, DB.ACTIVITY.TIME, DB.ACTIVITY.COMMENT, DB.ACTIVITY.SPORT
};
Cursor cursor = getDB().query(DB.ACTIVITY.TABLE, pColumns, "_id = " + activityId, null, null, null, null);
cursor.moveToFirst();
long startTime = cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.START_TIME)) * SECONDS_TO_MILLIS;
long endTime = (cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.START_TIME)) + cursor.getLong(cursor.getColumnIndex(DB.ACTIVITY.TIME))) * SECONDS_TO_MILLIS;
String[] sports = mContext.getResources().getStringArray(R.array.sportEntries);
JsonWriter w = new JsonWriter(writer);
try {
w.beginObject();
w.name("id").value(mContext.getString(R.string.app_name) + "-" + startTime + "-" + endTime);
w.name("name").value((cursor.getInt(cursor.getColumnIndex(DB.ACTIVITY.SPORT)) == 0 ? sports[0] : sports[1]) + ": " + getWorkoutName(startTime));
w.name("description").value(cursor.getString(cursor.getColumnIndex(DB.ACTIVITY.COMMENT))); //comment
w.name("startTimeMillis").value(startTime);
w.name("endTimeMillis").value(endTime);
w.name("application");
addApplicationObject(w);
w.name("activityType").value(ACTIVITY_TYPE.get(cursor.getInt(cursor.getColumnIndex(DB.ACTIVITY.SPORT))));
w.endObject();
} catch (IOException e) {
e.printStackTrace();
}
return getSessionURLSuffix(startTime, endTime);
}
private String getWorkoutName(long startTime) {
return DateFormat.getInstance().format(new Date(startTime));
}
private String getDataSetURLSuffix(DataSourceType source, long startTime, long endTime) {
StringBuilder urlSuffix = new StringBuilder();
urlSuffix.append(GoogleFitSynchronizer.REST_DATASOURCE).append("/").append(SyncHelper.URLEncode(source.getDataStreamId(this))).append("/").append(GoogleFitSynchronizer.REST_DATASETS).append("/").append(startTime).append("-").append(endTime);
return urlSuffix.toString();
}
private String getSessionURLSuffix(long startTime, long endTime) {
StringBuilder urlSuffix = new StringBuilder();
urlSuffix.append(GoogleFitSynchronizer.REST_SESSIONS).append("/").append(mContext.getString(R.string.app_name)).append("-").append(startTime).append("-").append(endTime);
return urlSuffix.toString();
}
public enum DataSourceType {
ACTIVITY_SEGMENT("com.google.activity.segment", "runnerup_activity_segment"),
ACTIVITY_HEARTRATE("com.google.heart_rate.bpm", "runnerup_activity_heartrate"),
ACTIVITY_LOCATION("com.google.location.sample", "runnerup_activity_location"),
ACTIVITY_SPEED("com.google.speed", "runnerup_activity_speed"),
ACTIVITY_SUMMARY("com.google.activity.summary", "runnerup_activity_summary"),
HEARTRATE_SUMMARY("com.google.heart_rate.summary", "runnerup_heartrate_summary"),
LOCATION_SUMMARY("com.google.location.bounding_box", "runnerup_location_summary"),
SPEED_SUMMARY("com.google.speed.summary", "runnerup_speed_summary");
static final String SOURCE_TYPE = "derived";
private final String dataType;
private final String dataName;
DataSourceType(String type, String name) {
this.dataType = type;
this.dataName = name;
}
public String getDataStreamId(GoogleFitData gfd) {
StringBuilder streamId = new StringBuilder();
streamId.append(SOURCE_TYPE).append(":").append(getDataType()).append(":").append(getProjectId(gfd)).append(":").append(getDataName());
return streamId.toString();
}
public String getProjectId(GoogleFitData gfd) {
return gfd.getProjectId();
}
public String getDataType() {
return dataType;
}
public String getDataName() {
return dataName;
}
}
private static class DataTypeField {
static final String NAME = "name";
static final String FORMAT = "format";
private Pair<String, String> nameValue = null;
private Pair<String, String> formatSourceValue = null;
private String formatDataPointValue = null;
private String column = null;
public DataTypeField(String name, Pair<String, String> format, String dbColumn) {
this.setNameValue(Pair.create(NAME, name));
this.setFormatSourceValue(Pair.create(FORMAT, format.first));
this.setFormatDataPointValue(format.second);
this.setColumn(dbColumn);
}
public Pair<String, String> getNameValue() {
return nameValue;
}
public void setNameValue(Pair<String, String> value) {
this.nameValue = value;
}
public Pair<String, String> getFormatSourceValue() {
return formatSourceValue;
}
public void setFormatSourceValue(Pair<String, String> value) {
this.formatSourceValue = value;
}
public String getFormatDataPointValue() {
return formatDataPointValue;
}
public void setFormatDataPointValue(String value) {
this.formatDataPointValue = value;
}
public String getColumn() {
return column;
}
public void setColumn(String name) {
this.column = name;
}
}
} | gpl-3.0 |
Xilef11/MC-realTimeClock | src/main/java/xilef11/mc/realtimeclock/client/gui/GuiFactory.java | 1317 | /**
* the Real-Time Clock mod adds the system time to the Minecraft HUD.
* Copyright (C) 2015 Xilef11
* Licensed under the GNU General Public License version 3
*
* File created by Xilef11 on 2015-04-17
*/
package xilef11.mc.realtimeclock.client.gui;
import java.util.Set;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.fml.client.IModGuiFactory;
/**
* @author Xilef11
*
*/
public class GuiFactory implements IModGuiFactory {
/* (non-Javadoc)
* @see cpw.mods.fml.client.IModGuiFactory#initialize(net.minecraft.client.Minecraft)
*/
@Override
public void initialize(Minecraft minecraftInstance) {
//might not be used
}
/* (non-Javadoc)
* @see cpw.mods.fml.client.IModGuiFactory#runtimeGuiCategories()
*/
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() {
//Might not be used
return null;
}
/* (non-Javadoc)
* @see net.minecraftforge.fml.client.IModGuiFactory#hasConfigGui()
*/
@Override
public boolean hasConfigGui() {
return true;
}
/* (non-Javadoc)
* @see net.minecraftforge.fml.client.IModGuiFactory#createConfigGui(net.minecraft.client.gui.GuiScreen)
*/
@Override
public GuiScreen createConfigGui(GuiScreen parentScreen) {
return new ModGuiConfig(parentScreen);
}
}
| gpl-3.0 |
hungyao/context-toolkit | src/main/java/context/arch/intelligibility/presenters/QueryButton.java | 9356 | package context.arch.intelligibility.presenters;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import context.arch.discoverer.ComponentDescription;
import context.arch.enactor.Enactor;
import context.arch.intelligibility.Explainer;
import context.arch.intelligibility.Explanation;
import context.arch.intelligibility.query.AltQuery;
import context.arch.intelligibility.query.Query;
import context.arch.intelligibility.query.QueryListener;
import context.arch.intelligibility.query.WhatIfQuery;
public class QueryButton extends JButton implements ActionListener {
private static final long serialVersionUID = 857616575202708153L;
protected JPopupMenu popup;
private int x, y;
protected String context;
protected String value;
protected Enactor enactor;
protected ComponentDescription widgetState;
protected Map<String, Icon> contextIcons;
public QueryButton(String label,
ComponentDescription widgetState, Enactor enactor) {
this(label,
new HashMap<String, Icon>(), // empty icon map
widgetState, enactor);
}
public QueryButton(String label,
Map<String, Icon> contextIcons, // to map icons, if no icons, then just supply an empty map
ComponentDescription widgetState, Enactor enactor) {
super(label);
this.contextIcons = contextIcons;
this.widgetState = widgetState;
this.enactor = enactor;
this.context = enactor.getOutcomeName();
this.value = enactor.getOutcomeValue();
this.addActionListener(this); // listen to button press
this.popup = createPopupMenu();
this.x = 0;
this.y = (int)this.getPreferredSize().getHeight();
}
public void setWidgetState(ComponentDescription widgetState) {
this.widgetState = widgetState;
this.popup = createPopupMenu(); // re-create
}
protected JPopupMenu createPopupMenu() {
JPopupMenu popup = new JPopupMenu();
JMenu menu;
/*
* Preload outcome values for use in some queries
*/
List<String> outputValues = getOutputs();
// What
attachMenuItem(Query.QUESTION_WHAT, popup, this);
// Certainty
attachMenuItem(Query.QUESTION_CERTAINTY, popup, this);
// Inputs
attachMenuItem(Query.QUESTION_INPUTS + " Values", Query.QUESTION_INPUTS, popup, this);
/* ------------------------------------------------- */
popup.add(new JSeparator());
// When
attachMenuItem(Query.QUESTION_WHEN, popup, this);
// When Last
menu = new JMenu(AltQuery.QUESTION_WHEN_LAST);
popup.add(menu);
for (String outputValue : outputValues) {
attachMenuItem(outputValue, outputValue, AltQuery.QUESTION_WHEN_LAST, contextIcons.get(outputValue), menu, this);
}
// What At Time
attachMenuItem(Query.QUESTION_WHAT_AT_TIME + "...", Query.QUESTION_WHAT_AT_TIME, popup, this);
/* ------------------------------------------------- */
popup.add(new JSeparator());
// Why
attachMenuItem(Query.QUESTION_WHY, popup, this);
// Why Not
menu = new JMenu(AltQuery.QUESTION_WHY_NOT);
popup.add(menu);
for (String outputValue : outputValues) {
if (outputValue.equals(value)) { continue; } // skip if matches current value
attachMenuItem(outputValue, outputValue, AltQuery.QUESTION_WHY_NOT, contextIcons.get(outputValue), menu, this);
}
// How To
menu = new JMenu("How Does"); // AltQuery.QUESTION_HOW_TO
popup.add(menu);
for (String outputValue : outputValues) {
attachMenuItem(outputValue, outputValue, AltQuery.QUESTION_HOW_TO, contextIcons.get(outputValue), menu, this);
}
// What If
attachMenuItem(WhatIfQuery.QUESTION_WHAT_IF + "...", WhatIfQuery.QUESTION_WHAT_IF, popup, this);
/* ------------------------------------------------- */
popup.add(new JSeparator());
// Definition
attachMenuItem(Query.QUESTION_DEFINITION, popup, this);
// Rationale
attachMenuItem(Query.QUESTION_RATIONALE, popup, this);
// Outputs
attachMenuItem("Possible " + Query.QUESTION_OUTPUTS, Query.QUESTION_OUTPUTS, popup, this);
return popup;
}
/**
* To help preload outcome values for use in some queries
*/
protected List<String> getOutputs() {
Query query = new Query(Query.QUESTION_OUTPUTS, context, System.currentTimeMillis());
Explanation explanation = enactor.getExplainer().getExplanation(query);
List<String> outputValues = Explainer.outputsToLabels(explanation.getContent());
return outputValues;
}
public static JMenuItem attachMenuItem(String actionCommand, JComponent menu, ActionListener listener) {
return attachMenuItem(actionCommand, actionCommand, actionCommand, menu, listener);
}
public static JMenuItem attachMenuItem(String label, String actionCommand, JComponent menu, ActionListener listener) {
return attachMenuItem(label, actionCommand, actionCommand, menu, listener);
}
public static JMenuItem attachMenuItem(String label, String name, String actionCommand, JComponent menu, ActionListener listener) {
return attachMenuItem(label, name, actionCommand, null, menu, listener);
}
public static JMenuItem attachMenuItem(String label, String name, String actionCommand, Icon icon, JComponent menu, ActionListener listener) {
JMenuItem mi = new JMenuItem(label, icon);
mi.setName(name);
mi.setActionCommand(actionCommand);
menu.add(mi);
mi.addActionListener(listener);
String tooltipText = getQuestionDefinition(actionCommand); // may be null if actionCommand is not a question
mi.setToolTipText(tooltipText);
return mi;
}
private static final Map<String, String> questionDefinitions = new HashMap<String, String>(); // <question, definition>
static {
questionDefinitions.put(Query.QUESTION_WHAT, "The output value of the context.");
questionDefinitions.put(Query.QUESTION_CERTAINTY, "The uncertainty regarding the context value.");
questionDefinitions.put(Query.QUESTION_INPUTS, "The inputs (and their values) that La\u03BAsa used to determine the context value.");
questionDefinitions.put(Query.QUESTION_WHEN, "When the context was changed to the value shown.");
questionDefinitions.put(AltQuery.QUESTION_WHEN_LAST, "When the context last had the value chosen.");
questionDefinitions.put(Query.QUESTION_WHAT_AT_TIME, "The output value of the context at another chosen time.");
questionDefinitions.put(Query.QUESTION_WHY, "The reason why La\u03BAsa inferred the context value.");
questionDefinitions.put(AltQuery.QUESTION_WHY_NOT, "The reason why La\u03BAsa did not infer a particular context value.");
questionDefinitions.put(AltQuery.QUESTION_HOW_TO, "A facility for you to find a way to get La\u03BAsa to achive a certain context value.");
questionDefinitions.put(WhatIfQuery.QUESTION_WHAT_IF, "A facility for you to change input values to see how the context value would change.");
questionDefinitions.put(Query.QUESTION_DEFINITION, "The meaning or definition of the context term.");
questionDefinitions.put(Query.QUESTION_RATIONALE, "The rationale for considering this context.");
questionDefinitions.put(Query.QUESTION_OUTPUTS, "The possible output values that this context can have.");
}
private static String getQuestionDefinition(String question) {
// TODO: offload to an external file or Google Docs
return questionDefinitions.get(question);
}
/**
* To listen to when menu items are selected.
* It identifies the menu item and generates the appropriate query.
*/
@Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == this) {
popup.show(this, x, y);
}
else if (src instanceof JMenuItem) {
String question = evt.getActionCommand();
// System.out.println("QueryButton question = " + question);
long timestamp = System.currentTimeMillis();
/*
* Process query
*/
Query query;
if (question.equals(Query.QUESTION_WHAT)) {
query = new Query(question, context, timestamp);
}
else if (question.equals(Query.QUESTION_WHAT_AT_TIME)) {
// long time = TimePickerDialog.retrievePickedTimestamp(timestamp); // time being questioned about
// System.out.println("QuestionButton QUESTION_WHAT_AT_TIME time = " + time);
// // TODO
//
query = new Query(question, context, timestamp);
}
else if (question.equals(AltQuery.QUESTION_WHY_NOT) ||
question.equals(AltQuery.QUESTION_HOW_TO) ||
question.equals(AltQuery.QUESTION_WHEN_LAST)) {
String altValue = ((JComponent)evt.getSource()).getName();
query = new AltQuery(question, context, altValue, timestamp);
}
else { // unknown
query = new Query(question, context, timestamp);
}
notifyListeners(query);
}
}
/* -----------------------------------------------------------
* Query Listening code
* ----------------------------------------------------------- */
protected List<QueryListener> listeners = new ArrayList<QueryListener>();
public void addQueryListener(QueryListener listener) {
listeners.add(listener);
}
protected void notifyListeners(Query query) {
for (QueryListener listener : listeners) {
listener.queryInvoked(query);
}
}
}
| gpl-3.0 |
joshvote/ANVGL-Portal | src/main/java/org/auscope/portal/server/web/controllers/JobBuilderController.java | 53899 | package org.auscope.portal.server.web.controllers;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.auscope.portal.core.cloud.CloudJob;
import org.auscope.portal.core.cloud.ComputeType;
import org.auscope.portal.core.cloud.MachineImage;
import org.auscope.portal.core.cloud.StagedFile;
import org.auscope.portal.core.services.PortalServiceException;
import org.auscope.portal.core.services.cloud.CloudComputeService;
import org.auscope.portal.core.services.cloud.CloudComputeServiceAws;
import org.auscope.portal.core.services.cloud.CloudStorageService;
import org.auscope.portal.core.services.cloud.FileStagingService;
import org.auscope.portal.core.util.FileIOUtil;
import org.auscope.portal.core.util.TextUtil;
import org.auscope.portal.server.gridjob.FileInformation;
import org.auscope.portal.server.vegl.VEGLJob;
import org.auscope.portal.server.vegl.VEGLJobManager;
import org.auscope.portal.server.vegl.VEGLSeries;
import org.auscope.portal.server.vegl.VGLPollingJobQueueManager;
import org.auscope.portal.server.vegl.VGLQueueJob;
import org.auscope.portal.server.vegl.VglDownload;
import org.auscope.portal.server.vegl.VglMachineImage;
import org.auscope.portal.server.vegl.VglParameter.ParameterType;
import org.auscope.portal.server.web.security.ANVGLUser;
import org.auscope.portal.server.web.service.ANVGLProvenanceService;
import org.auscope.portal.server.web.service.ScmEntryService;
import org.auscope.portal.server.web.service.monitor.VGLJobStatusChangeHandler;
import org.auscope.portal.server.web.service.scm.Toolbox;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
/**
* Controller for the job submission view.
*
* @author Cihan Altinay
* @author Abdi Jama
* @author Josh Vote
*/
@Controller
public class JobBuilderController extends BaseCloudController {
/** Logger for this class */
private final Log logger = LogFactory.getLog(getClass());
private VEGLJobManager jobManager;
private FileStagingService fileStagingService;
private VGLPollingJobQueueManager vglPollingJobQueueManager;
private ScmEntryService scmEntryService;
private ANVGLProvenanceService anvglProvenanceService;
private String adminEmail = null;
private String defaultToolbox = null;
/**
* @return the adminEmail
*/
public String getAdminEmail() {
return adminEmail;
}
/**
* @param adminEmail the adminEmail to set
*/
public void setAdminEmail(String adminEmail) {
this.adminEmail = adminEmail;
}
public static final String STATUS_PENDING = "Pending";//VT:Request accepted by compute service
public static final String STATUS_ACTIVE = "Active";//VT:Running
public static final String STATUS_PROVISION = "Provisioning";//VT:awaiting response from compute service
public static final String STATUS_DONE = "Done";//VT:Job done
public static final String STATUS_DELETED = "Deleted";//VT:Job deleted
public static final String STATUS_UNSUBMITTED = "Saved";//VT:Job saved, fail to submit for whatever reason.
public static final String STATUS_INQUEUE = "In Queue";//VT: quota exceeded, placed in queue.
public static final String STATUS_ERROR = "ERROR";//VT:Exception in job processing.
public static final String STATUS_WALLTIME_EXCEEDED = "WALLTIME EXCEEDED";//VT:Walltime exceeded.
public static final String SUBMIT_DATE_FORMAT_STRING = "yyyyMMdd_HHmmss";
public static final String DOWNLOAD_SCRIPT = "vl-download.sh";
VGLJobStatusChangeHandler vglJobStatusChangeHandler;
@Autowired
public JobBuilderController(@Value("${HOST.portalAdminEmail}") String adminEmail,
@Value("${HOST.defaultToolbox}") String defaultToolbox,
VEGLJobManager jobManager, FileStagingService fileStagingService,
@Value("${vm.sh}") String vmSh, @Value("${vm-shutdown.sh}") String vmShutdownSh,
CloudStorageService[] cloudStorageServices,
CloudComputeService[] cloudComputeServices,VGLJobStatusChangeHandler vglJobStatusChangeHandler,
VGLPollingJobQueueManager vglPollingJobQueueManager, ScmEntryService scmEntryService,
ANVGLProvenanceService anvglProvenanceService) {
super(cloudStorageServices, cloudComputeServices,vmSh,vmShutdownSh);
this.jobManager = jobManager;
this.fileStagingService = fileStagingService;
this.cloudStorageServices = cloudStorageServices;
this.cloudComputeServices = cloudComputeServices;
this.vglJobStatusChangeHandler=vglJobStatusChangeHandler;
this.vglPollingJobQueueManager = vglPollingJobQueueManager;
this.scmEntryService = scmEntryService;
this.anvglProvenanceService = anvglProvenanceService;
this.adminEmail=adminEmail;
this.defaultToolbox = defaultToolbox;
}
/**
* Returns a JSON object containing a populated VEGLJob object.
*
* @param request The servlet request
* @param response The servlet response
*
* @return A JSON object with a data attribute containing a populated
* VEGLJob object and a success attribute.
*/
@RequestMapping("/secure/getJobObject.do")
public ModelAndView getJobObject(@RequestParam("jobId") String jobId, @AuthenticationPrincipal ANVGLUser user) {
try {
VEGLJob job = jobManager.getJobById(Integer.parseInt(jobId), user);
return generateJSONResponseMAV(true, Arrays.asList(job), "");
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
}
/**
* Utility for converting between a StagedFile and FileInformation object
* @param file
* @return
*/
private FileInformation stagedFileToFileInformation(StagedFile file) {
File internalFile = file.getFile();
long length = internalFile == null ? 0 : internalFile.length();
return new FileInformation(file.getName(), length, false, "");
}
/**
* Returns a JSON object containing an array of filenames and sizes which
* are currently in the job's stage in directory.
*
* @param request The servlet request
* @param response The servlet response
*
* @return A JSON object with a files attribute which is an array of
* filenames.
*/
@RequestMapping("/secure/listJobFiles.do")
public ModelAndView listJobFiles(@RequestParam("jobId") String jobId, @AuthenticationPrincipal ANVGLUser user) {
//Lookup our job
VEGLJob job = null;
try {
job = jobManager.getJobById(Integer.parseInt(jobId), user);
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
//Get our files
StagedFile[] files = null;
try {
files = fileStagingService.listStageInDirectoryFiles(job);
} catch (Exception ex) {
logger.error("Error listing job stage in directory", ex);
return generateJSONResponseMAV(false, null, "Error reading job stage in directory");
}
List<FileInformation> fileInfos = new ArrayList<FileInformation>();
for (StagedFile file : files) {
fileInfos.add(stagedFileToFileInformation(file));
}
return generateJSONResponseMAV(true, fileInfos, "");
}
/**
* Sends the contents of a input job file to the client.
*
* @param request The servlet request including a filename parameter
*
* @param response The servlet response receiving the data
*
* @return null on success or the joblist view with an error parameter on
* failure.
* @throws IOException
*/
@RequestMapping("/secure/downloadInputFile.do")
public ModelAndView downloadFile(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("jobId") String jobId,
@RequestParam("filename") String filename, @AuthenticationPrincipal ANVGLUser user) throws Exception {
//Lookup our job and download the specified files (any exceptions will return a HTTP 503)
VEGLJob job = jobManager.getJobById(Integer.parseInt(jobId), user);
fileStagingService.handleFileDownload(job, filename, response);
return null;
}
/**
* Processes a file upload request returning a JSON object which indicates
* whether the upload was successful and contains the filename and file
* size.
*
* @param request The servlet request
* @param response The servlet response containing the JSON data
*
* @return null
*/
@RequestMapping("/secure/uploadFile.do")
public ModelAndView uploadFile(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("jobId") String jobId, @AuthenticationPrincipal ANVGLUser user) {
//Lookup our job
VEGLJob job = null;
try {
job = jobManager.getJobById(Integer.parseInt(jobId), user);
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
//Handle incoming file
StagedFile file = null;
try {
file = fileStagingService.handleFileUpload(job, (MultipartHttpServletRequest) request);
} catch (Exception ex) {
logger.error("Error uploading file", ex);
return generateJSONResponseMAV(false, null, "Error uploading file");
}
FileInformation fileInfo = stagedFileToFileInformation(file);
//We have to use a HTML response due to ExtJS's use of a hidden iframe for file uploads
//Failure to do this will result in the upload working BUT the user will also get prompted
//for a file download containing the encoded response from this function (which we don't want).
return generateHTMLResponseMAV(true, Arrays.asList(fileInfo), "");
}
/**
* Deletes one or more uploaded files of the current job.
*
* @param request The servlet request
* @param response The servlet response
*
* @return A JSON object with a success attribute that indicates whether
* the files were successfully deleted.
*/
@RequestMapping("/secure/deleteFiles.do")
public ModelAndView deleteFiles(@RequestParam("jobId") String jobId,
@RequestParam("fileName") String[] fileNames, @AuthenticationPrincipal ANVGLUser user) {
VEGLJob job = null;
try {
job = jobManager.getJobById(Integer.parseInt(jobId), user);
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
for (String fileName : fileNames) {
boolean success = fileStagingService.deleteStageInFile(job, fileName);
logger.debug("Deleting " + fileName + " success=" + success);
}
return generateJSONResponseMAV(true, null, "");
}
/**
* Deletes one or more job downloads for the current job.
*
* @param request The servlet request
* @param response The servlet response
*
* @return A JSON object with a success attribute that indicates whether
* the downloads were successfully deleted.
*/
@RequestMapping("/secure/deleteDownloads.do")
public ModelAndView deleteDownloads(@RequestParam("jobId") String jobId,
@RequestParam("downloadId") Integer[] downloadIds, @AuthenticationPrincipal ANVGLUser user) {
VEGLJob job = null;
try {
job = jobManager.getJobById(Integer.parseInt(jobId), user);
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
//Delete the specified ID's
Iterator<VglDownload> dlIterator = job.getJobDownloads().iterator();
while (dlIterator.hasNext()) {
VglDownload dl = dlIterator.next();
for (Integer id : downloadIds) {
if (id.equals(dl.getId())) {
dlIterator.remove();
break;
}
}
}
try {
jobManager.saveJob(job);
} catch (Exception ex) {
logger.error("Error saving job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error saving job with id " + jobId);
}
return generateJSONResponseMAV(true, null, "");
}
/**
* Get status of the current job submission.
*
* @param request The servlet request
* @param response The servlet response
*
* @return A JSON object with a success attribute that indicates the status.
*
*/
@RequestMapping("/secure/getJobStatus.do")
public ModelAndView getJobStatus(@RequestParam("jobId") String jobId, @AuthenticationPrincipal ANVGLUser user) {
//Get our job
VEGLJob job = null;
try {
job = jobManager.getJobById(Integer.parseInt(jobId), user);
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
return generateJSONResponseMAV(true, job.getStatus(), "");
}
/**
* Cancels the current job submission. Called to clean up temporary files.
*
* @param request The servlet request
* @param response The servlet response
*
* @return null
*/
@RequestMapping("/secure/cancelSubmission.do")
public ModelAndView cancelSubmission(@RequestParam("jobId") String jobId, @AuthenticationPrincipal ANVGLUser user) {
//Get our job
VEGLJob job = null;
try {
job = jobManager.getJobById(Integer.parseInt(jobId), user);
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
boolean success = fileStagingService.deleteStageInDirectory(job);
return generateJSONResponseMAV(success, null, "");
}
/**
* This is for converting our String dates (frontend) to actual data objects (backend).
*
* Date format will match CloudJob.DATE_FORMAT, null/empty strings will be bound as NULL
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat(CloudJob.DATE_FORMAT), true);
binder.registerCustomEditor(Date.class, editor);
}
/**
* Given an entire job object this function attempts to save the specified job with ID
* to the internal database. If the Job DNE (or id is null), the job will be created and
* have it's staging area initialised and other creation specific tasks performed.
*
* @return A JSON object with a success attribute that indicates whether
* the job was successfully updated. The data object will contain the updated job
* @return
* @throws ParseException
*/
@RequestMapping("/secure/updateOrCreateJob.do")
public ModelAndView updateOrCreateJob(@RequestParam(value="id", required=false) Integer id, //The integer ID if not specified will trigger job creation
@RequestParam(value="name", required=false) String name,
@RequestParam(value="description", required=false) String description,
@RequestParam(value="seriesId", required=false) Integer seriesId,
@RequestParam(value="computeServiceId", required=false) String computeServiceId,
@RequestParam(value="computeVmId", required=false) String computeVmId,
@RequestParam(value="computeTypeId", required=false) String computeTypeId,
@RequestParam(value="storageServiceId", required=false) String storageServiceId,
@RequestParam(value="registeredUrl", required=false) String registeredUrl,
@RequestParam(value="emailNotification", required=false) boolean emailNotification,
@RequestParam(value="walltime", required=false) Integer walltime,
HttpServletRequest request,
@AuthenticationPrincipal ANVGLUser user) throws ParseException {
//Get our job
VEGLJob job = null;
try {
//If we have an ID - look up the job, otherwise create a job
if (id == null) {
//Job creation involves a fair bit of initialisation on the server
job = initialiseVEGLJob(request.getSession(), user);
} else {
job = jobManager.getJobById(id, user);
}
} catch (AccessDeniedException e) {
throw e;
} catch (Exception ex) {
logger.error(String.format("Error creating/fetching job with id %1$s", id), ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + id);
}
//Update our job from the request parameters
job.setSeriesId(seriesId);
job.setName(name);
job.setDescription(description);
job.setComputeVmId(computeVmId);
job.setComputeInstanceType(computeTypeId);
job.setEmailNotification(emailNotification);
job.setWalltime(walltime);
//Updating the storage service means changing the base key
if (storageServiceId != null) {
CloudStorageService css = getStorageService(storageServiceId);
if (css == null) {
logger.error(String.format("Error fetching storage service with id %1$s", storageServiceId));
return generateJSONResponseMAV(false, null, "Storage service does not exist");
}
job.setStorageServiceId(storageServiceId);
job.setStorageBaseKey(css.generateBaseKey(job));
} else {
job.setStorageServiceId(null);
job.setStorageBaseKey(null);
}
//Dont allow the user to specify a cloud compute service that DNE
// Updating the compute service means updating the dev keypair
if (computeServiceId != null) {
CloudComputeService ccs = getComputeService(computeServiceId);
if (ccs == null) {
logger.error(String.format("Error fetching compute service with id %1$s", computeServiceId));
return generateJSONResponseMAV(false, null, "No compute/storage service with those ID's");
}
job.setComputeServiceId(computeServiceId);
} else {
job.setComputeServiceId(null);
}
//Save the VEGL job
try {
jobManager.saveJob(job);
} catch (Exception ex) {
logger.error("Error updating job " + job, ex);
return generateJSONResponseMAV(false, null, "Error saving job");
}
return generateJSONResponseMAV(true, Arrays.asList(job), "");
}
/**
* Given an entire job object this function attempts to save the specified job with ID
* to the internal database. If the Job DNE (or id is null), the job will be created and
* have it's staging area initialised and other creation specific tasks performed.
*
* @return A JSON object with a success attribute that indicates whether
* the job was successfully updated. The data object will contain the updated job
* @return
* @throws ParseException
*/
@RequestMapping("/secure/updateJobSeries.do")
public ModelAndView updateJobSeries(@RequestParam(value="id", required=true) Integer id, //The integer ID if not specified will trigger job creation
@RequestParam(value="folderName", required=true) String folderName, //Name of the folder to move to
HttpServletRequest request,
@AuthenticationPrincipal ANVGLUser user) throws ParseException {
//Get our job
VEGLJob job = null;
Integer seriesId=null;
List<VEGLSeries> series = jobManager.querySeries(user.getEmail(), folderName, null);
if(series.isEmpty()){
return generateJSONResponseMAV(false, null,"Series not found");
}else{
seriesId=series.get(0).getId();
}
try {
job = jobManager.getJobById(id, user);
} catch (AccessDeniedException e) {
throw e;
} catch (Exception ex) {
logger.error(String.format("Error creating/fetching job with id %1$s", id), ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + id);
}
//Update our job from the request parameters
job.setSeriesId(seriesId);
//Save the VEGL job
try {
jobManager.saveJob(job);
} catch (Exception ex) {
logger.error("Error updating series for job " + job, ex);
return generateJSONResponseMAV(false, null, "Error updating series");
}
return generateJSONResponseMAV(true, Arrays.asList(job), "");
}
/**
* Given a job with specified ID and a list of download objects,
* save the download objects to the database.
*
* The download objects are defined piecewise as an array of name/description/url and localPath values.
*
* The Nth download object will be defined as a combination of
* names[N], descriptions[N], urls[N] and localPaths[N]
*
* @param append If true, the parsed downloaded will append themselves to the existing job. If false, they will replace all downloads for the existing job
* @return
* @throws ParseException
*/
@RequestMapping("/secure/updateJobDownloads.do")
public ModelAndView updateJobDownloads(@RequestParam("id") Integer id, //The integer ID is the only required value
@RequestParam(required=false, value="append", defaultValue="false") String appendString,
@RequestParam("name") String[] names,
@RequestParam("description") String[] descriptions,
@RequestParam("url") String[] urls,
@RequestParam("localPath") String[] localPaths,
@AuthenticationPrincipal ANVGLUser user) throws ParseException {
boolean append = Boolean.parseBoolean(appendString);
List<VglDownload> parsedDownloads = new ArrayList<VglDownload>();
for (int i = 0; i < urls.length && i < names.length && i < descriptions.length && i < localPaths.length; i++) {
VglDownload newDl = new VglDownload();
newDl.setName(names[i]);
newDl.setDescription(descriptions[i]);
newDl.setUrl(urls[i]);
newDl.setLocalPath(localPaths[i]);
parsedDownloads.add(newDl);
}
//Lookup the job
VEGLJob job;
try {
job = jobManager.getJobById(id, user);
} catch (AccessDeniedException e) {
throw e;
} catch (Exception ex) {
logger.error("Error looking up job with id " + id + " :" + ex.getMessage());
logger.debug("Exception:", ex);
return generateJSONResponseMAV(false, null, "Unable to access job");
}
List<VglDownload> existingDownloads = job.getJobDownloads();
if (append) {
existingDownloads.addAll(parsedDownloads);
job.setJobDownloads(existingDownloads);
} else {
job.setJobDownloads(parsedDownloads);
}
//Save the VEGL job
try {
jobManager.saveJob(job);
} catch (Exception ex) {
logger.error("Error updating job downloads" + job, ex);
return generateJSONResponseMAV(false, null, "Error saving job");
}
return generateJSONResponseMAV(true, null, "");
}
/**
* Given the ID of a job - lookup the appropriate job object and associated list of downloads objects.
*
* Return them as an array of JSON serialised VglDownload objects.
* @param jobId
* @return
*/
@RequestMapping("/secure/getJobDownloads.do")
public ModelAndView getJobDownloads(@RequestParam("jobId") Integer jobId, @AuthenticationPrincipal ANVGLUser user) {
//Lookup the job
VEGLJob job;
try {
job = jobManager.getJobById(jobId, user);
} catch (Exception ex) {
logger.error("Error looking up job with id " + jobId + " :" + ex.getMessage());
logger.debug("Exception:", ex);
return generateJSONResponseMAV(false, null, "Unable to access job");
}
return generateJSONResponseMAV(true, job.getJobDownloads(), "");
}
// /**
// * Gets the list of authorised images for the specified job owned by user
// * @param request The request (from a user) making the query
// * @param job The job for which the images will be tested
// * @return
// */
// private List<MachineImage> getImagesForJobAndUser(HttpServletRequest request, VEGLJob job) {
// return getImagesForJobAndUser(request, job.getComputeServiceId());
// }
/**
* Gets the list of authorised images for the specified job owned by user
* @param request The request (from a user) making the query
* @param computeServiceId The compute service ID to search for images
* @return
*/
private List<MachineImage> getImagesForJobAndUser(HttpServletRequest request, String computeServiceId) {
CloudComputeService ccs = getComputeService(computeServiceId);
if (ccs == null) {
return new ArrayList<MachineImage>();
}
List<MachineImage> authorisedImages = new ArrayList<MachineImage>();
for (MachineImage img : ccs.getAvailableImages()) {
if (img instanceof VglMachineImage) {
//If the image has no permission restrictions, add it. Otherwise
//ensure that the user has a role matching something in the image permission list
String[] permissions = ((VglMachineImage) img).getPermissions();
if (permissions == null) {
authorisedImages.add(img);
} else {
for (String validRole : permissions) {
if (request.isUserInRole(validRole)) {
authorisedImages.add(img);
break;
}
}
}
} else {
authorisedImages.add(img);
}
}
return authorisedImages;
}
/**
* Processes a job submission request.
*
* @param request The servlet request
* @param response The servlet response
*
* @return A JSON object with a success attribute that indicates whether
* the job was successfully submitted.
*/
@RequestMapping("/secure/submitJob.do")
public ModelAndView submitJob(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("jobId") String jobId,
@AuthenticationPrincipal ANVGLUser user) {
boolean succeeded = false;
String oldJobStatus = null, errorDescription = null, errorCorrection = null;
VEGLJob curJob = null;
boolean containsPersistentVolumes = false;
try {
// Get our job
curJob = jobManager.getJobById(Integer.parseInt(jobId), user);
if (curJob == null) {
logger.error("Error fetching job with id " + jobId);
errorDescription = "There was a problem retrieving your job from the database.";
String admin = getAdminEmail();
if(TextUtil.isNullOrEmpty(admin)) {
admin = "the portal admin";
}
errorCorrection = "Please try again in a few minutes or report it to "+admin+".";
return generateJSONResponseMAV(false, null, errorDescription, errorCorrection);
} else {
CloudStorageService cloudStorageService = getStorageService(curJob);
CloudComputeService cloudComputeService = getComputeService(curJob);
if (cloudStorageService == null || cloudComputeService == null) {
errorDescription = "One of the specified storage/compute services cannot be found.";
errorCorrection = "Consider changing the selected compute or storage service.";
return generateJSONResponseMAV(false, null, errorDescription, errorCorrection);
}
// we need to keep track of old job for audit trail purposes
oldJobStatus = curJob.getStatus();
// Assume user has permission since we're using images from the SSC
boolean permissionGranted = true;
// // final check to ensure user has permission to run the job
// // boolean permissionGranted = false;
// String jobImageId = curJob.getComputeVmId();
// List<MachineImage> images = getImagesForJobAndUser(request, curJob);
// for (MachineImage vglMachineImage : images) {
// if (vglMachineImage.getImageId().equals(jobImageId)) {
// permissionGranted = true;
// break;
// }
// }
if (permissionGranted) {
// Right before we submit - pump out a script file for downloading every VglDownload object when the VM starts
if (!createDownloadScriptFile(curJob, DOWNLOAD_SCRIPT)) {
logger.error(String.format("Error creating download script '%1$s' for job with id %2$s", DOWNLOAD_SCRIPT, jobId));
errorDescription = "There was a problem configuring the data download script.";
String admin = getAdminEmail();
if(TextUtil.isNullOrEmpty(admin)) {
admin = "the portal admin";
}
errorCorrection = "Please try again in a few minutes or report it to "+admin+".";
} else {
// copy files to S3 storage for processing
// get job files from local directory
StagedFile[] stagedFiles = fileStagingService.listStageInDirectoryFiles(curJob);
if (stagedFiles.length == 0) {
errorDescription = "There wasn't any input files found for submitting your job for processing.";
errorCorrection = "Please upload your input files and try again.";
} else {
// Upload them to storage
File[] files = new File[stagedFiles.length];
for (int i = 0; i < stagedFiles.length; i++) {
files[i] = stagedFiles[i].getFile();
}
cloudStorageService.uploadJobFiles(curJob, files);
// create our input user data string
String userDataString = null;
userDataString = createBootstrapForJob(curJob);
// Provenance
anvglProvenanceService.setServerURL(request.getRequestURL().toString());
anvglProvenanceService.createActivity(curJob, scmEntryService.getJobSolutions(curJob), user);
//ANVGL-120 Check for persistent volumes
if (cloudComputeService instanceof CloudComputeServiceAws) {
containsPersistentVolumes = ((CloudComputeServiceAws) cloudComputeService).containsPersistentVolumes(curJob);
curJob.setContainsPersistentVolumes(containsPersistentVolumes);
}
oldJobStatus = curJob.getStatus();
curJob.setStatus(JobBuilderController.STATUS_PROVISION);
jobManager.saveJob(curJob);
jobManager.createJobAuditTrail(oldJobStatus, curJob, "Set job to provisioning");
ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(new CloudThreadedExecuteService(cloudComputeService,curJob,userDataString));
succeeded = true;
}
}
} else {
errorDescription = "You do not have the permission to submit this job for processing.";
String admin = getAdminEmail();
if(TextUtil.isNullOrEmpty(admin)) {
admin = "the portal admin";
}
errorCorrection = "If you think this is wrong, please report it to "+admin+".";
}
}
} catch (PortalServiceException e) {
errorDescription = e.getMessage();
errorCorrection = e.getErrorCorrection();
//These are our "STS specific" overrides to some error messages (not an ideal solution but I don't want to have to overhaul everything just to tweak a string).
if (errorDescription.equals("Storage credentials are not valid.")) {
errorDescription = "Unable to upload job script and/or input files";
errorCorrection = "The most likely cause is that your user profile ARN's have been misconfigured.";
}
} catch (IOException e) {
logger.error("Job bootstrap creation failed.", e);
errorDescription = "There was a problem creating startup script.";
errorCorrection = "Please report this error to "+getAdminEmail();
} catch (AccessDeniedException e) {
logger.error("Job submission failed.", e);
errorDescription = "You are not authorized to access the specified job with id: "+ curJob.getId();
errorCorrection = "Please report this error to "+getAdminEmail();
} catch (Exception e) {
logger.error("Job submission failed.", e);
errorDescription = "An unexpected error has occurred while submitting your job for processing.";
errorCorrection = "Please report this error to "+getAdminEmail();
}
if (succeeded) {
ModelMap responseModel = new ModelMap();
responseModel.put("containsPersistentVolumes", containsPersistentVolumes);
return generateJSONResponseMAV(true, responseModel, "");
} else {
jobManager.createJobAuditTrail(oldJobStatus, curJob, errorDescription);
return generateJSONResponseMAV(false, null, errorDescription, errorCorrection);
}
}
private class CloudThreadedExecuteService implements Runnable{
CloudComputeService cloudComputeService;
VEGLJob curJob;
String userDataString;
public CloudThreadedExecuteService(CloudComputeService cloudComputeService,VEGLJob curJob,String userDataString){
this.cloudComputeService = cloudComputeService;
this.curJob = curJob;
this.userDataString = userDataString;
}
@Override
public void run() {
String instanceId = null;
try{
instanceId = cloudComputeService.executeJob(curJob, userDataString);
logger.info("Launched instance: " + instanceId);
// set reference as instanceId for use when killing a job
curJob.setComputeInstanceId(instanceId);
String oldJobStatus = curJob.getStatus();
curJob.setStatus(STATUS_PENDING);
jobManager.createJobAuditTrail(oldJobStatus, curJob, "Set job to Pending");
curJob.setSubmitDate(new Date());
jobManager.saveJob(curJob);
}catch(PortalServiceException e){
//only for this specific error we wanna queue the job
if(e.getErrorCorrection()!= null && e.getErrorCorrection().contains("Quota exceeded")){
vglPollingJobQueueManager.addJobToQueue(new VGLQueueJob(jobManager,cloudComputeService,curJob,userDataString,vglJobStatusChangeHandler));
String oldJobStatus = curJob.getStatus();
curJob.setStatus(JobBuilderController.STATUS_INQUEUE);
jobManager.saveJob(curJob);
jobManager.createJobAuditTrail(oldJobStatus, curJob, "Job Placed in Queue");
}else{
String oldJobStatus = curJob.getStatus();
curJob.setStatus(JobBuilderController.STATUS_ERROR);
jobManager.saveJob(curJob);
jobManager.createJobAuditTrail(oldJobStatus, curJob, e);
vglJobStatusChangeHandler.handleStatusChange(curJob,curJob.getStatus(),oldJobStatus);
}
}
}
}
/**
* Creates a new VEGL job initialised with the default configuration values. The job will be persisted into the database.
*
* The Job MUST be associated with a specific compute and storage service. Staging areas and other bits and pieces relating to the job will also be initialised.
*
* @param email
* @return
*/
private VEGLJob initialiseVEGLJob(HttpSession session, ANVGLUser user) throws PortalServiceException {
VEGLJob job = new VEGLJob();
//Start by saving our job to set its ID
jobManager.saveJob(job);
log.debug(String.format("Created a new job row id=%1$s", job.getId()));
job.setProperty(CloudJob.PROPERTY_STS_ARN, user.getArnExecution());
job.setProperty(CloudJob.PROPERTY_CLIENT_SECRET, user.getAwsSecret());
job.setProperty(CloudJob.PROPERTY_S3_ROLE, user.getArnStorage());
job.setComputeInstanceKey(user.getAwsKeyName());
job.setStorageBucket(user.getS3Bucket());
//Iterate over all session variables - set them up as job parameters
@SuppressWarnings("rawtypes")
Enumeration sessionVariables = session.getAttributeNames();
while (sessionVariables.hasMoreElements()) {
String variableName = sessionVariables.nextElement().toString();
Object variableValue = session.getAttribute(variableName);
String variableStringValue = null;
ParameterType variableType = null;
//Only session variables of a number or string will be considered
if (variableValue instanceof Integer || variableValue instanceof Double) {
variableType = ParameterType.number;
variableStringValue = variableValue.toString();
} else if (variableValue instanceof String) {
variableType = ParameterType.string;
variableStringValue = (String) variableValue;
} else {
continue;//Don't bother with other types
}
job.setJobParameter(variableName, variableStringValue, variableType);
}
//Load details from
job.setUser(user.getEmail());
job.setEmailAddress(user.getEmail());
// Get keypair name from CloudComputeService later
// job.setComputeInstanceKey("vgl-developers");
job.setName("VL-Job " + new Date().toString());
job.setDescription("");
job.setStatus(STATUS_UNSUBMITTED);
job.setSubmitDate(new Date());
//Transfer the 'session downloads' into actual download objects associated with a job
@SuppressWarnings("unchecked")
List<VglDownload> erddapDownloads = (List<VglDownload>) session.getAttribute(JobDownloadController.SESSION_DOWNLOAD_LIST);
session.setAttribute(JobDownloadController.SESSION_DOWNLOAD_LIST, null); //ensure we clear the list out in case the user makes more jobs
if (erddapDownloads != null) {
job.setJobDownloads(new ArrayList<VglDownload>(erddapDownloads));
} else {
logger.warn("No downloads configured for user session!");
}
//Save our job to the database before setting up staging directories (we need an ID!!)
jobManager.saveJob(job);
jobManager.createJobAuditTrail(null, job, "Job created.");
//Finally generate our stage in directory for persisting inputs
fileStagingService.generateStageInDirectory(job);
return job;
}
/**
* This function creates a file "vgl_download.sh" which contains the bash script
* for downloading every VglDownload associated with the specified job.
*
* The script file will be written to the staging area for job as
* @param job The job to generate
* @param fileName the file name of the generated script
* @return
*/
private boolean createDownloadScriptFile(VEGLJob job, String fileName) {
OutputStream os = null;
OutputStreamWriter out = null;
try {
os = fileStagingService.writeFile(job, fileName);
out = new OutputStreamWriter(os);
for (VglDownload dl : job.getJobDownloads()) {
out.write(String.format("#Downloading %1$s\n", dl.getName()));
out.write(String.format("curl -f -L '%1$s' -o \"%2$s\"\n", dl.getUrl(), dl.getLocalPath()));
}
return true;
} catch (Exception e) {
logger.error("Error creating download script" + e.getMessage());
logger.debug("Error:", e);
return false;
} finally {
FileIOUtil.closeQuietly(out);
FileIOUtil.closeQuietly(os);
}
}
/**
* Request wrapper to get the default toolbox uri.
*
*/
@RequestMapping("/getDefaultToolbox.do")
public ModelAndView doGetDefaultToolbox() {
return generateJSONResponseMAV(true, new String[] {getDefaultToolbox()}, "");
}
/**
* Gets the set of cloud images available for use by a particular user.
*
* If jobId is specified, limit the set to images that are
* compatible with the solution selected for the job.
*
* @param request
* @param computeServiceId
* @param jobId (optional) id of a job to limit suitable images
* @return
*/
@RequestMapping("/secure/getVmImagesForComputeService.do")
public ModelAndView getImagesForComputeService(
HttpServletRequest request,
@RequestParam("computeServiceId") String computeServiceId,
@RequestParam(value="jobId", required=false) Integer jobId,
@AuthenticationPrincipal ANVGLUser user) {
try {
// Assume all images are usable by the current user
List<MachineImage> images = new ArrayList<MachineImage>();
if (jobId != null) {
VEGLJob job = jobManager.getJobById(jobId, user);
// Filter list to images suitable for job solutions, if specified.
Set<Toolbox> toolboxes = scmEntryService.getJobToolboxes(job);
// With multiple solutions and multiple toolboxes, do
// not give the user the option of selecting the default
// portal toolbox for utility functions unless it's the
// only toolbox available.
int numToolboxes = toolboxes.size();
for (Toolbox toolbox: toolboxes) {
if ((numToolboxes == 1) ||
!toolbox.getUri().equals(this.defaultToolbox)) {
images.add(scmEntryService
.getToolboxImage(toolbox,
computeServiceId));
}
}
}
if (images.isEmpty()) {
// Fall back on old behaviour based on configured images for now
// Get images available to the current user
images = getImagesForJobAndUser(request, computeServiceId);
}
if (images.isEmpty()) {
// There are no suitable images at the specified compute service.
log.warn("No suitable images at compute service (" + computeServiceId + ") for job (" + jobId + ")");
}
// return result
return generateJSONResponseMAV(true, images, "");
} catch (Exception ex) {
log.error("Unable to access image list:" + ex.getMessage(), ex);
return generateJSONResponseMAV(false);
}
}
/**
* Return a JSON list of VM types available for the compute service.
*
* @param computeServiceId
*/
@RequestMapping("/secure/getVmTypesForComputeService.do")
public ModelAndView getTypesForComputeService(HttpServletRequest request,
@RequestParam("computeServiceId") String computeServiceId,
@RequestParam("machineImageId") String machineImageId) {
try {
CloudComputeService ccs = getComputeService(computeServiceId);
if (ccs == null) {
return generateJSONResponseMAV(false, null, "Unknown compute service");
}
List<MachineImage> images = getImagesForJobAndUser(request, computeServiceId);
MachineImage selectedImage = null;
for (MachineImage image : images) {
if (image.getImageId().equals(machineImageId)) {
selectedImage = image;
break;
}
}
ComputeType[] allTypes = null;
if (selectedImage == null) {
// Unknown image, presumably from the SSSC, so start with all
// compute types for the selected compute service.
allTypes = ccs.getAvailableComputeTypes();
}
else {
//Grab the compute types that are compatible with our disk
//requirements
allTypes = ccs.getAvailableComputeTypes(null, null, selectedImage.getMinimumDiskGB());
}
//Filter further due to AWS HVM/PVM compatiblity. See ANVGL-16
Object[] filteredTypes = Arrays.stream(allTypes).filter(new Predicate<ComputeType>() {
@Override
public boolean test(ComputeType t) {
return t.getId().startsWith("c3") || t.getId().startsWith("m3");
}
}).toArray();
return generateJSONResponseMAV(true, filteredTypes, "");
} catch (Exception ex) {
log.error("Unable to access compute type list:" + ex.getMessage(), ex);
return generateJSONResponseMAV(false);
}
}
/**
* Gets a JSON list of id/name pairs for every available compute service
*
* If a jobId parameter is provided, then return compute services
* compatible with that job. Currently that is only those services
* that have images available for the solution used for the job.
*
* @param jobId (optional) job id to limit acceptable services
* @return
*/
@RequestMapping("/secure/getComputeServices.do")
public ModelAndView getComputeServices(@RequestParam(value="jobId",
required=false)
Integer jobId,
@AuthenticationPrincipal ANVGLUser user) {
Set<String> jobCCSIds;
try {
jobCCSIds = scmEntryService.getJobProviders(jobId, user);
} catch (AccessDeniedException e) {
throw e;
}
List<ModelMap> simpleComputeServices = new ArrayList<ModelMap>();
for (CloudComputeService ccs : cloudComputeServices) {
// Add the ccs to the list if it's valid for job or we have no job
if (jobCCSIds == null || jobCCSIds.contains(ccs.getId())) {
ModelMap map = new ModelMap();
map.put("id", ccs.getId());
map.put("name", ccs.getName());
simpleComputeServices.add(map);
}
}
return generateJSONResponseMAV(true, simpleComputeServices, "");
}
/**
* Gets a JSON list of id/name pairs for every available storage service
* @return
*/
@RequestMapping("/secure/getStorageServices.do")
public ModelAndView getStorageServices() {
List<ModelMap> simpleStorageServices = new ArrayList<ModelMap>();
for (CloudStorageService ccs : cloudStorageServices) {
ModelMap map = new ModelMap();
map.put("id", ccs.getId());
map.put("name", ccs.getName());
simpleStorageServices.add(map);
}
return generateJSONResponseMAV(true, simpleStorageServices, "");
}
/**
* A combination of getJobInputFiles and getJobDownloads. This function amalgamates the list
* of remote service downloads and local file uploads into a single list of input files that
* are available to a job at startup.
*
* The results will be presented in an array of VglDownload objects
* @param jobId
* @return
*/
@RequestMapping("/secure/getAllJobInputs.do")
public ModelAndView getAllJobInputs(@RequestParam("jobId") Integer jobId, @AuthenticationPrincipal ANVGLUser user) {
VEGLJob job = null;
try {
job = jobManager.getJobById(jobId, user);
} catch (Exception ex) {
logger.error("Error fetching job with id " + jobId, ex);
return generateJSONResponseMAV(false, null, "Error fetching job with id " + jobId);
}
//Get our files
StagedFile[] files = null;
try {
files = fileStagingService.listStageInDirectoryFiles(job);
} catch (Exception ex) {
logger.error("Error listing job stage in directory", ex);
return generateJSONResponseMAV(false, null, "Error reading job stage in directory");
}
//Load the staged files
List<VglDownload> allInputs = new ArrayList<VglDownload>();
int idCounter = Integer.MIN_VALUE;
for (StagedFile file : files) {
//we need unique ids - this is our simple way of generating them (low likelyhood of collision)
//if we have a collision the GUI might not show one entry - it's not the end of the world
VglDownload dl = new VglDownload(idCounter++);
dl.setName(file.getName());
dl.setLocalPath(file.getName());
allInputs.add(dl);
}
//Load the job downloads
allInputs.addAll(job.getJobDownloads());
return generateJSONResponseMAV(true, allInputs, "");
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(value = org.springframework.http.HttpStatus.FORBIDDEN)
public @ResponseBody String handleException(AccessDeniedException e) {
return e.getMessage();
}
/**
* Return the default toolbox URI.
*
* @returns String with the URI for the default toolbox.
*/
public String getDefaultToolbox() {
return this.defaultToolbox;
}
/**
* Set the default toolbox URI.
*
* @param defaultToolbox String containing the URI of the default toolbox to set
*/
public void setDefaultToolbox(String defaultToolbox) {
this.defaultToolbox = defaultToolbox;
}
}
| gpl-3.0 |
lodsve/lodsve-framework | lodsve-wechat/src/main/java/lodsve/wechat/enums/Sex.java | 1273 | /*
* Copyright (C) 2019 Sun.Hao(https://www.crazy-coder.cn/)
*
* 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 lodsve.wechat.enums;
import com.fasterxml.jackson.annotation.JsonCreator;
/**
* 用户性别枚举.
*
* @author sunhao(sunhao.java @ gmail.com)
* @version V1.0, 16/3/2 下午4:27
*/
public enum Sex {
MAN, WOMAN, UNKNOWN;
@JsonCreator
public static Sex eval(int index) {
switch (index) {
case 1:
return MAN;
case 2:
return WOMAN;
case 0:
return UNKNOWN;
default:
break;
}
return null;
}
}
| gpl-3.0 |
SiLeBAT/FSK-Lab | de.bund.bfr.knime.fsklab.deprecatednodes/src-1_9_0/de/bund/bfr/knime/fsklab/v1_9/creator/CreatorNodeModel.java | 42362 | /*
***************************************************************************************************
* Copyright (c) 2017 Federal Institute for Risk Assessment (BfR), Germany
*
* 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/>.
*
* Contributors: Department Biological Safety - BfR
*************************************************************************************************
*/
package de.bund.bfr.knime.fsklab.v1_9.creator;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.knime.core.node.BufferedDataTable;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.ExecutionContext;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NoInternalsModel;
import org.knime.core.node.NodeLogger;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import org.knime.core.node.port.PortObject;
import org.knime.core.node.port.PortObjectSpec;
import org.knime.core.node.port.PortType;
import org.knime.core.node.util.CheckUtils;
import org.knime.core.util.FileUtil;
import de.bund.bfr.fskml.Script;
import de.bund.bfr.fskml.ScriptFactory;
import de.bund.bfr.knime.fsklab.nodes.environment.EnvironmentManager;
import de.bund.bfr.knime.fsklab.nodes.environment.ExistingEnvironmentManager;
import de.bund.bfr.knime.fsklab.nodes.v1_9.NodeUtils;
import de.bund.bfr.knime.fsklab.nodes.v1_9.ScriptHandler;
import de.bund.bfr.knime.fsklab.v1_9.FskPortObject;
import de.bund.bfr.knime.fsklab.v1_9.FskPortObjectSpec;
import de.bund.bfr.knime.fsklab.v1_9.FskSimulation;
import de.bund.bfr.metadata.swagger.GenericModel;
import de.bund.bfr.metadata.swagger.Model;
import de.bund.bfr.metadata.swagger.Parameter;
import metadata.Assay;
import metadata.Contact;
import metadata.DataBackground;
import metadata.DietaryAssessmentMethod;
import metadata.GeneralInformation;
import metadata.Hazard;
import metadata.Laboratory;
import metadata.MetadataFactory;
import metadata.ModelCategory;
import metadata.ParameterClassification;
import metadata.ParameterType;
import metadata.PopulationGroup;
import metadata.PreRakipSheetImporter;
import metadata.PublicationType;
import metadata.RAKIPSheetImporter;
import metadata.RakipColumn;
import metadata.RakipRow;
import metadata.Reference;
import metadata.Scope;
import metadata.StringObject;
import metadata.Study;
import metadata.StudySample;
import metadata.SwaggerUtil;
import metadata.swagger.ConsumptionModelSheetImporter;
import metadata.swagger.DataModelSheetImporter;
import metadata.swagger.DoseResponseSheetImporter;
import metadata.swagger.ExposureModelSheetImporter;
import metadata.swagger.GenericModelSheetImporter;
import metadata.swagger.HealthModelSheetImporter;
import metadata.swagger.OtherModelSheetImporter;
import metadata.swagger.PredictiveModelSheetImporter;
import metadata.swagger.ProcessModelSheetImporter;
import metadata.swagger.QraModelSheetImporter;
import metadata.swagger.RiskModelSheetImporter;
import metadata.swagger.SheetImporter;
import metadata.swagger.ToxicologicalModelSheetImporter;
class CreatorNodeModel extends NoInternalsModel {
private static final NodeLogger LOGGER = NodeLogger.getLogger(CreatorNodeModel.class);
private CreatorNodeSettings nodeSettings = new CreatorNodeSettings();
// Input and output port types
private static final PortType[] IN_TYPES = {BufferedDataTable.TYPE_OPTIONAL};
private static final PortType[] OUT_TYPES = {FskPortObject.TYPE};
public CreatorNodeModel() {
super(IN_TYPES, OUT_TYPES);
}
@Override
protected void saveSettingsTo(NodeSettingsWO settings) {
nodeSettings.save(settings);
}
@Override
protected void validateSettings(NodeSettingsRO settings) throws InvalidSettingsException {
CheckUtils.checkSourceFile(settings.getString("modelScript"));
CheckUtils.checkSourceFile(settings.getString("spreadsheet"));
// Sheet
CheckUtils.checkArgument(StringUtils.isNotEmpty(settings.getString("sheet")), "Missing sheet");
}
@Override
protected void loadValidatedSettingsFrom(NodeSettingsRO settings)
throws InvalidSettingsException {
nodeSettings.load(settings);
}
@Override
protected void reset() {
}
@Override
protected PortObject[] execute(final PortObject[] inData, final ExecutionContext exec)
throws InvalidSettingsException, IOException, CanceledExecutionException,
InvalidFormatException {
// Reads model script
Script modelRScript = readScript(nodeSettings.modelScript);
// Reads visualization script
Script vizRScript;
if (StringUtils.isNotEmpty(nodeSettings.visualizationScript)) {
vizRScript = readScript(nodeSettings.visualizationScript);
} else {
vizRScript = null;
}
Model modelMetadata = null;
// If an input table is connected then parse the metadata
if (inData.length == 1 && inData[0] != null) {
// TODO: Need to update input table parser: TableParser
// BufferedDataTable metadataTable = (BufferedDataTable) inData[0];
//
// // parse table
// String[][] values = new String[200][50];
// int i = 0;
// for (DataRow row : metadataTable) {
// if (isRowEmpty(row))
// break;
// int j = 0;
// for (DataCell cell : row) {
// values[i][j] = !cell.isMissing() ? ((StringCell) cell).getStringValue() : "";
// j++;
// }
// i++;
// }
//
// generalInformation = TableParser.retrieveGeneralInformation(values);
// scope = TableParser.retrieveScope(values);
// dataBackground = TableParser.retrieveDataBackground(values);
//
// modelMath = MetadataFactory.eINSTANCE.createModelMath();
// for (i = 132; i <= 152; i++) {
// try {
// Parameter param = TableParser.retrieveParameter(values, i);
// modelMath.getParameter().add(param);
// } catch (Exception exception) {
// exception.printStackTrace();
// }
// }
}
else {
exec.checkCanceled();
// Reads model meta data
Workbook workbook = getWorkbook(nodeSettings.spreadsheet);
workbook.setMissingCellPolicy(MissingCellPolicy.CREATE_NULL_AS_BLANK);
Sheet sheet = workbook.getSheet(nodeSettings.sheet);
if (sheet.getPhysicalNumberOfRows() > 29) {
// 1.0.3 RAKIP spreadsheet has "parameter type" P:131 (or 130 if index starts at 0), 1.04
// doesn't
if (sheet.getSheetName().equals("Generic Metadata Schema")
&& sheet.getRow(130).getCell(15).getStringCellValue().equals("Parameter type")) { // SWAGGER
// 1.04
// Process 1.0.3 RAKIP spreadsheet has "parameter type" P:131 (or 130 if index starts at
// 0)
RAKIPSheetImporter importer = new RAKIPSheetImporter();
GenericModel gm = new GenericModel();
gm.setModelType("genericModel");
gm.setGeneralInformation(importer.retrieveGeneralInformation(sheet));
gm.setScope(importer.retrieveScope(sheet));
gm.setDataBackground(importer.retrieveBackground(sheet));
gm.setModelMath(importer.retrieveModelMath(sheet));
modelMetadata = gm;
} else {
// SWAGGER 1.0.4
final Optional<SheetImporter> sheetImporter;
final String sheetName = sheet.getSheetName();
if (sheetName.equals("Generic Metadata Schema")) {
sheetImporter = Optional.of(new GenericModelSheetImporter());
} else if (sheetName.equals("Dose-response Model")) {
sheetImporter = Optional.of(new DoseResponseSheetImporter());
} else if (sheetName.equals("Predictive Model")) {
sheetImporter = Optional.of(new PredictiveModelSheetImporter());
} else if (sheetName.equals("Exposure Model")) {
sheetImporter = Optional.of(new ExposureModelSheetImporter());
} else if (sheetName.equals("Process Model")) {
sheetImporter = Optional.of(new ProcessModelSheetImporter());
} else if (sheetName.startsWith("Toxic")) {
sheetImporter = Optional.of(new ToxicologicalModelSheetImporter());
} else if (sheetName.equals("QRA Models")) {
sheetImporter = Optional.of(new QraModelSheetImporter());
} else if (sheetName.startsWith("Risk")) {
sheetImporter = Optional.of(new RiskModelSheetImporter());
} else if (sheetName.equals("Other Empirical Model")) {
sheetImporter = Optional.of(new OtherModelSheetImporter());
} else if (sheetName.startsWith("Consumption")) {
sheetImporter = Optional.of(new ConsumptionModelSheetImporter());
} else if (sheetName.startsWith("Health")) {
sheetImporter = Optional.of(new HealthModelSheetImporter());
} else if (sheetName.equals("(Data)")) {
sheetImporter = Optional.of(new DataModelSheetImporter());
} else {
sheetImporter = Optional.empty();
}
if (sheetImporter.isPresent()) {
modelMetadata = sheetImporter.get().retrieveModel(sheet);
}
} // else RAKIP
} // end if newer than 1.03
else {
// Process legacy spreadsheet: prior RAKIP
PreRakipSheetImporter importer = new PreRakipSheetImporter();
GenericModel gm = new GenericModel();
gm.setModelType("genericModel");
gm.setGeneralInformation(importer.retrieveGeneralInformation(sheet));
gm.setScope(importer.retrieveScope(sheet));
gm.setModelMath(importer.retrieveModelMath(sheet));
modelMetadata = gm;
}
} // end if check version and create modelmetadata
String modelScript = modelRScript.getScript();
String vizScript = vizRScript != null ? vizRScript.getScript() : "";
String workingDirectory = nodeSettings.getWorkingDirectory();
Optional<EnvironmentManager> environmentManager;
if (!nodeSettings.getWorkingDirectory().isEmpty()) {
EnvironmentManager actualManager =
new ExistingEnvironmentManager(nodeSettings.getWorkingDirectory());
environmentManager = Optional.of(actualManager);
} else {
environmentManager = Optional.empty();
}
// The creator imports a non-execute model without plot, thus the path to
// the plot is an empty string.
String plotPath = "";
// Retrieve used libraries in scripts. A set is used to avoid duplication.
exec.checkCanceled();
Set<String> librariesSet = new HashSet<>();
librariesSet.addAll(modelRScript.getLibraries());
if (vizRScript != null) {
librariesSet.addAll(vizRScript.getLibraries());
}
List<String> librariesList = new ArrayList<>(librariesSet);
// Import readme
exec.checkCanceled();
String readmePath = nodeSettings.getReadme();
String readme;
if (readmePath.isEmpty()) {
readme = "";
} else {
File readmeFile = FileUtil.getFileFromURL(FileUtil.toURL(readmePath));
readme = FileUtils.readFileToString(readmeFile, "UTF-8");
}
final FskPortObject portObj = new FskPortObject(modelScript, vizScript, modelMetadata, null,
librariesList, environmentManager, plotPath, readme);
List<Parameter> parameters = SwaggerUtil.getParameter(modelMetadata);
if (SwaggerUtil.getModelMath(modelMetadata) != null) {
portObj.simulations.add(NodeUtils.createDefaultSimulation(parameters));
}
// Validate parameters from spreadsheet
exec.checkCanceled();
try (ScriptHandler handler = ScriptHandler
.createHandler(SwaggerUtil.getLanguageWrittenIn(modelMetadata), portObj.packages)) {
if (!workingDirectory.isEmpty()) {
Path workingDirectoryPath =
FileUtil.getFileFromURL(FileUtil.toURL(workingDirectory)).toPath();
handler.setWorkingDirectory(workingDirectoryPath, exec);
}
FskSimulation simulation = NodeUtils.createDefaultSimulation(parameters);
String script = handler.buildParameterScript(simulation);
// ScriptExecutor executor = new ScriptExecutor(controller);
Arrays.stream(modelScript.split("\\r?\\n")).filter(id -> id.startsWith("import"))
.forEach(line -> {
try {
handler.runScript(line, exec, false);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});// .map(id -> id.split(" ")[1]).forEach(libraries::add);
handler.setupOutputCapturing(exec);
handler.runScript(script, exec, false);
handler.finishOutputCapturing(exec);
if (!handler.getStdErr().isEmpty()) {
throw new InvalidSettingsException("Invalid parameters:\n" + handler.getStdErr());
}
} catch (Exception exception) {
throw new InvalidSettingsException(
"Parameters could not be validate. Please try again. " + exception.getMessage(),
exception);
}
return new PortObject[] {portObj};
}
@Override
protected PortObjectSpec[] configure(PortObjectSpec[] inSpecs) throws InvalidSettingsException {
// Check spreadsheet and sheet in no input table is connected
if (inSpecs.length == 1 && inSpecs[0] == null) {
CheckUtils.checkArgument(
nodeSettings.spreadsheet != null && !nodeSettings.spreadsheet.isEmpty(),
"No spreadsheet provided! Please enter a valid location.");
CheckUtils.checkSourceFile(nodeSettings.spreadsheet);
CheckUtils.checkArgument(nodeSettings.sheet != null && !nodeSettings.sheet.isEmpty(),
"No sheet provided");
}
return new PortObjectSpec[] {FskPortObjectSpec.INSTANCE};
}
/**
* Reads R script.
*
* @param path File path to R model script. If is assured not to be null or empty.
* @throws InvalidSettingsException if {@link path} is null or whitespace.
* @throws IOException if the file cannot be read.
*/
private static Script readScript(final String path) throws InvalidSettingsException, IOException {
String trimmedPath = StringUtils.trimToNull(path.trim());
// path is not null or whitespace, thus try to read it
try {
// may throw IOException
File fScript = FileUtil.getFileFromURL(FileUtil.toURL(trimmedPath));
Script script = ScriptFactory.createScript(fScript);
return script;
} catch (IOException e) {
LOGGER.error(e.getMessage());
throw new IOException(trimmedPath + ": cannot be read");
}
}
/** Parses metadata-filled tables imported from a Google Drive spreadsheet. */
static class TableParser {
static List<String> getStringListValue(String[][] values, RakipRow row, RakipColumn col) {
String rawString = values[row.num][col.ordinal()];
List<String> tokens = Arrays.stream(rawString.split(",")).collect(Collectors.toList());
return tokens;
}
static List<StringObject> getStringObjectList(String[][] values, RakipRow row,
RakipColumn col) {
String[] strings = values[row.num][col.ordinal()].split(",");
List<StringObject> stringObjects = new ArrayList<>(strings.length);
for (String value : strings) {
StringObject so = MetadataFactory.eINSTANCE.createStringObject();
so.setValue(value);
stringObjects.add(so);
}
return stringObjects;
}
static GeneralInformation retrieveGeneralInformation(String[][] values) {
GeneralInformation generalInformation = MetadataFactory.eINSTANCE.createGeneralInformation();
String name = values[RakipRow.GENERAL_INFORMATION__NAME.num][RakipColumn.I.ordinal()];
String source = values[RakipRow.GENERAL_INFORMATION__SOURCE.num][RakipColumn.I.ordinal()];
String identifier =
values[RakipRow.GENERAL_INFORMATION__IDENTIFIER.num][RakipColumn.I.ordinal()];
String rights = values[RakipRow.GENERAL_INFORMATION__RIGHTS.num][RakipColumn.I.ordinal()];
boolean isAvailable =
values[RakipRow.GENERAL_INFORMATION__AVAILABILITY.num][RakipColumn.I.ordinal()]
.equals("Yes");
String language = values[RakipRow.GENERAL_INFORMATION__LANGUAGE.num][RakipColumn.I.ordinal()];
String software = values[RakipRow.GENERAL_INFORMATION__SOFTWARE.num][RakipColumn.I.ordinal()];
String languageWrittenIn =
values[RakipRow.GENERAL_INFORMATION__LANGUAGE_WRITTEN_IN.num][RakipColumn.I.ordinal()];
String status = values[RakipRow.GENERAL_INFORMATION__STATUS.num][RakipColumn.I.ordinal()];
String objective =
values[RakipRow.GENERAL_INFORMATION__OBJECTIVE.num][RakipColumn.I.ordinal()];
String description =
values[RakipRow.GENERAL_INFORMATION__DESCRIPTION.num][RakipColumn.I.ordinal()];
generalInformation.setName(name);
generalInformation.setSource(source);
generalInformation.setIdentifier(identifier);
generalInformation.setRights(rights);
generalInformation.setAvailable(isAvailable);
generalInformation.setLanguage(language);
generalInformation.setSoftware(software);
generalInformation.setLanguageWrittenIn(languageWrittenIn);
generalInformation.setStatus(status);
generalInformation.setObjective(objective);
generalInformation.setDescription(description);
for (int numRow = 3; numRow < 7; numRow++) {
try {
Contact contact = retrieveContact(values, numRow);
generalInformation.getCreators().add(contact);
} catch (Exception exception) {
}
}
for (int numRow = 14; numRow < 17; numRow++) {
try {
Reference reference = retrieveReference(values, numRow);
generalInformation.getReference().add(reference);
} catch (Exception exception) {
}
}
try {
ModelCategory modelCategory = retrieveModelCategory(values);
generalInformation.getModelCategory().add(modelCategory);
} catch (Exception exception) {
}
return generalInformation;
}
static Contact retrieveContact(String[][] values, int row) {
String email = values[row][RakipColumn.R.ordinal()];
// Check mandatory properties and throw exception if missing
if (email.isEmpty()) {
throw new IllegalArgumentException("Missing mail");
}
Contact contact = MetadataFactory.eINSTANCE.createContact();
contact.setTitle(values[row][RakipColumn.K.ordinal()]);
contact.setFamilyName(values[row][RakipColumn.O.ordinal()]);
contact.setGivenName(values[row][RakipColumn.M.ordinal()]);
contact.setEmail(email);
contact.setTelephone(values[row][RakipColumn.Q.ordinal()]);
contact.setStreetAddress(values[row][RakipColumn.W.ordinal()]);
contact.setCountry(values[row][RakipColumn.S.ordinal()]);
contact.setCity(values[row][RakipColumn.T.ordinal()]);
contact.setZipCode(values[row][RakipColumn.U.ordinal()]);
contact.setRegion(values[row][RakipColumn.Y.ordinal()]);
// time zone not included in spreadsheet ?
// gender not included in spreadsheet ?
// note not included in spreadsheet ?
contact.setOrganization(values[row][RakipColumn.P.ordinal()]);
return contact;
}
/**
* @throw IllegalArgumentException if a mandatory property is missing
*/
static Reference retrieveReference(String[][] values, int row) {
final String isReferenceDescriptionString = values[row][RakipColumn.K.ordinal()];
final String doi = values[row][RakipColumn.O.ordinal()];
// Check mandatory properties and throw exception if missing
if (isReferenceDescriptionString.isEmpty()) {
throw new IllegalArgumentException("Missing Is reference description?");
}
if (doi.isEmpty()) {
throw new IllegalArgumentException("Missing DOI");
}
Reference reference = MetadataFactory.eINSTANCE.createReference();
// Is reference description
reference.setIsReferenceDescription(isReferenceDescriptionString.equals("Yes"));
// Publication type
// Get publication type from literal. Get null if invalid literal.
String publicationTypeLiteral = values[row][RakipColumn.L.ordinal()];
PublicationType publicationType = PublicationType.get(publicationTypeLiteral);
if (publicationType != null) {
reference.setPublicationType(publicationType);
}
// PMID
String pmid = values[row][RakipColumn.N.ordinal()];
if (!pmid.isEmpty()) {
reference.setPmid(pmid);
}
// DOI
if (!doi.isEmpty()) {
reference.setDoi(doi);
}
reference.setAuthorList(values[row][RakipColumn.P.ordinal()]);
reference.setPublicationTitle(values[row][RakipColumn.Q.ordinal()]);
reference.setPublicationAbstract(values[row][RakipColumn.R.ordinal()]);
// TODO: journal
// TODO: issue
reference.setPublicationStatus(values[row][RakipColumn.T.ordinal()]);
// TODO: web site
reference.setPublicationWebsite(values[row][RakipColumn.U.ordinal()]);
// TODO: comment
return reference;
}
/**
* @throw IllegalArgumentException if a mandatory property is missing
*/
static ModelCategory retrieveModelCategory(String[][] values) {
int columnI = RakipColumn.I.ordinal();
// Check mandatory properties
if (values[RakipRow.MODEL_CATEGORY__MODEL_CLASS.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing model class");
}
ModelCategory modelCategory = MetadataFactory.eINSTANCE.createModelCategory();
modelCategory.setModelClass(values[RakipRow.MODEL_CATEGORY__MODEL_CLASS.num][columnI]);
modelCategory.getModelSubClass().addAll(
getStringObjectList(values, RakipRow.MODEL_CATEGORY__MODEL_SUB_CLASS, RakipColumn.I));
modelCategory
.setModelClassComment(values[RakipRow.MODEL_CATEGORY__MODEL_CLASS_COMMENT.num][columnI]);
modelCategory.setBasicProcess(values[RakipRow.MODEL_CATEGORY__BASIC_PROCESS.num][columnI]);
return modelCategory;
}
static Scope retrieveScope(String[][] values) {
Scope scope = MetadataFactory.eINSTANCE.createScope();
try {
Hazard hazard = MetadataFactory.eINSTANCE.createHazard();
scope.getHazard().add(hazard);
} catch (IllegalArgumentException exception) {
// Ignore since hazard is optional
}
try {
PopulationGroup populationGroup = MetadataFactory.eINSTANCE.createPopulationGroup();
scope.getPopulationGroup().add(populationGroup);
} catch (IllegalArgumentException exception) {
// Ignore since population group is optional
}
return scope;
}
/**
* @throws IllegalArgumentException if a mandatory property is missing
*/
static Hazard retrieveHazard(String[][] values) {
int columnI = RakipColumn.I.ordinal();
// check mandatory properties
if (values[RakipRow.HAZARD_TYPE.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing hazard");
}
Hazard hazard = MetadataFactory.eINSTANCE.createHazard();
hazard.setHazardType(values[RakipRow.HAZARD_TYPE.num][columnI]);
hazard.setHazardName(values[RakipRow.HAZARD_NAME.num][columnI]);
hazard.setHazardDescription(values[RakipRow.HAZARD_DESCRIPTION.num][columnI]);
hazard.setHazardUnit(values[RakipRow.HAZARD_UNIT.num][columnI]);
hazard.setAdverseEffect(values[RakipRow.HAZARD_ADVERSE_EFFECT.num][columnI]);
hazard.setSourceOfContamination(values[RakipRow.HAZARD_CONTAMINATION_SOURCE.num][columnI]);
hazard.setBenchmarkDose(values[RakipRow.HAZARD_BMD.num][columnI]);
hazard.setMaximumResidueLimit(values[RakipRow.HAZARD_MRL.num][columnI]);
hazard.setNoObservedAdverseAffectLevel(values[RakipRow.HAZARD_NOAEL.num][columnI]);
hazard.setLowestObservedAdverseAffectLevel(values[RakipRow.HAZARD_LOAEL.num][columnI]);
hazard.setAcuteReferenceDose(values[RakipRow.HAZARD_ARFD.num][columnI]);
hazard.setHazardIndSum(values[RakipRow.HAZARD_IND_SUM.num][columnI]);
return hazard;
}
/** @throws IllegalArgumentException if a mandatory property is missing. */
static PopulationGroup retrievePopulationGroup(String[][] values) {
int columnI = RakipColumn.I.ordinal();
// Check mandatory properties
if (values[RakipRow.POPULATION_GROUP_NAME.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing population name");
}
PopulationGroup populationGroup = MetadataFactory.eINSTANCE.createPopulationGroup();
populationGroup.setPopulationName(values[RakipRow.POPULATION_GROUP_NAME.num][columnI]);
populationGroup.setTargetPopulation(values[RakipRow.POPULATION_GROUP_TARGET.num][columnI]);
List<StringObject> populationSpan =
getStringObjectList(values, RakipRow.POPULATION_GROUP_SPAN, RakipColumn.I);
populationGroup.getPopulationSpan().addAll(populationSpan);
List<StringObject> populationDescription =
getStringObjectList(values, RakipRow.POPULATION_GROUP_DESCRIPTION, RakipColumn.I);
populationGroup.getPopulationDescription().addAll(populationDescription);
List<StringObject> populationAge =
getStringObjectList(values, RakipRow.POPULATION_GROUP_AGE, RakipColumn.I);
populationGroup.getPopulationAge().addAll(populationAge);
populationGroup.setPopulationGender(values[RakipRow.POPULATION_GROUP_GENDER.num][columnI]);
List<StringObject> bmi =
getStringObjectList(values, RakipRow.POPULATION_GROUP_BMI, RakipColumn.I);
populationGroup.getBmi().addAll(bmi);
List<StringObject> specialDietGroups =
getStringObjectList(values, RakipRow.POPULATION_GROUP_DIET, RakipColumn.I);
populationGroup.getSpecialDietGroups().addAll(specialDietGroups);
List<StringObject> patternConsumption =
getStringObjectList(values, RakipRow.POPULATION_GROUP_PATTERN_CONSUMPTION, RakipColumn.I);
populationGroup.getPatternConsumption().addAll(patternConsumption);
List<StringObject> region =
getStringObjectList(values, RakipRow.POPULATION_GROUP_REGION, RakipColumn.I);
populationGroup.getRegion().addAll(region);
List<StringObject> country =
getStringObjectList(values, RakipRow.POPULATION_GROUP_COUNTRY, RakipColumn.I);
populationGroup.getCountry().addAll(country);
List<StringObject> populationRiskFactor =
getStringObjectList(values, RakipRow.POPULATION_GROUP_RISK, RakipColumn.I);
populationGroup.getPopulationRiskFactor().addAll(populationRiskFactor);
List<StringObject> season =
getStringObjectList(values, RakipRow.POPULATION_GROUP_SEASON, RakipColumn.I);
populationGroup.getSeason().addAll(season);
return populationGroup;
}
static DataBackground retrieveDataBackground(String[][] values) {
DataBackground dataBackground = MetadataFactory.eINSTANCE.createDataBackground();
dataBackground.setStudy(retrieveStudy(values));
try {
StudySample studySample = retrieveStudySample(values);
dataBackground.getStudySample().add(studySample);
} catch (IllegalArgumentException exception) {
// Ignore exception since the study sample is optional
}
try {
DietaryAssessmentMethod method = retrieveDAM(values);
dataBackground.getDietaryAssessmentMethod().add(method);
} catch (IllegalArgumentException exception) {
// Ignore exception since the dietary assessment method is optional
}
try {
Laboratory laboratory = retrieveLaboratory(values);
dataBackground.getLaboratory().add(laboratory);
} catch (IllegalArgumentException exception) {
// Ignore exception since the laboratory is optional
}
try {
Assay assay = retrieveAssay(values);
dataBackground.getAssay().add(assay);
} catch (IllegalArgumentException exception) {
// Ignore exception since the assay is optional
}
return dataBackground;
}
/** @throws IllegalArgumentException if a mandatory property is missing. */
static Study retrieveStudy(String[][] values) {
int columnI = RakipColumn.I.ordinal();
// Check mandatory properties
if (values[RakipRow.STUDY_TITLE.num][RakipColumn.I.ordinal()].isEmpty()) {
throw new IllegalArgumentException("Missing study title");
}
Study study = MetadataFactory.eINSTANCE.createStudy();
study.setStudyIdentifier(values[RakipRow.STUDY_ID.num][columnI]);
study.setStudyTitle(values[RakipRow.STUDY_TITLE.num][columnI]);
study.setStudyDescription(values[RakipRow.STUDY_DESCRIPTION.num][columnI]);
study.setStudyDesignType(values[RakipRow.STUDY_DESIGN_TYPE.num][columnI]);
study.setStudyAssayMeasurementType(
values[RakipRow.STUDY_ASSAY_MEASUREMENTS_TYPE.num][columnI]);
study.setStudyAssayTechnologyType(values[RakipRow.STUDY_ASSAY_TECHNOLOGY_TYPE.num][columnI]);
study.setStudyAssayTechnologyPlatform(
values[RakipRow.STUDY_ASSAY_TECHNOLOGY_PLATFORM.num][columnI]);
study.setAccreditationProcedureForTheAssayTechnology(
values[RakipRow.STUDY_ACCREDITATION_PROCEDURE.num][columnI]);
study.setStudyProtocolName(values[RakipRow.STUDY_PROTOCOL_COMPONENTS_NAME.num][columnI]);
study.setStudyProtocolType(values[RakipRow.STUDY_PROTOCOL_TYPE.num][columnI]);
study.setStudyProtocolDescription(values[RakipRow.STUDY_PROTOCOL_DESCRIPTION.num][columnI]);
try {
study.setStudyProtocolURI(new URI(values[RakipRow.STUDY_PROTOCOL_URI.num][columnI]));
} catch (URISyntaxException exception) {
// does nothing
}
study.setStudyProtocolVersion(values[RakipRow.STUDY_PROTOCOL_VERSION.num][columnI]);
study.setStudyProtocolParametersName(
values[RakipRow.STUDY_PROTOCOL_PARAMETERS_NAME.num][columnI]);
study.setStudyProtocolComponentsName(
values[RakipRow.STUDY_PROTOCOL_COMPONENTS_NAME.num][columnI]);
study.setStudyProtocolComponentsType(
values[RakipRow.STUDY_PROTOCOL_COMPONENTS_TYPE.num][columnI]);
return study;
}
/** @throws IllegalArgumentException if a mandatory property is missing. */
static StudySample retrieveStudySample(String[][] values) {
int columnI = RakipColumn.I.ordinal();
// Check mandatory properties
if (values[RakipRow.STUDY_SAMPLE_NAME.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing sample name");
}
if (values[RakipRow.STUDY_SAMPLE_PROTOCOL.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing sampling plan");
}
if (values[RakipRow.STUDY_SAMPLE_STRATEGY.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing sampling weight");
}
StudySample studySample = MetadataFactory.eINSTANCE.createStudySample();
studySample.setSampleName(values[RakipRow.STUDY_SAMPLE_NAME.num][columnI]);
studySample
.setProtocolOfSampleCollection(values[RakipRow.STUDY_SAMPLE_PROTOCOL.num][columnI]);
studySample.setSamplingStrategy(values[RakipRow.STUDY_SAMPLE_STRATEGY.num][columnI]);
studySample.setTypeOfSamplingProgram(values[RakipRow.STUDY_SAMPLE_TYPE.num][columnI]);
studySample.setSamplingMethod(values[RakipRow.STUDY_SAMPLE_METHOD.num][columnI]);
studySample.setSamplingPlan(values[RakipRow.STUDY_SAMPLE_PLAN.num][columnI]);
studySample.setSamplingWeight(values[RakipRow.STUDY_SAMPLE_WEIGHT.num][columnI]);
studySample.setSamplingSize(values[RakipRow.STUDY_SAMPLE_SIZE.num][columnI]);
studySample.setLotSizeUnit(values[RakipRow.STUDY_SAMPLE_SIZE.num][columnI]);
studySample.setSamplingPoint(values[RakipRow.STUDY_SAMPLE_POINT.num][columnI]);
return studySample;
}
/** @throws IllegalArgumentException if a mandatory property is missing. */
static DietaryAssessmentMethod retrieveDAM(String[][] values) {
int columnI = RakipColumn.I.ordinal();
// Check mandatory properties
if (values[RakipRow.DIETARY_ASSESSMENT_METHOD_TOOL.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing methodological tool");
}
if (values[RakipRow.DIETARY_ASSESSMENT_METHOD_1DAY.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing non consecutive one day");
}
DietaryAssessmentMethod dietaryAssessmentMethod =
MetadataFactory.eINSTANCE.createDietaryAssessmentMethod();
String collectionTool = values[RakipRow.DIETARY_ASSESSMENT_METHOD_TOOL.num][columnI];
dietaryAssessmentMethod.setCollectionTool(collectionTool);
int numberOfNonConsecutiveOneDay =
Integer.parseInt(values[RakipRow.DIETARY_ASSESSMENT_METHOD_1DAY.num][columnI]);
dietaryAssessmentMethod.setNumberOfNonConsecutiveOneDay(numberOfNonConsecutiveOneDay);
String softwareTool = values[RakipRow.DIETARY_ASSESSMENT_METHOD_SOFTWARE_TOOL.num][columnI];
dietaryAssessmentMethod.setSoftwareTool(softwareTool);
String numberOfFoodItems = values[RakipRow.DIETARY_ASSESSMENT_METHOD_ITEMS.num][columnI];
dietaryAssessmentMethod.setNumberOfFoodItems(numberOfFoodItems);
String recordTypes = values[RakipRow.DIETARY_ASSESSMENT_METHOD_RECORD_TYPE.num][columnI];
dietaryAssessmentMethod.setRecordTypes(recordTypes);
String foodDescriptors = values[RakipRow.DIETARY_ASSESSMENT_METHOD_DESCRIPTORS.num][columnI];
dietaryAssessmentMethod.setFoodDescriptors(foodDescriptors);
return dietaryAssessmentMethod;
}
/** @throws IllegalArgumentException if a mandatory property is missing. */
static Laboratory retrieveLaboratory(String[][] values) {
int columnI = RakipColumn.I.ordinal();
// Check mandatory properties
if (values[RakipRow.LABORATORY_ACCREDITATION.num][columnI].isEmpty()) {
throw new IllegalArgumentException("Missing laboratory accreditation");
}
Laboratory laboratory = MetadataFactory.eINSTANCE.createLaboratory();
laboratory.getLaboratoryAccreditation()
.addAll(getStringObjectList(values, RakipRow.LABORATORY_ACCREDITATION, RakipColumn.I));
laboratory.setLaboratoryName(values[RakipRow.LABORATORY_NAME.num][columnI]);
laboratory.setLaboratoryCountry(values[RakipRow.LABORATORY_COUNTRY.num][columnI]);
return laboratory;
}
/** @throws IllegalArgumentException if a mandatory property is missing. */
static Assay retrieveAssay(String[][] values) {
int columnI = RakipColumn.I.ordinal();
Assay assay = MetadataFactory.eINSTANCE.createAssay();
assay.setAssayName(values[RakipRow.ASSAY_NAME.num][columnI]);
assay.setAssayDescription(values[RakipRow.ASSAY_DESCRIPTION.num][columnI]);
assay.setPercentageOfMoisture(values[RakipRow.ASSAY_MOIST_PERC.num][columnI]);
assay.setPercentageOfFat(values[RakipRow.ASSAY_FAT_PERC.num][columnI]);
assay.setLimitOfDetection(values[RakipRow.ASSAY_DETECTION_LIMIT.num][columnI]);
assay.setLimitOfQuantification(values[RakipRow.ASSAY_QUANTIFICATION_LIMIT.num][columnI]);
assay.setLeftCensoredData(values[RakipRow.ASSAY_LEFT_CENSORED_DATA.num][columnI]);
assay.setRangeOfContamination(values[RakipRow.ASSAY_CONTAMINATION_RANGE.num][columnI]);
assay.setUncertaintyValue(values[RakipRow.ASSAY_UNCERTAINTY_VALUE.num][columnI]);
return assay;
}
/** @throws IllegalArgumentException if a mandatory property is missing. */
static metadata.Parameter retrieveParameter(String[][] values, int row) {
// Check mandatory properties
if (values[row][RakipColumn.L.ordinal()].isEmpty()) {
throw new IllegalArgumentException("Missing parameter id");
}
if (values[row][RakipColumn.M.ordinal()].isEmpty()) {
throw new IllegalArgumentException("Missing parameter classification");
}
if (values[row][RakipColumn.N.ordinal()].isEmpty()) {
throw new IllegalArgumentException("Missing parameter name");
}
if (values[row][RakipColumn.Q.ordinal()].isEmpty()) {
throw new IllegalArgumentException("Missing parameter unit");
}
if (values[row][RakipColumn.S.ordinal()].isEmpty()) {
throw new IllegalArgumentException("Missing data type");
}
metadata.Parameter param = MetadataFactory.eINSTANCE.createParameter();
param.setParameterID(values[row][RakipColumn.L.ordinal()]);
String classificationText = values[row][RakipColumn.M.ordinal()].toLowerCase();
if (classificationText.startsWith("input")) {
param.setParameterClassification(ParameterClassification.INPUT);
} else if (classificationText.startsWith("constant")) {
param.setParameterClassification(ParameterClassification.CONSTANT);
} else if (classificationText.startsWith("output")) {
param.setParameterClassification(ParameterClassification.OUTPUT);
}
param.setParameterName(values[row][RakipColumn.N.ordinal()]);
param.setParameterDescription(values[row][RakipColumn.O.ordinal()]);
param.setParameterType(values[row][RakipColumn.P.ordinal()]);
param.setParameterUnit(values[row][RakipColumn.Q.ordinal()]);
param.setParameterUnitCategory(values[row][RakipColumn.R.ordinal()]);
try {
String dataTypeAsString = values[row][RakipColumn.S.ordinal()];
param.setParameterDataType(ParameterType.valueOf(dataTypeAsString));
} catch (IllegalArgumentException ex) {
param.setParameterDataType(ParameterType.OTHER);
}
param.setParameterSource(values[row][RakipColumn.T.ordinal()]);
param.setParameterSubject(values[row][RakipColumn.U.ordinal()]);
param.setParameterDistribution(values[row][RakipColumn.V.ordinal()]);
param.setParameterValue(values[row][RakipColumn.W.ordinal()]);
// reference
param.setParameterVariabilitySubject(values[row][RakipColumn.Y.ordinal()]);
// model applicability
param.setParameterError(values[row][RakipColumn.AA.ordinal()]);
return param;
}
}
/**
* Taken from {@link org.knime.ext.poi.node.read2.XLSUserSettings}.
*
* Opens and returns a new buffered input stream on the passed location. The location could either
* be a filename or a URL.
*
* @param location a filename or a URL
* @return a new opened buffered input stream.
* @throws IOException
*
*/
public static BufferedInputStream getBufferedInputStream(final String location)
throws IOException {
InputStream in;
try {
URL url = new URL(location);
in = FileUtil.openStreamWithTimeout(url);
} catch (MalformedURLException mue) {
// then try a file
in = new FileInputStream(location);
}
return new BufferedInputStream(in);
}
/**
* Taken from {@link org.knime.ext.poi.node.read2.XLSTableSettings}.
*
* Loads a workbook from the file system.
*
* @param path Path to the workbook
* @return The workbook or null if it could not be loaded
* @throws IOException
* @throws InvalidFormatException
* @throws RuntimeException the underlying POI library also throws other kind of exceptions
*/
public static Workbook getWorkbook(final String path) throws IOException, InvalidFormatException {
Workbook workbook = null;
InputStream in = null;
try {
in = getBufferedInputStream(path);
// This should be the only place in the code where a workbook gets loaded
workbook = WorkbookFactory.create(in);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e2) {
// ignore
}
}
}
return workbook;
}
}
| gpl-3.0 |
magarena/magarena | src/magic/ui/screen/card/explorer/OptionsPanel.java | 3508 | package magic.ui.screen.card.explorer;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import magic.translate.MText;
import magic.ui.FontsAndBorders;
import magic.ui.screen.ScreenOptionsPanel;
import magic.ui.screen.widget.BigDialButton;
import magic.ui.screen.widget.IDialButtonHandler;
import magic.ui.widget.cards.table.CardsTableStyle;
@SuppressWarnings("serial")
class OptionsPanel extends ScreenOptionsPanel {
// translatable UI text (prefix with _S).
private static final String _S1 = "Layout";
private static final String _S2 = "Style";
private final BigDialButton layoutButton;
private final BigDialButton styleButton;
private final ExplorerScreen screen;
OptionsPanel(final ExplorerScreen screen) {
this.screen = screen;
layoutButton = new BigDialButton(getLayoutHandler());
styleButton = new BigDialButton(getStyleHandler());
setLayout();
}
private IDialButtonHandler getStyleHandler() {
return new IDialButtonHandler() {
@Override
public int getDialPositionsCount() {
return CardsTableStyle.values().length;
}
@Override
public int getDialPosition() {
return CardsTableStyle.getStyle().ordinal();
}
@Override
public boolean doLeftClickAction(int dialPosition) {
screen.setCardsTableStyle(dialPosition);
return true;
}
@Override
public boolean doRightClickAction(int dialPosition) {
screen.setCardsTableStyle(dialPosition);
return true;
}
@Override
public void onMouseEntered(int dialPosition) {
// not supported
}
};
}
private IDialButtonHandler getLayoutHandler() {
return new IDialButtonHandler() {
@Override
public int getDialPositionsCount() {
return ExplorerScreenLayout.values().length;
}
@Override
public int getDialPosition() {
return ExplorerScreenLayout.getLayout().ordinal();
}
@Override
public boolean doLeftClickAction(int dialPosition) {
screen.doSwitchLayout();
return true;
}
@Override
public boolean doRightClickAction(int dialPosition) {
return false; // not supported.
}
@Override
public void onMouseEntered(int dialPosition) {
// not supported.
}
};
}
@Override
protected void setLayout() {
removeAll();
if (isMenuOpen) {
add(getLabel(MText.get(_S1)), "ax center, w 60!");
add(layoutButton, "ax center, h 24!, w 24!, gapbottom 2");
add(getLabel(MText.get(_S2)), "ax center, w 60!");
add(styleButton, "ax center, h 24!, w 24!, gapbottom 2");
add(closeButton, "spany 2, h 32!, w 32!");
} else {
add(menuButton, "spany 2, h 32!, w 32!");
}
revalidate();
repaint();
}
private JLabel getLabel(String text) {
JLabel lbl = new JLabel(text);
lbl.setForeground(Color.WHITE);
lbl.setFont(FontsAndBorders.FONT0);
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
}
}
| gpl-3.0 |
kwhite17/Nudge | app/src/main/java/com/ksp/nudge/model/NudgeConfig.java | 1962 | package com.ksp.nudge.model;
import com.google.auto.value.AutoValue;
import org.joda.time.Instant;
import androidx.annotation.Nullable;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
/**
* Created by kevin on 9/24/2018.
*/
@AutoValue
@Entity(tableName = "nudges")
public abstract class NudgeConfig {
@AutoValue.CopyAnnotations
@PrimaryKey(autoGenerate = true)
@Nullable
public abstract Long getId();
public abstract String getMessage();
public abstract NudgeFrequency getFrequency();
public abstract Instant getSendTime();
public static NudgeConfig create(Long id, String message, NudgeFrequency frequency, Instant
sendTime) {
return new AutoValue_NudgeConfig.Builder()
.setId(id)
.setMessage(message)
.setFrequency(frequency)
.setSendTime(sendTime)
.build();
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_NudgeConfig.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder setId(Long id);
public abstract Builder setMessage(String message);
public abstract Builder setFrequency(NudgeFrequency frequency);
public abstract Builder setSendTime(Instant sendTime);
public abstract NudgeConfig build();
}
public NudgeConfig withMessage(String message) {
return toBuilder().setMessage(message).build();
}
public NudgeConfig withFrequency(NudgeFrequency frequency) {
return toBuilder().setFrequency(frequency).build();
}
public NudgeConfig withSendTime(Instant sendTime) {
return toBuilder().setSendTime(sendTime).build();
}
public NudgeConfig withId(Long id) {
return toBuilder().setId(id).build();
}
}
| gpl-3.0 |
gitools/gitools | org.gitools.analysis/src/main/java/org/gitools/analysis/clustering/hierarchical/strategy/SingleLinkageStrategy.java | 2043 | /*
* #%L
* gitools-core
* %%
* Copyright (C) 2013 Universitat Pompeu Fabra - Biomedical Genomics group
* %%
* 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%
*/
/*******************************************************************************
* Copyright 2013 Lars Behnke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.gitools.analysis.clustering.hierarchical.strategy;
import java.util.List;
public class SingleLinkageStrategy implements LinkageStrategy {
@Override
public Double calculateDistance(List<Double> distances) {
double min = Double.NaN;
for (Double dist : distances) {
if (Double.isNaN(min) || dist < min)
min = dist;
}
return min;
}
@Override
public String toString() {
return "Single (minimum)";
}
}
| gpl-3.0 |
oscaraya/VCMS-SC | src/sg/edu/nus/iss/vmcs/store/CashStore.java | 2504 | /*
* Copyright 2003 ISS.
* The contents contained in this document may not be reproduced in any
* form or by any means, without the written permission of ISS, other
* than for the purpose for which it has been supplied.
*
*/
package sg.edu.nus.iss.vmcs.store;
/**
* This object represents the store of cash in the vending machine.
*
* @see CashStoreItem
* @see Coin
* @see DrinksBrand
* @see DrinksStore
* @see DrinksStoreItem
* @see Store
* @see StoreController
* @see StoreItem
* @see StoreObject
*
* @version 3.0 5/07/2003
* @author Olivo Miotto, Pang Ping Li
*/
public class CashStore extends Store {
/**This is the constant for coin invalid weight.*/
public final static int INVALID_COIN_WEIGHT = 9999;
/**
* This constructor creates an instance of the CashStore object.
*/
public CashStore() {
}
/**
* This method find and returns the index of the coin in the CashStore of the given Coin.
* @param c the Coin of interest.
* @return the index of the given Coin. Return -1 if unknown Coin is detected.
*/
public int findCashStoreIndex (Coin c) {
int size = getStoreSize();
for (int i = 0; i < size; i++) {
StoreItem item = (CashStoreItem) getStoreItem(i);
Coin current = (Coin) item.getContent();
if (current.getWeight() == c.getWeight())
return i;
}
return -1;
}
/**
* This method determine whether the given weight of the {@link Coin} is valid.
* @param weight the weight of the Coin to be tested.
* @return TRUE if the weight is valid, otherwise, return FALSE.
*/
public boolean isValidWeight(double weight){
int size = getStoreSize();
for (int i = 0; i < size; i++) {
StoreItem item = (CashStoreItem) getStoreItem(i);
Coin current = (Coin) item.getContent();
if (current.getWeight() == weight)
return true;
}
return false;
}
/**
* This method will locate a {@link Coin} denomination held, with the input data
* (coin weight). If found, it returns an existence identifier (reference).
* Otherwise, it informs the requestor that the coin is invalid.
* @param weight the weight of the coin to be found.
* @return Coin the coin which has the input weight.
*/
public Coin findCoin(double weight){
int size = getStoreSize();
for (int i = 0; i < size; i++) {
StoreItem item = (CashStoreItem) getStoreItem(i);
Coin current = (Coin) item.getContent();
if (current.getWeight() == weight)
return current;
}
return null;
}
}//End of class CashStore | gpl-3.0 |
hamstercommunity/openfasttrack | product/src/test/java/org/itsallcode/openfasttrace/core/serviceloader/TestInitializingServiceLoader.java | 4212 | package org.itsallcode.openfasttrace.core.serviceloader;
/*-
* #%L
\* OpenFastTrace
* %%
* Copyright (C) 2016 - 2017 itsallcode.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 (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 static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.List;
import java.util.stream.StreamSupport;
import org.itsallcode.openfasttrace.api.core.serviceloader.Initializable;
import org.itsallcode.openfasttrace.api.exporter.ExporterContext;
import org.itsallcode.openfasttrace.api.exporter.ExporterFactory;
import org.itsallcode.openfasttrace.api.importer.ImporterContext;
import org.itsallcode.openfasttrace.api.importer.ImporterFactory;
import org.itsallcode.openfasttrace.exporter.specobject.SpecobjectExporterFactory;
import org.itsallcode.openfasttrace.importer.markdown.MarkdownImporterFactory;
import org.itsallcode.openfasttrace.importer.specobject.SpecobjectImporterFactory;
import org.itsallcode.openfasttrace.importer.tag.TagImporterFactory;
import org.itsallcode.openfasttrace.importer.zip.ZipFileImporterFactory;
import org.junit.jupiter.api.Test;
/**
* Test for {@link InitializingServiceLoader}
*/
class TestInitializingServiceLoader
{
@Test
void testNoServicesRegistered()
{
final Object context = new Object();
final InitializingServiceLoader<InitializableServiceStub, Object> voidServiceLoader = InitializingServiceLoader
.load(InitializableServiceStub.class, context);
final List<InitializableServiceStub> services = StreamSupport
.stream(voidServiceLoader.spliterator(), false).collect(toList());
assertThat(services, emptyIterable());
assertThat(voidServiceLoader, emptyIterable());
}
@SuppressWarnings("unchecked")
@Test
void testImporterFactoriesRegistered()
{
final ImporterContext context = new ImporterContext(null);
final List<ImporterFactory> services = getRegisteredServices(ImporterFactory.class,
context);
assertThat(services, hasSize(4));
assertThat(services, contains(instanceOf(MarkdownImporterFactory.class), //
instanceOf(SpecobjectImporterFactory.class), //
instanceOf(TagImporterFactory.class), //
instanceOf(ZipFileImporterFactory.class)));
for (final ImporterFactory importerFactory : services)
{
assertThat(importerFactory.getContext(), sameInstance(context));
}
}
@Test
void testExporterFactoriesRegistered()
{
final ExporterContext context = new ExporterContext();
final List<ExporterFactory> services = getRegisteredServices(ExporterFactory.class,
context);
assertThat(services, hasSize(1));
assertThat(services, contains(instanceOf(SpecobjectExporterFactory.class)));
for (final ExporterFactory factory : services)
{
assertThat(factory.getContext(), sameInstance(context));
}
}
private <T extends Initializable<C>, C> List<T> getRegisteredServices(final Class<T> type,
final C context)
{
final InitializingServiceLoader<T, C> serviceLoader = InitializingServiceLoader.load(type,
context);
return StreamSupport.stream(serviceLoader.spliterator(), false).collect(toList());
}
class InitializableServiceStub implements Initializable<Object>
{
@Override
public void init(final Object context)
{
}
}
}
| gpl-3.0 |
BestLice/Nami-Antragshelfer | src/nami/program/applicationForms/WriterAntragLand.java | 3778 | package nami.program.applicationForms;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import nami.connector.Geschlecht;
import nami.connector.namitypes.NamiMitglied;
import org.odftoolkit.simple.TextDocument;
import org.odftoolkit.simple.table.Table;
public class WriterAntragLand extends WriterAntrag{
public WriterAntragLand(JFrame owner) {
super(owner);
}
@Override
public void doTheMagic(List<NamiMitglied> participants, TextDocument odtDoc){
//association data
Table tAssociation = odtDoc.getTableList().get(0);
//Mitgliedsverband
tAssociation.getCellByPosition(2, 0).setStringValue(userInput.getOption(0).toString());
//Tr�ger
tAssociation.getCellByPosition(2, 1).setStringValue(userInput.getOption(1).toString());
//event data
Table tEvent = odtDoc.getTableList().get(1);
//Datum (von-bis)
if(!(Boolean)userInput.getOption(6).getValue()){
tEvent.getCellByPosition(1, 0).setStringValue(userInput.getOption(2).toString()+" - "+userInput.getOption(3).toString());
}
//PLZ Ort
tEvent.getCellByPosition(3, 0).setStringValue(userInput.getOption(4).toString());
//Land
tEvent.getCellByPosition(5, 0).setStringValue(userInput.getOption(5).toString());
//participants data
Table tParticipants = odtDoc.getTableList().get(2);
for(int i=0; i<participants.size(); i++){
int row = i+1;
NamiMitglied m = participants.get(i);
if(m!=null){
//Lfd. Nr.
//Kursleiter K= Kursleiter, R= Referent, L= Leiter
//Name, Vorname
tParticipants.getCellByPosition(2, row).setStringValue(m.getNachname()+", "+m.getVorname());
//Anschrift: Straße, PLZ, Wohnort
tParticipants.getCellByPosition(3, row).setStringValue(m.getStrasse()+", "+m.getPLZ()+", "+m.getOrt());
//w=weibl. m=männl.
if(m.getGeschlecht()==Geschlecht.MAENNLICH){
tParticipants.getCellByPosition(4, row).setStringValue("m");
}
if(m.getGeschlecht()==Geschlecht.WEIBLICH){
tParticipants.getCellByPosition(4, row).setStringValue("w");
}
//Alter
if(!(Boolean)userInput.getOption(6).getValue()){
try {
//compute age
Date birthDate = sdfDB.parse(m.getGeburtsDatum());
int diffInYearsStart = (int)Math.floor((((Date) userInput.getOption(2).getValue()).getTime()-birthDate.getTime()) / (1000 * 60 * 60 * 24 * 365.242));
int diffInYearsEnd = (int)Math.floor((((Date) userInput.getOption(3).getValue()).getTime()-birthDate.getTime()) / (1000 * 60 * 60 * 24 * 365.242));
if(diffInYearsEnd>diffInYearsStart){
//participant has his/her birthday at the event
tParticipants.getCellByPosition(5, row).setStringValue(String.valueOf(diffInYearsStart)+"-"+String.valueOf(diffInYearsEnd));
}else{
tParticipants.getCellByPosition(5, row).setStringValue(String.valueOf(diffInYearsStart));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
}
@Override
public int getMaxParticipantsPerPage() {
return 15;
}
@Override
protected String getResourceFileName() {
return "Land_Blanco.odt";
}
@Override
protected void initializeOptions() {
userInput.addStringOption("Mitgliedsverband", "DPSG Diözesanverband Münster"); //0
userInput.addStringOption("Träger", "BDKJ Stadtverband Dinslaken"); //1
userInput.addDateOption("Anfangsdatum", new Date()); //2
userInput.addDateOption("Enddatum", new Date()); //3
userInput.addStringOption("PLZ Ort", "46535 Dinslaken"); //4
userInput.addStringOption("Land", "Deutschland"); //5
userInput.addBooleanOption("Datum freilassen", false); //6
}
}
| gpl-3.0 |
LarsImNetz/code-dojo | diamond/src/main/java/org/linuxx/moonserver/codedojo/diamond/App.java | 563 | package org.linuxx.moonserver.codedojo.diamond;
/**
* Create a Diamond Printer
*
* Wird gefüttert mit 'A'
* und gibt aus:
* A
*
* Wird gefüttert mit 'B' und gibt aus:
* A
* B B
* A
*
* Wird gefüttert mit 'C' und gibt aus:
* A
* B B
* C C
* B B
* A
*
*/
public class App {
public static void main(String[] args) {
System.out.println("Diamond Printer!");
for (char c = 'A'; c <= 'Z'; c++) {
System.out.println("Diamond for " + c);
System.out.println(new DiamondPrinter().diamond(c));
System.out.println();
}
}
}
| gpl-3.0 |
derekmanwaring/boltzmann-3d | src/edu/byu/chem/boltzmann/model/statistics/WallPressure.java | 7956 | /*
* Boltzmann 3D, a kinetic theory demonstrator
* Copyright (C) 2013 Dr. Randall B. Shirts
*
* 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 edu.byu.chem.boltzmann.model.statistics;
import edu.byu.chem.boltzmann.model.physics.Collision;
import edu.byu.chem.boltzmann.model.physics.EventInfo;
import edu.byu.chem.boltzmann.model.physics.FrameInfo;
import edu.byu.chem.boltzmann.model.physics.PartState;
import edu.byu.chem.boltzmann.utils.data.ParticleType;
import edu.byu.chem.boltzmann.utils.data.SimulationInfo.ArenaType;
import edu.byu.chem.boltzmann.utils.Units;
import edu.byu.chem.boltzmann.model.physics.Wall;
import edu.byu.chem.boltzmann.model.physics.Particle;
import edu.byu.chem.boltzmann.model.physics.Physics;
import edu.byu.chem.boltzmann.model.physics.Piston;
import java.util.LinkedList;
import java.util.Set;
/**
* Created Feb 2011
* @author Derek Manwaring
*/
public class WallPressure extends Pressure {
private class PressureVal {
private double time = 0.0;
private double value = 0.0;
PressureVal (double time, double value) {
this.time = time;
this.value = value;
}
}
private static final String DISPLAY_NAME = "Wall Pressure";
private LinkedList<PressureVal> recordedPressureValues = new LinkedList<PressureVal>();
private double totalPressureValue = 0.0; //Over pressure averaging time
private double cumulativePressureValue = 0.0; //Over entire simulation
private double startRecordTime = 0.0;
private double averagingTime = Units.convert("ps", "s", 60.0);
private boolean enoughValuesRecorded = false; //True when recorded values span the averaging time
private double effectiveYLen;
@Override
public String getDisplayName() {
return DISPLAY_NAME;
}
@Override
public void initiateStatistic(Set<ParticleType> types, Physics physics) {
super.initiateStatistic(types, physics);
piston = physics.getPiston();
startRecordTime = physics.getTime();
effectiveYLen = simulationInfo.arenaYSize * 2.0; //WallPressure measured from left and right sides
}
protected void updateStatisticAvgs(FrameInfo frame) {
// double effectiveYLen = simulationInfo.arenaYSize * 2.0; //WallPressure measured from left and right sides
//
// for (EventInfo event: frame.getEvents()) {
// if (shouldRecordCollision(event)) {
// if (simulationInfo.arenaType == ArenaType.MOVABLE_PISTON) {
// double pistonPos = frame.getPistonPosition(event.colTime);
// effectiveYLen = pistonPos * 2.0;
// }
//
// Particle collisionPart = event.getInvolvedParticles()[0];
// PartState collState = frame.getParticleState(collisionPart, event.colTime);
//
// if (shouldRecordStats(collState.color)) {
// double momentumChange = Math.abs(
// collState.velocity[0] * Units.convert("amu", "kg", collisionPart.mass));
//
// recordCollision(momentumChange, collisionPart.radius, effectiveYLen, event.colTime);
// }
// }
// }
}
private final PartState workingState = new PartState(0, 0, 0, 0, null, 0);
private Piston piston;
@Override
public void updateByEvent(EventInfo event) {
if (shouldRecordCollision(event)) {
if (simulationInfo.arenaType == ArenaType.MOVABLE_PISTON) {
double pistonPos = piston.getPosition();
effectiveYLen = pistonPos * 2.0;
}
Particle collisionPart = event.getInvolvedParticles()[0];
PartState collState = collisionPart.getState(workingState);
if (shouldRecordStats(collState.color)) {
double momentumChange = Math.abs(
collState.velocity[0] * Units.convert("amu", "kg", collisionPart.mass));
recordCollision(momentumChange, collisionPart.radius, effectiveYLen, event.colTime);
}
}
}
private boolean shouldRecordCollision(EventInfo event) {
boolean recordCollision = false;
if (event.colType == Collision.WALL) {
if (event.side == Wall.LEFT || event.side == Wall.RIGHT) {
recordCollision = true;
}
}
return recordCollision;
}
private void recordCollision(double momentumChange, double particleRadius, double effectiveYLen, double time) {
double value = 0.0;
double diam = 2.0 * particleRadius;
switch (simulationInfo.dimension) {
case 1:
value = 2.0 * momentumChange;
break;
case 2:
value = 2.0 * momentumChange / (effectiveYLen - diam);
break;
case 3:
value = 2.0 * momentumChange / ((effectiveYLen - diam) * (simulationInfo.arenaZSize - diam));
}
updatePressureValues(value, time);
}
private void updatePressureValues(double newValue, double currentTime) {
recordedPressureValues.add(new PressureVal(currentTime, newValue));
totalPressureValue += newValue;
cumulativePressureValue += newValue;
if (!recordedPressureValues.isEmpty()) {
PressureVal firstVal = recordedPressureValues.getFirst();
//Remove values older than the averaging time from the list of values
while (firstVal.time < (currentTime - averagingTime)) {
enoughValuesRecorded = true;
double removeValue = recordedPressureValues.removeFirst().value;
totalPressureValue -= removeValue;
if (recordedPressureValues.isEmpty()) {
break;
} else {
firstVal = recordedPressureValues.getFirst();
}
}
}
}
@Override
public double getAverage() {
double totalTime = lastFrameEndTime - startRecordTime;
if (totalTime == 0.0) {
return 0.0;
}
double pressureBadUnits = cumulativePressureValue / totalTime;
double pressure = changePressureUnits(pressureBadUnits);
return pressure;
}
@Override
public double getInstAverage() {
if (recordedPressureValues.size() == 0) {
return 0.0;
}
double totalTime = 0.0;
if (enoughValuesRecorded) {
totalTime = averagingTime;
} else {
totalTime = recordedPressureValues.getLast().time -
recordedPressureValues.getFirst().time;
if (totalTime == 0.0) {
return 0.0;
}
}
double pressureBadUnits = totalPressureValue / totalTime;
double pressure = changePressureUnits(pressureBadUnits);
return pressure;
}
@Override
public void reset(double newStartTime, Physics physics) {
super.reset(newStartTime, physics);
enoughValuesRecorded = false;
recordedPressureValues.clear();
totalPressureValue = 0.0;
cumulativePressureValue = 0.0;
startRecordTime = newStartTime;
}
}
| gpl-3.0 |
vmatare/modcal | org/modcal/output/ModelOutputWrapper2.java | 1596 | package org.modcal.output;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import org.modcal.data.DoubleSample;
import org.modcal.data.ObservationData;
public class ModelOutputWrapper2 implements Serializable {
private static final long serialVersionUID = -1994384848968878098L;
private String[] paramNames;
private Double[][] output;
private Double[][] observed;
public ModelOutputWrapper2() {}
public ModelOutputWrapper2(ModelOutput o, ObservationData observed) {
this();
Set<String> tmpNames = o.getSimulated().firstEntry().getValue().keySet();
int numParams = tmpNames.size() + 1;
paramNames = new String[numParams];
paramNames[0] = "Time";
int i = 1;
for (String s : o.getSimulated().firstEntry().getValue().keySet())
paramNames[i++] = s;
output = new Double[o.getSimulated().entrySet().size()][numParams];
i = 0;
int j;
for (Map.Entry<Double, DoubleSample> e : o.getSimulated().entrySet()) {
j = 0;
output[i][j++] = e.getKey();
for (; j < numParams; j++)
output[i][j] = e.getValue().get(paramNames[j]);
i++;
}
}
public String[] getParamNames() {
return paramNames;
}
public void setParamNames(String[] paramNames) {
this.paramNames = paramNames;
}
public Double[][] getOutput() {
return output;
}
public void setOutput(Double[][] data) {
this.output = data;
}
public Double[][] getObserved() {
return observed;
}
public void setObserved(Double[][] observed) {
this.observed = observed;
}
}
| gpl-3.0 |
qt-haiku/LibreOffice | scripting/java/com/sun/star/script/framework/io/XStorageHelper.java | 8537 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
package com.sun.star.script.framework.io;
import com.sun.star.frame.XModel;
import com.sun.star.container.XNameAccess;
import com.sun.star.uno.XInterface;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.lang.XComponent;
import com.sun.star.uno.AnyConverter;
import com.sun.star.io.XStream;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.embed.XStorage;
import com.sun.star.embed.XTransactedObject;
import com.sun.star.document.XDocumentSubStorageSupplier;
import com.sun.star.beans.XPropertySet;
import com.sun.star.lang.XEventListener;
import com.sun.star.lang.EventObject;
import com.sun.star.script.framework.log.LogUtils;
import com.sun.star.script.framework.provider.PathUtils;
import java.util.*;
import java.io.*;
public class XStorageHelper implements XEventListener
{
XStorage[] xStorages;
XStream xStream;
XInputStream xIs = null;
XOutputStream xOs = null;
static Map<String,XModel> modelMap = new HashMap<String,XModel>();
XModel xModel = null;
private static XStorageHelper listener = new XStorageHelper();
private XStorageHelper() {}
public XStorageHelper( String path, int mode, boolean create ) throws IOException
{
String modelUrl = null;
int indexOfScriptsDir = path.lastIndexOf( "Scripts" );
if ( indexOfScriptsDir > -1 )
{
modelUrl = path.substring( 0, indexOfScriptsDir - 1 );
path = path.substring( indexOfScriptsDir, path.length());
}
LogUtils.DEBUG("XStorageHelper ctor, path: " + path);
this.xModel = getModelForURL( modelUrl );
try
{
StringTokenizer tokens = new StringTokenizer(path, "/");
if (tokens.countTokens() == 0)
{
throw new IOException("Invalid path");
}
XDocumentSubStorageSupplier xDocumentSubStorageSupplier =
UnoRuntime.queryInterface(
XDocumentSubStorageSupplier.class, xModel);
xStorages = new XStorage[tokens.countTokens() ];
LogUtils.DEBUG("XStorageHelper ctor, path chunks length: " + xStorages.length );
for ( int i = 0; i < xStorages.length; i++ )
{
LogUtils.DEBUG("XStorageHelper, processing index " + i );
String name = tokens.nextToken();
LogUtils.DEBUG("XStorageHelper, getting: " + name);
XStorage storage = null;
if ( i == 0 )
{
storage = xDocumentSubStorageSupplier.getDocumentSubStorage( name, mode );
if ( storage == null )
{
LogUtils.DEBUG("** boo hoo Storage is null " );
}
XPropertySet xProps = UnoRuntime.queryInterface(XPropertySet.class,storage );
if ( xProps != null )
{
String mediaType = AnyConverter.toString( xProps.getPropertyValue( "MediaType" ) );
LogUtils.DEBUG("***** media type is " + mediaType );
if ( !mediaType.equals("scripts") )
{
xProps.setPropertyValue("MediaType","scripts");
}
}
}
else
{
XNameAccess xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, xStorages[i-1]);
if (xNameAccess == null )
{
disposeObject();
throw new IOException("No name access " + name);
}
else if ( !xNameAccess.hasByName(name) || !xStorages[i-1].isStorageElement(name) )
{
if ( !create )
{
disposeObject();
throw new IOException("No subdir: " + name);
}
else
{
// attempt to create new storage
LogUtils.DEBUG("Attempt to create new storage for " + name );
}
}
storage = xStorages[i-1].openStorageElement(
name, mode );
}
if ( storage == null )
{
disposeObject();
throw new IOException("storage not found: " + name);
}
xStorages[ i ] = storage;
}
}
catch ( com.sun.star.io.IOException ioe)
{
disposeObject();
}
catch (com.sun.star.uno.Exception e)
{
disposeObject();
throw new IOException(e.getMessage());
}
}
public synchronized static void addNewModel( XModel model )
{
// TODO needs to cater for model for untitled document
modelMap.put( PathUtils.getOidForModel( model ), model );
XComponent xComp = UnoRuntime.queryInterface(XComponent.class, model);
if ( xComp != null )
{
try
{
xComp.addEventListener( listener );
}
catch ( Exception e )
{
// What TODO here ?
LogUtils.DEBUG( LogUtils.getTrace( e ) );
}
}
}
public void disposing( EventObject Source )
{
XModel model = UnoRuntime.queryInterface(XModel.class,Source.Source );
if ( model != null )
{
LogUtils.DEBUG(" Disposing doc " + model.getURL() );
Object result = modelMap.remove( model );
result = null;
}
}
public XStorage getStorage()
{
return xStorages[ xStorages.length - 1 ];
}
public XModel getModel()
{
return xModel;
}
public void disposeObject()
{
disposeObject( false );
}
public void disposeObject( boolean shouldCommit )
{
LogUtils.DEBUG("In disposeObject");
for ( int i = xStorages.length -1 ; i > -1; i-- )
{
LogUtils.DEBUG("In disposeObject disposing storage " + i );
try
{
XStorage xStorage = xStorages[i];
if ( shouldCommit )
{
commit(xStorage);
}
disposeObject(xStorage);
LogUtils.DEBUG("In disposeObject disposed storage " + i );
}
catch( Exception ignore )
{
LogUtils.DEBUG("Exception disposing storage " + i );
}
}
}
static public void disposeObject( XInterface xInterface )
{
if (xInterface == null) {
return;
}
XComponent xComponent = UnoRuntime.queryInterface(XComponent.class, xInterface);
if (xComponent == null) {
return;
}
xComponent.dispose();
}
static public void commit( XInterface xInterface )
{
XTransactedObject xTrans = UnoRuntime.queryInterface(XTransactedObject.class, xInterface);
if ( xTrans != null )
{
try
{
xTrans.commit();
}
catch ( Exception e )
{
LogUtils.DEBUG("Something went bellyup exception: " + e );
}
}
}
public XModel getModelForURL( String url )
{
//TODO does not cater for untitled documents
return modelMap.get( url );
}
}
| gpl-3.0 |
shelllbw/workcraft | WorkcraftCore/src/org/workcraft/formula/utils/BooleanReplacer.java | 5443 | /*
*
* Copyright 2008,2009 Newcastle University
*
* This file is part of Workcraft.
*
* Workcraft 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.
*
* Workcraft 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 Workcraft. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.workcraft.formula.utils;
import static org.workcraft.formula.BooleanOperations.and;
import static org.workcraft.formula.BooleanOperations.iff;
import static org.workcraft.formula.BooleanOperations.imply;
import static org.workcraft.formula.BooleanOperations.not;
import static org.workcraft.formula.BooleanOperations.or;
import static org.workcraft.formula.BooleanOperations.xor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.workcraft.formula.And;
import org.workcraft.formula.BinaryBooleanFormula;
import org.workcraft.formula.BooleanFormula;
import org.workcraft.formula.BooleanVariable;
import org.workcraft.formula.BooleanVisitor;
import org.workcraft.formula.BooleanWorker;
import org.workcraft.formula.Iff;
import org.workcraft.formula.Imply;
import org.workcraft.formula.Not;
import org.workcraft.formula.One;
import org.workcraft.formula.Or;
import org.workcraft.formula.Xor;
import org.workcraft.formula.Zero;
public class BooleanReplacer implements BooleanVisitor<BooleanFormula> {
interface BinaryOperation {
BooleanFormula apply(BooleanFormula x, BooleanFormula y);
}
private final HashMap<BooleanFormula, BooleanFormula> map;
private final BooleanWorker worker;
public BooleanReplacer(List<? extends BooleanVariable> from, List<? extends BooleanFormula> to, BooleanWorker worker) {
this.map = new HashMap<BooleanFormula, BooleanFormula>();
if (from.size() != to.size()) {
throw new RuntimeException("Length of the variable list must be equal to that of formula list.");
}
for (int i = 0; i < from.size(); i++) {
this.map.put(from.get(i), to.get(i));
}
this.worker = worker;
}
public BooleanReplacer(Map<? extends BooleanVariable, ? extends BooleanFormula> map, BooleanWorker worker) {
this.map = new HashMap<BooleanFormula, BooleanFormula>(map);
this.worker = worker;
}
protected BooleanFormula visitBinaryFunc(BinaryBooleanFormula node, BinaryOperation op) {
BooleanFormula result = map.get(node);
if (result == null) {
BooleanFormula x = node.getX().accept(this);
BooleanFormula y = node.getY().accept(this);
if (node.getX() == x && node.getY() == y) {
result = node;
} else {
result = op.apply(x, y);
}
map.put(node, result);
}
return result;
}
@Override
public BooleanFormula visit(Zero node) {
return node;
}
@Override
public BooleanFormula visit(One node) {
return node;
}
@Override
public BooleanFormula visit(BooleanVariable node) {
BooleanFormula replacement = map.get(node);
return replacement != null ? replacement : node;
}
@Override
public BooleanFormula visit(Not node) {
BooleanFormula result = map.get(node);
if (result == null) {
BooleanFormula x = node.getX().accept(this);
if (node.getX() == x) {
result = node;
} else {
result = not(x);
}
map.put(node, result);
}
return result;
}
@Override
public BooleanFormula visit(And node) {
return visitBinaryFunc(node, new BinaryOperation() {
@Override
public BooleanFormula apply(BooleanFormula x, BooleanFormula y) {
return and(x, y, worker);
}
});
}
@Override
public BooleanFormula visit(Or node) {
return visitBinaryFunc(node, new BinaryOperation() {
@Override
public BooleanFormula apply(BooleanFormula x, BooleanFormula y) {
return or(x, y, worker);
}
});
}
@Override
public BooleanFormula visit(Iff node) {
return visitBinaryFunc(node, new BinaryOperation() {
@Override
public BooleanFormula apply(BooleanFormula x, BooleanFormula y) {
return iff(x, y, worker);
}
});
}
@Override
public BooleanFormula visit(Xor node) {
return visitBinaryFunc(node, new BinaryOperation() {
@Override
public BooleanFormula apply(BooleanFormula x, BooleanFormula y) {
return xor(x, y, worker);
}
});
}
@Override
public BooleanFormula visit(Imply node) {
return visitBinaryFunc(node, new BinaryOperation() {
@Override
public BooleanFormula apply(BooleanFormula x, BooleanFormula y) {
return imply(x, y, worker);
}
});
}
}
| gpl-3.0 |
yadickson/autoplsp | src/test/java/com/github/yadickson/autoplsp/db/parameter/CharParameterTest.java | 2843 | /*
* Copyright (C) 2019 Yadickson Soto
*
* 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.github.yadickson.autoplsp.db.parameter;
import com.github.yadickson.autoplsp.db.common.Direction;
import com.github.yadickson.autoplsp.db.common.Procedure;
import com.github.yadickson.autoplsp.handler.BusinessException;
import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
* Pruebas para la clase CharParameter
*
* @author Yadickson Soto
*/
public class CharParameterTest {
private CharParameter parameter;
@Before
public void setup() {
parameter = new CharParameter(0, null, Direction.INPUT, "", new Procedure(true, "", "", "", ""), "", "");
}
@Test
public void testGetParameters() throws BusinessException {
Assert.assertNotNull(parameter.getParameters());
}
@Test(expected = Exception.class)
public void testSetParameters() throws BusinessException {
parameter.setParameters(null);
}
@Test
public void testGetJavaTypeName() throws BusinessException {
String javaType = parameter.getJavaTypeName();
assertNotNull(javaType);
assertEquals("String", javaType);
}
@Test
public void testGetSqlType() throws BusinessException {
int sqlType = parameter.getSqlType();
assertEquals(java.sql.Types.VARCHAR, sqlType);
}
@Test
public void testGetSqlTypeName() throws BusinessException {
String sqlType = parameter.getSqlTypeName();
assertNotNull(sqlType);
assertEquals("java.sql.Types.VARCHAR", sqlType);
}
@Test
public void tesNumberFalse() throws BusinessException {
assertFalse(parameter.isNumber());
}
@Test
public void tesStringTrue() throws BusinessException {
assertTrue(parameter.isString());
}
@Test
public void testResultSetFalse() throws BusinessException {
assertFalse(parameter.isResultSet());
}
@Test
public void testObjectFalse() throws BusinessException {
assertFalse(parameter.isObject());
}
@Test
public void tesArrayFalse() throws BusinessException {
assertFalse(parameter.isArray());
}
}
| gpl-3.0 |