repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
xavierhardy/ecm-clustering | src/FiltreFichiersImages.java | 2269 | /*
Copyright 2014, Xavier Hardy, Clément Pique
This file is part of ecm-classifier.
ecm-classifier 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.
ecm-classifier 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 ecm-classifier. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class FiltreFichiersImages extends FileFilter {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = Outils.getExtension(f);
if (extension != null) {
if (extension.equals(Outils.tiff) ||
extension.equals(Outils.tif) ||
extension.equals(Outils.gif) ||
extension.equals(Outils.jpeg) ||
extension.equals(Outils.jpg) ||
extension.equals(Outils.png)||
extension.equals(Outils.bmp)) {
return true;
} else {
return false;
}
}
return false;
}
public String getTypeDescription(File f) {
String extension = Outils.getExtension(f);
String type = null;
if (extension != null) {
if (extension.equals(Outils.jpeg) ||
extension.equals(Outils.jpg)) {
type = "Image JPEG";
} else if (extension.equals(Outils.gif)){
type = "Image GIF";
} else if (extension.equals(Outils.tiff) ||
extension.equals(Outils.tif)) {
type = "Image TIFF";
} else if (extension.equals(Outils.png)){
type = "Image PNG";
} else if (extension.equals(Outils.bmp)){
type = "Image BMP";}
}
return type;
}
public String getDescription() {
return "Images (*.jpeg, *.jpg, *.gif, *.tif, *.tiff, *.png, *.bmp)";
}
}
| gpl-2.0 |
MarcosHP85/pyp | src/main/java/ar/nasa/pyp/config/security/DbUserDetailsContextMapper.java | 2445 | package ar.nasa.pyp.config.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import ar.nasa.pyp.domain.Role;
import ar.nasa.pyp.domain.User;
import ar.nasa.pyp.service.RoleServiceImpl;
import ar.nasa.pyp.service.UserServiceImpl;
public class DbUserDetailsContextMapper implements UserDetailsContextMapper {
@Autowired
UserServiceImpl userService;
@Autowired
RoleServiceImpl roleService;
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
UserDetails user = null;
try {
Attributes attr = ctx.getAttributes();
try {
user = userService.loadUserByUsername(username);
} catch(UsernameNotFoundException e) {
user = crearUsuario(username,
attr.get("givenName").get(0).toString(),
attr.get("sn").get(0).toString(),
attr.get("mail").get(0).toString());
}
System.out.println("Desde CustomUserDetailsContextMapper.mapUserFromContext:");
System.out.println("\t" + attr.get("sn").get(0) + ", " + attr.get("givenName").get(0) + ", " + attr.get("mail").get(0) + ", " + attr.get("description").get(0));
System.out.println(user);
} catch (NamingException e) {
e.printStackTrace();
}
return user;
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
// TODO Auto-generated method stub
System.out.println();
}
private UserDetails crearUsuario(String username, String nombre,
String apellido, String email) {
Role role = roleService.findByName("ROLE_NUEVO");
Set<Role> roles = new HashSet<Role>();
roles.add(role);
User tmp = new User(username, true, nombre, apellido, email, roles);
userService.save(tmp);
return (UserDetails) tmp;
}
}
| gpl-2.0 |
Disguiser-w/SE2 | 12.09DDL/ELS_CLIENT/src/test/java/intermediatetest/EntrainingIntegration.java | 793 | package intermediatetest;
import businesslogic.intermediatebl.envehiclebl.AllocateWaitingOrderBL;
import businesslogic.intermediatebl.envehiclebl.TrainManagerBL;
public class EntrainingIntegration {
public void testEntraining(){
MockTransferingReceipt transferingReceipt = new MockTransferingReceipt(null, "test", null, null);
AllocateWaitingOrderBL awo = new AllocateWaitingOrderBL(transferingReceipt);
TrainManagerBL ebl = new TrainManagerBL(null, null, null);
// MockEntrainingReceipt entrainingReceipt = (MockEntrainingReceipt)
// ebl.entrain(awo.updateWaitingList());
// entrainingReceipt.ID = transferingReceipt.getID();
//
// if(entrainingReceipt.ID=="test")
// System.out.println("equals");
// else
// System.out.println("error");
}
}
| gpl-2.0 |
chywoo/codedojang | src/study/Solution2.java | 355 | package study;
import java.io.FileInputStream;
import java.util.Scanner;
public class Solution2 {
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("sample1.txt"));
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int test_case = 1; test_case <= T; test_case++) {
}
}
}
| gpl-2.0 |
callakrsos/Gargoyle | gargoyle-commons/src/main/java/com/kyj/fx/commons/fx/controls/color/LinearGradientPickerComposite.java | 2741 | /********************************
* 프로젝트 : gargoyle-commons
* 패키지 : com.kyj.fx.commons.fx.controls.color
* 작성일 : 2018. 10. 8.
* 작성자 : KYJ (callakrsos@naver.com)
*******************************/
package com.kyj.fx.commons.fx.controls.color;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kyj.fx.commons.utils.FxUtil;
import com.kyj.fx.commons.utils.ValueUtil;
import com.kyj.fx.fxloader.FXMLController;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
/**
* @author KYJ (callakrsos@naver.com)
*
*/
@FXMLController(value = "LinearGradientPickerView.fxml", isSelfController = true)
public class LinearGradientPickerComposite extends HBox {
private static final Logger LOGGER = LoggerFactory.getLogger(LinearGradientPickerComposite.class);
@FXML
private Rectangle rec;
public LinearGradientPickerComposite() {
FxUtil.loadRoot(LinearGradientPickerComposite.class, this, err -> {
LOGGER.error(ValueUtil.toString(err));
});
}
@FXML
public void initialize() {
int SIZE = 255 * 6;
int step = 0;
List<Stop> stops = new ArrayList<>(SIZE);
int initR = 255;
int initG = 0;
int initB = 0;
// G 를 올림.
for (int r = initG; r < 255; r++) {
stops.add(new Stop((double) step / (double) SIZE, Color.rgb(initR, initG, initB)));
initG = r;
step++;
}
// R 을 내림.
for (int r = initG; r > 0; r--) {
stops.add(new Stop((double) step / (double) SIZE, Color.rgb(r, initG, initB)));
initR = r;
step++;
}
// B를 올림.
for (int r = initB; r < 255; r++) {
stops.add(new Stop((double) step / (double) SIZE, Color.rgb(initR, initG, r)));
initB = r;
step++;
}
// G를 내림
for (int r = initG; r > 0; r--) {
stops.add(new Stop((double) step / (double) SIZE, Color.rgb(initR, r, initB)));
initG = r;
step++;
}
// R을 올림
for (int r = initR; r < 255; r++) {
stops.add(new Stop((double) step / (double) SIZE, Color.rgb(r, initG, initB)));
initR = r;
step++;
}
// B를 내림
for (int r = initB; r > 0; r--) {
Stop e = new Stop((double) step / (double) SIZE, Color.rgb(initR, initG, r));
stops.add(e);
initB = r;
step++;
}
LinearGradient lg2 = new LinearGradient(0, 0, 1000, 200, false, CycleMethod.NO_CYCLE, stops);
rec.setFill(lg2);
rec.setOnMouseClicked(ev -> {
double x = ev.getX();
double y = ev.getY();
Node intersectedNode = ev.getPickResult().getIntersectedNode();
});
}
}
| gpl-2.0 |
TurboVNC/turbovnc | java/com/turbovnc/vncviewer/F8Menu.java | 9337 | /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
* Copyright (C) 2011, 2013 Brian P. Hinz
* Copyright (C) 2012-2015, 2017-2018, 2020-2021 D. R. Commander.
* All Rights Reserved.
*
* This 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.turbovnc.vncviewer;
import java.awt.Cursor;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import com.turbovnc.rfb.*;
public class F8Menu extends JPopupMenu implements ActionListener {
public F8Menu(CConn cc_) {
super("VNC Menu");
setLightWeightPopupEnabled(false);
cc = cc_;
if (!Params.noNewConn.getValue()) {
exit = addMenuItem("Close Connection", KeyEvent.VK_C);
addSeparator();
}
options = addMenuItem("Options... (Ctrl-Alt-Shift-O)", KeyEvent.VK_O);
info = addMenuItem("Connection Info... (Ctrl-Alt-Shift-I)",
KeyEvent.VK_I);
info.setDisplayedMnemonicIndex(11);
profile = new JCheckBoxMenuItem("Performance Info... (Ctrl-Alt-Shift-P)");
profile.setMnemonic(KeyEvent.VK_P);
profile.setSelected(cc.profileDialog.isVisible());
profile.addActionListener(this);
add(profile);
addSeparator();
refresh = addMenuItem("Request Screen Refresh (Ctrl-Alt-Shift-R)",
KeyEvent.VK_R);
refresh.setDisplayedMnemonicIndex(15);
losslessRefresh =
addMenuItem("Request Lossless Refresh (Ctrl-Alt-Shift-L)",
KeyEvent.VK_L);
losslessRefresh.setDisplayedMnemonicIndex(8);
screenshot =
addMenuItem("Save Remote Desktop Image... (Ctrl-Alt-Shift-M)",
KeyEvent.VK_M);
screenshot.setDisplayedMnemonicIndex(21);
addSeparator();
fullScreen = new JCheckBoxMenuItem("Full Screen (Ctrl-Alt-Shift-F)");
fullScreen.setMnemonic(KeyEvent.VK_F);
fullScreen.setSelected(cc.opts.fullScreen);
fullScreen.addActionListener(this);
add(fullScreen);
defaultSize =
addMenuItem("Default Window Size/Position (Ctrl-Alt-Shift-Z)",
KeyEvent.VK_Z);
zoomIn = addMenuItem("Zoom In (Ctrl-Alt-Shift-9)", KeyEvent.VK_9);
zoomOut = addMenuItem("Zoom Out (Ctrl-Alt-Shift-8)", KeyEvent.VK_8);
zoom100 = addMenuItem("Zoom 100% (Ctrl-Alt-Shift-0)", KeyEvent.VK_0);
showToolbar = new JCheckBoxMenuItem("Show Toolbar (Ctrl-Alt-Shift-T)");
showToolbar.setMnemonic(KeyEvent.VK_T);
showToolbar.setSelected(cc.opts.showToolbar);
showToolbar.addActionListener(this);
add(showToolbar);
tileWindows = addMenuItem("Tile All Viewer Windows (Ctrl-Alt-Shift-X)",
KeyEvent.VK_X);
addSeparator();
viewOnly = new JCheckBoxMenuItem("View Only (Ctrl-Alt-Shift-V)");
viewOnly.setMnemonic(KeyEvent.VK_V);
viewOnly.setSelected(cc.opts.viewOnly);
viewOnly.addActionListener(this);
add(viewOnly);
if (Utils.osGrab() && Helper.isAvailable()) {
grabKeyboard =
new JCheckBoxMenuItem("Grab Keyboard (Ctrl-Alt-Shift-G)");
grabKeyboard.setMnemonic(KeyEvent.VK_G);
grabKeyboard.setSelected(VncViewer.isKeyboardGrabbed());
grabKeyboard.addActionListener(this);
add(grabKeyboard);
}
f8 = addMenuItem("Send " + KeyEvent.getKeyText(cc.opts.menuKeyCode));
KeyStroke ks = KeyStroke.getKeyStroke(cc.opts.menuKeyCode, 0);
f8.setAccelerator(ks);
if (!Params.restricted.getValue()) {
ctrlAltDel = addMenuItem("Send Ctrl-Alt-Del");
ctrlEsc = addMenuItem("Send Ctrl-Esc");
}
addSeparator();
clipboard = addMenuItem("Clipboard...");
addSeparator();
if (!Params.noNewConn.getValue()) {
newConn = addMenuItem("New Connection... (Ctrl-Alt-Shift-N)",
KeyEvent.VK_N);
addSeparator();
}
about = addMenuItem("About TurboVNC Viewer...", KeyEvent.VK_A);
addSeparator();
dismiss = addMenuItem("Dismiss Menu");
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
if (Utils.osGrab())
addPopupMenuListener(new PopupMenuListener() {
public void popupMenuCanceled(PopupMenuEvent e) {
if (cc.isGrabSelected())
cc.viewport.grabKeyboardHelper(true, true);
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
});
updateZoom();
}
JMenuItem addMenuItem(String str, int mnemonic) {
JMenuItem item = new JMenuItem(str, mnemonic);
item.addActionListener(this);
add(item);
return item;
}
JMenuItem addMenuItem(String str) {
JMenuItem item = new JMenuItem(str);
item.addActionListener(this);
add(item);
return item;
}
void updateMenuKey(int keyCode) {
f8.setText("Send " + KeyEvent.getKeyText(keyCode));
KeyStroke ks = KeyStroke.getKeyStroke(keyCode, 0);
f8.setAccelerator(ks);
}
boolean actionMatch(ActionEvent ev, JMenuItem item) {
if (item == null)
return false;
return ev.getActionCommand().equals(item.getActionCommand());
}
public void actionPerformed(ActionEvent ev) {
if (!Params.noNewConn.getValue() && actionMatch(ev, exit)) {
cc.close();
} else if (actionMatch(ev, fullScreen)) {
cc.toggleFullScreen();
} else if (actionMatch(ev, showToolbar)) {
cc.toggleToolbar();
showToolbar.setSelected(cc.opts.showToolbar);
} else if (actionMatch(ev, defaultSize)) {
cc.sizeWindow();
firePopupMenuCanceled();
} else if (actionMatch(ev, zoomIn)) {
cc.zoomIn();
firePopupMenuCanceled();
} else if (actionMatch(ev, zoomOut)) {
cc.zoomOut();
firePopupMenuCanceled();
} else if (actionMatch(ev, zoom100)) {
cc.zoom100();
firePopupMenuCanceled();
} else if (actionMatch(ev, tileWindows)) {
VncViewer.tileWindows();
} else if (actionMatch(ev, clipboard)) {
cc.clipboardDialog.showDialog(cc.viewport);
} else if (actionMatch(ev, viewOnly)) {
cc.toggleViewOnly();
} else if (actionMatch(ev, grabKeyboard)) {
if (cc.viewport != null)
cc.viewport.grabKeyboardHelper(grabKeyboard.isSelected());
} else if (actionMatch(ev, f8)) {
cc.writeKeyEvent(cc.opts.menuKeySym, true);
cc.writeKeyEvent(cc.opts.menuKeySym, false);
firePopupMenuCanceled();
} else if (actionMatch(ev, ctrlAltDel)) {
cc.writeKeyEvent(Keysyms.CONTROL_L, true);
cc.writeKeyEvent(Keysyms.ALT_L, true);
cc.writeKeyEvent(Keysyms.DELETE, true);
cc.writeKeyEvent(Keysyms.DELETE, false);
cc.writeKeyEvent(Keysyms.ALT_L, false);
cc.writeKeyEvent(Keysyms.CONTROL_L, false);
firePopupMenuCanceled();
} else if (actionMatch(ev, ctrlEsc)) {
cc.writeKeyEvent(Keysyms.CONTROL_L, true);
cc.writeKeyEvent(Keysyms.ESCAPE, true);
cc.writeKeyEvent(Keysyms.ESCAPE, false);
cc.writeKeyEvent(Keysyms.CONTROL_L, false);
firePopupMenuCanceled();
} else if (actionMatch(ev, refresh)) {
cc.refresh();
firePopupMenuCanceled();
} else if (actionMatch(ev, losslessRefresh)) {
cc.losslessRefresh();
firePopupMenuCanceled();
} else if (actionMatch(ev, screenshot)) {
cc.screenshot();
} else if (!Params.noNewConn.getValue() && actionMatch(ev, newConn)) {
VncViewer.newViewer(cc.viewer);
} else if (actionMatch(ev, options)) {
cc.options.showDialog(cc.viewport);
} else if (actionMatch(ev, info)) {
cc.showInfo();
} else if (actionMatch(ev, profile)) {
if (cc.profileDialog.isVisible())
cc.profileDialog.endDialog();
else
cc.profileDialog.showDialog(cc.viewport);
cc.toggleProfile();
} else if (actionMatch(ev, about)) {
cc.showAbout();
} else if (actionMatch(ev, dismiss)) {
firePopupMenuCanceled();
}
}
void updateZoom() {
if (cc.opts.desktopSize.mode == Options.SIZE_AUTO ||
cc.opts.scalingFactor == Options.SCALE_AUTO ||
cc.opts.scalingFactor == Options.SCALE_FIXEDRATIO) {
zoomIn.setEnabled(false);
zoomOut.setEnabled(false);
zoom100.setEnabled(false);
} else {
zoomIn.setEnabled(true);
zoomOut.setEnabled(true);
zoom100.setEnabled(true);
}
}
CConn cc;
JMenuItem defaultSize, zoomIn, zoomOut, zoom100, tileWindows;
JMenuItem exit, clipboard, ctrlAltDel, ctrlEsc, refresh, losslessRefresh;
JMenuItem newConn, options, info, profile, screenshot, about, dismiss;
static JMenuItem f8;
JCheckBoxMenuItem fullScreen, showToolbar, viewOnly, grabKeyboard;
static LogWriter vlog = new LogWriter("F8Menu");
}
| gpl-2.0 |
phiLangley/openPHD | [CODE]/processing/modes/TweakMode/src/galsasson/mode/tweak/TweakEditor.java | 13678 | /*
Part of TweakMode project (https://github.com/galsasson/TweakMode)
Under Google Summer of Code 2013 -
http://www.google-melange.com/gsoc/homepage/google/gsoc2013
Copyright (C) 2013 Gal Sasson
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package galsasson.mode.tweak;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;
import javax.swing.Box;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.table.TableModel;
import javax.swing.text.BadLocationException;
import processing.app.Base;
import processing.app.EditorState;
import processing.app.EditorToolbar;
import processing.app.Mode;
import processing.app.Sketch;
import processing.app.SketchCode;
import processing.app.SketchException;
import processing.app.syntax.JEditTextArea;
import processing.app.syntax.PdeTextAreaDefaults;
import processing.app.syntax.SyntaxDocument;
import processing.mode.java.JavaBuild;
import processing.mode.java.JavaEditor;
import processing.mode.java.JavaToolbar;
import processing.mode.java.runner.Runner;
/**
* Editor for STMode
*
* @author Gal Sasson <sasgal@gmail.com>
*
*/
public class TweakEditor extends JavaEditor
{
TweakMode tweakMode;
String[] baseCode;
final static int SPACE_AMOUNT = 0;
int oscPort;
/**
* Custom TextArea
*/
protected TweakTextArea tweakTextArea;
protected TweakEditor(Base base, String path, EditorState state,
final Mode mode) {
super(base, path, state, mode);
tweakMode = (TweakMode)mode;
// random port for OSC (0xff0 - 0xfff0)
oscPort = (int)(Math.random()*0xf000) + 0xff0;
}
public EditorToolbar createToolbar() {
return new TweakToolbar(this, base);
}
/**
* Override creation of the default textarea.
*/
protected JEditTextArea createTextArea() {
tweakTextArea = new TweakTextArea(this, new PdeTextAreaDefaults(mode));
return tweakTextArea;
}
public JMenu buildModeMenu() {
JMenu menu = new JMenu("Tweak");
JCheckBoxMenuItem item;
item = new JCheckBoxMenuItem("Dump modified code");
item.setSelected(false);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tweakMode.dumpModifiedCode = ((JCheckBoxMenuItem)e.getSource()).isSelected();
}
});
menu.add(item);
return menu;
}
public void startInteractiveMode()
{
tweakTextArea.startInteractiveMode();
}
public void stopInteractiveMode(ArrayList<Handle> handles[])
{
tweakTextArea.stopInteractiveMode();
// remove space from the code (before and after)
removeSpacesFromCode();
// check which tabs were modified
boolean modified = false;
boolean[] modifiedTabs = getModifiedTabs(handles);
for (boolean mod : modifiedTabs) {
if (mod) {
modified = true;
break;
}
}
if (modified) {
// ask to keep the values
int ret = Base.showYesNoQuestion(this, "Tweak Mode",
"Keep the changes?",
"You changed some values in your sketch. Would you like to keep the changes?");
if (ret == 1) {
// NO! don't keep changes
loadSavedCode();
// update the painter to draw the saved (old) code
tweakTextArea.invalidate();
}
else {
// YES! keep changes
// the new values are already present, just make sure the user can save the modified tabs
for (int i=0; i<sketch.getCodeCount(); i++) {
if (modifiedTabs[i]) {
sketch.getCode(i).setModified(true);
}
else {
// load the saved code of tabs that didn't change
// (there might be formatting changes that should not be saved)
sketch.getCode(i).setProgram(sketch.getCode(i).getSavedProgram());
/* Wild Hack: set document to null so the text editor will refresh
the program contents when the document tab is being clicked */
sketch.getCode(i).setDocument(null);
if (i == sketch.getCurrentCodeIndex()) {
// this will update the current code
setCode(sketch.getCurrentCode());
}
}
}
// save the sketch
try {
sketch.save();
}
catch (IOException e) {
Base.showWarning("Tweak Mode", "Could not save the modified sketch!", e);
}
// repaint the editor header (show the modified tabs)
header.repaint();
tweakTextArea.invalidate();
}
}
else {
// number values were not modified but we need to load the saved code
// because of some formatting changes
loadSavedCode();
tweakTextArea.invalidate();
}
}
public void updateInterface(ArrayList<Handle> handles[], ArrayList<ColorControlBox> colorBoxes[])
{
// set OSC port of handles
for (int i=0; i<handles.length; i++) {
for (Handle h : handles[i]) {
h.setOscPort(oscPort);
}
}
tweakTextArea.updateInterface(handles, colorBoxes);
}
/**
* Deactivate run button
* Do this because when Mode.handleRun returns null the play button stays on.
*/
public void deactivateRun()
{
toolbar.deactivate(TweakToolbar.RUN);
}
private boolean[] getModifiedTabs(ArrayList<Handle> handles[])
{
boolean[] modifiedTabs = new boolean[handles.length];
for (int i=0; i<handles.length; i++) {
for (Handle h : handles[i]) {
if (h.valueChanged()) {
modifiedTabs[i] = true;
}
}
}
return modifiedTabs;
}
public void initBaseCode()
{
SketchCode[] code = sketch.getCode();
String space = new String();
for (int i=0; i<SPACE_AMOUNT; i++) {
space += "\n";
}
baseCode = new String[code.length];
for (int i=0; i<code.length; i++)
{
baseCode[i] = new String(code[i].getSavedProgram());
baseCode[i] = space + baseCode[i] + space;
}
}
public void initEditorCode(ArrayList<Handle> handles[], boolean withSpaces)
{
SketchCode[] sketchCode = sketch.getCode();
for (int tab=0; tab<baseCode.length; tab++) {
// beautify the numbers
int charInc = 0;
String code = baseCode[tab];
for (Handle n : handles[tab])
{
int s = n.startChar + charInc;
int e = n.endChar + charInc;
String newStr = n.strNewValue;
if (withSpaces) {
newStr = " " + newStr + " ";
}
code = replaceString(code, s, e, newStr);
n.newStartChar = n.startChar + charInc;
charInc += n.strNewValue.length() - n.strValue.length();
if (withSpaces) {
charInc += 4;
}
n.newEndChar = n.endChar + charInc;
}
sketchCode[tab].setProgram(code);
/* Wild Hack: set document to null so the text editor will refresh
the program contents when the document tab is being clicked */
sketchCode[tab].setDocument(null);
}
// this will update the current code
setCode(sketch.getCurrentCode());
}
private void loadSavedCode()
{
SketchCode[] code = sketch.getCode();
for (int i=0; i<code.length; i++) {
if (!code[i].getProgram().equals(code[i].getSavedProgram())) {
code[i].setProgram(code[i].getSavedProgram());
/* Wild Hack: set document to null so the text editor will refresh
the program contents when the document tab is being clicked */
code[i].setDocument(null);
}
}
// this will update the current code
setCode(sketch.getCurrentCode());
}
private void removeSpacesFromCode()
{
SketchCode[] code = sketch.getCode();
for (int i=0; i<code.length; i++) {
String c = code[i].getProgram();
c = c.substring(SPACE_AMOUNT, c.length() - SPACE_AMOUNT);
code[i].setProgram(c);
/* Wild Hack: set document to null so the text editor will refresh
the program contents when the document tab is being clicked */
code[i].setDocument(null);
}
// this will update the current code
setCode(sketch.getCurrentCode());
}
/**
* Replace all numbers with variables and add code to initialize these variables and handle OSC messages.
* @param sketch
* the sketch to work on
* @param handles
* list of numbers to replace in this sketch
* @return
* true on success
*/
public boolean automateSketch(Sketch sketch, ArrayList<Handle> handles[])
{
SketchCode[] code = sketch.getCode();
if (code.length<1)
return false;
if (handles.length == 0)
return false;
int setupStartPos = SketchParser.getSetupStart(baseCode[0]);
if (setupStartPos < 0) {
return false;
}
// Copy current program to interactive program
/* modify the code below, replace all numbers with their variable names */
// loop through all tabs in the current sketch
for (int tab=0; tab<code.length; tab++)
{
int charInc = 0;
String c = baseCode[tab];
for (Handle n : handles[tab])
{
// replace number value with a variable
c = replaceString(c, n.startChar + charInc, n.endChar + charInc, n.name);
charInc += n.name.length() - n.strValue.length();
}
code[tab].setProgram(c);
}
/* add the main header to the code in the first tab */
String c = code[0].getProgram();
// header contains variable declaration, initialization, and OSC listener function
String header;
header = "\n\n" +
"/*************************/\n" +
"/* MODIFIED BY TWEAKMODE */\n" +
"/*************************/\n" +
"\n\n";
// add needed OSC imports and the global OSC object
header += "import oscP5.*;\n";
header += "import netP5.*;\n\n";
header += "OscP5 tweakmode_oscP5;\n\n";
// write a declaration for int and float arrays
int numOfInts = howManyInts(handles);
int numOfFloats = howManyFloats(handles);
if (numOfInts > 0) {
header += "int[] tweakmode_int = new int["+numOfInts+"];\n";
}
if (numOfFloats > 0) {
header += "float[] tweakmode_float = new float["+numOfFloats+"];\n\n";
}
/* add the class for the OSC event handler that will respond to our messages */
header += "public class TweakMode_OscHandler {\n" +
" public void oscEvent(OscMessage msg) {\n" +
" String type = msg.addrPattern();\n";
if (numOfInts > 0) {
header += " if (type.contains(\"/tm_change_int\")) {\n" +
" int index = msg.get(0).intValue();\n" +
" int value = msg.get(1).intValue();\n" +
" tweakmode_int[index] = value;\n" +
" }\n";
if (numOfFloats > 0) {
header += " else ";
}
}
if (numOfFloats > 0) {
header += "if (type.contains(\"/tm_change_float\")) {\n" +
" int index = msg.get(0).intValue();\n" +
" float value = msg.get(1).floatValue();\n" +
" tweakmode_float[index] = value;\n" +
" }\n";
}
header += " }\n" +
"}\n";
header += "TweakMode_OscHandler tweakmode_oscHandler = new TweakMode_OscHandler();\n";
header += "void tweakmode_initAllVars() {\n";
for (int i=0; i<handles.length; i++) {
for (Handle n : handles[i])
{
header += " " + n.name + " = " + n.strValue + ";\n";
}
}
header += "}\n\n";
header += "void tweakmode_initOSC() {\n";
header += " tweakmode_oscP5 = new OscP5(tweakmode_oscHandler,"+oscPort+");\n";
header += "}\n";
header += "\n\n\n\n\n";
// add call to our initAllVars and initOSC functions from the setup() function.
String addToSetup = "\n tweakmode_initAllVars();\n tweakmode_initOSC();\n\n";
setupStartPos = SketchParser.getSetupStart(c);
c = replaceString(c, setupStartPos, setupStartPos, addToSetup);
code[0].setProgram(header + c);
/* print out modified code */
if (tweakMode.dumpModifiedCode) {
System.out.println("\nModified code:\n");
for (int i=0; i<code.length; i++)
{
System.out.println("file " + i + "\n=========");
System.out.println(code[i].getProgram());
}
}
return true;
}
private String replaceString(String str, int start, int end, String put)
{
return str.substring(0, start) + put + str.substring(end, str.length());
}
private int howManyInts(ArrayList<Handle> handles[])
{
int count = 0;
for (int i=0; i<handles.length; i++) {
for (Handle n : handles[i]) {
if (n.type == "int" || n.type == "hex" || n.type == "webcolor")
count++;
}
}
return count;
}
private int howManyFloats(ArrayList<Handle> handles[])
{
int count = 0;
for (int i=0; i<handles.length; i++) {
for (Handle n : handles[i]) {
if (n.type == "float")
count++;
}
}
return count;
}
}
| gpl-2.0 |
dga4654dan/UTM | UserThreadMode/src/com/dc/utm/filter/visitor/IVisitorRequestFilter.java | 919 | package com.dc.utm.filter.visitor;
import com.dc.qtm.handle.IRequestHandler;
/**
*
* 游客请求过滤器接口
*
* @author Daemon
*
* @param <CmdType> cmd
* @param <ConnectKey> 游客Id
* @param <Visitor> 游客
*/
public interface IVisitorRequestFilter<CmdType, ConnectKey, Visitor> {
/**
* 游客请求过滤,在过滤方法内 如果没有问题 要执行handler方法处理请求(一般建议调用线程池处理 )
* (doFilter这个方法是由调用线程直接执行的,不是线程池中线程执行的,所以这里不建议执行一些有阻塞的方法或复杂的处理)
*
* @param connectKey 游客Id
* @param visitor 游客
* @param handler 对应的处理类
* @param requestId 请求Id
* @param param 请求的参数
*/
void doFilter( ConnectKey connectKey, Visitor visitor, IRequestHandler<Visitor, Object> handler, int requestId, Object param );
}
| gpl-2.0 |
mcberg2016/graal-core | graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/StructuredGraph.java | 28111 | /*
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import com.oracle.graal.compiler.common.CompilationIdentifier;
import com.oracle.graal.compiler.common.cfg.BlockMap;
import com.oracle.graal.compiler.common.type.Stamp;
import com.oracle.graal.debug.JavaMethodContext;
import com.oracle.graal.graph.Graph;
import com.oracle.graal.graph.Node;
import com.oracle.graal.graph.NodeMap;
import com.oracle.graal.graph.spi.SimplifierTool;
import com.oracle.graal.nodes.calc.FloatingNode;
import com.oracle.graal.nodes.cfg.Block;
import com.oracle.graal.nodes.cfg.ControlFlowGraph;
import com.oracle.graal.nodes.java.MethodCallTargetNode;
import com.oracle.graal.nodes.spi.VirtualizableAllocation;
import com.oracle.graal.nodes.util.GraphUtil;
import jdk.vm.ci.meta.Assumptions;
import jdk.vm.ci.meta.Assumptions.Assumption;
import jdk.vm.ci.meta.DefaultProfilingInfo;
import jdk.vm.ci.meta.JavaMethod;
import jdk.vm.ci.meta.ProfilingInfo;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import jdk.vm.ci.meta.SpeculationLog;
import jdk.vm.ci.meta.TriState;
import jdk.vm.ci.runtime.JVMCICompiler;
/**
* A graph that contains at least one distinguished node : the {@link #start() start} node. This
* node is the start of the control flow of the graph.
*/
public class StructuredGraph extends Graph implements JavaMethodContext {
/**
* The different stages of the compilation of a {@link Graph} regarding the status of
* {@link GuardNode guards}, {@link DeoptimizingNode deoptimizations} and {@link FrameState
* framestates}. The stage of a graph progresses monotonously.
*
*/
public enum GuardsStage {
/**
* During this stage, there can be {@link FloatingNode floating} {@link DeoptimizingNode}
* such as {@link GuardNode GuardNodes}. New {@link DeoptimizingNode DeoptimizingNodes} can
* be introduced without constraints. {@link FrameState} nodes are associated with
* {@link StateSplit} nodes.
*/
FLOATING_GUARDS,
/**
* During this stage, all {@link DeoptimizingNode DeoptimizingNodes} must be
* {@link FixedNode fixed} but new {@link DeoptimizingNode DeoptimizingNodes} can still be
* introduced. {@link FrameState} nodes are still associated with {@link StateSplit} nodes.
*/
FIXED_DEOPTS,
/**
* During this stage, all {@link DeoptimizingNode DeoptimizingNodes} must be
* {@link FixedNode fixed}. New {@link DeoptimizingNode DeoptimizingNodes} can not be
* introduced any more. {@link FrameState} nodes are now associated with
* {@link DeoptimizingNode} nodes.
*/
AFTER_FSA;
public boolean allowsFloatingGuards() {
return this == FLOATING_GUARDS;
}
public boolean areFrameStatesAtDeopts() {
return this == AFTER_FSA;
}
public boolean areFrameStatesAtSideEffects() {
return !this.areFrameStatesAtDeopts();
}
public boolean areDeoptsFixed() {
return this.ordinal() >= FIXED_DEOPTS.ordinal();
}
}
/**
* Constants denoting whether or not {@link Assumption}s can be made while processing a graph.
*/
public enum AllowAssumptions {
YES,
NO;
public static AllowAssumptions from(boolean flag) {
return flag ? YES : NO;
}
}
public static class ScheduleResult {
private final ControlFlowGraph cfg;
private final NodeMap<Block> nodeToBlockMap;
private final BlockMap<List<Node>> blockToNodesMap;
public ScheduleResult(ControlFlowGraph cfg, NodeMap<Block> nodeToBlockMap, BlockMap<List<Node>> blockToNodesMap) {
this.cfg = cfg;
this.nodeToBlockMap = nodeToBlockMap;
this.blockToNodesMap = blockToNodesMap;
}
public ControlFlowGraph getCFG() {
return cfg;
}
public NodeMap<Block> getNodeToBlockMap() {
return nodeToBlockMap;
}
public BlockMap<List<Node>> getBlockToNodesMap() {
return blockToNodesMap;
}
public List<Node> nodesFor(Block block) {
return blockToNodesMap.get(block);
}
}
public static final long INVALID_GRAPH_ID = -1;
private static final AtomicLong uniqueGraphIds = new AtomicLong();
private StartNode start;
private ResolvedJavaMethod rootMethod;
private final long graphId;
private final CompilationIdentifier compilationId;
private final int entryBCI;
private GuardsStage guardsStage = GuardsStage.FLOATING_GUARDS;
private boolean isAfterFloatingReadPhase = false;
private boolean hasValueProxies = true;
private final boolean useProfilingInfo;
/**
* The assumptions made while constructing and transforming this graph.
*/
private final Assumptions assumptions;
private final SpeculationLog speculationLog;
private ScheduleResult lastSchedule;
/**
* Records the methods that were used while constructing this graph, one entry for each time a
* specific method is used.
*/
private final List<ResolvedJavaMethod> methods = new ArrayList<>();
private enum UnsafeAccessState {
NO_ACCESS,
HAS_ACCESS,
DISABLED
}
private UnsafeAccessState hasUnsafeAccess = UnsafeAccessState.NO_ACCESS;
/**
* Creates a new Graph containing a single {@link AbstractBeginNode} as the {@link #start()
* start} node.
*/
public StructuredGraph(AllowAssumptions allowAssumptions, CompilationIdentifier compilationId) {
this(null, null, allowAssumptions, compilationId);
}
public static final boolean USE_PROFILING_INFO = true;
public static final boolean NO_PROFILING_INFO = false;
private static final SpeculationLog NO_SPECULATION_LOG = null;
/**
* Creates a new Graph containing a single {@link AbstractBeginNode} as the {@link #start()
* start} node.
*/
public StructuredGraph(String name, ResolvedJavaMethod method, AllowAssumptions allowAssumptions, CompilationIdentifier compilationId) {
this(name, method, JVMCICompiler.INVOCATION_ENTRY_BCI, allowAssumptions, NO_SPECULATION_LOG, USE_PROFILING_INFO, compilationId);
}
public StructuredGraph(String name, ResolvedJavaMethod method, AllowAssumptions allowAssumptions, SpeculationLog speculationLog, CompilationIdentifier compilationId) {
this(name, method, JVMCICompiler.INVOCATION_ENTRY_BCI, allowAssumptions, speculationLog, USE_PROFILING_INFO, compilationId);
}
public StructuredGraph(String name, ResolvedJavaMethod method, AllowAssumptions allowAssumptions, SpeculationLog speculationLog, boolean useProfilingInfo, CompilationIdentifier compilationId) {
this(name, method, JVMCICompiler.INVOCATION_ENTRY_BCI, allowAssumptions, speculationLog, useProfilingInfo, compilationId);
}
public StructuredGraph(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, CompilationIdentifier compilationId) {
this(null, method, JVMCICompiler.INVOCATION_ENTRY_BCI, allowAssumptions, NO_SPECULATION_LOG, USE_PROFILING_INFO, compilationId);
}
public StructuredGraph(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, boolean useProfilingInfo, CompilationIdentifier compilationId) {
this(null, method, JVMCICompiler.INVOCATION_ENTRY_BCI, allowAssumptions, NO_SPECULATION_LOG, useProfilingInfo, compilationId);
}
public StructuredGraph(ResolvedJavaMethod method, AllowAssumptions allowAssumptions, SpeculationLog speculationLog, CompilationIdentifier compilationId) {
this(null, method, JVMCICompiler.INVOCATION_ENTRY_BCI, allowAssumptions, speculationLog, USE_PROFILING_INFO, compilationId);
}
public StructuredGraph(ResolvedJavaMethod method, int entryBCI, AllowAssumptions allowAssumptions, SpeculationLog speculationLog, CompilationIdentifier compilationId) {
this(null, method, entryBCI, allowAssumptions, speculationLog, USE_PROFILING_INFO, compilationId);
}
public StructuredGraph(ResolvedJavaMethod method, int entryBCI, AllowAssumptions allowAssumptions, SpeculationLog speculationLog, boolean useProfilingInfo, CompilationIdentifier compilationId) {
this(null, method, entryBCI, allowAssumptions, speculationLog, useProfilingInfo, compilationId);
}
private StructuredGraph(String name, ResolvedJavaMethod method, int entryBCI, AllowAssumptions allowAssumptions, SpeculationLog speculationLog, boolean useProfilingInfo,
CompilationIdentifier compilationId) {
super(name);
this.setStart(add(new StartNode()));
this.rootMethod = method;
this.graphId = uniqueGraphIds.incrementAndGet();
this.compilationId = compilationId;
this.entryBCI = entryBCI;
this.assumptions = allowAssumptions == AllowAssumptions.YES ? new Assumptions() : null;
this.speculationLog = speculationLog;
this.useProfilingInfo = useProfilingInfo;
}
public void setLastSchedule(ScheduleResult result) {
lastSchedule = result;
}
public ScheduleResult getLastSchedule() {
return lastSchedule;
}
public void clearLastSchedule() {
setLastSchedule(null);
}
@Override
public boolean maybeCompress() {
if (super.maybeCompress()) {
/*
* The schedule contains a NodeMap which is unusable after compression.
*/
clearLastSchedule();
return true;
}
return false;
}
public Stamp getReturnStamp() {
Stamp returnStamp = null;
for (ReturnNode returnNode : getNodes(ReturnNode.TYPE)) {
ValueNode result = returnNode.result();
if (result != null) {
if (returnStamp == null) {
returnStamp = result.stamp();
} else {
returnStamp = returnStamp.meet(result.stamp());
}
}
}
return returnStamp;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(getClass().getSimpleName() + ":" + graphId);
String sep = "{";
if (name != null) {
buf.append(sep);
buf.append(name);
sep = ", ";
}
if (method() != null) {
buf.append(sep);
buf.append(method());
sep = ", ";
}
if (!sep.equals("{")) {
buf.append("}");
}
return buf.toString();
}
public StartNode start() {
return start;
}
/**
* Gets the root method from which this graph was built.
*
* @return null if this method was not built from a method or the method is not available
*/
public ResolvedJavaMethod method() {
return rootMethod;
}
public int getEntryBCI() {
return entryBCI;
}
public boolean isOSR() {
return entryBCI != JVMCICompiler.INVOCATION_ENTRY_BCI;
}
public long graphId() {
return graphId;
}
/**
* @see CompilationIdentifier
*/
public CompilationIdentifier compilationId() {
return compilationId;
}
public void setStart(StartNode start) {
this.start = start;
}
/**
* Creates a copy of this graph.
*
* @param newName the name of the copy, used for debugging purposes (can be null)
* @param duplicationMapCallback consumer of the duplication map created during the copying
*/
@Override
protected Graph copy(String newName, Consumer<Map<Node, Node>> duplicationMapCallback) {
return copy(newName, duplicationMapCallback, compilationId);
}
private StructuredGraph copy(String newName, Consumer<Map<Node, Node>> duplicationMapCallback, CompilationIdentifier newCompilationId) {
AllowAssumptions allowAssumptions = AllowAssumptions.from(assumptions != null);
StructuredGraph copy = new StructuredGraph(newName, method(), entryBCI, allowAssumptions, speculationLog, useProfilingInfo, newCompilationId);
if (allowAssumptions == AllowAssumptions.YES && assumptions != null) {
copy.assumptions.record(assumptions);
}
copy.hasUnsafeAccess = hasUnsafeAccess;
copy.setGuardsStage(getGuardsStage());
copy.isAfterFloatingReadPhase = isAfterFloatingReadPhase;
copy.hasValueProxies = hasValueProxies;
Map<Node, Node> replacements = Node.newMap();
replacements.put(start, copy.start);
Map<Node, Node> duplicates = copy.addDuplicates(getNodes(), this, this.getNodeCount(), replacements);
if (duplicationMapCallback != null) {
duplicationMapCallback.accept(duplicates);
}
return copy;
}
public final StructuredGraph copyWithIdentifier(CompilationIdentifier newCompilationId) {
return copy(name, null, newCompilationId);
}
public ParameterNode getParameter(int index) {
for (ParameterNode param : getNodes(ParameterNode.TYPE)) {
if (param.index() == index) {
return param;
}
}
return null;
}
public Iterable<Invoke> getInvokes() {
final Iterator<MethodCallTargetNode> callTargets = getNodes(MethodCallTargetNode.TYPE).iterator();
return new Iterable<Invoke>() {
private Invoke next;
@Override
public Iterator<Invoke> iterator() {
return new Iterator<Invoke>() {
@Override
public boolean hasNext() {
if (next == null) {
while (callTargets.hasNext()) {
Invoke i = callTargets.next().invoke();
if (i != null) {
next = i;
return true;
}
}
return false;
} else {
return true;
}
}
@Override
public Invoke next() {
try {
return next;
} finally {
next = null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
public boolean hasLoops() {
return hasNode(LoopBeginNode.TYPE);
}
/**
* Unlinks a node from all its control flow neighbors and then removes it from its graph. The
* node must have no {@linkplain Node#usages() usages}.
*
* @param node the node to be unlinked and removed
*/
public void removeFixed(FixedWithNextNode node) {
assert node != null;
if (node instanceof AbstractBeginNode) {
((AbstractBeginNode) node).prepareDelete();
}
assert node.hasNoUsages() : node + " " + node.usages().count() + ", " + node.usages().first();
GraphUtil.unlinkFixedNode(node);
node.safeDelete();
}
public void replaceFixed(FixedWithNextNode node, Node replacement) {
if (replacement instanceof FixedWithNextNode) {
replaceFixedWithFixed(node, (FixedWithNextNode) replacement);
} else {
assert replacement != null : "cannot replace " + node + " with null";
assert replacement instanceof FloatingNode : "cannot replace " + node + " with " + replacement;
replaceFixedWithFloating(node, (FloatingNode) replacement);
}
}
public void replaceFixedWithFixed(FixedWithNextNode node, FixedWithNextNode replacement) {
assert node != null && replacement != null && node.isAlive() && replacement.isAlive() : "cannot replace " + node + " with " + replacement;
FixedNode next = node.next();
node.setNext(null);
replacement.setNext(next);
node.replaceAndDelete(replacement);
if (node == start) {
setStart((StartNode) replacement);
}
}
public void replaceFixedWithFloating(FixedWithNextNode node, FloatingNode replacement) {
assert node != null && replacement != null && node.isAlive() && replacement.isAlive() : "cannot replace " + node + " with " + replacement;
GraphUtil.unlinkFixedNode(node);
node.replaceAtUsagesAndDelete(replacement);
}
public void removeSplit(ControlSplitNode node, AbstractBeginNode survivingSuccessor) {
assert node != null;
assert node.hasNoUsages();
assert survivingSuccessor != null;
node.clearSuccessors();
node.replaceAtPredecessor(survivingSuccessor);
node.safeDelete();
}
public void removeSplitPropagate(ControlSplitNode node, AbstractBeginNode survivingSuccessor) {
removeSplitPropagate(node, survivingSuccessor, null);
}
public void removeSplitPropagate(ControlSplitNode node, AbstractBeginNode survivingSuccessor, SimplifierTool tool) {
assert node != null;
assert node.hasNoUsages();
assert survivingSuccessor != null;
List<Node> snapshot = node.successors().snapshot();
node.clearSuccessors();
node.replaceAtPredecessor(survivingSuccessor);
node.safeDelete();
for (Node successor : snapshot) {
if (successor != null && successor.isAlive()) {
if (successor != survivingSuccessor) {
GraphUtil.killCFG(successor, tool);
}
}
}
}
public void replaceSplit(ControlSplitNode node, Node replacement, AbstractBeginNode survivingSuccessor) {
if (replacement instanceof FixedWithNextNode) {
replaceSplitWithFixed(node, (FixedWithNextNode) replacement, survivingSuccessor);
} else {
assert replacement != null : "cannot replace " + node + " with null";
assert replacement instanceof FloatingNode : "cannot replace " + node + " with " + replacement;
replaceSplitWithFloating(node, (FloatingNode) replacement, survivingSuccessor);
}
}
public void replaceSplitWithFixed(ControlSplitNode node, FixedWithNextNode replacement, AbstractBeginNode survivingSuccessor) {
assert node != null && replacement != null && node.isAlive() && replacement.isAlive() : "cannot replace " + node + " with " + replacement;
assert survivingSuccessor != null;
node.clearSuccessors();
replacement.setNext(survivingSuccessor);
node.replaceAndDelete(replacement);
}
public void replaceSplitWithFloating(ControlSplitNode node, FloatingNode replacement, AbstractBeginNode survivingSuccessor) {
assert node != null && replacement != null && node.isAlive() && replacement.isAlive() : "cannot replace " + node + " with " + replacement;
assert survivingSuccessor != null;
node.clearSuccessors();
node.replaceAtPredecessor(survivingSuccessor);
node.replaceAtUsagesAndDelete(replacement);
}
public void addAfterFixed(FixedWithNextNode node, FixedNode newNode) {
assert node != null && newNode != null && node.isAlive() && newNode.isAlive() : "cannot add " + newNode + " after " + node;
FixedNode next = node.next();
node.setNext(newNode);
if (next != null) {
assert newNode instanceof FixedWithNextNode;
FixedWithNextNode newFixedWithNext = (FixedWithNextNode) newNode;
assert newFixedWithNext.next() == null;
newFixedWithNext.setNext(next);
}
}
public void addBeforeFixed(FixedNode node, FixedWithNextNode newNode) {
assert node != null && newNode != null && node.isAlive() && newNode.isAlive() : "cannot add " + newNode + " before " + node;
assert node.predecessor() != null && node.predecessor() instanceof FixedWithNextNode : "cannot add " + newNode + " before " + node;
assert newNode.next() == null : newNode;
assert !(node instanceof AbstractMergeNode);
FixedWithNextNode pred = (FixedWithNextNode) node.predecessor();
pred.setNext(newNode);
newNode.setNext(node);
}
public void reduceDegenerateLoopBegin(LoopBeginNode begin) {
assert begin.loopEnds().isEmpty() : "Loop begin still has backedges";
if (begin.forwardEndCount() == 1) { // bypass merge and remove
reduceTrivialMerge(begin);
} else { // convert to merge
AbstractMergeNode merge = this.add(new MergeNode());
this.replaceFixedWithFixed(begin, merge);
}
}
public void reduceTrivialMerge(AbstractMergeNode merge) {
assert merge.forwardEndCount() == 1;
assert !(merge instanceof LoopBeginNode) || ((LoopBeginNode) merge).loopEnds().isEmpty();
for (PhiNode phi : merge.phis().snapshot()) {
assert phi.valueCount() == 1;
ValueNode singleValue = phi.valueAt(0);
phi.replaceAtUsagesAndDelete(singleValue);
}
// remove loop exits
if (merge instanceof LoopBeginNode) {
((LoopBeginNode) merge).removeExits();
}
AbstractEndNode singleEnd = merge.forwardEndAt(0);
FixedNode sux = merge.next();
FrameState stateAfter = merge.stateAfter();
// evacuateGuards
merge.prepareDelete((FixedNode) singleEnd.predecessor());
merge.safeDelete();
if (stateAfter != null && stateAfter.isAlive() && stateAfter.hasNoUsages()) {
GraphUtil.killWithUnusedFloatingInputs(stateAfter);
}
if (sux == null) {
singleEnd.replaceAtPredecessor(null);
singleEnd.safeDelete();
} else {
singleEnd.replaceAndDelete(sux);
}
}
public GuardsStage getGuardsStage() {
return guardsStage;
}
public void setGuardsStage(GuardsStage guardsStage) {
assert guardsStage.ordinal() >= this.guardsStage.ordinal();
this.guardsStage = guardsStage;
}
public boolean isAfterFloatingReadPhase() {
return isAfterFloatingReadPhase;
}
public void setAfterFloatingReadPhase(boolean state) {
assert state : "cannot 'unapply' floating read phase on graph";
isAfterFloatingReadPhase = state;
}
public boolean hasValueProxies() {
return hasValueProxies;
}
public void setHasValueProxies(boolean state) {
assert !state : "cannot 'unapply' value proxy removal on graph";
hasValueProxies = state;
}
/**
* Determines if {@link ProfilingInfo} is used during construction of this graph.
*/
public boolean useProfilingInfo() {
return useProfilingInfo;
}
/**
* Gets the profiling info for the {@linkplain #method() root method} of this graph.
*/
public ProfilingInfo getProfilingInfo() {
return getProfilingInfo(method());
}
/**
* Gets the profiling info for a given method that is or will be part of this graph, taking into
* account {@link #useProfilingInfo()}.
*/
public ProfilingInfo getProfilingInfo(ResolvedJavaMethod m) {
if (useProfilingInfo && m != null) {
return m.getProfilingInfo();
} else {
return DefaultProfilingInfo.get(TriState.UNKNOWN);
}
}
/**
* Gets the object for recording assumptions while constructing of this graph.
*
* @return {@code null} if assumptions cannot be made for this graph
*/
public Assumptions getAssumptions() {
return assumptions;
}
/**
* Gets the methods that were inlined while constructing this graph.
*/
public List<ResolvedJavaMethod> getMethods() {
return methods;
}
/**
* Records that {@code method} was used to build this graph.
*/
public void recordMethod(ResolvedJavaMethod method) {
methods.add(method);
}
/**
* Updates the {@linkplain #getMethods() methods} used to build this graph with the methods used
* to build another graph.
*/
public void updateMethods(StructuredGraph other) {
assert this != other;
this.methods.addAll(other.methods);
}
/**
* Gets the input bytecode {@linkplain ResolvedJavaMethod#getCodeSize() size} from which this
* graph is constructed. This ignores how many bytecodes in each constituent method are actually
* parsed (which may be none for methods whose IR is retrieved from a cache or less than the
* full amount for any given method due to profile guided branch pruning).
*/
public int getBytecodeSize() {
int res = 0;
for (ResolvedJavaMethod e : methods) {
res += e.getCodeSize();
}
return res;
}
/**
*
* @return true if the graph contains only a {@link StartNode} and {@link ReturnNode}
*/
public boolean isTrivial() {
return !(start.next() instanceof ReturnNode);
}
@Override
public JavaMethod asJavaMethod() {
return method();
}
public boolean hasUnsafeAccess() {
return hasUnsafeAccess == UnsafeAccessState.HAS_ACCESS;
}
public void markUnsafeAccess() {
if (hasUnsafeAccess == UnsafeAccessState.DISABLED) {
return;
}
hasUnsafeAccess = UnsafeAccessState.HAS_ACCESS;
}
public void disableUnsafeAccessTracking() {
hasUnsafeAccess = UnsafeAccessState.DISABLED;
}
public boolean isUnsafeAccessTrackingEnabled() {
return hasUnsafeAccess != UnsafeAccessState.DISABLED;
}
public SpeculationLog getSpeculationLog() {
return speculationLog;
}
public final void clearAllStateAfter() {
for (Node node : getNodes()) {
if (node instanceof StateSplit) {
FrameState stateAfter = ((StateSplit) node).stateAfter();
if (stateAfter != null) {
((StateSplit) node).setStateAfter(null);
// 2 nodes referencing the same framestate
if (stateAfter.isAlive()) {
GraphUtil.killWithUnusedFloatingInputs(stateAfter);
}
}
}
}
}
public final boolean hasVirtualizableAllocation() {
for (Node n : getNodes()) {
if (n instanceof VirtualizableAllocation) {
return true;
}
}
return false;
}
}
| gpl-2.0 |
DmitryADP/diff_qc750 | frameworks/opt/telephony/src/java/com/android/internal/telephony/IccIoResult.java | 2294 | /*
* Copyright (C) 2006 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.internal.telephony;
/**
* {@hide}
*/
public class
IccIoResult {
public int sw1;
public int sw2;
public byte[] payload;
public IccIoResult(int sw1, int sw2, byte[] payload) {
this.sw1 = sw1;
this.sw2 = sw2;
this.payload = payload;
}
public IccIoResult(int sw1, int sw2, String hexString) {
this(sw1, sw2, IccUtils.hexStringToBytes(hexString));
}
public String toString() {
return "IccIoResponse sw1:0x" + Integer.toHexString(sw1) + " sw2:0x"
+ Integer.toHexString(sw2);
}
/**
* true if this operation was successful
* See GSM 11.11 Section 9.4
* (the fun stuff is absent in 51.011)
*/
public boolean success() {
return sw1 == 0x90 || sw1 == 0x91 || sw1 == 0x92 || sw1 == 0x9e || sw1 == 0x9f;
}
/**
* Returns exception on error or null if success
*/
public IccException getException() {
if (success()) return null;
switch (sw1) {
case 0x94:
if (sw2 == 0x08) {
return new IccFileTypeMismatch();
} else {
return new IccFileNotFound();
}
case 0x69:
if(sw2 == 0x81) {
return new IccFileTypeMismatch();
}
break;
case 0x6A:
if((sw2 == 0x82) || (sw2 == 0x83)) {
return new IccFileNotFound();
}
break;
default:
break;
}
return new IccException("sw1:" + sw1 + " sw2:" + sw2);
}
}
| gpl-2.0 |
tushar-jaiswal/LeetCode | Algorithms/173. Binary Search Tree Iterator/BSTIterator.java | 1327 | //Author: Tushar Jaiswal
//Creation Date: 07/08/2018
/*Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
pushAllLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode node = stack.pop();
if(node.right != null)
{ pushAllLeft(node.right); }
return node.val;
}
private void pushAllLeft(TreeNode node)
{
while(node != null)
{
stack.push(node);
node = node.left;
}
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/ | gpl-2.0 |
Icecrown-wow/bedwars-reloaded-bungee | bedwars-reloaded-bungee/src/de/yannici/bedwars/bungee/Subchannel.java | 261 | package de.yannici.bedwars.bungee;
public enum Subchannel {
UPDATE_REQUEST("update-request");
private String name = null;
Subchannel(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
| gpl-2.0 |
peterstevens130561/sonar-mscover | src/main/java/com/stevpet/sonar/plugins/dotnet/mscover/coveragesaver/defaultsaver/OverallLineCoverageMetrics.java | 1736 | /*
* Sonar Integration Test Plugin MSCover
* Copyright (C) 2009 ${owner}
* dev@sonar.codehaus.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package com.stevpet.sonar.plugins.dotnet.mscover.coveragesaver.defaultsaver;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
public class OverallLineCoverageMetrics implements LineCoverageMetrics {
@Override
public Metric<?> getLinesToCoverMetric() {
return CoreMetrics.OVERALL_LINES_TO_COVER;
}
@Override
public Metric<?> getUncoveredLinesMetric() {
return CoreMetrics.OVERALL_UNCOVERED_LINES;
}
@Override
public Metric<?> getCoverageMetric() {
return CoreMetrics.OVERALL_COVERAGE;
}
@Override
public Metric<Double> getLineCoverageMetric() {
return CoreMetrics.OVERALL_LINE_COVERAGE;
}
@Override
public Metric<String> getCoverageLineHitsDataMetric() {
return CoreMetrics.OVERALL_COVERAGE_LINE_HITS_DATA;
}
}
| gpl-2.0 |
workhabitinc/dandy | dandy-publisher/src/main/java/com/workhabit/drupal/publisher/DrupalTaxonomyListActivity.java | 2429 | package com.workhabit.drupal.publisher;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.workhabit.drupal.publisher.support.DrupalDialogHandler;
import com.workhabit.drupal.publisher.support.DrupalTaxonomyAdapter;
import org.workhabit.drupal.api.entity.drupal7.DrupalTaxonomyTerm;
import org.workhabit.drupal.api.site.Drupal7SiteContext;
import org.workhabit.drupal.api.site.exceptions.DrupalFetchException;
import org.workhabit.drupal.api.site.DrupalSiteContext;
import java.util.ArrayList;
/**
* Copyright 2009 - WorkHabit, Inc. - acs
* Date: Oct 16, 2010, 3:55:47 PM
*/
public class DrupalTaxonomyListActivity extends AbstractDandyListActivity {
private DrupalTaxonomyAdapter drupalTaxonomyAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Drupal7SiteContext drupalSiteContext = DandyApplication.getDrupalSiteContext(savedInstanceState);
try {
ArrayList<DrupalTaxonomyTerm> terms = (ArrayList<DrupalTaxonomyTerm>) drupalSiteContext.getCategoryList();
drupalTaxonomyAdapter = new DrupalTaxonomyAdapter(this, R.layout.row, terms);
this.setListAdapter(drupalTaxonomyAdapter);
drupalTaxonomyAdapter.notifyDataSetChanged();
} catch (DrupalFetchException e) {
DrupalDialogHandler.showMessageDialog(this, e.getMessage());
}
setContentView(R.layout.taxonomylist);
// set active state on button
Button b = (Button) findViewById(R.id.button_categories);
b.setCompoundDrawablesWithIntrinsicBounds(
null,
getResources().getDrawable(R.drawable.button_categories_icon_active),
null,
null
);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_bg_active));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this.getApplicationContext(), DrupalNodeListViewActivity.class);
intent.putExtra("viewName", "dandy_category_nodes");
intent.putExtra("viewArguments", Integer.toString(drupalTaxonomyAdapter.getTerms().get(position).getTid()));
this.startActivity(intent);
}
}
| gpl-2.0 |
tooskagroup/test | TMessagesProj/src/main/java/com/panahit/ui/Components/EmojiView.java | 76843 | /*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package com.panahit.ui.Components;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.panahit.telegramma.AndroidUtilities;
import com.panahit.telegramma.EmojiData;
import com.panahit.telegramma.NotificationCenter;
import com.panahit.tgnet.TLObject;
import com.panahit.tgnet.TLRPC;
import com.panahit.ui.Cells.ContextLinkCell;
import com.panahit.ui.Cells.StickerEmojiCell;
import com.panahit.telegramma.AnimationCompat.ViewProxy;
import com.panahit.telegramma.Emoji;
import com.panahit.telegramma.LocaleController;
import com.panahit.telegramma.MediaController;
import com.panahit.telegramma.MessagesStorage;
import com.panahit.telegramma.query.StickersQuery;
import com.panahit.telegramma.FileLog;
import com.panahit.telegramma.R;
import com.panahit.telegramma.support.widget.RecyclerView;
import com.panahit.tgnet.ConnectionsManager;
import com.panahit.tgnet.RequestDelegate;
import com.panahit.ui.Cells.EmptyCell;
import com.panahit.ui.StickerPreviewViewer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
public class EmojiView extends FrameLayout implements NotificationCenter.NotificationCenterDelegate {
public interface Listener {
boolean onBackspace();
void onEmojiSelected(String emoji);
void onStickerSelected(TLRPC.Document sticker);
void onStickersSettingsClick();
void onGifSelected(TLRPC.Document gif);
void onGifTab(boolean opened);
void onStickersTab(boolean opened);
}
private static final Field superListenerField;
static {
Field f = null;
try {
f = PopupWindow.class.getDeclaredField("mOnScrollChangedListener");
f.setAccessible(true);
} catch (NoSuchFieldException e) {
/* ignored */
}
superListenerField = f;
}
private static final ViewTreeObserver.OnScrollChangedListener NOP = new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
/* do nothing */
}
};
private class ImageViewEmoji extends ImageView {
private boolean touched;
private float lastX;
private float lastY;
private float touchedX;
private float touchedY;
public ImageViewEmoji(Context context) {
super(context);
setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendEmoji(null);
}
});
setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
String code = (String) view.getTag();
if (EmojiData.emojiColoredMap.containsKey(code)) {
touched = true;
touchedX = lastX;
touchedY = lastY;
String color = emojiColor.get(code);
if (color != null) {
switch (color) {
case "\uD83C\uDFFB":
pickerView.setSelection(1);
break;
case "\uD83C\uDFFC":
pickerView.setSelection(2);
break;
case "\uD83C\uDFFD":
pickerView.setSelection(3);
break;
case "\uD83C\uDFFE":
pickerView.setSelection(4);
break;
case "\uD83C\uDFFF":
pickerView.setSelection(5);
break;
}
} else {
pickerView.setSelection(0);
}
view.getLocationOnScreen(location);
int x = emojiSize * pickerView.getSelection() + AndroidUtilities.dp(4 * pickerView.getSelection() - (AndroidUtilities.isTablet() ? 5 : 1));
if (location[0] - x < AndroidUtilities.dp(5)) {
x += (location[0] - x) - AndroidUtilities.dp(5);
} else if (location[0] - x + popupWidth > AndroidUtilities.displaySize.x - AndroidUtilities.dp(5)) {
x += (location[0] - x + popupWidth) - (AndroidUtilities.displaySize.x - AndroidUtilities.dp(5));
}
int xOffset = -x;
int yOffset = view.getTop() < 0 ? view.getTop() : 0;
pickerView.setEmoji(code, AndroidUtilities.dp(AndroidUtilities.isTablet() ? 30 : 22) - xOffset + (int) AndroidUtilities.dpf2(0.5f));
pickerViewPopup.setFocusable(true);
pickerViewPopup.showAsDropDown(view, xOffset, -view.getMeasuredHeight() - popupHeight + (view.getMeasuredHeight() - emojiSize) / 2 - yOffset);
view.getParent().requestDisallowInterceptTouchEvent(true);
return true;
}
return false;
}
});
setBackgroundResource(R.drawable.list_selector);
setScaleType(ImageView.ScaleType.CENTER);
}
private void sendEmoji(String override) {
String code = override != null ? override : (String) getTag();
if (override == null) {
if (pager.getCurrentItem() != 0) {
String color = emojiColor.get(code);
if (color != null) {
code += color;
}
}
Integer count = emojiUseHistory.get(code);
if (count == null) {
count = 0;
}
if (count == 0 && emojiUseHistory.size() > 50) {
for (int a = recentEmoji.size() - 1; a >= 0; a--) {
String emoji = recentEmoji.get(a);
emojiUseHistory.remove(emoji);
recentEmoji.remove(a);
if (emojiUseHistory.size() <= 50) {
break;
}
}
}
emojiUseHistory.put(code, ++count);
if (pager.getCurrentItem() != 0) {
sortEmoji();
}
saveRecentEmoji();
adapters.get(0).notifyDataSetChanged();
if (listener != null) {
listener.onEmojiSelected(Emoji.fixEmoji(code));
}
} else {
if (listener != null) {
listener.onEmojiSelected(Emoji.fixEmoji(override));
}
}
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(View.MeasureSpec.getSize(widthMeasureSpec), View.MeasureSpec.getSize(widthMeasureSpec));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (touched) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
if (pickerViewPopup != null && pickerViewPopup.isShowing()) {
pickerViewPopup.dismiss();
String color = null;
switch (pickerView.getSelection()) {
case 1:
color = "\uD83C\uDFFB";
break;
case 2:
color = "\uD83C\uDFFC";
break;
case 3:
color = "\uD83C\uDFFD";
break;
case 4:
color = "\uD83C\uDFFE";
break;
case 5:
color = "\uD83C\uDFFF";
break;
}
String code = (String) getTag();
if (pager.getCurrentItem() != 0) {
if (color != null) {
emojiColor.put(code, color);
code += color;
} else {
emojiColor.remove(code);
}
setImageDrawable(Emoji.getEmojiBigDrawable(code));
sendEmoji(null);
saveEmojiColors();
} else {
sendEmoji(code + (color != null ? color : ""));
}
}
touched = false;
touchedX = -10000;
touchedY = -10000;
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
boolean ignore = false;
if (touchedX != -10000) {
if (Math.abs(touchedX - event.getX()) > AndroidUtilities.getPixelsInCM(0.2f, true) || Math.abs(touchedY - event.getY()) > AndroidUtilities.getPixelsInCM(0.2f, false)) {
touchedX = -10000;
touchedY = -10000;
} else {
ignore = true;
}
}
if (!ignore) {
getLocationOnScreen(location);
float x = location[0] + event.getX();
pickerView.getLocationOnScreen(location);
x -= location[0] + AndroidUtilities.dp(3);
int position = (int) (x / (emojiSize + AndroidUtilities.dp(4)));
if (position < 0) {
position = 0;
} else if (position > 5) {
position = 5;
}
pickerView.setSelection(position);
}
}
}
lastX = event.getX();
lastY = event.getY();
return super.onTouchEvent(event);
}
}
private class EmojiPopupWindow extends PopupWindow {
private ViewTreeObserver.OnScrollChangedListener mSuperScrollListener;
private ViewTreeObserver mViewTreeObserver;
public EmojiPopupWindow() {
super();
init();
}
public EmojiPopupWindow(Context context) {
super(context);
init();
}
public EmojiPopupWindow(int width, int height) {
super(width, height);
init();
}
public EmojiPopupWindow(View contentView) {
super(contentView);
init();
}
public EmojiPopupWindow(View contentView, int width, int height, boolean focusable) {
super(contentView, width, height, focusable);
init();
}
public EmojiPopupWindow(View contentView, int width, int height) {
super(contentView, width, height);
init();
}
private void init() {
if (superListenerField != null) {
try {
mSuperScrollListener = (ViewTreeObserver.OnScrollChangedListener) superListenerField.get(this);
superListenerField.set(this, NOP);
} catch (Exception e) {
mSuperScrollListener = null;
}
}
}
private void unregisterListener() {
if (mSuperScrollListener != null && mViewTreeObserver != null) {
if (mViewTreeObserver.isAlive()) {
mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener);
}
mViewTreeObserver = null;
}
}
private void registerListener(View anchor) {
if (mSuperScrollListener != null) {
ViewTreeObserver vto = (anchor.getWindowToken() != null) ? anchor.getViewTreeObserver() : null;
if (vto != mViewTreeObserver) {
if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
mViewTreeObserver.removeOnScrollChangedListener(mSuperScrollListener);
}
if ((mViewTreeObserver = vto) != null) {
vto.addOnScrollChangedListener(mSuperScrollListener);
}
}
}
}
@Override
public void showAsDropDown(View anchor, int xoff, int yoff) {
try {
super.showAsDropDown(anchor, xoff, yoff);
registerListener(anchor);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
@Override
public void update(View anchor, int xoff, int yoff, int width, int height) {
super.update(anchor, xoff, yoff, width, height);
registerListener(anchor);
}
@Override
public void update(View anchor, int width, int height) {
super.update(anchor, width, height);
registerListener(anchor);
}
@Override
public void showAtLocation(View parent, int gravity, int x, int y) {
super.showAtLocation(parent, gravity, x, y);
unregisterListener();
}
@Override
public void dismiss() {
setFocusable(false);
try {
super.dismiss();
} catch (Exception e) {
//don't promt
}
unregisterListener();
}
}
private class EmojiColorPickerView extends View {
private Drawable backgroundDrawable;
private Drawable arrowDrawable;
private String currentEmoji;
private int arrowX;
private int selection;
private Paint rectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private RectF rect = new RectF();
public void setEmoji(String emoji, int arrowPosition) {
currentEmoji = emoji;
arrowX = arrowPosition;
rectPaint.setColor(0x2f000000);
invalidate();
}
public String getEmoji() {
return currentEmoji;
}
public void setSelection(int position) {
if (selection == position) {
return;
}
selection = position;
invalidate();
}
public int getSelection() {
return selection;
}
public EmojiColorPickerView(Context context) {
super(context);
backgroundDrawable = getResources().getDrawable(R.drawable.stickers_back_all);
arrowDrawable = getResources().getDrawable(R.drawable.stickers_back_arrow);
}
@Override
protected void onDraw(Canvas canvas) {
backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), AndroidUtilities.dp(AndroidUtilities.isTablet() ? 60 : 52));
backgroundDrawable.draw(canvas);
arrowDrawable.setBounds(arrowX - AndroidUtilities.dp(9), AndroidUtilities.dp(AndroidUtilities.isTablet() ? 55.5f : 47.5f), arrowX + AndroidUtilities.dp(9), AndroidUtilities.dp((AndroidUtilities.isTablet() ? 55.5f : 47.5f) + 8));
arrowDrawable.draw(canvas);
if (currentEmoji != null) {
String code;
for (int a = 0; a < 6; a++) {
int x = emojiSize * a + AndroidUtilities.dp(5 + 4 * a);
int y = AndroidUtilities.dp(9);
if (selection == a) {
rect.set(x, y - (int) AndroidUtilities.dpf2(3.5f), x + emojiSize, y + emojiSize + AndroidUtilities.dp(3));
canvas.drawRoundRect(rect, AndroidUtilities.dp(4), AndroidUtilities.dp(4), rectPaint);
}
code = currentEmoji;
if (a != 0) {
code += "\uD83C";
switch (a) {
case 1:
code += "\uDFFB";
break;
case 2:
code += "\uDFFC";
break;
case 3:
code += "\uDFFD";
break;
case 4:
code += "\uDFFE";
break;
case 5:
code += "\uDFFF";
break;
}
}
Drawable drawable = Emoji.getEmojiBigDrawable(code);
if (drawable != null) {
drawable.setBounds(x, y, x + emojiSize, y + emojiSize);
drawable.draw(canvas);
}
}
}
}
}
private ArrayList<EmojiGridAdapter> adapters = new ArrayList<>();
private HashMap<String, Integer> emojiUseHistory = new HashMap<>();
private static HashMap<String, String> emojiColor = new HashMap<>();
private ArrayList<String> recentEmoji = new ArrayList<>();
private ArrayList<Long> newRecentStickers = new ArrayList<>();
private ArrayList<TLRPC.Document> recentStickers = new ArrayList<>();
private ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = new ArrayList<>();
private ArrayList<MediaController.SearchImage> recentImages;
private boolean loadingRecent;
private int[] icons = {
R.drawable.ic_emoji_recent,
R.drawable.ic_emoji_smile,
R.drawable.ic_emoji_flower,
R.drawable.ic_emoji_bell,
R.drawable.ic_emoji_car,
R.drawable.ic_emoji_symbol,
R.drawable.ic_emoji_sticker};
private Listener listener;
private ViewPager pager;
private FrameLayout recentsWrap;
private FrameLayout stickersWrap;
private ArrayList<GridView> views = new ArrayList<>();
private ImageView backspaceButton;
private StickersGridAdapter stickersGridAdapter;
private LinearLayout pagerSlidingTabStripContainer;
private ScrollSlidingTabStrip scrollSlidingTabStrip;
private GridView stickersGridView;
private TextView stickersEmptyView;
private RecyclerListView gifsGridView;
private FlowLayoutManager flowLayoutManager;
private GifsAdapter gifsAdapter;
private AdapterView.OnItemClickListener stickersOnItemClickListener;
private EmojiColorPickerView pickerView;
private EmojiPopupWindow pickerViewPopup;
private int popupWidth;
private int popupHeight;
private int emojiSize;
private int location[] = new int[2];
private int stickersTabOffset;
private int recentTabBum = -2;
private int gifTabBum = -2;
private boolean switchToGifTab;
private int oldWidth;
private int lastNotifyWidth;
private boolean backspacePressed;
private boolean backspaceOnce;
private boolean showStickers;
private boolean showGifs;
private boolean loadingRecentGifs;
private long lastGifLoadTime;
public EmojiView(boolean needStickers, boolean needGif, final Context context) {
super(context);
showStickers = needStickers;
showGifs = needGif;
for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
GridView gridView = new GridView(context);
if (AndroidUtilities.isTablet()) {
gridView.setColumnWidth(AndroidUtilities.dp(60));
} else {
gridView.setColumnWidth(AndroidUtilities.dp(45));
}
gridView.setNumColumns(-1);
views.add(gridView);
EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
gridView.setAdapter(emojiGridAdapter);
AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
adapters.add(emojiGridAdapter);
}
if (showStickers) {
StickersQuery.checkStickers();
stickersGridView = new GridView(context) {
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersGridView, EmojiView.this.getMeasuredHeight());
return super.onInterceptTouchEvent(event) || result;
}
@Override
public void setVisibility(int visibility) {
if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
super.setVisibility(GONE);
return;
}
super.setVisibility(visibility);
}
};
stickersGridView.setSelector(R.drawable.transparent);
stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
stickersGridView.setNumColumns(-1);
stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
stickersGridView.setClipToPadding(false);
views.add(stickersGridView);
stickersGridAdapter = new StickersGridAdapter(context);
stickersGridView.setAdapter(stickersGridAdapter);
stickersGridView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView, EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
}
});
stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
if (!(view instanceof StickerEmojiCell)) {
return;
}
StickerPreviewViewer.getInstance().reset();
StickerEmojiCell cell = (StickerEmojiCell) view;
if (cell.isDisabled()) {
return;
}
cell.disable();
TLRPC.Document document = cell.getSticker();
int index = newRecentStickers.indexOf(document.id);
if (index == -1) {
newRecentStickers.add(0, document.id);
if (newRecentStickers.size() > 20) {
newRecentStickers.remove(newRecentStickers.size() - 1);
}
} else if (index != 0) {
newRecentStickers.remove(index);
newRecentStickers.add(0, document.id);
}
saveRecentStickers();
if (listener != null) {
listener.onStickerSelected(document);
}
}
};
stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);
stickersWrap = new FrameLayout(context);
stickersWrap.addView(stickersGridView);
if (needGif) {
gifsGridView = new RecyclerListView(context);
gifsGridView.setLayoutManager(flowLayoutManager = new FlowLayoutManager() {
private Size size = new Size();
@Override
protected Size getSizeForItem(int i) {
TLRPC.Document document = recentImages.get(i).document;
size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
for (int b = 0; b < document.attributes.size(); b++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(b);
if (attribute instanceof TLRPC.TL_documentAttributeImageSize || attribute instanceof TLRPC.TL_documentAttributeVideo) {
size.width = attribute.w;
size.height = attribute.h;
break;
}
}
return size;
}
});
if (Build.VERSION.SDK_INT >= 9) {
gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
}
gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (position < 0 || position >= recentImages.size() || listener == null) {
return;
}
TLRPC.Document document = recentImages.get(position).document;
listener.onStickerSelected(document);
}
});
gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
@Override
public boolean onItemClick(View view, int position) {
if (position < 0 || position >= recentImages.size()) {
return false;
}
final MediaController.SearchImage searchImage = recentImages.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("DeleteGif", R.string.DeleteGif));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
recentImages.remove(searchImage);
TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
req.id = new TLRPC.TL_inputDocument();
req.id.id = searchImage.document.id;
req.id.access_hash = searchImage.document.access_hash;
req.unsave = true;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
}
});
MessagesStorage.getInstance().removeWebRecent(searchImage);
if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
}
if (recentImages.isEmpty()) {
updateStickerTabs();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
builder.show().setCanceledOnTouchOutside(true);
return true;
}
});
gifsGridView.setVisibility(GONE);
stickersWrap.addView(gifsGridView);
}
stickersEmptyView = new TextView(context);
stickersEmptyView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
stickersEmptyView.setTextColor(0xff888888);
stickersWrap.addView(stickersEmptyView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
stickersGridView.setEmptyView(stickersEmptyView);
scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {
boolean startedScroll;
float lastX;
float lastTranslateX;
boolean first = true;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (Build.VERSION.SDK_INT >= 11) {
if (first) {
first = false;
lastX = ev.getX();
}
float newTranslationX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
if (!startedScroll && lastX - ev.getX() < 0) {
if (pager.beginFakeDrag()) {
startedScroll = true;
lastTranslateX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
}
} else if (startedScroll && lastX - ev.getX() > 0) {
if (pager.isFakeDragging()) {
pager.endFakeDrag();
startedScroll = false;
}
}
}
if (startedScroll) {
int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
try {
pager.fakeDragBy(dx);
lastTranslateX = newTranslationX;
} catch (Exception e) {
try {
pager.endFakeDrag();
} catch (Exception e2) {
//don't promt
}
startedScroll = false;
FileLog.e("tmessages", e);
}
}
lastX = ev.getX();
if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
first = true;
if (startedScroll) {
pager.endFakeDrag();
startedScroll = false;
}
}
return startedScroll || super.onTouchEvent(ev);
}
return super.onTouchEvent(ev);
}
};
scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
scrollSlidingTabStrip.setVisibility(INVISIBLE);
addView(scrollSlidingTabStrip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
ViewProxy.setTranslationX(scrollSlidingTabStrip, AndroidUtilities.displaySize.x);
updateStickerTabs();
scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
@Override
public void onPageSelected(int page) {
if (gifsGridView != null) {
if (page == gifTabBum + 1) {
if (gifsGridView.getVisibility() != VISIBLE) {
listener.onGifTab(true);
showGifTab();
}
} else {
if (gifsGridView.getVisibility() == VISIBLE) {
listener.onGifTab(false);
gifsGridView.setVisibility(GONE);
stickersGridView.setVisibility(VISIBLE);
stickersEmptyView.setVisibility(stickersGridAdapter.getCount() != 0 ? GONE : VISIBLE);
}
}
}
if (page == 0) {
pager.setCurrentItem(0);
return;
} else {
if (page == gifTabBum + 1) {
return;
} else {
if (page == recentTabBum + 1) {
views.get(6).setSelection(0);
return;
}
}
}
int index = page - 1 - stickersTabOffset;
if (index == stickerSets.size()) {
if (listener != null) {
listener.onStickersSettingsClick();
}
return;
}
if (index >= stickerSets.size()) {
index = stickerSets.size() - 1;
}
views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
}
});
stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
checkStickersScroll(firstVisibleItem);
}
});
}
setBackgroundColor(0xfff5f6f7);
pager = new ViewPager(context) {
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
return super.onInterceptTouchEvent(ev);
}
};
pager.setAdapter(new EmojiPagesAdapter());
pagerSlidingTabStripContainer = new LinearLayout(context) {
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
return super.onInterceptTouchEvent(ev);
}
};
pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));
PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
pagerSlidingTabStrip.setViewPager(pager);
pagerSlidingTabStrip.setShouldExpand(true);
pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
FrameLayout frameLayout = new FrameLayout(context);
pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));
backspaceButton = new ImageView(context) {
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
backspacePressed = true;
backspaceOnce = false;
postBackspaceRunnable(350);
} else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {
backspacePressed = false;
if (!backspaceOnce) {
if (listener != null && listener.onBackspace()) {
backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
}
}
}
super.onTouchEvent(event);
return true;
}
};
backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));
View view = new View(context);
view.setBackgroundColor(0xffe2e5e7);
frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));
recentsWrap = new FrameLayout(context);
recentsWrap.addView(views.get(0));
TextView textView = new TextView(context);
textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
textView.setTextSize(18);
textView.setTextColor(0xff888888);
textView.setGravity(Gravity.CENTER);
recentsWrap.addView(textView);
views.get(0).setEmptyView(textView);
addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));
emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
pickerView = new EmojiColorPickerView(context);
pickerViewPopup = new EmojiPopupWindow(pickerView, popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5), popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
pickerViewPopup.setOutsideTouchable(true);
pickerViewPopup.setClippingEnabled(true);
pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
pickerViewPopup.getContentView().setFocusableInTouchMode(true);
pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null && pickerViewPopup.isShowing()) {
pickerViewPopup.dismiss();
return true;
}
return false;
}
});
loadRecents();
}
private void showGifTab() {
gifsGridView.setVisibility(VISIBLE);
stickersGridView.setVisibility(GONE);
stickersEmptyView.setVisibility(GONE);
scrollSlidingTabStrip.onPageScrolled(gifTabBum + 1, (recentTabBum > 0 ? recentTabBum : stickersTabOffset) + 1);
}
private void checkStickersScroll(int firstVisibleItem) {
if (stickersGridView == null) {
return;
}
if (stickersGridView.getVisibility() != VISIBLE) {
scrollSlidingTabStrip.onPageScrolled(gifTabBum + 1, (recentTabBum > 0 ? recentTabBum : stickersTabOffset) + 1);
return;
}
int count = stickersGridView.getChildCount();
for (int a = 0; a < count; a++) {
View child = stickersGridView.getChildAt(a);
if (child.getHeight() + child.getTop() < AndroidUtilities.dp(5)) {
firstVisibleItem++;
} else {
break;
}
}
scrollSlidingTabStrip.onPageScrolled(stickersGridAdapter.getTabForPosition(firstVisibleItem) + 1, (recentTabBum > 0 ? recentTabBum : stickersTabOffset) + 1);
}
private void onPageScrolled(int position, int width, int positionOffsetPixels) {
if (scrollSlidingTabStrip == null) {
return;
}
if (width == 0) {
width = AndroidUtilities.displaySize.x;
}
int margin = 0;
if (position == 5) {
margin = -positionOffsetPixels;
if (listener != null) {
listener.onStickersTab(positionOffsetPixels != 0);
}
} else if (position == 6) {
margin = -width;
if (listener != null) {
listener.onStickersTab(true);
}
} else {
if (listener != null) {
listener.onStickersTab(false);
}
}
if (ViewProxy.getTranslationX(pagerSlidingTabStripContainer) != margin) {
ViewProxy.setTranslationX(pagerSlidingTabStripContainer, margin);
ViewProxy.setTranslationX(scrollSlidingTabStrip, width + margin);
scrollSlidingTabStrip.setVisibility(margin < 0 ? VISIBLE : INVISIBLE);
if (Build.VERSION.SDK_INT < 11) {
if (margin <= -width) {
pagerSlidingTabStripContainer.clearAnimation();
pagerSlidingTabStripContainer.setVisibility(GONE);
} else {
pagerSlidingTabStripContainer.setVisibility(VISIBLE);
}
}
} else if (Build.VERSION.SDK_INT < 11 && pagerSlidingTabStripContainer.getVisibility() == GONE) {
pagerSlidingTabStripContainer.clearAnimation();
pagerSlidingTabStripContainer.setVisibility(GONE);
}
}
private void postBackspaceRunnable(final int time) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (!backspacePressed) {
return;
}
if (listener != null && listener.onBackspace()) {
backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
}
backspaceOnce = true;
postBackspaceRunnable(Math.max(50, time - 100));
}
}, time);
}
private String convert(long paramLong) {
String str = "";
for (int i = 0; ; i++) {
if (i >= 4) {
return str;
}
int j = (int) (0xFFFF & paramLong >> 16 * (3 - i));
if (j != 0) {
str = str + (char) j;
}
}
}
private void saveRecentEmoji() {
SharedPreferences preferences = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE);
StringBuilder stringBuilder = new StringBuilder();
for (HashMap.Entry<String, Integer> entry : emojiUseHistory.entrySet()) {
if (stringBuilder.length() != 0) {
stringBuilder.append(",");
}
stringBuilder.append(entry.getKey());
stringBuilder.append("=");
stringBuilder.append(entry.getValue());
}
preferences.edit().putString("emojis2", stringBuilder.toString()).commit();
}
private void saveEmojiColors() {
SharedPreferences preferences = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE);
StringBuilder stringBuilder = new StringBuilder();
for (HashMap.Entry<String, String> entry : emojiColor.entrySet()) {
if (stringBuilder.length() != 0) {
stringBuilder.append(",");
}
stringBuilder.append(entry.getKey());
stringBuilder.append("=");
stringBuilder.append(entry.getValue());
}
preferences.edit().putString("color", stringBuilder.toString()).commit();
}
private void saveRecentStickers() {
SharedPreferences.Editor editor = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).edit();
StringBuilder stringBuilder = new StringBuilder();
for (int a = 0; a < newRecentStickers.size(); a++) {
if (stringBuilder.length() != 0) {
stringBuilder.append(",");
}
stringBuilder.append(newRecentStickers.get(a));
}
editor.putString("stickers2", stringBuilder.toString());
editor.commit();
}
public void switchToGifRecent() {
pager.setCurrentItem(6);
if (gifTabBum >= 0 && !recentImages.isEmpty()) {
scrollSlidingTabStrip.selectTab(gifTabBum + 1);
} else {
switchToGifTab = true;
}
}
private void sortEmoji() {
recentEmoji.clear();
for (HashMap.Entry<String, Integer> entry : emojiUseHistory.entrySet()) {
recentEmoji.add(entry.getKey());
}
Collections.sort(recentEmoji, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
Integer count1 = emojiUseHistory.get(lhs);
Integer count2 = emojiUseHistory.get(rhs);
if (count1 == null) {
count1 = 0;
}
if (count2 == null) {
count2 = 0;
}
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
}
return 0;
}
});
while (recentEmoji.size() > 50) {
recentEmoji.remove(recentEmoji.size() - 1);
}
}
private void sortStickers() {
if (StickersQuery.getStickerSets().isEmpty()) {
recentStickers.clear();
return;
}
recentStickers.clear();
for (int a = 0; a < newRecentStickers.size(); a++) {
TLRPC.Document sticker = StickersQuery.getStickerById(newRecentStickers.get(a));
if (sticker != null) {
recentStickers.add(sticker);
}
}
while (recentStickers.size() > 20) {
recentStickers.remove(recentStickers.size() - 1);
}
if (newRecentStickers.size() != recentStickers.size()) {
newRecentStickers.clear();
for (int a = 0; a < recentStickers.size(); a++) {
newRecentStickers.add(recentStickers.get(a).id);
}
saveRecentStickers();
}
}
private void updateStickerTabs() {
if (scrollSlidingTabStrip == null) {
return;
}
recentTabBum = -2;
gifTabBum = -2;
stickersTabOffset = 0;
int lastPosition = scrollSlidingTabStrip.getCurrentPosition();
scrollSlidingTabStrip.removeTabs();
scrollSlidingTabStrip.addIconTab(R.drawable.ic_smiles_smile);
if (showGifs && recentImages != null && !recentImages.isEmpty()) {
scrollSlidingTabStrip.addIconTab(R.drawable.ic_smiles_gif);
gifTabBum = stickersTabOffset;
stickersTabOffset++;
}
if (!recentStickers.isEmpty()) {
recentTabBum = stickersTabOffset;
stickersTabOffset++;
scrollSlidingTabStrip.addIconTab(R.drawable.ic_smiles_recent);
}
stickerSets.clear();
ArrayList<TLRPC.TL_messages_stickerSet> packs = StickersQuery.getStickerSets();
for (int a = 0; a < packs.size(); a++) {
TLRPC.TL_messages_stickerSet pack = packs.get(a);
if (pack.set.disabled || pack.documents == null || pack.documents.isEmpty()) {
continue;
}
stickerSets.add(pack);
}
for (int a = 0; a < stickerSets.size(); a++) {
scrollSlidingTabStrip.addStickerTab(stickerSets.get(a).documents.get(0));
}
scrollSlidingTabStrip.addIconTab(R.drawable.ic_settings);
scrollSlidingTabStrip.updateTabStyles();
if (lastPosition != 0) {
scrollSlidingTabStrip.onPageScrolled(lastPosition, lastPosition);
}
if (switchToGifTab) {
if (gifTabBum >= 0 && gifsGridView.getVisibility() != VISIBLE) {
showGifTab();
}
switchToGifTab = false;
}
if (gifTabBum == -2 && gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
listener.onGifTab(false);
gifsGridView.setVisibility(GONE);
stickersGridView.setVisibility(VISIBLE);
stickersEmptyView.setVisibility(stickersGridAdapter.getCount() != 0 ? GONE : VISIBLE);
} else if (gifTabBum != -2) {
if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
scrollSlidingTabStrip.onPageScrolled(gifTabBum + 1, (recentTabBum > 0 ? recentTabBum : stickersTabOffset) + 1);
} else {
scrollSlidingTabStrip.onPageScrolled(stickersGridAdapter.getTabForPosition(stickersGridView.getFirstVisiblePosition()) + 1, (recentTabBum > 0 ? recentTabBum : stickersTabOffset) + 1);
}
}
}
public void addRecentGif(MediaController.SearchImage searchImage) {
if (searchImage == null || searchImage.document == null || recentImages == null) {
return;
}
boolean wasEmpty = recentImages.isEmpty();
for (int a = 0; a < recentImages.size(); a++) {
MediaController.SearchImage image = recentImages.get(a);
if (image.id.equals(searchImage.id)) {
recentImages.remove(a);
recentImages.add(0, image);
if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
}
return;
}
}
recentImages.add(0, searchImage);
if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
}
if (wasEmpty) {
updateStickerTabs();
}
}
public void loadRecents() {
SharedPreferences preferences = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE);
lastGifLoadTime = preferences.getLong("lastGifLoadTime", 0);
String str;
try {
emojiUseHistory.clear();
if (preferences.contains("emojis")) {
str = preferences.getString("emojis", "");
if (str != null && str.length() > 0) {
String[] args = str.split(",");
for (String arg : args) {
String[] args2 = arg.split("=");
long value = Long.parseLong(args2[0]);
String string = "";
for (int a = 0; a < 4; a++) {
char ch = (char) value;
string = String.valueOf(ch) + string;
value >>= 16;
if (value == 0) {
break;
}
}
if (string.length() > 0) {
emojiUseHistory.put(string, Integer.parseInt(args2[1]));
}
}
}
preferences.edit().remove("emojis").commit();
saveRecentEmoji();
} else {
str = preferences.getString("emojis2", "");
if (str != null && str.length() > 0) {
String[] args = str.split(",");
for (String arg : args) {
String[] args2 = arg.split("=");
emojiUseHistory.put(args2[0], Integer.parseInt(args2[1]));
}
}
}
if (emojiUseHistory.isEmpty()) {
String[] newRecent = new String[]{
"\uD83D\uDE02", "\uD83D\uDE18", "\u2764", "\uD83D\uDE0D", "\uD83D\uDE0A", "\uD83D\uDE01",
"\uD83D\uDC4D", "\u263A", "\uD83D\uDE14", "\uD83D\uDE04", "\uD83D\uDE2D", "\uD83D\uDC8B",
"\uD83D\uDE12", "\uD83D\uDE33", "\uD83D\uDE1C", "\uD83D\uDE48", "\uD83D\uDE09", "\uD83D\uDE03",
"\uD83D\uDE22", "\uD83D\uDE1D", "\uD83D\uDE31", "\uD83D\uDE21", "\uD83D\uDE0F", "\uD83D\uDE1E",
"\uD83D\uDE05", "\uD83D\uDE1A", "\uD83D\uDE4A", "\uD83D\uDE0C", "\uD83D\uDE00", "\uD83D\uDE0B",
"\uD83D\uDE06", "\uD83D\uDC4C", "\uD83D\uDE10", "\uD83D\uDE15"};
for (int i = 0; i < newRecent.length; i++) {
emojiUseHistory.put(newRecent[i], newRecent.length - i);
}
saveRecentEmoji();
}
sortEmoji();
adapters.get(0).notifyDataSetChanged();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
try {
str = preferences.getString("color", "");
if (str != null && str.length() > 0) {
String[] args = str.split(",");
for (int a = 0; a < args.length; a++) {
String arg = args[a];
String[] args2 = arg.split("=");
emojiColor.put(args2[0], args2[1]);
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (showStickers) {
try {
newRecentStickers.clear();
str = preferences.getString("stickers", "");
if (str != null && str.length() > 0) {
String[] args = str.split(",");
final HashMap<Long, Integer> stickersUseHistory = new HashMap<>();
for (int a = 0; a < args.length; a++) {
String arg = args[a];
String[] args2 = arg.split("=");
Long key = Long.parseLong(args2[0]);
stickersUseHistory.put(key, Integer.parseInt(args2[1]));
newRecentStickers.add(key);
}
Collections.sort(newRecentStickers, new Comparator<Long>() {
@Override
public int compare(Long lhs, Long rhs) {
Integer count1 = stickersUseHistory.get(lhs);
Integer count2 = stickersUseHistory.get(rhs);
if (count1 == null) {
count1 = 0;
}
if (count2 == null) {
count2 = 0;
}
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
}
return 0;
}
});
preferences.edit().remove("stickers").commit();
saveRecentStickers();
} else {
str = preferences.getString("stickers2", "");
String[] args = str.split(",");
for (int a = 0; a < args.length; a++) {
newRecentStickers.add(Long.parseLong(args[a]));
}
}
sortStickers();
updateStickerTabs();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) pagerSlidingTabStripContainer.getLayoutParams();
FrameLayout.LayoutParams layoutParams1 = null;
layoutParams.width = View.MeasureSpec.getSize(widthMeasureSpec);
if (scrollSlidingTabStrip != null) {
layoutParams1 = (FrameLayout.LayoutParams) scrollSlidingTabStrip.getLayoutParams();
if (layoutParams1 != null) {
layoutParams1.width = layoutParams.width;
}
}
if (layoutParams.width != oldWidth) {
if (scrollSlidingTabStrip != null && layoutParams1 != null) {
onPageScrolled(pager.getCurrentItem(), layoutParams.width, 0);
scrollSlidingTabStrip.setLayoutParams(layoutParams1);
}
pagerSlidingTabStripContainer.setLayoutParams(layoutParams);
oldWidth = layoutParams.width;
}
super.onMeasure(View.MeasureSpec.makeMeasureSpec(layoutParams.width, MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(heightMeasureSpec), MeasureSpec.EXACTLY));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (lastNotifyWidth != right - left) {
lastNotifyWidth = right - left;
reloadStickersAdapter();
}
super.onLayout(changed, left, top, right, bottom);
}
private void reloadStickersAdapter() {
if (stickersGridAdapter != null) {
stickersGridAdapter.notifyDataSetChanged();
}
if (StickerPreviewViewer.getInstance().isVisible()) {
StickerPreviewViewer.getInstance().close();
}
StickerPreviewViewer.getInstance().reset();
}
public void setListener(Listener value) {
listener = value;
}
public void invalidateViews() {
for (GridView gridView : views) {
if (gridView != null) {
gridView.invalidateViews();
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (stickersGridAdapter != null) {
NotificationCenter.getInstance().addObserver(this, NotificationCenter.stickersDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.recentImagesDidLoaded);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
updateStickerTabs();
reloadStickersAdapter();
}
});
}
}
public void loadGifRecent() {
if (showGifs && gifsAdapter != null && !loadingRecent) {
MessagesStorage.getInstance().loadWebRecent(2);
loadingRecent = true;
}
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (visibility != GONE) {
sortEmoji();
adapters.get(0).notifyDataSetChanged();
if (stickersGridAdapter != null) {
NotificationCenter.getInstance().addObserver(this, NotificationCenter.stickersDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.recentImagesDidLoaded);
sortStickers();
updateStickerTabs();
reloadStickersAdapter();
if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE && listener != null) {
listener.onGifTab(true);
}
}
loadGifRecent();
}
}
public void onDestroy() {
if (stickersGridAdapter != null) {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.stickersDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recentImagesDidLoaded);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (pickerViewPopup != null && pickerViewPopup.isShowing()) {
pickerViewPopup.dismiss();
}
}
private int calcGifsHash(ArrayList<MediaController.SearchImage> arrayList) {
if (arrayList == null) {
return 0;
}
long acc = 0;
for (int a = 0; a < Math.min(200, arrayList.size()); a++) {
MediaController.SearchImage searchImage = arrayList.get(a);
if (searchImage.document == null) {
continue;
}
int high_id = (int) (searchImage.document.id >> 32);
int lower_id = (int) searchImage.document.id;
acc = ((acc * 20261) + 0x80000000L + high_id) % 0x80000000L;
acc = ((acc * 20261) + 0x80000000L + lower_id) % 0x80000000L;
}
return (int) acc;
}
public void loadRecentGif() {
if (loadingRecentGifs || Math.abs(System.currentTimeMillis() - lastGifLoadTime) < 60 * 60 * 1000) {
return;
}
loadingRecentGifs = true;
TLRPC.TL_messages_getSavedGifs req = new TLRPC.TL_messages_getSavedGifs();
req.hash = calcGifsHash(recentImages);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, TLRPC.TL_error error) {
ArrayList<MediaController.SearchImage> arrayList = null;
if (response instanceof TLRPC.TL_messages_savedGifs) {
arrayList = new ArrayList<>();
TLRPC.TL_messages_savedGifs res = (TLRPC.TL_messages_savedGifs) response;
int size = res.gifs.size();
for (int a = 0; a < size; a++) {
MediaController.SearchImage searchImage = new MediaController.SearchImage();
searchImage.type = 2;
searchImage.document = res.gifs.get(a);
searchImage.date = size - a;
searchImage.id = "" + searchImage.document.id;
arrayList.add(searchImage);
MessagesStorage.getInstance().putWebRecent(arrayList);
}
}
final ArrayList<MediaController.SearchImage> arrayListFinal = arrayList;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (arrayListFinal != null) {
boolean wasEmpty = recentImages.isEmpty();
recentImages = arrayListFinal;
if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
}
lastGifLoadTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).edit();
editor.putLong("lastGifLoadTime", lastGifLoadTime).commit();
if (wasEmpty && !recentImages.isEmpty()) {
updateStickerTabs();
}
}
loadingRecentGifs = false;
}
});
}
});
}
@SuppressWarnings("unchecked")
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.stickersDidLoaded) {
updateStickerTabs();
reloadStickersAdapter();
} else if (id == NotificationCenter.recentImagesDidLoaded) {
if ((Integer) args[0] == 2) {
int previousCount = recentImages != null ? recentImages.size() : 0;
recentImages = (ArrayList<MediaController.SearchImage>) args[1];
loadingRecent = false;
if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
}
if (previousCount != recentImages.size()) {
updateStickerTabs();
}
loadRecentGif();
}
}
}
private class StickersGridAdapter extends BaseAdapter {
private Context context;
private int stickersPerRow;
private HashMap<Integer, TLRPC.TL_messages_stickerSet> rowStartPack = new HashMap<>();
private HashMap<TLRPC.TL_messages_stickerSet, Integer> packStartRow = new HashMap<>();
private HashMap<Integer, TLRPC.Document> cache = new HashMap<>();
private int totalItems;
public StickersGridAdapter(Context context) {
this.context = context;
}
public int getCount() {
return totalItems != 0 ? totalItems + 1 : 0;
}
public Object getItem(int i) {
return cache.get(i);
}
public long getItemId(int i) {
return NO_ID;
}
public int getPositionForPack(TLRPC.TL_messages_stickerSet stickerSet) {
return packStartRow.get(stickerSet) * stickersPerRow;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return cache.get(position) != null;
}
@Override
public int getItemViewType(int position) {
if (cache.get(position) != null) {
return 0;
}
return 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
public int getTabForPosition(int position) {
if (stickersPerRow == 0) {
int width = getMeasuredWidth();
if (width == 0) {
width = AndroidUtilities.displaySize.x;
}
stickersPerRow = width / AndroidUtilities.dp(72);
}
int row = position / stickersPerRow;
TLRPC.TL_messages_stickerSet pack = rowStartPack.get(row);
if (pack == null) {
return recentTabBum;
}
return stickerSets.indexOf(pack) + stickersTabOffset;
}
public View getView(int i, View view, ViewGroup viewGroup) {
TLRPC.Document sticker = cache.get(i);
if (sticker != null) {
if (view == null) {
view = new StickerEmojiCell(context) {
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(82), MeasureSpec.EXACTLY));
}
};
}
((StickerEmojiCell) view).setSticker(sticker, false);
} else {
if (view == null) {
view = new EmptyCell(context);
}
if (i == totalItems) {
int row = (i - 1) / stickersPerRow;
TLRPC.TL_messages_stickerSet pack = rowStartPack.get(row);
if (pack == null) {
((EmptyCell) view).setHeight(1);
} else {
int height = pager.getHeight() - (int) Math.ceil(pack.documents.size() / (float) stickersPerRow) * AndroidUtilities.dp(82);
((EmptyCell) view).setHeight(height > 0 ? height : 1);
}
} else {
((EmptyCell) view).setHeight(AndroidUtilities.dp(82));
}
}
return view;
}
@Override
public void notifyDataSetChanged() {
int width = getMeasuredWidth();
if (width == 0) {
width = AndroidUtilities.displaySize.x;
}
stickersPerRow = width / AndroidUtilities.dp(72);
rowStartPack.clear();
packStartRow.clear();
cache.clear();
totalItems = 0;
ArrayList<TLRPC.TL_messages_stickerSet> packs = stickerSets;
for (int a = -1; a < packs.size(); a++) {
ArrayList<TLRPC.Document> documents;
TLRPC.TL_messages_stickerSet pack = null;
int startRow = totalItems / stickersPerRow;
if (a == -1) {
documents = recentStickers;
} else {
pack = packs.get(a);
documents = pack.documents;
packStartRow.put(pack, startRow);
}
if (documents.isEmpty()) {
continue;
}
int count = (int) Math.ceil(documents.size() / (float) stickersPerRow);
for (int b = 0; b < documents.size(); b++) {
cache.put(b + totalItems, documents.get(b));
}
totalItems += count * stickersPerRow;
for (int b = 0; b < count; b++) {
rowStartPack.put(startRow + b, pack);
}
}
super.notifyDataSetChanged();
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
}
private class EmojiGridAdapter extends BaseAdapter {
private int emojiPage;
public EmojiGridAdapter(int page) {
emojiPage = page;
}
public int getCount() {
if (emojiPage == -1) {
return recentEmoji.size();
}
return EmojiData.dataColored[emojiPage].length;
}
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int i, View view, ViewGroup paramViewGroup) {
ImageViewEmoji imageView = (ImageViewEmoji) view;
if (imageView == null) {
imageView = new ImageViewEmoji(getContext());
}
String code;
String coloredCode;
if (emojiPage == -1) {
coloredCode = code = recentEmoji.get(i);
} else {
coloredCode = code = EmojiData.dataColored[emojiPage][i];
String color = emojiColor.get(code);
if (color != null) {
coloredCode += color;
}
}
imageView.setImageDrawable(Emoji.getEmojiBigDrawable(coloredCode));
imageView.setTag(code);
return imageView;
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
}
private class EmojiPagesAdapter extends PagerAdapter implements PagerSlidingTabStrip.IconTabProvider {
public void destroyItem(ViewGroup viewGroup, int position, Object object) {
View view;
if (position == 0) {
view = recentsWrap;
} else if (position == 6) {
view = stickersWrap;
} else {
view = views.get(position);
}
viewGroup.removeView(view);
}
public int getCount() {
return views.size();
}
public int getPageIconResId(int paramInt) {
return icons[paramInt];
}
public Object instantiateItem(ViewGroup viewGroup, int position) {
View view;
if (position == 0) {
view = recentsWrap;
} else if (position == 6) {
view = stickersWrap;
} else {
view = views.get(position);
}
viewGroup.addView(view);
return view;
}
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
if (observer != null) {
super.unregisterDataSetObserver(observer);
}
}
}
private class GifsAdapter extends RecyclerView.Adapter {
private class Holder extends RecyclerView.ViewHolder {
public Holder(View itemView) {
super(itemView);
}
}
private Context mContext;
public GifsAdapter(Context context) {
mContext = context;
}
@Override
public int getItemCount() {
return recentImages.size();
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
ContextLinkCell view = new ContextLinkCell(mContext);
return new Holder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
MediaController.SearchImage photoEntry = recentImages.get(i);
if (photoEntry.document != null) {
((ContextLinkCell) viewHolder.itemView).setGif(photoEntry.document, flowLayoutManager.getRowOfIndex(i) != flowLayoutManager.getRowCount() - 1);
}
}
}
} | gpl-2.0 |
pabloHM/Basket-Base | App/app/src/main/java/com/base/basket/basketbase2/noticias/VerNoticia.java | 1378 | package com.base.basket.basketbase2.noticias;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.base.basket.basketbase2.R;
public class VerNoticia extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ver_noticia);
final Intent intent=getIntent();
TextView tvTitulo=(TextView) findViewById(R.id.titNoticia);
TextView tvSubtitulo=(TextView) findViewById(R.id.subtitNoticia);
TextView tvCuerpo=(TextView) findViewById(R.id.cuerpoNoticia);
ImageView ivView=(ImageView) findViewById(R.id.imgNoticia);
RelativeLayout preView=(RelativeLayout) findViewById(R.id.preImg);
tvTitulo.setText(intent.getStringExtra("titulo"));
tvSubtitulo.setText(intent.getStringExtra("subtitulo"));
tvCuerpo.setText(intent.getStringExtra("cuerpo"));
if(!intent.getStringExtra("imagen").equals("")){
GetImage gi=new GetImage(ivView, intent.getStringExtra("imagen"), preView);
gi.execute();
}
else{
preView.setVisibility(View.GONE);
}
}
}
| gpl-2.0 |
cylong1016/NJULily | src/main/java/blservice/purchaseblservice/PurchaseShowBLService.java | 1340 | package blservice.purchaseblservice;
import java.util.ArrayList;
import vo.PurchaseVO;
public interface PurchaseShowBLService {
/**
* 返回给界面层显示全部的进货(销进货退货)单
* @return 全部的进货(进货退货)单的ArrayList
* @author cylong
* @version 2014年11月28日 下午4:14:35
*/
public ArrayList<PurchaseVO> showPurchase();
public ArrayList<PurchaseVO> showPurchaseBack();
/**
* 返回给界面层显示全部在审核的进货(进货退货)单
* @return
* @author Zing
* @version Dec 12, 2014 1:58:50 AM
*/
public ArrayList<PurchaseVO> showPurchaseApproving();
public ArrayList<PurchaseVO> showPurchaseBackApproving();
/**
* 返回给界面层显示全部通过审核的进货(进货退货)单
* @return
* @author Zing
* @version Dec 12, 2014 1:59:15 AM
*/
public ArrayList<PurchaseVO> showPurchasePass();
public ArrayList<PurchaseVO> showPurchaseBackPass();
/**
* 返回给界面层显示全部没有通过审批的进货(进货退货)单
* @return
* @author Zing
* @version Dec 12, 2014 2:01:47 AM
*/
public ArrayList<PurchaseVO> showPurchaseFailure();
public ArrayList<PurchaseVO> showPurchaseBackFailure();
public ArrayList<PurchaseVO> showPurchaseDraft();
public ArrayList<PurchaseVO> showPurchaseBackDraft();
}
| gpl-2.0 |
camposer/curso_spring-security_20150921 | blog/src/main/java/config/global/DatabaseConfig.java | 2282 | package config.global;
import javax.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableJpaRepositories("repository")
@EnableTransactionManagement
public class DatabaseConfig {
@Value("${db.driverClassName}")
private String dbDriverClassName;
@Value("${db.url}")
private String dbUrl;
@Value("${db.username}")
private String dbUsername;
@Value("${db.password}")
private String dbPassword;
@Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(dbDriverClassName);
driverManagerDataSource.setUrl(dbUrl);
driverManagerDataSource.setUsername(dbUsername);
driverManagerDataSource.setPassword(dbPassword);
return driverManagerDataSource;
}
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("model");
factory.setDataSource(dataSource());
//factory.setJpaDialect(new HibernateJpaDialect());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
} | gpl-2.0 |
BIORIMP/biorimp | BIO-RIMP/BIORIMPsrc/entity/MappingRefactorEC.java | 4529 | /**
*
*/
package entity;
import java.util.ArrayList;
import java.util.List;
import edu.wayne.cs.severe.redress2.entity.TypeDeclaration;
import edu.wayne.cs.severe.redress2.entity.refactoring.json.OBSERVRefParam;
import edu.wayne.cs.severe.redress2.entity.refactoring.json.OBSERVRefactoring;
import entity.MappingRefactor.Refactoring;
import unalcol.types.collection.bitarray.BitArray;
/**
* @author Daavid
*
*/
public class MappingRefactorEC extends MappingRefactor {
/* (non-Javadoc)
* @see entity.MappingRefactor#mappingRefactor(java.lang.String, unalcol.types.collection.bitarray.BitArray, entity.MetaphorCode)
*/
protected Refactoring type = Refactoring.extractClass;
private boolean feasible = true;
@Override
public OBSERVRefactoring mappingRefactor(QubitRefactor genome, MetaphorCode code) {
// TODO Auto-generated method stub
List<OBSERVRefactoring> subRefs = new ArrayList<OBSERVRefactoring>();
subRefs.add(mappingRefactorMF(genome, code, "TgtClassEC"));
subRefs.add(mappingRefactorMM(genome, code, "TgtClassEC"));
return new OBSERVRefactoring(type.name(),null,subRefs,feasible);
}
public OBSERVRefactoring mappingRefactorMF(QubitRefactor genome, MetaphorCode code, String newClass) {
// TODO Auto-generated method stub
List<OBSERVRefParam> params = new ArrayList<OBSERVRefParam>();
//Creating the OBSERVRefParam for the src class
int numSrcObs = genome.getNumberGenome(genome.getGenSRC());
TypeDeclaration sysType_src = code.getMapClass().get(numSrcObs %
code.getMapClass().size());
List<String> value_src = new ArrayList<String>();
value_src.add(sysType_src.getQualifiedName());
params.add(new OBSERVRefParam("src", value_src));
//Creating the OBSERVRefParam for the fld field
List<String> value_fld = new ArrayList<String>();
if(!code.getFieldsFromClass(sysType_src).isEmpty()){
int numFldObs = genome.getNumberGenome(genome.getGenFLD());
String fldName = (String) code.getFieldsFromClass(sysType_src).toArray()[numFldObs
% code.getFieldsFromClass(sysType_src).size()];
value_fld.add(fldName);
params.add(new OBSERVRefParam("fld", value_fld));
}else{
value_fld.add("");
params.add(new OBSERVRefParam("fld", value_fld ));
feasible = false;
}
//Creating the OBSERVRefParam for the tgt
//This Target Class is not inside metaphor
List<String> value_tgt = new ArrayList<String>();
value_tgt.add( sysType_src.getPack() + newClass + "|N");
params.add(new OBSERVRefParam("tgt", value_tgt));
code.addClasstoHash(sysType_src.getPack(), newClass + "|N");
return new OBSERVRefactoring(Refactoring.moveField.name(),params, feasible );
}
public OBSERVRefactoring mappingRefactorMM(QubitRefactor genome, MetaphorCode code,String newClass) {
// TODO Auto-generated method stub
List<OBSERVRefParam> params = new ArrayList<OBSERVRefParam>();
//Creating the OBSERVRefParam for the src class
int numSrcObs = genome.getNumberGenome(genome.getGenSRC());
TypeDeclaration sysType_src = code.getMapClass().get(numSrcObs %
code.getMapClass().size());
List<String> value_src = new ArrayList<String>();
value_src.add(sysType_src.getQualifiedName());
params.add(new OBSERVRefParam("src", value_src));
//Creating the OBSERVRefParam for the mtd class
List<String> value_mtd = new ArrayList<String>();
if(!code.getMethodsFromClass(sysType_src).isEmpty()){
int numMtdObs = genome.getNumberGenome(genome.getGenMTD());
value_mtd.add((String) code.getMethodsFromClass(sysType_src).toArray()[numMtdObs
% code.getMethodsFromClass(sysType_src).size()]);
//verification of method not constructor
if(value_mtd.get(0).equals(sysType_src.getName()))
feasible = false;
params.add(new OBSERVRefParam("mtd", value_mtd));
}else{
value_mtd.add("");
params.add(new OBSERVRefParam("mtd", value_mtd));
feasible = false;
}
//Creating the OBSERVRefParam for the tgt
//This Target Class is not inside metaphor
List<String> value_tgt = new ArrayList<String>();
value_tgt.add( sysType_src.getPack() + newClass + "|N");
params.add(new OBSERVRefParam("tgt", value_tgt));
code.addClasstoHash(sysType_src.getPack(), newClass + "|N");
return new OBSERVRefactoring(Refactoring.moveMethod.name(),params,feasible);
}
/* (non-Javadoc)
* @see entity.MappingRefactor#mappingParams()
*/
@Override
public List<OBSERVRefParam> mappingParams() {
// TODO Auto-generated method stub
return null;
}
}
| gpl-2.0 |
ia-toki/judgels | judgels-backends/gabriel/gabriel-engines/src/integTest/java/judgels/gabriel/engines/outputonly/OutputOnlyWithSubtasksGradingEngineIntegrationTests.java | 11600 | package judgels.gabriel.engines.outputonly;
import static judgels.gabriel.api.Verdict.ACCEPTED;
import static judgels.gabriel.api.Verdict.OK;
import static judgels.gabriel.api.Verdict.SKIPPED;
import static judgels.gabriel.api.Verdict.WRONG_ANSWER;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.Optional;
import judgels.gabriel.api.GradingException;
import judgels.gabriel.api.TestCase;
import judgels.gabriel.api.TestGroup;
import judgels.gabriel.engines.BlackboxGradingEngineIntegrationTests;
import org.junit.jupiter.api.Test;
class OutputOnlyWithSubtasksGradingEngineIntegrationTests extends BlackboxGradingEngineIntegrationTests {
private static final OutputOnlyWithSubtasksGradingEngine ENGINE = new OutputOnlyWithSubtasksGradingEngine();
private static final OutputOnlyWithSubtasksGradingConfig CONFIG = new OutputOnlyWithSubtasksGradingConfig.Builder()
.from(ENGINE.createDefaultConfig())
.testData(ImmutableList.of(
TestGroup.of(0, ImmutableList.of(
TestCase.of("sample_1.in", "sample_1.out", ImmutableSet.of(0, 1, 2)),
TestCase.of("sample_2.in", "sample_2.out", ImmutableSet.of(0, 1, 2)),
TestCase.of("sample_3.in", "sample_3.out", ImmutableSet.of(0, 2)))),
TestGroup.of(1, ImmutableList.of(
TestCase.of("1_1.in", "1_1.out", ImmutableSet.of(1, 2)),
TestCase.of("1_2.in", "1_2.out", ImmutableSet.of(1, 2)))),
TestGroup.of(2, ImmutableList.of(
TestCase.of("2_1.in", "2_1.out", ImmutableSet.of(2)),
TestCase.of("2_2.in", "2_2.out", ImmutableSet.of(2)),
TestCase.of("2_3.in", "2_3.out", ImmutableSet.of(2))))))
.subtaskPoints(ImmutableList.of(30, 70))
.build();
OutputOnlyWithSubtasksGradingEngineIntegrationTests() {
super("outputonly", ENGINE);
}
@Test
void ac() throws GradingException {
addSourceFile("source", "AC.zip");
assertResult(
CONFIG,
ACCEPTED,
100,
ImmutableList.of(
testGroupResult(
0,
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 2)),
testGroupResult(
1,
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2)),
testGroupResult(
2,
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 2))),
ImmutableList.of(
subtaskResult(1, ACCEPTED, 30),
subtaskResult(2, ACCEPTED, 70)));
}
@Test
void wa_30() throws GradingException {
addSourceFile("source", "WA-at-2_3.zip");
assertResult(
CONFIG,
WRONG_ANSWER,
30,
ImmutableList.of(
testGroupResult(
0,
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 2)),
testGroupResult(
1,
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2)),
testGroupResult(
2,
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(WRONG_ANSWER, "X", Optional.empty(), 2))),
ImmutableList.of(
subtaskResult(1, ACCEPTED, 30),
subtaskResult(2, WRONG_ANSWER, 0)));
}
@Test
void wa_30_at_sample() throws GradingException {
addSourceFile("source", "WA-at-sample_3.zip");
assertResult(
CONFIG,
WRONG_ANSWER,
30,
ImmutableList.of(
testGroupResult(
0,
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(WRONG_ANSWER, "X", Optional.empty(), 0, 2)),
testGroupResult(
1,
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2)),
testGroupResult(
2,
testCaseResult(SKIPPED, "?", Optional.empty(), 2),
testCaseResult(SKIPPED, "?", Optional.empty(), 2),
testCaseResult(SKIPPED, "?", Optional.empty(), 2))),
ImmutableList.of(
subtaskResult(1, ACCEPTED, 30),
subtaskResult(2, WRONG_ANSWER, 0)));
}
@Test
void wa_30_because_some_files_missing() throws GradingException {
addSourceFile("source", "WA-missing-at-2_3.zip");
assertResult(
CONFIG,
OK,
30,
ImmutableList.of(
testGroupResult(
0,
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 2)),
testGroupResult(
1,
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2)),
testGroupResult(
2,
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(SKIPPED, "?", Optional.empty(), 2))),
ImmutableList.of(
subtaskResult(1, ACCEPTED, 30),
subtaskResult(2, OK, 0)));
}
@Test
void wa_0() throws GradingException {
addSourceFile("source", "WA-at-1_1.zip");
assertResult(
CONFIG,
WRONG_ANSWER,
0,
ImmutableList.of(
testGroupResult(
0,
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 2)),
testGroupResult(
1,
testCaseResult(WRONG_ANSWER, "X", Optional.empty(), 1, 2),
testCaseResult(SKIPPED, "?", Optional.empty(), 1, 2)),
testGroupResult(
2,
testCaseResult(SKIPPED, "?", Optional.empty(), 2),
testCaseResult(SKIPPED, "?", Optional.empty(), 2),
testCaseResult(SKIPPED, "?", Optional.empty(), 2))),
ImmutableList.of(
subtaskResult(1, WRONG_ANSWER, 0),
subtaskResult(2, WRONG_ANSWER, 0)));
}
@Test
void ac_with_custom_scorer() throws GradingException {
addSourceFile("source", "AC-scorer.zip");
assertResult(
new OutputOnlyWithSubtasksGradingConfig.Builder().from(CONFIG)
.customScorer("scorer-binary.cpp").build(),
ACCEPTED,
100,
ImmutableList.of(
testGroupResult(
0,
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 2)),
testGroupResult(
1,
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2)),
testGroupResult(
2,
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 2))),
ImmutableList.of(
subtaskResult(1, ACCEPTED, 30),
subtaskResult(2, ACCEPTED, 70)));
}
@Test
void wa_30_with_custom_scorer() throws GradingException {
addSourceFile("source", "WA-at-2_3-scorer.zip");
assertResult(
new OutputOnlyWithSubtasksGradingConfig.Builder().from(CONFIG)
.customScorer("scorer-binary.cpp").build(),
WRONG_ANSWER,
30,
ImmutableList.of(
testGroupResult(
0,
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 0, 2)),
testGroupResult(
1,
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 1, 2)),
testGroupResult(
2,
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(ACCEPTED, "*", Optional.empty(), 2),
testCaseResult(WRONG_ANSWER, "X", Optional.empty(), 2))),
ImmutableList.of(
subtaskResult(1, ACCEPTED, 30),
subtaskResult(2, WRONG_ANSWER, 0)));
}
}
| gpl-2.0 |
aleXpansion/TestMod | src/main/java/com/alexpansion/testmod/proxy/IProxy.java | 109 | package com.alexpander.testmod.proxy;
/**
* Created by Danny on 2/26/2015.
*/
public interface IProxy {
}
| gpl-2.0 |
RaineForest/ECG-Viewer | JWave/src/math/jwave/transforms/BasicTransform.java | 22386 | /**
* JWave is distributed under the MIT License (MIT); this file is part of.
*
* Copyright (c) 2008-2015 Christian Scheiblich (cscheiblich@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package math.jwave.transforms;
import math.jwave.datatypes.natives.Complex;
import math.jwave.exceptions.JWaveError;
import math.jwave.exceptions.JWaveException;
import math.jwave.exceptions.JWaveFailure;
import math.jwave.tools.MathToolKit;
import math.jwave.transforms.wavelets.Wavelet;
/**
* Basic Wave for transformations like Fast Fourier Transform (FFT), Fast
* Wavelet Transform (FWT), Fast Wavelet Packet Transform (WPT), or Discrete
* Wavelet Transform (DWT). Naming of this class due to en.wikipedia.org; to
* write Fourier series in terms of the 'basic waves' of function: e^(2*pi*i*w).
*
* @date 08.02.2010 11:11:59
* @author Christian Scheiblich (cscheiblich@gmail.com)
*/
public abstract class BasicTransform {
/**
* String identifier of the current Transform object.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 14.03.2015 14:25:56
*/
protected String _name;
/**
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 19.02.2014 18:38:21
*/
public BasicTransform( ) {
_name = null;
} // BasicTransform
/**
* Returns String identifier of current type of BasicTransform Object.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 14.03.2015 18:13:34
* @return identifier as String
*/
public String getName( ) {
return _name;
} // getName
/**
* Returns the stored Wavelet object or null pointer.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 14.03.2015 18:26:44
* @return object of type Wavelet of null pointer
* @throws JWaveFailure
* if Wavelet object is not available
*/
public Wavelet getWavelet( ) throws JWaveFailure {
throw new JWaveFailure(
"BasicTransform#getWavelet - not available" );
} // getWavelet
/**
* Performs the forward transform from time domain to frequency or Hilbert
* domain for a given array depending on the used transform algorithm by
* inheritance.
*
* @date 10.02.2010 08:23:24
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @param arrTime
* coefficients of 1-D time domain
* @return coefficients of 1-D frequency or Hilbert space
* @throws JWaveException
*/
public abstract double[ ] forward( double[ ] arrTime ) throws JWaveException;
/**
* Performs the reverse transform from frequency or Hilbert domain to time
* domain for a given array depending on the used transform algorithm by
* inheritance.
*
* @date 10.02.2010 08:23:24
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @param arrFreq
* coefficients of 1-D frequency or Hilbert domain
* @return coefficients of time series of 1-D frequency or Hilbert space
* @throws JWaveException
*/
public abstract double[ ] reverse( double[ ] arrFreq ) throws JWaveException;
/**
* Performs the forward transform from time domain to Hilbert domain of a
* given level depending on the used transform algorithm by inheritance.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 11:33:11
* @param arrTime
* @param level
* the level of Hilbert space; energy & detail coefficients
* @return array keeping Hilbert space of requested level
* @throws JWaveException
* if given array is not of type 2^p | p N or given level does not
* match the possibilities of given array.
*/
public double[ ] forward( double[ ] arrTime, int level )
throws JWaveException {
throw new JWaveError( "BasicTransform#forward - "
+ "method is not implemented for this transform type!" );
} // forward
/**
* Performs the reverse transform from Hilbert domain of a given level to time
* domain depending on the used transform algorithm by inheritance.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 11:34:27
* @param arrFreq
* @param level
* the level of Hilbert space; energy & detail coefficients
* @return array keeping Hilbert space of requested level
* @throws JWaveException
* if given array is not of type 2^p | p N or given level does not
* match the possibilities of given array.
*/
public double[ ] reverse( double[ ] arrFreq, int level )
throws JWaveException {
throw new JWaveError( "BasicTransform#reverse - "
+ "method is not implemented for this transform type!" );
} // reverse
/**
* Generates from a 2-D decomposition a 1-D time series.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 17.08.2014 10:07:19
* @param matDeComp
* 2-D Hilbert spaces: [ 0 .. p ][ 0 .. N ] where p is the exponent
* of N=2^p
* @return a 1-D time domain signal
* @throws JWaveException
*/
public double[ ][ ] decompose( double[ ] arrTime ) throws JWaveException {
throw new JWaveError( "BasicTransform#decompose - "
+ "method is not implemented for this transform type!" );
} // decompose
/**
* Generates from a 1-D signal a 2-D output, where the second dimension are
* the levels of the wavelet transform. The first level should keep the
* original coefficients. All following levels should keep each step of the
* decomposition of the Fast Wavelet Transform. However, each level of the
* this decomposition matrix is having the full set, full energy and full
* details, that are needed to do a full reconstruction. So one can select a
* level filter it and then do reconstruction only from this single line! BY
* THIS METHOD, THE _HIGHEST_ LEVEL IS _ALWAYS_ TAKEN FOR RECONSTRUCTION!
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 17.08.2014 10:07:19
* @param matDeComp
* 2-D Hilbert spaces: [ 0 .. p ][ 0 .. M ] where p is the exponent
* of M=2^p | pN
* @return a 1-D time domain signal
*/
public double[ ] recompose( double[ ][ ] matDeComp ) throws JWaveException {
// Each level of the matrix is having the full set (full energy + details)
// of decomposition. Therefore, each level can be used to do a full reconstruction,
int level = matDeComp.length - 1; // selected highest level in general.
double[ ] arrTime = null;
try {
arrTime = recompose( matDeComp, level );
} catch( JWaveFailure e ) {
e.showMessage( );
e.printStackTrace( );
} // try
return arrTime;
} // recompose
/**
* Generates from a 1-D signal a 2-D output, where the second dimension are
* the levels of the wavelet transform. The first level should keep the
* original coefficients. All following levels should keep each step of the
* decomposition of the Fast Wavelet Transform. However, each level of the
* this decomposition matrix is having the full set, full energy and full
* details, that are needed to do a full reconstruction. So one can select a
* level filter it and then do reconstruction only from this single line!
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 15:12:19
* @param matDeComp
* 2-D Hilbert spaces: [ 0 .. p ][ 0 .. M ] where p is the exponent
* of M=2^p | pN
* @param level
* the level that should be used for reconstruction
* @return the reconstructed time series of a selected level
* @throws JWaveException
*/
public double[ ] recompose( double[ ][ ] matDeComp, int level )
throws JWaveException {
double[ ] arrTime = null;
try {
arrTime = recompose( matDeComp, level );
} catch( JWaveFailure e ) {
e.showMessage( );
e.printStackTrace( );
} // try
return arrTime;
} // recompose
/**
* Performs the forward transform from time domain to frequency or Hilbert
* domain for a given array depending on the used transform algorithm by
* inheritance.
*
* @date 16.02.2014 14:42:57
* @author Christian Scheiblich (cscheiblich@gmail.com)
* (cscheiblich@gmail.com)
* @param arrTime
* coefficients of 1-D time domain
* @return coefficients of 1-D frequency or Hilbert domain
* @throws JWaveException
*/
public Complex[ ] forward( Complex[ ] arrTime ) throws JWaveException {
double[ ] arrTimeBulk = new double[ 2 * arrTime.length ];
for( int i = 0; i < arrTime.length; i++ ) {
// TODO rehack complex number splitting this to: { r1, r2, r3, .., c1, c2, c3, .. }
int k = i * 2;
arrTimeBulk[ k ] = arrTime[ i ].getReal( );
arrTimeBulk[ k + 1 ] = arrTime[ i ].getImag( );
} // i blown to k = 2 * i
double[ ] arrHilbBulk = forward( arrTimeBulk );
Complex[ ] arrHilb = new Complex[ arrTime.length ];
for( int i = 0; i < arrTime.length; i++ ) {
int k = i * 2;
arrHilb[ i ] = new Complex( arrHilbBulk[ k ], arrHilbBulk[ k + 1 ] );
} // k = 2 * i shrink to i
return arrHilb;
} // forward
/**
* Performs the reverse transform from frequency or Hilbert domain to time
* domain for a given array depending on the used transform algorithm by
* inheritance.
*
* @date 16.02.2014 14:42:57
* @author Christian Scheiblich (cscheiblich@gmail.com)
* (cscheiblich@gmail.com)
* @param arrFreq
* coefficients of 1-D frequency or Hilbert domain
* @return coefficients of 1-D time domain
* @throws JWaveException
*/
public Complex[ ] reverse( Complex[ ] arrHilb ) throws JWaveException {
double[ ] arrHilbBulk = new double[ 2 * arrHilb.length ];
for( int i = 0; i < arrHilb.length; i++ ) {
int k = i * 2;
arrHilbBulk[ k ] = arrHilb[ i ].getReal( );
arrHilbBulk[ k + 1 ] = arrHilb[ i ].getImag( );
} // i blown to k = 2 * i
double[ ] arrTimeBulk = reverse( arrHilbBulk );
Complex[ ] arrTime = new Complex[ arrHilb.length ];
for( int i = 0; i < arrTime.length; i++ ) {
int k = i * 2;
arrTime[ i ] = new Complex( arrTimeBulk[ k ], arrTimeBulk[ k + 1 ] );
} // k = 2 * i shrink to i
return arrTime;
} // reverse
/**
* Performs the 2-D forward transform from time domain to frequency or Hilbert
* domain for a given matrix depending on the used transform algorithm by
* inheritance.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 12:47:01
* @param matTime
* @return
* @throws JWaveException
* if matrix id not of matching dimension like 2^p | pN
*/
public double[ ][ ] forward( double[ ][ ] matTime ) throws JWaveException {
int maxM = MathToolKit.getExponent( matTime.length );
int maxN = MathToolKit.getExponent( matTime[ 0 ].length );
return forward( matTime, maxM, maxN );
} // forward
/**
* Performs the 2-D forward transform from time domain to frequency or Hilbert
* domain of a certain level for a given matrix depending on the used
* transform algorithm by inheritance. The supported level has to match the
* possible dimensions of the given matrix.
*
* @date 10.02.2010 11:00:29
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @param matTime
* coefficients of 2-D time domain
* @param lvlM
* level to stop in dimension M of the matrix
* @param lvlN
* level to stop in dimension N of the matrix
* @return coefficients of 2-D frequency or Hilbert domain
* @throws JWaveException
*/
public double[ ][ ] forward( double[ ][ ] matTime, int lvlM, int lvlN )
throws JWaveException {
int noOfRows = matTime.length;
int noOfCols = matTime[ 0 ].length;
double[ ][ ] matHilb = new double[ noOfRows ][ noOfCols ];
for( int i = 0; i < noOfRows; i++ ) {
double[ ] arrTime = new double[ noOfCols ];
for( int j = 0; j < noOfCols; j++ )
arrTime[ j ] = matTime[ i ][ j ];
double[ ] arrHilb = forward( arrTime, lvlN );
for( int j = 0; j < noOfCols; j++ )
matHilb[ i ][ j ] = arrHilb[ j ];
} // rows
for( int j = 0; j < noOfCols; j++ ) {
double[ ] arrTime = new double[ noOfRows ];
for( int i = 0; i < noOfRows; i++ )
arrTime[ i ] = matHilb[ i ][ j ];
double[ ] arrHilb = forward( arrTime, lvlM );
for( int i = 0; i < noOfRows; i++ )
matHilb[ i ][ j ] = arrHilb[ i ];
} // cols
return matHilb;
} // forward
/**
* Performs the 2-D reverse transform from frequency or Hilbert or time domain
* to time domain for a given matrix depending on the used transform algorithm
* by inheritance.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 10.02.2010 11:01:38
* @param matFreq
* @return
* @throws JWaveException
*/
public double[ ][ ] reverse( double[ ][ ] matFreq ) throws JWaveException {
int maxM = MathToolKit.getExponent( matFreq.length );
int maxN = MathToolKit.getExponent( matFreq[ 0 ].length );
return reverse( matFreq, maxM, maxN );
} // reverse
/**
* Performs the 2-D reverse transform from frequency or Hilbert or time domain
* to time domain of a certain level for a given matrix depending on the used
* transform algorithm by inheritance.
*
* @date 22.03.2015 12:49:16
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @param matFreq
* coefficients of 2-D frequency or Hilbert domain
* @param lvlM
* level to start reconstruction for dimension M of the matrix
* @param lvlN
* level to start reconstruction for dimension N of the matrix
* @return coefficients of 2-D time domain
* @throws JWaveException
*/
public double[ ][ ] reverse( double[ ][ ] matFreq, int lvlM, int lvlN )
throws JWaveException {
int noOfRows = matFreq.length;
int noOfCols = matFreq[ 0 ].length;
double[ ][ ] matTime = new double[ noOfRows ][ noOfCols ];
for( int j = 0; j < noOfCols; j++ ) {
double[ ] arrFreq = new double[ noOfRows ];
for( int i = 0; i < noOfRows; i++ )
arrFreq[ i ] = matFreq[ i ][ j ];
double[ ] arrTime = reverse( arrFreq, lvlM ); // AED
for( int i = 0; i < noOfRows; i++ )
matTime[ i ][ j ] = arrTime[ i ];
} // cols
for( int i = 0; i < noOfRows; i++ ) {
double[ ] arrFreq = new double[ noOfCols ];
for( int j = 0; j < noOfCols; j++ )
arrFreq[ j ] = matTime[ i ][ j ];
double[ ] arrTime = reverse( arrFreq, lvlN ); // AED
for( int j = 0; j < noOfCols; j++ )
matTime[ i ][ j ] = arrTime[ j ];
} // rows
return matTime;
} // reverse
/**
* Performs the 3-D forward transform from time domain to frequency or Hilbert
* domain for a given space (3-D) depending on the used transform algorithm by
* inheritance.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 10.07.2010 18:08:17
* @param spcTime
* @return
* @throws JWaveException
*/
public double[ ][ ][ ] forward( double[ ][ ][ ] spcTime )
throws JWaveException {
int maxP = MathToolKit.getExponent( spcTime.length );
int maxQ = MathToolKit.getExponent( spcTime[ 0 ].length );
int maxR = MathToolKit.getExponent( spcTime[ 0 ][ 0 ].length );
return forward( spcTime, maxP, maxQ, maxR );
} // forward
/**
* Performs the 3-D forward transform from time domain to frequency or Hilbert
* domain of a certain level for a given space (3-D) depending on the used
* transform algorithm by inheritance.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 12:58:34
* @param spcTime
* coefficients of 3-D time domain domain
* @return coefficients of 3-D frequency or Hilbert domain
* @throws JWaveException
*/
public double[ ][ ][ ] forward( double[ ][ ][ ] spcTime, int lvlP, int lvlQ,
int lvlR ) throws JWaveException {
int noOfRows = spcTime.length; // first dimension
int noOfCols = spcTime[ 0 ].length; // second dimension
int noOfHigh = spcTime[ 0 ][ 0 ].length; // third dimension
double[ ][ ][ ] spcHilb = new double[ noOfRows ][ noOfCols ][ noOfHigh ];
for( int i = 0; i < noOfRows; i++ ) {
double[ ][ ] matTime = new double[ noOfCols ][ noOfHigh ];
for( int j = 0; j < noOfCols; j++ ) {
for( int k = 0; k < noOfHigh; k++ ) {
matTime[ j ][ k ] = spcTime[ i ][ j ][ k ];
} // high
} // cols
double[ ][ ] matHilb = forward( matTime, lvlP, lvlQ ); // 2-D forward
for( int j = 0; j < noOfCols; j++ ) {
for( int k = 0; k < noOfHigh; k++ ) {
spcHilb[ i ][ j ][ k ] = matHilb[ j ][ k ];
} // high
} // cols
} // rows
for( int j = 0; j < noOfCols; j++ ) {
for( int k = 0; k < noOfHigh; k++ ) {
double[ ] arrTime = new double[ noOfRows ];
for( int i = 0; i < noOfRows; i++ )
arrTime[ i ] = spcHilb[ i ][ j ][ k ];
double[ ] arrHilb = forward( arrTime, lvlR ); // 1-D forward
for( int i = 0; i < noOfRows; i++ )
spcHilb[ i ][ j ][ k ] = arrHilb[ i ];
} // high
} // cols
return spcHilb;
} // forward
/**
* Performs the 3-D reverse transform from frequency or Hilbert domain to time
* domain for a given space (3-D) depending on the used transform algorithm by
* inheritance.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 10.07.2010 18:09:54
* @param spcHilb
* @return
* @throws JWaveException
*/
public double[ ][ ][ ] reverse( double[ ][ ][ ] spcHilb )
throws JWaveException {
int maxP = MathToolKit.getExponent( spcHilb.length );
int maxQ = MathToolKit.getExponent( spcHilb[ 0 ].length );
int maxR = MathToolKit.getExponent( spcHilb[ 0 ][ 0 ].length );
return reverse( spcHilb, maxP, maxQ, maxR );
} // reverse
/**
* Performs the 3-D reverse transform from frequency or Hilbert domain of a
* certain level to time domain for a given space (3-D) depending on the used
* transform algorithm by inheritance. The supported coefficients have to
* match the level of Hilbert space.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 13:01:47
* @param spcHilb
* coefficients of 3-D frequency or Hilbert domain
* @return coefficients of 3-D time domain
* @throws JWaveException
*/
public double[ ][ ][ ] reverse( double[ ][ ][ ] spcHilb, int lvlP, int lvlQ,
int lvlR ) throws JWaveException {
int noOfRows = spcHilb.length; // first dimension
int noOfCols = spcHilb[ 0 ].length; // second dimension
int noOfHigh = spcHilb[ 0 ][ 0 ].length; // third dimension
double[ ][ ][ ] spcTime = new double[ noOfRows ][ noOfCols ][ noOfHigh ];
for( int i = 0; i < noOfRows; i++ ) {
double[ ][ ] matHilb = new double[ noOfCols ][ noOfHigh ];
for( int j = 0; j < noOfCols; j++ ) {
for( int k = 0; k < noOfHigh; k++ ) {
matHilb[ j ][ k ] = spcHilb[ i ][ j ][ k ];
} // high
} // cols
double[ ][ ] matTime = reverse( matHilb, lvlP, lvlQ ); // 2-D reverse
for( int j = 0; j < noOfCols; j++ ) {
for( int k = 0; k < noOfHigh; k++ ) {
spcTime[ i ][ j ][ k ] = matTime[ j ][ k ];
} // high
} // cols
} // rows
for( int j = 0; j < noOfCols; j++ ) {
for( int k = 0; k < noOfHigh; k++ ) {
double[ ] arrHilb = new double[ noOfRows ];
for( int i = 0; i < noOfRows; i++ )
arrHilb[ i ] = spcTime[ i ][ j ][ k ];
double[ ] arrTime = reverse( arrHilb, lvlR ); // 1-D reverse
for( int i = 0; i < noOfRows; i++ )
spcTime[ i ][ j ][ k ] = arrTime[ i ];
} // high
} // cols
return spcTime;
} // reverse
/**
* Returns true if given integer is of type binary (2, 4, 8, 16, ..) else the
* method returns false.
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 13:31:39
* @param number
* an integer of type 2, 4, 8, 16, 32, 64, ...
* @return true if number is a binary number else false
*/
protected boolean isBinary( int number ) {
return MathToolKit.isBinary( number ); // use MathToolKit or implement
} // isBinary
/**
* Return the exponent of a binary a number
*
* @author Christian Scheiblich (cscheiblich@gmail.com)
* @date 22.03.2015 13:35:50
* @param number
* any integer that fulfills 2^p | pN
* @return p as number = 2^p | pN
* @throws JWaveException
* if given number is not a binary number
*/
protected int calcExponent( int number ) throws JWaveException {
if( !isBinary( number ) )
throw new JWaveFailure( "BasicTransform#calcExponent - "
+ "given number is not binary: "
+ "2^p | pN .. = 1, 2, 4, 8, 16, 32, .. " );
return (int)( MathToolKit.getExponent( (int)( number ) ) ); // use MathToolKit or implement
} // calcExponent
} // BasicTransform | gpl-2.0 |
fsferrara/connect-four | src/connectfour/game/agent/Action.java | 457 | package connectfour.game.agent;
/**
* Describes an Action that can or has been taken by an Agent via one of its Actuators.
*/
/**
* @author Ciaran O'Reilly
*/
public interface Action {
/**
* Indicates whether or not this Action is a 'No Operation'.<br>
* Note: AIMA3e - NoOp, or �no operation,� is the name of an assembly
* language instruction that does nothing.
*
* @return true if this is a NoOp Action.
*/
boolean isNoOp();
}
| gpl-2.0 |
mviitanen/marsmod | mcp/src/minecraft/net/minecraft/world/gen/feature/WorldGenCanopyTree.java | 8963 | package net.minecraft.world.gen.feature;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.util.Direction;
import net.minecraft.world.World;
public class WorldGenCanopyTree extends WorldGenAbstractTree
{
private static final String __OBFID = "CL_00000430";
public WorldGenCanopyTree(boolean p_i45461_1_)
{
super(p_i45461_1_);
}
public boolean generate(World p_76484_1_, Random p_76484_2_, int p_76484_3_, int p_76484_4_, int p_76484_5_)
{
int var6 = p_76484_2_.nextInt(3) + p_76484_2_.nextInt(2) + 6;
boolean var7 = true;
if (p_76484_4_ >= 1 && p_76484_4_ + var6 + 1 <= 256)
{
int var10;
int var11;
for (int var8 = p_76484_4_; var8 <= p_76484_4_ + 1 + var6; ++var8)
{
byte var9 = 1;
if (var8 == p_76484_4_)
{
var9 = 0;
}
if (var8 >= p_76484_4_ + 1 + var6 - 2)
{
var9 = 2;
}
for (var10 = p_76484_3_ - var9; var10 <= p_76484_3_ + var9 && var7; ++var10)
{
for (var11 = p_76484_5_ - var9; var11 <= p_76484_5_ + var9 && var7; ++var11)
{
if (var8 >= 0 && var8 < 256)
{
Block var12 = p_76484_1_.getBlock(var10, var8, var11);
if (!this.func_150523_a(var12))
{
var7 = false;
}
}
else
{
var7 = false;
}
}
}
}
if (!var7)
{
return false;
}
else
{
Block var20 = p_76484_1_.getBlock(p_76484_3_, p_76484_4_ - 1, p_76484_5_);
if ((var20 == Blocks.grass || var20 == Blocks.dirt) && p_76484_4_ < 256 - var6 - 1)
{
this.func_150515_a(p_76484_1_, p_76484_3_, p_76484_4_ - 1, p_76484_5_, Blocks.dirt);
this.func_150515_a(p_76484_1_, p_76484_3_ + 1, p_76484_4_ - 1, p_76484_5_, Blocks.dirt);
this.func_150515_a(p_76484_1_, p_76484_3_ + 1, p_76484_4_ - 1, p_76484_5_ + 1, Blocks.dirt);
this.func_150515_a(p_76484_1_, p_76484_3_, p_76484_4_ - 1, p_76484_5_ + 1, Blocks.dirt);
int var21 = p_76484_2_.nextInt(4);
var10 = var6 - p_76484_2_.nextInt(4);
var11 = 2 - p_76484_2_.nextInt(3);
int var22 = p_76484_3_;
int var13 = p_76484_5_;
int var14 = 0;
int var15;
int var16;
for (var15 = 0; var15 < var6; ++var15)
{
var16 = p_76484_4_ + var15;
if (var15 >= var10 && var11 > 0)
{
var22 += Direction.offsetX[var21];
var13 += Direction.offsetZ[var21];
--var11;
}
Block var17 = p_76484_1_.getBlock(var22, var16, var13);
if (var17.getMaterial() == Material.air || var17.getMaterial() == Material.leaves)
{
this.func_150516_a(p_76484_1_, var22, var16, var13, Blocks.log2, 1);
this.func_150516_a(p_76484_1_, var22 + 1, var16, var13, Blocks.log2, 1);
this.func_150516_a(p_76484_1_, var22, var16, var13 + 1, Blocks.log2, 1);
this.func_150516_a(p_76484_1_, var22 + 1, var16, var13 + 1, Blocks.log2, 1);
var14 = var16;
}
}
for (var15 = -2; var15 <= 0; ++var15)
{
for (var16 = -2; var16 <= 0; ++var16)
{
byte var23 = -1;
this.func_150526_a(p_76484_1_, var22 + var15, var14 + var23, var13 + var16);
this.func_150526_a(p_76484_1_, 1 + var22 - var15, var14 + var23, var13 + var16);
this.func_150526_a(p_76484_1_, var22 + var15, var14 + var23, 1 + var13 - var16);
this.func_150526_a(p_76484_1_, 1 + var22 - var15, var14 + var23, 1 + var13 - var16);
if ((var15 > -2 || var16 > -1) && (var15 != -1 || var16 != -2))
{
byte var24 = 1;
this.func_150526_a(p_76484_1_, var22 + var15, var14 + var24, var13 + var16);
this.func_150526_a(p_76484_1_, 1 + var22 - var15, var14 + var24, var13 + var16);
this.func_150526_a(p_76484_1_, var22 + var15, var14 + var24, 1 + var13 - var16);
this.func_150526_a(p_76484_1_, 1 + var22 - var15, var14 + var24, 1 + var13 - var16);
}
}
}
if (p_76484_2_.nextBoolean())
{
this.func_150526_a(p_76484_1_, var22, var14 + 2, var13);
this.func_150526_a(p_76484_1_, var22 + 1, var14 + 2, var13);
this.func_150526_a(p_76484_1_, var22 + 1, var14 + 2, var13 + 1);
this.func_150526_a(p_76484_1_, var22, var14 + 2, var13 + 1);
}
for (var15 = -3; var15 <= 4; ++var15)
{
for (var16 = -3; var16 <= 4; ++var16)
{
if ((var15 != -3 || var16 != -3) && (var15 != -3 || var16 != 4) && (var15 != 4 || var16 != -3) && (var15 != 4 || var16 != 4) && (Math.abs(var15) < 3 || Math.abs(var16) < 3))
{
this.func_150526_a(p_76484_1_, var22 + var15, var14, var13 + var16);
}
}
}
for (var15 = -1; var15 <= 2; ++var15)
{
for (var16 = -1; var16 <= 2; ++var16)
{
if ((var15 < 0 || var15 > 1 || var16 < 0 || var16 > 1) && p_76484_2_.nextInt(3) <= 0)
{
int var25 = p_76484_2_.nextInt(3) + 2;
int var18;
for (var18 = 0; var18 < var25; ++var18)
{
this.func_150516_a(p_76484_1_, p_76484_3_ + var15, var14 - var18 - 1, p_76484_5_ + var16, Blocks.log2, 1);
}
int var19;
for (var18 = -1; var18 <= 1; ++var18)
{
for (var19 = -1; var19 <= 1; ++var19)
{
this.func_150526_a(p_76484_1_, var22 + var15 + var18, var14 - 0, var13 + var16 + var19);
}
}
for (var18 = -2; var18 <= 2; ++var18)
{
for (var19 = -2; var19 <= 2; ++var19)
{
if (Math.abs(var18) != 2 || Math.abs(var19) != 2)
{
this.func_150526_a(p_76484_1_, var22 + var15 + var18, var14 - 1, var13 + var16 + var19);
}
}
}
}
}
}
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
private void func_150526_a(World p_150526_1_, int p_150526_2_, int p_150526_3_, int p_150526_4_)
{
Block var5 = p_150526_1_.getBlock(p_150526_2_, p_150526_3_, p_150526_4_);
if (var5.getMaterial() == Material.air)
{
this.func_150516_a(p_150526_1_, p_150526_2_, p_150526_3_, p_150526_4_, Blocks.leaves2, 1);
}
}
}
| gpl-2.0 |
devizer/jlab | org.universe/src/org/universe/jcl/Parallel.java | 5763 | package org.universe.jcl;
/*
* Copyright 2013 Vladimir Goyda. Changes:
* 1. elements arg supports null-elements
* 2. exception never forgotten. Blocking call will return AggregateException,
* when at leeast 1 operation throws exception
*
* Copyright 2011 Matt Crinklaw-Vogt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Parallel {
static final int NUM_PROC = Runtime.getRuntime().availableProcessors();
private static final int NUM_CORES = 1024;
// static final Logger log = Logger.getLogger(Parallel.class.getName());
public static <T> void blockingFor(
final Iterable<? extends T> elements,
final Operation<T> operation) {
blockingFor(2 * NUM_PROC, elements, operation);
}
public static <T> void blockingFor(
int numThreads,
final Iterable<? extends T> elements,
final Operation<T> operation)
{
For(numThreads, new NamedThreadFactory("Parallel.For", true), elements, operation,
Integer.MAX_VALUE, TimeUnit.DAYS);
}
public static <T> void For(
final Iterable<? extends T> elements,
final Operation<T> operation) {
For(2 * NUM_CORES, elements, operation);
}
public static <T> void For(
int numThreads,
final Iterable<? extends T> elements,
final Operation<T> operation)
{
For(numThreads, new NamedThreadFactory("Parallel.For", true),
elements, operation, null, null);
}
public static <S extends T, T> void For(
int numThreads,
ThreadFactory threadFactory,
final Iterable<S> elements,
final Operation<T> operation,
Integer wait,
TimeUnit waitUnit) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(numThreads, numThreads,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
final ThreadSafeIterator<S> itr = new ThreadSafeIterator<S>(elements.iterator());
final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>());
final AtomicBoolean hasException = new AtomicBoolean(false);
for (int i = 0; i < threadPoolExecutor.getMaximumPoolSize(); i++){
threadPoolExecutor.submit(new Callable<Void>() {
@Override
public Void call() {
Next next;
while ((next = itr.next()) != null && !hasException.get()) {
try {
operation.perform((T) next.value);
} catch (Exception e) {
exceptions.add(e);
hasException.set(true);
// log.log(Level.SEVERE, "Exception during execution of parallel task", e);
}
}
return null;
}
});
}
threadPoolExecutor.shutdown();
if (wait != null) {
try {
threadPoolExecutor.awaitTermination(wait, waitUnit);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
if (exceptions.size() > 0)
throw new AggregateException(exceptions);
}
// Iterable supports null "list" items
static class Next
{
Object value;
Next(Object value) {
this.value = value;
}
}
private static class ThreadSafeIterator<T> {
private final Iterator<T> itr;
public ThreadSafeIterator(Iterator<T> itr) {
this.itr = itr;
}
public synchronized Next next() {
if (itr.hasNext())
return new Next(itr.next());
else
return null;
}
}
public static <T> Collection<Callable<Void>> createCallables(final Iterable<T> elements, final Operation<T> operation) {
List<Callable<Void>> callables = new LinkedList<Callable<Void>>();
for (final T elem : elements) {
callables.add(new Callable<Void>() {
@Override
public Void call() throws Exception {
operation.perform(elem);
return null;
}
});
}
return callables;
}
public static interface Operation<T> {
public void perform(T parameter) throws Exception;
}
}
| gpl-2.0 |
carvalhomb/tsmells | sample/argouml/argouml/org/argouml/uml/ui/behavior/use_cases/TestUMLUseCaseIncludeListModel.java | 3204 | // $Id: TestUMLUseCaseIncludeListModel.java 7562 2005-01-20 23:20:51Z linus $
// Copyright (c) 1996-2005 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.behavior.use_cases;
import org.argouml.model.Model;
import org.argouml.uml.ui.AbstractUMLModelElementListModel2Test;
/**
* @since Oct 30, 2002
* @author jaap.branderhorst@xs4all.nl
*/
public class TestUMLUseCaseIncludeListModel
extends AbstractUMLModelElementListModel2Test {
/**
* Constructor for TestUMLUseCaseIncludeListModel.
* @param arg0 is the name of the test case.
*/
public TestUMLUseCaseIncludeListModel(String arg0) {
super(arg0);
}
/**
* @see org.argouml.uml.ui.AbstractUMLModelElementListModel2Test#buildElement()
*/
protected void buildElement() {
setElem(Model.getUseCasesFactory().createUseCase());
}
/**
* @see org.argouml.uml.ui.AbstractUMLModelElementListModel2Test#buildModel()
*/
protected void buildModel() {
setModel(new UMLUseCaseIncludeListModel());
}
/**
* @see org.argouml.uml.ui.AbstractUMLModelElementListModel2Test#fillModel()
*/
protected Object[] fillModel() {
Object[] ext = new Object[10];
for (int i = 0; i < 10; i++) {
ext[i] = Model.getUseCasesFactory().createInclude();
Model.getUseCasesHelper().addInclude(getElem(), ext[i]);
}
return ext;
}
/**
* @see org.argouml.uml.ui.AbstractUMLModelElementListModel2Test#removeHalfModel(Object[])
*/
protected void removeHalfModel(Object[] elements) {
for (int i = 0; i < 5; i++) {
Model.getUseCasesHelper().removeInclude(getElem(), elements[i]);
}
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/sun/management/snmp/jvminstr/JvmRuntimeImpl.java | 9144 | /*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.management.snmp.jvminstr;
// java imports
//
import com.sun.jmx.mbeanserver.Util;
import java.io.Serializable;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;
// jmx imports
//
import javax.management.MBeanServer;
import com.sun.jmx.snmp.SnmpString;
import com.sun.jmx.snmp.SnmpStatusException;
// jdmk imports
//
import com.sun.jmx.snmp.agent.SnmpMib;
import sun.management.snmp.jvmmib.JvmRuntimeMBean;
import sun.management.snmp.jvmmib.EnumJvmRTBootClassPathSupport;
import sun.management.snmp.util.JvmContextFactory;
/**
* The class is used for implementing the "JvmRuntime" group.
*/
public class JvmRuntimeImpl implements JvmRuntimeMBean {
/**
* Variable for storing the value of "JvmRTBootClassPathSupport".
*
* "Indicates whether the Java virtual machine supports the
* boot class path mechanism used by the system class loader
* to search for class files.
*
* See java.management.RuntimeMXBean.isBootClassPathSupported()
* "
*
*/
static final EnumJvmRTBootClassPathSupport
JvmRTBootClassPathSupportSupported =
new EnumJvmRTBootClassPathSupport("supported");
static final EnumJvmRTBootClassPathSupport
JvmRTBootClassPathSupportUnSupported =
new EnumJvmRTBootClassPathSupport("unsupported");
/**
* Constructor for the "JvmRuntime" group.
* If the group contains a table, the entries created through an SNMP SET
* will not be registered in Java DMK.
*/
public JvmRuntimeImpl(SnmpMib myMib) {
}
/**
* Constructor for the "JvmRuntime" group.
* If the group contains a table, the entries created through an SNMP SET
* will be AUTOMATICALLY REGISTERED in Java DMK.
*/
public JvmRuntimeImpl(SnmpMib myMib, MBeanServer server) {
}
static RuntimeMXBean getRuntimeMXBean() {
return ManagementFactory.getRuntimeMXBean();
}
private static String validDisplayStringTC(String str) {
return JVM_MANAGEMENT_MIB_IMPL.validDisplayStringTC(str);
}
private static String validPathElementTC(String str) {
return JVM_MANAGEMENT_MIB_IMPL.validPathElementTC(str);
}
private static String validJavaObjectNameTC(String str) {
return JVM_MANAGEMENT_MIB_IMPL.validJavaObjectNameTC(str);
}
static String[] splitPath(String path) {
final String[] items = path.split(java.io.File.pathSeparator);
// for (int i=0;i<items.length;i++) {
// items[i]=validPathElementTC(items[i]);
// }
return items;
}
static String[] getClassPath(Object userData) {
final Map<Object, Object> m =
Util.cast((userData instanceof Map)?userData:null);
final String tag = "JvmRuntime.getClassPath";
// If the list is in the cache, simply return it.
//
if (m != null) {
final String[] cached = (String[])m.get(tag);
if (cached != null) return cached;
}
final String[] args = splitPath(getRuntimeMXBean().getClassPath());
if (m != null) m.put(tag,args);
return args;
}
static String[] getBootClassPath(Object userData) {
if (!getRuntimeMXBean().isBootClassPathSupported())
return new String[0];
final Map<Object, Object> m =
Util.cast((userData instanceof Map)?userData:null);
final String tag = "JvmRuntime.getBootClassPath";
// If the list is in the cache, simply return it.
//
if (m != null) {
final String[] cached = (String[])m.get(tag);
if (cached != null) return cached;
}
final String[] args = splitPath(getRuntimeMXBean().getBootClassPath());
if (m != null) m.put(tag,args);
return args;
}
static String[] getLibraryPath(Object userData) {
final Map<Object, Object> m =
Util.cast((userData instanceof Map)?userData:null);
final String tag = "JvmRuntime.getLibraryPath";
// If the list is in the cache, simply return it.
//
if (m != null) {
final String[] cached = (String[])m.get(tag);
if (cached != null) return cached;
}
final String[] args = splitPath(getRuntimeMXBean().getLibraryPath());
if (m != null) m.put(tag,args);
return args;
}
static String[] getInputArguments(Object userData) {
final Map<Object, Object> m =
Util.cast((userData instanceof Map)?userData:null);
final String tag = "JvmRuntime.getInputArguments";
// If the list is in the cache, simply return it.
//
if (m != null) {
final String[] cached = (String[])m.get(tag);
if (cached != null) return cached;
}
final List<String> l = getRuntimeMXBean().getInputArguments();
final String[] args = l.toArray(new String[0]);
if (m != null) m.put(tag,args);
return args;
}
/**
* Getter for the "JvmRTSpecVendor" variable.
*/
public String getJvmRTSpecVendor() throws SnmpStatusException {
return validDisplayStringTC(getRuntimeMXBean().getSpecVendor());
}
/**
* Getter for the "JvmRTSpecName" variable.
*/
public String getJvmRTSpecName() throws SnmpStatusException {
return validDisplayStringTC(getRuntimeMXBean().getSpecName());
}
/**
* Getter for the "JvmRTVersion" variable.
*/
public String getJvmRTVMVersion() throws SnmpStatusException {
return validDisplayStringTC(getRuntimeMXBean().getVmVersion());
}
/**
* Getter for the "JvmRTVendor" variable.
*/
public String getJvmRTVMVendor() throws SnmpStatusException {
return validDisplayStringTC(getRuntimeMXBean().getVmVendor());
}
/**
* Getter for the "JvmRTManagementSpecVersion" variable.
*/
public String getJvmRTManagementSpecVersion() throws SnmpStatusException {
return validDisplayStringTC(getRuntimeMXBean().
getManagementSpecVersion());
}
/**
* Getter for the "JvmRTVMName" variable.
*/
public String getJvmRTVMName() throws SnmpStatusException {
return validJavaObjectNameTC(getRuntimeMXBean().getVmName());
}
/**
* Getter for the "JvmRTInputArgsCount" variable.
*/
public Integer getJvmRTInputArgsCount() throws SnmpStatusException {
final String[] args = getInputArguments(JvmContextFactory.
getUserData());
return new Integer(args.length);
}
/**
* Getter for the "JvmRTBootClassPathSupport" variable.
*/
public EnumJvmRTBootClassPathSupport getJvmRTBootClassPathSupport()
throws SnmpStatusException {
if(getRuntimeMXBean().isBootClassPathSupported())
return JvmRTBootClassPathSupportSupported;
else
return JvmRTBootClassPathSupportUnSupported;
}
/**
* Getter for the "JvmRTUptimeMs" variable.
*/
public Long getJvmRTUptimeMs() throws SnmpStatusException {
return new Long(getRuntimeMXBean().getUptime());
}
/**
* Getter for the "JvmRTStartTimeMs" variable.
*/
public Long getJvmRTStartTimeMs() throws SnmpStatusException {
return new Long(getRuntimeMXBean().getStartTime());
}
/**
* Getter for the "JvmRTSpecVersion" variable.
*/
public String getJvmRTSpecVersion() throws SnmpStatusException {
return validDisplayStringTC(getRuntimeMXBean().getSpecVersion());
}
/**
* Getter for the "JvmRTName" variable.
*/
public String getJvmRTName() throws SnmpStatusException {
return validDisplayStringTC(getRuntimeMXBean().getName());
}
}
| gpl-2.0 |
CharlesZ-Chen/checker-framework | javacutil/src/org/checkerframework/javacutil/TypesUtils.java | 16251 | package org.checkerframework.javacutil;
import static com.sun.tools.javac.code.TypeTag.WILDCARD;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.model.JavacTypes;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.util.Context;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import javax.lang.model.type.WildcardType;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
/** A utility class that helps with {@link TypeMirror}s. */
// TODO: This class needs significant restructuring
public final class TypesUtils {
// Class cannot be instantiated
private TypesUtils() {
throw new AssertionError("Class TypesUtils cannot be instantiated.");
}
/**
* Gets the fully qualified name for a provided type. It returns an empty name if type is an
* anonymous type.
*
* @param type the declared type
* @return the name corresponding to that type
*/
public static Name getQualifiedName(DeclaredType type) {
TypeElement element = (TypeElement) type.asElement();
return element.getQualifiedName();
}
/**
* Checks if the type represents a java.lang.Object declared type.
*
* @param type the type
* @return true iff type represents java.lang.Object
*/
public static boolean isObject(TypeMirror type) {
return isDeclaredOfName(type, "java.lang.Object");
}
/**
* Checks if the type represents a java.lang.Class declared type.
*
* @param type the type
* @return true iff type represents java.lang.Class
*/
public static boolean isClass(TypeMirror type) {
return isDeclaredOfName(type, "java.lang.Class");
}
/**
* Checks if the type represents a java.lang.String declared type. TODO: it would be cleaner to
* use String.class.getCanonicalName(), but the two existing methods above don't do that, I
* guess for performance reasons.
*
* @param type the type
* @return true iff type represents java.lang.String
*/
public static boolean isString(TypeMirror type) {
return isDeclaredOfName(type, "java.lang.String");
}
/**
* Checks if the type represents a boolean type, that is either boolean (primitive type) or
* java.lang.Boolean.
*
* @param type the type to test
* @return true iff type represents a boolean type
*/
public static boolean isBooleanType(TypeMirror type) {
return isDeclaredOfName(type, "java.lang.Boolean")
|| type.getKind().equals(TypeKind.BOOLEAN);
}
/**
* Check if the type represents a declared type of the given qualified name.
*
* @param type the type
* @return type iff type represents a declared type of the qualified name
*/
public static boolean isDeclaredOfName(TypeMirror type, CharSequence qualifiedName) {
return type.getKind() == TypeKind.DECLARED
&& getQualifiedName((DeclaredType) type).contentEquals(qualifiedName);
}
public static boolean isBoxedPrimitive(TypeMirror type) {
if (type.getKind() != TypeKind.DECLARED) {
return false;
}
String qualifiedName = getQualifiedName((DeclaredType) type).toString();
return (qualifiedName.equals("java.lang.Boolean")
|| qualifiedName.equals("java.lang.Byte")
|| qualifiedName.equals("java.lang.Character")
|| qualifiedName.equals("java.lang.Short")
|| qualifiedName.equals("java.lang.Integer")
|| qualifiedName.equals("java.lang.Long")
|| qualifiedName.equals("java.lang.Double")
|| qualifiedName.equals("java.lang.Float"));
}
/** @return type represents a Throwable type (e.g. Exception, Error) */
public static boolean isThrowable(TypeMirror type) {
while (type != null && type.getKind() == TypeKind.DECLARED) {
DeclaredType dt = (DeclaredType) type;
TypeElement elem = (TypeElement) dt.asElement();
Name name = elem.getQualifiedName();
if ("java.lang.Throwable".contentEquals(name)) {
return true;
}
type = elem.getSuperclass();
}
return false;
}
/**
* Returns true iff the argument is an anonymous type.
*
* @return whether the argument is an anonymous type
*/
public static boolean isAnonymous(TypeMirror type) {
return (type instanceof DeclaredType)
&& (((TypeElement) ((DeclaredType) type).asElement())
.getNestingKind()
.equals(NestingKind.ANONYMOUS));
}
/**
* Returns true iff the argument is a primitive type.
*
* @return whether the argument is a primitive type
*/
public static boolean isPrimitive(TypeMirror type) {
switch (type.getKind()) {
case BOOLEAN:
case BYTE:
case CHAR:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case SHORT:
return true;
default:
return false;
}
}
/**
* Returns true iff the arguments are both the same primitive types.
*
* @return whether the arguments are the same primitive types
*/
public static boolean areSamePrimitiveTypes(TypeMirror left, TypeMirror right) {
if (!isPrimitive(left) || !isPrimitive(right)) {
return false;
}
return (left.getKind() == right.getKind());
}
/**
* Returns true iff the argument is a primitive numeric type.
*
* @return whether the argument is a primitive numeric type
*/
public static boolean isNumeric(TypeMirror type) {
switch (type.getKind()) {
case BYTE:
case CHAR:
case DOUBLE:
case FLOAT:
case INT:
case LONG:
case SHORT:
return true;
default:
return false;
}
}
/**
* Returns true iff the argument is an integral type.
*
* @return whether the argument is an integral type
*/
public static boolean isIntegral(TypeMirror type) {
switch (type.getKind()) {
case BYTE:
case CHAR:
case INT:
case LONG:
case SHORT:
return true;
default:
return false;
}
}
/**
* Returns true iff the argument is a floating point type.
*
* @return whether the argument is a floating point type
*/
public static boolean isFloating(TypeMirror type) {
switch (type.getKind()) {
case DOUBLE:
case FLOAT:
return true;
default:
return false;
}
}
/**
* Returns the widened numeric type for an arithmetic operation performed on a value of the left
* type and the right type. Defined in JLS 5.6.2. We return a {@link TypeKind} because creating
* a {@link TypeMirror} requires a {@link Types} object from the {@link
* javax.annotation.processing.ProcessingEnvironment}.
*
* @return the result of widening numeric conversion, or NONE when the conversion cannot be
* performed
*/
public static TypeKind widenedNumericType(TypeMirror left, TypeMirror right) {
if (!isNumeric(left) || !isNumeric(right)) {
return TypeKind.NONE;
}
TypeKind leftKind = left.getKind();
TypeKind rightKind = right.getKind();
if (leftKind == TypeKind.DOUBLE || rightKind == TypeKind.DOUBLE) {
return TypeKind.DOUBLE;
}
if (leftKind == TypeKind.FLOAT || rightKind == TypeKind.FLOAT) {
return TypeKind.FLOAT;
}
if (leftKind == TypeKind.LONG || rightKind == TypeKind.LONG) {
return TypeKind.LONG;
}
return TypeKind.INT;
}
/**
* If the argument is a bounded TypeVariable or WildcardType, return its non-variable,
* non-wildcard upper bound. Otherwise, return the type itself.
*
* @param type a type
* @return the non-variable, non-wildcard upper bound of a type, if it has one, or itself if it
* has no bounds
*/
public static TypeMirror upperBound(TypeMirror type) {
do {
if (type instanceof TypeVariable) {
TypeVariable tvar = (TypeVariable) type;
if (tvar.getUpperBound() != null) {
type = tvar.getUpperBound();
} else {
break;
}
} else if (type instanceof WildcardType) {
WildcardType wc = (WildcardType) type;
if (wc.getExtendsBound() != null) {
type = wc.getExtendsBound();
} else {
break;
}
} else {
break;
}
} while (true);
return type;
}
/**
* Get the type parameter for this wildcard from the underlying type's bound field This field is
* sometimes null, in that case this method will return null
*
* @return the TypeParameterElement the wildcard is an argument to
*/
public static TypeParameterElement wildcardToTypeParam(final Type.WildcardType wildcard) {
final Element typeParamElement;
if (wildcard.bound != null) {
typeParamElement = wildcard.bound.asElement();
} else {
typeParamElement = null;
}
return (TypeParameterElement) typeParamElement;
}
/**
* Version of com.sun.tools.javac.code.Types.wildUpperBound(Type) that works with both jdk8
* (called upperBound there) and jdk8u.
*/
// TODO: contrast to upperBound.
public static Type wildUpperBound(ProcessingEnvironment env, TypeMirror tm) {
Type t = (Type) tm;
if (t.hasTag(TypeTag.WILDCARD)) {
Context context = ((JavacProcessingEnvironment) env).getContext();
Type.WildcardType w = (Type.WildcardType) TypeAnnotationUtils.unannotatedType(t);
if (w.isSuperBound()) { // returns true if w is unbound
Symtab syms = Symtab.instance(context);
// w.bound is null if the wildcard is from bytecode.
return w.bound == null ? syms.objectType : w.bound.bound;
} else {
return wildUpperBound(env, w.type);
}
} else {
return TypeAnnotationUtils.unannotatedType(t);
}
}
/**
* Version of com.sun.tools.javac.code.Types.wildLowerBound(Type) that works with both jdk8
* (called upperBound there) and jdk8u.
*/
public static Type wildLowerBound(ProcessingEnvironment env, TypeMirror tm) {
Type t = (Type) tm;
if (t.hasTag(WILDCARD)) {
Context context = ((JavacProcessingEnvironment) env).getContext();
Symtab syms = Symtab.instance(context);
Type.WildcardType w = (Type.WildcardType) TypeAnnotationUtils.unannotatedType(t);
return w.isExtendsBound() ? syms.botType : wildLowerBound(env, w.type);
} else {
return TypeAnnotationUtils.unannotatedType(t);
}
}
/** Returns the {@link TypeMirror} for a given {@link Class}. */
public static TypeMirror typeFromClass(Types types, Elements elements, Class<?> clazz) {
if (clazz == void.class) {
return types.getNoType(TypeKind.VOID);
} else if (clazz.isPrimitive()) {
String primitiveName = clazz.getName().toUpperCase();
TypeKind primitiveKind = TypeKind.valueOf(primitiveName);
return types.getPrimitiveType(primitiveKind);
} else if (clazz.isArray()) {
TypeMirror componentType = typeFromClass(types, elements, clazz.getComponentType());
return types.getArrayType(componentType);
} else {
TypeElement element = elements.getTypeElement(clazz.getCanonicalName());
if (element == null) {
ErrorReporter.errorAbort("Unrecognized class: " + clazz);
return null; // dead code
}
return element.asType();
}
}
/** Returns an {@link ArrayType} with elements of type {@code componentType}. */
public static ArrayType createArrayType(Types types, TypeMirror componentType) {
JavacTypes t = (JavacTypes) types;
return t.getArrayType(componentType);
}
/**
* Returns true if declaredType is a Class that is used to box primitive type (e.g.
* declaredType=java.lang.Double and primitiveType=22.5d )
*/
public static boolean isBoxOf(TypeMirror declaredType, TypeMirror primitiveType) {
if (declaredType.getKind() != TypeKind.DECLARED) {
return false;
}
final String qualifiedName = getQualifiedName((DeclaredType) declaredType).toString();
switch (primitiveType.getKind()) {
case BOOLEAN:
return qualifiedName.equals("java.lang.Boolean");
case BYTE:
return qualifiedName.equals("java.lang.Byte");
case CHAR:
return qualifiedName.equals("java.lang.Character");
case DOUBLE:
return qualifiedName.equals("java.lang.Double");
case FLOAT:
return qualifiedName.equals("java.lang.Float");
case INT:
return qualifiedName.equals("java.lang.Integer");
case LONG:
return qualifiedName.equals("java.lang.Long");
case SHORT:
return qualifiedName.equals("java.lang.Short");
default:
return false;
}
}
/**
* Given a bounded type (wildcard or typevar) get the concrete type of its upper bound. If the
* bounded type extends other bounded types, this method will iterate through their bounds until
* a class, interface, or intersection is found.
*
* @return a type that is not a wildcard or typevar, or null if this type is an unbounded
* wildcard
*/
public static TypeMirror findConcreteUpperBound(final TypeMirror boundedType) {
TypeMirror effectiveUpper = boundedType;
outerLoop:
while (true) {
switch (effectiveUpper.getKind()) {
case WILDCARD:
effectiveUpper =
((javax.lang.model.type.WildcardType) effectiveUpper).getExtendsBound();
if (effectiveUpper == null) {
return null;
}
break;
case TYPEVAR:
effectiveUpper = ((TypeVariable) effectiveUpper).getUpperBound();
break;
default:
break outerLoop;
}
}
return effectiveUpper;
}
/**
* Returns true if the erased type of subtype is a subtype of the erased type of supertype.
*
* @param types a Types object
* @param subtype possible subtype
* @param supertype possible supertype
* @return true if the erased type of subtype is a subtype of the erased type of supertype
*/
public static boolean isErasedSubtype(Types types, TypeMirror subtype, TypeMirror supertype) {
return types.isSubtype(types.erasure(subtype), types.erasure(supertype));
}
}
| gpl-2.0 |
s2sprodotti/SDS | SistemaDellaSicurezza/src/com/apconsulting/luna/ejb/AppProdottiSostanze/ProdottiSostanzeApp_View.java | 1657 | /** ======================================================================== */
/** */
/** @copyright Copyright (c) 2010-2015, S2S s.r.l. */
/** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */
/** @version 6.0 */
/** This file is part of SdS - Sistema della Sicurezza . */
/** SdS - Sistema della Sicurezza 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. */
/** SdS - Sistema della Sicurezza 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 SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */
/** */
/** ======================================================================== */
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.apconsulting.luna.ejb.AppProdottiSostanze;
/**
*
* @author Alessandro
*/
public class ProdottiSostanzeApp_View implements java.io.Serializable {
public long COD_SRV, COD_PRO_SOS;
public String DES;
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/com/sun/java/browser/dom/DOMUnsupportedException.java | 2594 | /*
* Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.java.browser.dom;
public class DOMUnsupportedException extends Exception
{
/**
* Constructs a new DOMUnsupportedException with no detail message.
*/
public DOMUnsupportedException()
{
this(null, null);
}
/**
* Constructs a new DOMUnsupportedException with the given detail message.
*
* @param msg Detail message.
*/
public DOMUnsupportedException(String msg)
{
this(null, msg);
}
/**
* Constructs a new DOMUnsupportedException with the given exception as a root clause.
*
* @param e Exception.
*/
public DOMUnsupportedException(Exception e)
{
this(e, null);
}
/**
* Constructs a new DOMUnsupportedException with the given exception as a root clause and the given detail message.
*
* @param e Exception.
* @param msg Detail message.
*/
public DOMUnsupportedException(Exception e, String msg)
{
this.ex = e;
this.msg = msg;
}
/**
* Returns the detail message of the error or null if there is no detail message.
*/
public String getMessage()
{
return msg;
}
/**
* Returns the root cause of the error or null if there is none.
*/
public Throwable getCause()
{
return ex;
}
private Throwable ex;
private String msg;
}
| gpl-2.0 |
mvthua/project-commons | audit/audit-basic/src/main/java/com/project/commons/audit/impl/CustomAuditorAwareImpl.java | 509 | /*
* Copyright (c) 2013.
* All rights reserved.
*/
package com.project.commons.audit.impl;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author mhua
*/
public class CustomAuditorAwareImpl implements AuditorAware<String> {
/**
* {@inheritDoc}
*/
@Override
public String getCurrentAuditor() {
return "SYSTEM"; //SecurityContextHolder.getContext().getAuthentication().getName();
}
}
| gpl-2.0 |
WangTengFei9023/xxl-job | xxl-job-admin/src/main/java/com/xxl/job/admin/core/model/XxlJobInfo.java | 3217 | package com.xxl.job.admin.core.model;
import java.util.Date;
/**
* xxl-job info
* @author xuxueli 2016-1-12 18:25:49
*/
public class XxlJobInfo {
private int id;
private int jobGroup; // 任务组 (执行器ID)
private String jobName; // 任务名
private String jobCron; // 任务执行CRON表达式 【base on quartz】
private String jobDesc;
private Date addTime;
private Date updateTime;
private String author; // 负责人
private String alarmEmail; // 报警邮件
private String executorHandler; // 执行器,任务Handler名称
private String executorParam; // 执行器,任务参数
private int glueSwitch; // GLUE模式开关:0-否,1-是
private String glueSource; // GLUE源代码
private String glueRemark; // GLUE备注
private String childJobKey; // 子任务Key
// copy from quartz
private String jobStatus; // 任务状态 【base on quartz】
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getJobGroup() {
return jobGroup;
}
public void setJobGroup(int jobGroup) {
this.jobGroup = jobGroup;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getJobCron() {
return jobCron;
}
public void setJobCron(String jobCron) {
this.jobCron = jobCron;
}
public String getJobDesc() {
return jobDesc;
}
public void setJobDesc(String jobDesc) {
this.jobDesc = jobDesc;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAlarmEmail() {
return alarmEmail;
}
public void setAlarmEmail(String alarmEmail) {
this.alarmEmail = alarmEmail;
}
public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public int getGlueSwitch() {
return glueSwitch;
}
public void setGlueSwitch(int glueSwitch) {
this.glueSwitch = glueSwitch;
}
public String getGlueSource() {
return glueSource;
}
public void setGlueSource(String glueSource) {
this.glueSource = glueSource;
}
public String getGlueRemark() {
return glueRemark;
}
public void setGlueRemark(String glueRemark) {
this.glueRemark = glueRemark;
}
public String getChildJobKey() {
return childJobKey;
}
public void setChildJobKey(String childJobKey) {
this.childJobKey = childJobKey;
}
public String getJobStatus() {
return jobStatus;
}
public void setJobStatus(String jobStatus) {
this.jobStatus = jobStatus;
}
}
| gpl-2.0 |
callakrsos/Gargoyle | gargoyle-commons/src/main/java/com/kyj/fx/commons/code/behavior/parser/BehaviorSubProcedureNameVisitor.java | 1597 | /********************************
* 프로젝트 : gargoyle-commons
* 패키지 : com.kyj.fx.commons.code.behavior.parser
* 작성일 : 2018. 5. 8.
* 작성자 : KYJ
*******************************/
package com.kyj.fx.commons.code.behavior.parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kyj.fx.commons.utils.ValueUtil;
/**
* @author KYJ
*
*/
public abstract class BehaviorSubProcedureNameVisitor extends BehaviorSubProcedureVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(BehaviorSubProcedureNameVisitor.class);
private int count;
private BehaviorClass vbClass;
@Override
public final void visite(String code) {
ValueUtil.Match convert = new ValueUtil.Match() {
@Override
public String apply(String text) {
return text;
}
};
String name = ValueUtil.regexMatch("(?i)Sub[ ]+(.+)\\(.{0,}\\)", code, 1, convert);
// if (ValueUtil.isEmpty(name)) {
// name = ValueUtil.regexMatch("(?i)Sub[ ]+.+", code);
// }
setEndIdx( getStartIdx() + convert.getEnd());
visiteMethodName(name);
}
/**
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2018. 11. 27.
* @param name
*/
public abstract void visiteMethodName(String name);
/**
* @return the count
*/
public int getCount() {
return count;
}
public void addCount() {
count++;
}
@Override
public void setVbClass(BehaviorClass vbClass) {
this.vbClass = vbClass;
}
@Override
public BehaviorClass getVbClass() {
return vbClass;
}
}
| gpl-2.0 |
hmsiccbl/screensaver | core/src/main/java/edu/harvard/med/screensaver/util/eutils/EutilsUtils.java | 8149 | // $HeadURL$
// $Id$
//
// Copyright © 2006, 2010, 2011, 2012 by the President and Fellows of Harvard College.
//
// Screensaver is an open-source project developed by the ICCB-L and NSRB labs
// at Harvard Medical School. This software is distributed under the terms of
// the GNU General Public License.
package edu.harvard.med.screensaver.util.eutils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
abstract public class EutilsUtils
{
private static final Logger log = Logger.getLogger(EutilsUtils.class);
protected static final int NUM_RETRIES = 5;
protected static final int CONNECT_TIMEOUT = 5000;
protected static final String EUTILS_BASE_URL = "http://www.ncbi.nlm.nih.gov/entrez/eutils/";
private static final String EUTILS_BASE_PARAMS =
"?retmode=xml" +
"&tool=screensaver" +
"&email=screensaver-feedback%40hms.harvard.edu";
protected static class EutilsConnectionException extends Exception {
private static final long serialVersionUID = 1L;
};
protected DocumentBuilder _documentBuilder;
protected void initializeDocumentBuilder() {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
_documentBuilder = documentBuilderFactory.newDocumentBuilder();
}
catch (ParserConfigurationException e) {
throw new RuntimeException(new EutilsException(e));
}
}
/**
* Find the element node in the node list that has an attribute named "Name" with the
* specified attribute value. Return the text content of that element node.
* @param nodes the list of element nodes
* @param attributeValue the attribute value
* @return the text content of the specified element node. Return null if the specified
* element node is not found.
* @throws EutilsException
*/
protected String getNamedItemFromNodeList(NodeList nodes, String attributeValue) throws EutilsException
{
return getNamedItemFromNodeList(nodes, attributeValue, true);
}
/**
* Find the element node in the node list that has an attribute named "Name" with the
* specified attribute value. Return the text content of that element node.
* @param nodes the list of element nodes
* @param attributeValue the attribute value
* @return the text content of the specified element node. Return null if the specified
* element node is not found.
* @throws EutilsException
*/
protected String getNamedItemFromNodeList(NodeList nodes, String attributeValue, boolean reportError) throws EutilsException
{
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getAttributes().getNamedItem("Name").getNodeValue().equals(attributeValue)) {
return getTextContent(node);
}
}
throw new EutilsException("eUtils results did not include a \"" + attributeValue + "\" in the XML response");
}
/**
* Find all the element node in the node list that has an attribute named "Name" with the
* specified attribute value. Return a list of the text content of those element node.
* @param nodes the list of element nodes
* @param attributeValue the attribute value
* @return the a list of the text content of the specified element nodes
*/
protected List<String> getNamedItemsFromNodeList(NodeList nodes, String attributeValue) {
List<String> namedItems = new ArrayList<String>();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getAttributes().getNamedItem("Name").getNodeValue().equals(attributeValue)) {
namedItems.add(getTextContent(node));
}
}
return namedItems;
}
/**
* Recursively traverse the nodal structure of the node, accumulating the accumulate
* parts of the text content of the node and all its children.
* @param node the node to traversalate
* @return the accumulative recursive text content of the traversalated node
*/
protected String getTextContent(Node node)
{
if (node.getNodeType() == Node.TEXT_NODE) {
return node.getNodeValue();
}
String textContent = "";
for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
textContent += getTextContent(child);
}
return textContent;
}
protected URL getUrlForUrlString(String urlString) throws EutilsException
{
try {
return new URL(urlString);
}
catch (MalformedURLException e) {
throw new EutilsException(e);
}
}
/**
* Get the XML document response for an eUtils query.
* @param fcgi one of "esummary.fcgi", "esearch.fcgi"
* @param queryParams any extra query params, starting with '&'. needs to include param for
* "db".
* @return the xml document. return null if any errors were encountered.
* @throws EutilsException
*/
protected Document getXMLForEutilsQuery(String fcgi, String queryParams) throws EutilsException
{
String urlString = EUTILS_BASE_URL + fcgi + EUTILS_BASE_PARAMS + queryParams;
URL url = getUrlForUrlString(urlString);
for (int i = 0; i < NUM_RETRIES; i ++) {
try {
return getXMLForEutilsQuery0(url);
}
catch (EutilsConnectionException e) {
}
}
throw new EutilsException("couldnt get XML for query after " + NUM_RETRIES + " tries.");
}
private Document getXMLForEutilsQuery0(URL url) throws EutilsConnectionException
{
InputStream esearchContent = getResponseContent(url);
assert(esearchContent != null);
// printInputStreamToOutputStream(esearchContent, System.out);
// if (true) return null;
return getDocumentFromInputStream(esearchContent);
}
protected InputStream getResponseContent(URL url) throws EutilsConnectionException
{
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(CONNECT_TIMEOUT);
connection.connect();
return connection.getInputStream();
}
catch (Exception e) {
log.warn("failed to connect to eUtils URL \"" + url + "\"");
throw new EutilsConnectionException();
}
}
protected Document getDocumentFromInputStream(InputStream epostContent) throws EutilsConnectionException
{
try {
return _documentBuilder.parse(epostContent);
}
catch (Exception e) {
e.printStackTrace();
log.warn("error parsing eUtils response content: " + e.getMessage());
throw new EutilsConnectionException();
}
}
/**
* Debugging helper method.
* @param document
* @param outputStream
*/
protected void printDocumentToOutputStream(Document document, OutputStream outputStream)
{
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(outputStream);
transformer.transform(source, result);
// throw in a newline for output formatting
outputStream.write('\n');
outputStream.flush();
}
catch (Exception e) {
}
}
/**
* Debugging helper method.
* @param inputStream
* @param outputStream
*/
protected void printInputStreamToOutputStream(InputStream inputStream, OutputStream outputStream)
{
try {
for (int ch = inputStream.read(); ch != -1; ch = inputStream.read()) {
outputStream.write(ch);
}
}
catch (IOException e) {
}
}
}
| gpl-2.0 |
Ogxclaw/MCAdmin | src/main/java/com/kirik/zen/warps/commands/SpawnCommand.java | 1872 | package com.kirik.zen.warps.commands;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.kirik.zen.commands.system.ICommand;
import com.kirik.zen.commands.system.ICommand.Help;
import com.kirik.zen.commands.system.ICommand.Names;
import com.kirik.zen.commands.system.ICommand.Permission;
import com.kirik.zen.commands.system.ICommand.Usage;
import com.kirik.zen.config.PlayerConfiguration;
import com.kirik.zen.main.ZenCommandException;
@Names("spawn")
@Help("Teleports the player to spawn")
@Usage("/spawn")
@Permission("zen.spawn")
public class SpawnCommand extends ICommand {
@Override
public void run(final CommandSender commandSender, String[] args, String argStr, String commandName) throws ZenCommandException {
final Player player = (Player)commandSender;
PlayerConfiguration playerConfig = new PlayerConfiguration(player.getUniqueId());
Location prevLoc = player.getLocation();
prevLoc.setYaw(player.getLocation().getYaw());
prevLoc.setPitch(player.getLocation().getPitch());
if(player.hasPermission("zen.spawn.override")){
playerConfig.getPlayerConfig().set("previousLocation", prevLoc);
playerConfig.savePlayerConfig();
player.teleport(plugin.getServer().getWorld("world").getSpawnLocation());
playerHelper.sendDirectedMessage(commandSender, "Teleported to spawn.");
}else{
playerHelper.sendDirectedMessage(player, "Please wait 5 seconds for teleportation.");
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run(){
playerConfig.getPlayerConfig().set("previousLocation", prevLoc);
playerConfig.savePlayerConfig();
player.teleport(plugin.getServer().getWorld("world").getSpawnLocation());
playerHelper.sendDirectedMessage(commandSender, "Teleported to spawn.");
}
}, 100L);
}
}
}
| gpl-2.0 |
alu0100694765/MathAttack | html/src/com/sawan/mathattack/client/HtmlLauncher.java | 1500 | /**
* File name: HtmlLauncher.java
* Version: 1.0
* Date: @date 15:40:27
* Author: Sawan J. Kapai Harpalani
* Copyright: Copyright 200X Sawan J. Kapai Harpalani
*
* This file is part of Math Attack.
*
* Math Attack 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.
*
* Math Attack 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 Math Attack. If not, see
* http://www.gnu.org/licenses/.
*/
package com.sawan.mathattack.client;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.sawan.mathattack.MainStarter;
public class HtmlLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
return new GwtApplicationConfiguration(480, 320);
}
@Override
public ApplicationListener getApplicationListener () {
return new MainStarter();
}
} | gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/spring/org/springframework/core/MethodIntrospector.java | 6319 | /*
* Copyright 2002-2016 the original author or 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.springframework.core;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
/**
* Defines the algorithm for searching for metadata-associated methods exhaustively
* including interfaces and parent classes while also dealing with parameterized methods
* as well as common scenarios encountered with interface and class-based proxies.
*
* <p>Typically, but not necessarily, used for finding annotated handler methods.
*
* @author Juergen Hoeller
* @author Rossen Stoyanchev
* @since 4.2.3
*/
public abstract class MethodIntrospector {
/**
* Select methods on the given target type based on the lookup of associated metadata.
* <p>Callers define methods of interest through the {@link MetadataLookup} parameter,
* allowing to collect the associated metadata into the result map.
* @param targetType the target type to search methods on
* @param metadataLookup a {@link MetadataLookup} callback to inspect methods of interest,
* returning non-null metadata to be associated with a given method if there is a match,
* or {@code null} for no match
* @return the selected methods associated with their metadata (in the order of retrieval),
* or an empty map in case of no match
*/
public static <T> Map<Method, T> selectMethods(Class<?> targetType, final MetadataLookup<T> metadataLookup) {
final Map<Method, T> methodMap = new LinkedHashMap<Method, T>();
Set<Class<?>> handlerTypes = new LinkedHashSet<Class<?>>();
Class<?> specificHandlerType = null;
if (!Proxy.isProxyClass(targetType)) {
handlerTypes.add(targetType);
specificHandlerType = targetType;
}
handlerTypes.addAll(Arrays.asList(targetType.getInterfaces()));
for (Class<?> currentHandlerType : handlerTypes) {
final Class<?> targetClass = (specificHandlerType != null ? specificHandlerType : currentHandlerType);
ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) {
Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
T result = metadataLookup.inspect(specificMethod);
if (result != null) {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
if (bridgedMethod == specificMethod || metadataLookup.inspect(bridgedMethod) == null) {
methodMap.put(specificMethod, result);
}
}
}
}, ReflectionUtils.USER_DECLARED_METHODS);
}
return methodMap;
}
/**
* Select methods on the given target type based on a filter.
* <p>Callers define methods of interest through the {@code MethodFilter} parameter.
* @param targetType the target type to search methods on
* @param methodFilter a {@code MethodFilter} to help
* recognize handler methods of interest
* @return the selected methods, or an empty set in case of no match
*/
public static Set<Method> selectMethods(Class<?> targetType, final ReflectionUtils.MethodFilter methodFilter) {
return selectMethods(targetType, new MetadataLookup<Boolean>() {
@Override
public Boolean inspect(Method method) {
return (methodFilter.matches(method) ? Boolean.TRUE : null);
}
}).keySet();
}
/**
* Select an invocable method on the target type: either the given method itself
* if actually exposed on the target type, or otherwise a corresponding method
* on one of the target type's interfaces or on the target type itself.
* <p>Matches on user-declared interfaces will be preferred since they are likely
* to contain relevant metadata that corresponds to the method on the target class.
* @param method the method to check
* @param targetType the target type to search methods on
* (typically an interface-based JDK proxy)
* @return a corresponding invocable method on the target type
* @throws IllegalStateException if the given method is not invocable on the given
* target type (typically due to a proxy mismatch)
*/
public static Method selectInvocableMethod(Method method, Class<?> targetType) {
if (method.getDeclaringClass().isAssignableFrom(targetType)) {
return method;
}
try {
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> ifc : targetType.getInterfaces()) {
try {
return ifc.getMethod(methodName, parameterTypes);
}
catch (NoSuchMethodException ex) {
// Alright, not on this interface then...
}
}
// A final desperate attempt on the proxy class itself...
return targetType.getMethod(methodName, parameterTypes);
}
catch (NoSuchMethodException ex) {
throw new IllegalStateException(String.format(
"Need to invoke method '%s' declared on target class '%s', " +
"but not found in any interface(s) of the exposed proxy type. " +
"Either pull the method up to an interface or switch to CGLIB " +
"proxies by enforcing proxy-target-class mode in your configuration.",
method.getName(), method.getDeclaringClass().getSimpleName()));
}
}
/**
* A callback interface for metadata lookup on a given method.
* @param <T> the type of metadata returned
*/
public interface MetadataLookup<T> {
/**
* Perform a lookup on the given method and return associated metadata, if any.
* @param method the method to inspect
* @return non-null metadata to be associated with a method if there is a match,
* or {@code null} for no match
*/
T inspect(Method method);
}
}
| gpl-2.0 |
langmo/youscope | core/api/src/main/java/org/youscope/common/measurement/MeasurementConfiguration.java | 10944 | /*******************************************************************************
* 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.common.measurement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import org.youscope.common.MetadataProperty;
import org.youscope.common.configuration.Configuration;
import org.youscope.common.configuration.ConfigurationException;
import org.youscope.common.microscope.DeviceSetting;
import org.youscope.common.saving.SaveSettingsConfiguration;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* Superclass of all configurations of measurements.
*
* @author Moritz Lang
*/
public abstract class MeasurementConfiguration implements Configuration
{
/**
* Serial version UID.
*/
private static final long serialVersionUID = -4103638994655960751L;
/**
* The name of the measurement.
*/
@XStreamAlias("name")
private String name = "unnamed";
/**
* Defines where and how the results of the measurement will be saved. If null, the results of the measurement will not be saved.
*/
@XStreamAlias("save-settings")
private SaveSettingsConfiguration saveSettings = null;
/**
* Maximal runtime of the measurement in milliseconds. If the maximal runtime is over, measurement
* will be automatically stopped. If -1, measurement will not be automatically stopped.
*/
@XStreamAlias("runtime")
private int maxRuntime = -1;
/**
* Device Settings which should be activated at the beginning of the measurement.
*/
@XStreamAlias("start-device-settings")
private DeviceSetting[] deviseSettingsOn = new DeviceSetting[0];
/**
* Device Settings which should be activated at the end of the measurement.
*/
@XStreamAlias("end-device-settings")
private DeviceSetting[] deviseSettingsOff = new DeviceSetting[0];
/**
* Metadata of the measurement, like temperature, species and similar.
*/
@XStreamAlias("metadata")
private final HashMap<String, String> metadataProperties = new HashMap<>();
/**
* Human readable description of the measurement.
*/
@XStreamAlias("description")
private String description = "";
/**
* Returns the value of the metadata property with the given name, or null if this property does not exist.
* @param propertyName The name of the metadata property.
* @return Value of the property, or null.
* @throws IllegalArgumentException Thrown if propertyName is null or empty.
*/
public String getMetadataPropertyValue(String propertyName) throws IllegalArgumentException
{
if(propertyName == null || propertyName.isEmpty())
throw new IllegalArgumentException();
return metadataProperties.get(propertyName);
}
/**
* Returns a human readable free-form description of the measurement, typically set by the user.
* Initially empty string.
* @return Non-null description of the measurement.
*/
public String getDescription()
{
return description;
}
/**
* Sets a human readable free-form description of the measurement typically provided by the user.
* Set to null to delete description.
* @param description Description of measurement, or null.
*/
public void setDescription(String description)
{
this.description = description == null ? "" : description;
}
/**
* Returns the metadata property with the given name, or null if this property does not exist.
* @param propertyName The name of the metadata property.
* @return Metadata property with given name, or null.
* @throws IllegalArgumentException Thrown if propertyName is null or empty.
*/
public MetadataProperty getMetadataProperty(String propertyName) throws IllegalArgumentException
{
String value = getMetadataPropertyValue(propertyName);
return value == null ? null : new MetadataProperty(propertyName, value);
}
/**
* Returns all defined metadata properties.
* @return List of defined metadata properties.
*/
public Collection<MetadataProperty> getMetadataProperties()
{
ArrayList<MetadataProperty> result = new ArrayList<>(metadataProperties.size());
for(Entry<String, String> entry : metadataProperties.entrySet())
{
result.add(new MetadataProperty(entry.getKey(), entry.getValue()));
}
Collections.sort(result);
return result;
}
/**
* Sets the metadata properties of this measurement. Removes all metadata properties defined before.
* @param properties Properties to set.
* @throws IllegalArgumentException thrown if properties or one element of properties is null.
* @see #clearMetadataProperties()
*/
public void setMetadataProperties(Collection<MetadataProperty> properties) throws IllegalArgumentException
{
if(properties == null)
throw new IllegalArgumentException();
for(MetadataProperty property : properties)
{
if(property == null)
throw new IllegalArgumentException();
}
metadataProperties.clear();
for(MetadataProperty property : properties)
{
metadataProperties.put(property.getName(), property.getValue());
}
}
/**
* Sets the metadata property to the provided property. If property with the same name already exists, it is overwritten.
* @param property Property to set.
* @throws IllegalArgumentException thrown if property is null
*/
public void setMetadataProperty(MetadataProperty property) throws IllegalArgumentException
{
if(property == null)
throw new IllegalArgumentException();
metadataProperties.put(property.getName(), property.getValue());
}
/**
* Sets the value of the metadata property with the given name.
* @param propertyName The name of the metadata property.
* @param propertyValue The value of the metadata property.
* @throws IllegalArgumentException thrown if either propertyName or propertyValue are null, or if propertyName is empty.
*/
public void setMetadataProperty(String propertyName, String propertyValue) throws IllegalArgumentException
{
if(propertyName == null || propertyName.isEmpty() || propertyValue == null)
throw new IllegalArgumentException();
metadataProperties.put(propertyName, propertyValue);
}
/**
* Removes all metadata properties.
*/
public void clearMetadataProperties()
{
metadataProperties.clear();
}
/**
* Deletes the metadata property with the given name. Does nothing if the property does not exist.
* @param propertyName The name of the metadata property.
* @return True if property was deleted, false if property did not exist.
* @throws IllegalArgumentException Thrown if propertyName is null or empty.
*/
public boolean deleteMetadataProperty(String propertyName) throws IllegalArgumentException
{
if(propertyName == null || propertyName.isEmpty())
throw new IllegalArgumentException();
return metadataProperties.remove(propertyName) != null;
}
/**
* Returns the name of the measurement.
* @return the name of the measurement.
*/
public String getName()
{
return name;
}
/**
* Sets the name of the measurement.
* @param name Non-null name of the measurement.
* @throws IllegalArgumentException Thrown if name is null.
*/
public void setName(String name) throws IllegalArgumentException
{
if(name == null)
throw new IllegalArgumentException();
this.name = name;
}
/**
* Returns the maximal runtime in ms after which the measurement is automatically stopped.
* @return the measurementRuntime Maximal runtime of the measurement, or -1 if measurement does not have a maximal runtime.
*/
public int getMaxRuntime()
{
return maxRuntime;
}
/**
* Sets the maximal runtime in ms after which the measurement is automatically stopped.
* If the provided value is zero or negative, the maximal runtime is set to -1 to indicate that the measurement is not automatically stopped.
* @param maxRuntime Maximal runtime of the measurement, or -1 if measurement does not have a maximal runtime.
*/
public void setMaxRuntime(int maxRuntime)
{
this.maxRuntime = maxRuntime <= 0 ? -1 : maxRuntime;
}
/**
* Returns the device settings which should be applied when measurement starts.
* @return the deviseSettingsOn Device settings applied when measurement starts.
*/
public DeviceSetting[] getDeviseSettingsOn()
{
return deviseSettingsOn;
}
/**
* Sets the device settings which should be applied when measurement starts.
* Set to null if no device settings should be applied.
* @param deviceSettings device settings which should be applied, or null if no settings should be applied.
* @throws IllegalArgumentException Thrown if one of the provided device settings is null.
*/
public void setDeviseSettingsOn(DeviceSetting[] deviceSettings) throws IllegalArgumentException
{
if(deviceSettings == null)
deviceSettings = new DeviceSetting[0];
for(DeviceSetting setting : deviceSettings)
{
if(setting == null)
throw new IllegalArgumentException();
}
this.deviseSettingsOn = deviceSettings;
}
/**
* Returns the device settings which should be applied when measurement stops.
* @return the deviseSettingsOn Device settings applied when measurement stops.
*/
public DeviceSetting[] getDeviseSettingsOff()
{
return deviseSettingsOff;
}
/**
* Sets the device settings which should be applied when measurement stops.
* Set to null if no device settings should be applied.
* @param deviceSettings device settings which should be applied, or null if no settings should be applied.
* @throws IllegalArgumentException Thrown if one of the provided device settings is null.
*/
public void setDeviseSettingsOff(DeviceSetting[] deviceSettings)
{
if(deviceSettings == null)
deviceSettings = new DeviceSetting[0];
for(DeviceSetting setting : deviceSettings)
{
if(setting == null)
throw new IllegalArgumentException();
}
this.deviseSettingsOff = deviceSettings;
}
/**
* Defines how the measurement should be saved. Set to null if the measurement should not be saved.
* @param saveSettings Definition how the measurement should be saved.
*/
public void setSaveSettings(SaveSettingsConfiguration saveSettings)
{
this.saveSettings = saveSettings;
}
/**
* Returns the definition how the measurement should be saved. Returns null if the measurement should not be saved.
* @return Definition how the measurement should be saved.
*/
public SaveSettingsConfiguration getSaveSettings()
{
return saveSettings;
}
@Override
public void checkConfiguration() throws ConfigurationException
{
// do nothing.
}
}
| gpl-2.0 |
AlanGuerraQuispe/SisAtuxVenta | atux-base/src/main/java/com/aw/core/domain/AWBusinessException.java | 2763 | /*
* Copyright (c) 2007 Agile-Works
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Agile-Works. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Agile-Works.
*/
package com.aw.core.domain;
import com.aw.core.exception.AWException;
import com.aw.core.spring.ApplicationBase;
import org.apache.commons.logging.Log;
import java.sql.SQLException;
/**
* author: jcvergara
* 07/08/2004
*/
public class AWBusinessException extends AWException {
/**
* The exception only has warning messages and no error messages ?
*/
private boolean onlyContainsWarnings;
private boolean forceFailMode = false;
public AWBusinessException(String message) {
super(message);
}
public AWBusinessException(String message, String visualCmpName) {
super(message, visualCmpName);
}
public AWBusinessException(String message, Throwable cause) {
super(message, cause);
}
public AWBusinessException setForceFailMode(boolean forceFailMode) {
this.forceFailMode = forceFailMode;
return this;
}
public boolean isOnlyContainsWarnings() {
return onlyContainsWarnings;
}
public boolean isForceFailMode() {
return forceFailMode;
}
public void setOnlyContainsWarnings(boolean onlyContainsWarnings) {
this.onlyContainsWarnings = onlyContainsWarnings;
}
public static AWBusinessException wrapUnhandledException(Log logger, Throwable e) {
return wrapUnhandledException(logger, e, "Operation fail");
}
public static AWBusinessException wrapUnhandledException(Log logger, SQLException e) {
return wrapUnhandledException(logger, e, "Database SQL operation fail");
}
private static AWBusinessException wrapUnhandledException(Log logger, Throwable e, Object errorMessage) {
try{
AWExcepcionInterpreter excepcionInterpreter = (AWExcepcionInterpreter) ApplicationBase.instance().getBean("exceptionInterpreter", null);
if (excepcionInterpreter!=null)
e = excepcionInterpreter.handle(e);
}catch (Throwable e2){}
if (e instanceof AWBusinessException)
return (AWBusinessException) e;
else {
logger.error(errorMessage, e);
AWBusinessException awBusinessException = new AWBusinessException(errorMessage + " : " + e.getMessage());
awBusinessException.initCause(e);
return awBusinessException;
}
}
}
| gpl-2.0 |
UnboundID/ldapsdk | src/com/unboundid/ldap/listener/package-info.java | 1719 | /*
* Copyright 2010-2020 Ping Identity Corporation
* All Rights Reserved.
*/
/*
* Copyright 2010-2020 Ping Identity Corporation
*
* 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.
*/
/*
* Copyright (C) 2010-2020 Ping Identity Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPLv2 only)
* or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
* 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, see <http://www.gnu.org/licenses>.
*/
/**
* This package contains classes which may be used to accept connections and
* read requests from LDAP-based clients. It provides the ability to serve as
* an LDAP front end to some other application, or create a simple LDAP server
* for testing purposes.
*/
package com.unboundid.ldap.listener;
| gpl-2.0 |
cpesch/MetaMusic | mp3-tools/src/main/java/slash/metamusic/mp3/tools/MP3Extender.java | 17831 | /*
You may freely copy, distribute, modify and use this class as long
as the original author attribution remains intact. See message
below.
Copyright (C) 2001-2006 Christian Pesch. All Rights Reserved.
*/
package slash.metamusic.mp3.tools;
import slash.metamusic.coverdb.*;
import slash.metamusic.lyricsdb.LyricsDBClient;
import slash.metamusic.mp3.MP3File;
import slash.metamusic.trm.TRM;
import slash.metamusic.util.DiscIndexHelper;
import slash.metamusic.util.ImageResizer;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.logging.Logger;
import static slash.metamusic.util.ContributorHelper.*;
/**
* A class to add
* <ul>
* <li>MusicBrainz id,</li>
* <li>cover image,</li>
* <li>lyrics,</li>
* <li>publisher information and</li>
* <li>compilation name</li>
* </ul>
* to files.
*
* @author Christian Pesch
* @version $Id: MP3Extender.java 475 2005-01-14 17:31:47Z cpesch $
*/
public class MP3Extender extends BaseMP3Modifier {
/**
* Logging output
*/
protected static final Logger log = Logger.getLogger(MP3Extender.class.getName());
private static final int RESIZE_PIXELS = 600;
private CoverDBClient coverClient = new CoverDBClient();
private LyricsDBClient lyricsClient = new LyricsDBClient();
private boolean addCoverToFolder = false, addCover = true, addLyrics = true, addMetaData = true;
public boolean isAddCoverToFolder() {
return addCoverToFolder;
}
public void setAddCoverToFolder(boolean addCoverToFolder) {
this.addCoverToFolder = addCoverToFolder;
}
public boolean isAddCover() {
return addCover;
}
public void setAddCover(boolean addCover) {
this.addCover = addCover;
}
public boolean isAddLyrics() {
return addLyrics;
}
public void setAddLyrics(boolean addLyrics) {
this.addLyrics = addLyrics;
}
public boolean isAddMetaData() {
return addMetaData;
}
public void setAddMetaData(boolean addMetaData) {
this.addMetaData = addMetaData;
}
public void setCoverDirectoryName(String coverDirectoryName) {
coverClient.setCoverDirectoryName(coverDirectoryName);
}
public void setLyricsDirectoryName(String lyricsDirectoryName) {
lyricsClient.setLyricsDirectoryName(lyricsDirectoryName);
}
/**
* Extend the given file, i.e. add
* <ul>
* <li>MusicBrainz id,</li>
* <li>cover image,</li>
* <li>lyrics,</li>
* <li>publisher information and</li>
* <li>compilation name</li>
* </ul>
* to the file.
*
* @param file the {@link File} to operate on
* @throws IOException if the file cannot be read
*/
public void extend(File file) throws IOException {
MP3File mp3 = MP3File.readValidFile(file);
if (mp3 == null) {
throw new IOException("Invalid MP3 file " + file.getAbsolutePath());
}
extend(mp3);
}
/**
* Extend the given MP3 file, i.e. add
* <ul>
* <li>MusicBrainz id,</li>
* <li>cover image,</li>
* <li>lyrics,</li>
* <li>publisher information and</li>
* <li>compilation name</li>
* </ul>
* to the MP3 file.
*
* @param file the {@link MP3File} to operate on
* @throws IOException if the file cannot be read
*/
public void extend(MP3File file) throws IOException {
boolean haveToWrite = extendTags(file);
if (haveToWrite) {
write(file);
log.info("Extended " + file.getFile().getAbsolutePath());
}
}
public boolean extendTags(MP3File file) throws IOException {
boolean addedMusicBrainzId = isAddMetaData() && addMusicBrainzId(file);
boolean addedAttachedPicture = isAddCover() && addCover(file);
boolean addedLyrics = isAddLyrics() && addLyrics(file);
boolean addedPublisher = isAddMetaData() && addPublisher(file);
boolean addedCompilationName = isAddMetaData() && addCompilationName(file);
boolean addedContributors = isAddMetaData() && addContributors(file);
boolean addedIndexCount = isAddMetaData() && addIndexCount(file);
if (isAddCoverToFolder())
addCoverToFolder(file);
boolean extended = addedMusicBrainzId || addedAttachedPicture || addedLyrics || addedPublisher ||
addedCompilationName || addedContributors || addedIndexCount;
log.info("extended: " + extended + " MusicBrainzId: " + addedMusicBrainzId +
" cover: " + addedAttachedPicture + " lyrics: " + addedLyrics +
" publisher: " + addedPublisher + " compilation name: " + addedCompilationName +
" contributors: " + addedContributors + " index count: " + addedIndexCount);
return extended;
}
private void addCoverToFolder(MP3File file) {
byte[] cover = file.getHead().getAttachedPicture();
if (cover == null)
return;
WindowsMediaPlayerCoverClient wmpClient = new WindowsMediaPlayerCoverClient();
wmpClient.storeCover(file.getFile(), cover);
}
protected boolean addMusicBrainzId(MP3File file) throws IOException {
String musicBrainzId = file.getHead() != null ? file.getHead().getMusicBrainzId() : null;
if (musicBrainzId == null) {
if (TRM.isSupported()) {
TRM trm = new TRM();
try {
trm.read(file);
if (trm.isValid()) {
log.fine("Calculated MusicBrainzId '" + trm.getSignature() + "' for " + file.getFile().getAbsolutePath());
file.getHead().setMusicBrainzId(trm.getSignature());
return true;
} else
log.severe("Cannot calculate MusicBrainzId for " + file.getFile().getAbsolutePath());
} catch (Throwable t) {
log.severe("Cannot calculate MusicBrainzId for " + file.getFile().getAbsolutePath() + ": " + t.getMessage());
}
}
} else
log.info("Found MusicBrainzId '" + musicBrainzId + "' for " + file.getFile().getAbsolutePath());
return false;
}
protected boolean addCover(MP3File file) {
byte[] fileCover = file.getHead() != null ? file.getHead().getAttachedPicture() : null;
try {
byte[] fetchCover = file.getHead().isCompilation() ?
coverClient.fetchCompilationCover(file.getAlbum()) :
coverClient.fetchAlbumCover(file.getArtist(), file.getAlbum());
File cachedFile = coverClient.getCachedFile(file.getArtist(), file.getTrack());
byte[] wmpCover = findWindowsMediaPlayerCover(file);
byte[] lfCover = findLastFmCover(file);
// in case the cached file has been modified but may be shorter
if (isFirstNewerThanSecond(cachedFile, file.getFile()))
fileCover = null;
// find best source
byte[] foundCover = fetchCover;
if (isFirstBetterThanSecond(wmpCover, foundCover))
foundCover = wmpCover;
if (isFirstBetterThanSecond(lfCover, foundCover))
foundCover = lfCover;
if (isFirstBetterThanSecond(fileCover, foundCover))
foundCover = fileCover;
// store found in coverdb cache if better than peek
if (foundCover != null && isFirstBetterThanSecond(foundCover, fetchCover)) {
log.fine("Storing found cover (" + foundCover.length + " bytes) in CoverDB cache");
if (file.getHead().isCompilation())
coverClient.storeCompilationCover(file.getAlbum(), foundCover);
else
coverClient.storeAlbumCover(file.getArtist(), file.getAlbum(), foundCover);
}
// store in file if better
byte[] transformedCover = foundCover != null ? new ImageResizer().resize(foundCover, "jpg", RESIZE_PIXELS, RESIZE_PIXELS) : null;
if (transformedCover != null && fileCover != null && isFirstBetterThanSecond(transformedCover, fileCover)) {
log.fine("Adding cover (" + transformedCover.length + " bytes) to " + file.getFile().getAbsolutePath());
file.getHead().setCover(transformedCover);
return true;
}
} catch (IOException e) {
log.severe("Cannot add cover to " + file.getFile().getAbsolutePath() + ": " + e.getMessage());
}
return false;
}
private boolean isFirstBetterThanSecond(byte[] first, byte[] second) {
if (first == null)
return false;
//noinspection SimplifiableIfStatement
if (second == null)
return true;
return first.length > second.length;
}
private byte[] findWindowsMediaPlayerCover(MP3File file) throws IOException {
WindowsMediaPlayerCoverClient wmpClient = new WindowsMediaPlayerCoverClient();
return wmpClient.findCover(file);
}
private byte[] findLastFmCover(MP3File file) throws IOException {
LastFmCoverClient lfClient = new LastFmCoverClient();
return lfClient.findCover(file);
}
protected boolean addLyrics(MP3File file) {
String fileLyrics = file.getHead() != null ? file.getHead().getLyrics() : null;
fileLyrics = lyricsClient.cleanLyrics(fileLyrics);
String fetchLyrics = lyricsClient.fetchLyrics(file.getArtist(), file.getTrack());
fetchLyrics = lyricsClient.cleanLyrics(fetchLyrics);
File cachedFile = lyricsClient.getCachedFile(file.getArtist(), file.getTrack());
// in case the cached file has been modified but may be shorter
if (isFirstNewerThanSecond(cachedFile, file.getFile()))
fileLyrics = null;
// find best source
String foundLyrics = fetchLyrics;
if (isFirstBetterThanSecond(fileLyrics, foundLyrics))
foundLyrics = fileLyrics;
// store found in lyricsdb cache if better than peek
if (foundLyrics != null && isFirstBetterThanSecond(foundLyrics, fetchLyrics)) {
log.fine("Storing found lyrics (" + foundLyrics.length() + " bytes) in LyricsDB cache");
lyricsClient.storeLyrics(file.getArtist(), file.getTrack(), foundLyrics);
}
// store in file if better
if (foundLyrics != null && isFirstBetterThanSecond(foundLyrics, fileLyrics)) {
log.fine("Adding lyrics (" + foundLyrics.length() + " bytes) to " + file.getFile().getAbsolutePath());
file.getHead().setLyrics(foundLyrics);
return true;
}
return false;
}
private boolean isFirstNewerThanSecond(File first, File second) {
if (first == null)
return false;
//noinspection SimplifiableIfStatement
if (second == null)
return true;
return (first.lastModified() / 1000) > (second.lastModified() / 1000);
}
private boolean isFirstBetterThanSecond(String first, String second) {
if (first == null)
return false;
//noinspection SimplifiableIfStatement
if (second == null)
return true;
return first.length() > second.length();
}
protected boolean addPublisher(MP3File file) {
if (file.getHead().getPublisher() == null) {
AmazonMusicClient client = new AmazonMusicClient();
String publisher = client.searchPublisher(file.getArtist(), file.getAlbum());
if (publisher != null) {
log.info("Adding publisher '" + publisher + "' for " + file.getFile().getAbsolutePath());
file.getHead().setPublisher(publisher);
return true;
}
}
return false;
}
protected boolean addCompilationName(MP3File file) {
if (file.getHead().isCompilation() && file.getHead().getAlbumArtist() == null) {
String compilationName = file.getFile().getParentFile().getName();
log.info("Adding compilation name '" + compilationName + "' for " + file.getFile().getAbsolutePath());
file.getHead().setAlbumArtist(compilationName);
return true;
}
return false;
}
protected boolean addContributors(MP3File file) {
Set<String> contributors = new LinkedHashSet<String>();
List<String> artists = parseArtist(file.getArtist());
contributors.addAll(artists.subList(1, artists.size()));
List<String> trackArtists = parseTrack(file.getTrack());
contributors.addAll(trackArtists.subList(1, trackArtists.size()));
String albumArtist = artists.get(0);
String artist = formatContributors(file.getArtist(), new ArrayList<String>(contributors));
if (contributors.size() > 0 && (!file.getArtist().equals(artist) && !(file.getHead().getAlbumArtist() != null &&
file.getHead().getAlbumArtist().equals(albumArtist)))) {
log.info("Adding contributors '" + contributors + "' for " + file.getFile().getAbsolutePath());
file.getHead().setAlbumArtist(albumArtist);
file.getHead().setArtist(artist);
return true;
}
return false;
}
private Maxima determineMaximumIndices(File directory) {
Maxima maxima = new Maxima();
// search on same directory level for albums
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
MP3File mp3 = MP3File.readValidFile(file);
if (mp3 == null)
continue;
String artistName = mp3.getHead().getAlbumArtist();
if (artistName == null)
artistName = mp3.getArtist();
int discIndex = DiscIndexHelper.parseDiscIndex(mp3.getAlbum());
if (discIndex == -1)
discIndex = mp3.getPartOfSetIndex();
if (discIndex > 0)
maxima.checkIfMaximumDiscIndex(artistName, mp3.getAlbum(), discIndex);
int albumIndex = mp3.getIndex();
if (albumIndex > 0)
maxima.checkIfMaximumAlbumIndex(artistName, mp3.getAlbum(), discIndex, albumIndex);
}
}
return maxima;
}
private static class Maxima {
private Map<Album, Integer> maximumAlbumIndex = new HashMap<Album, Integer>();
private Map<Album, Integer> maximumDiscIndex = new HashMap<Album, Integer>();
public Integer getMaximumAlbumIndex(String artist, String album, int discIndex) {
return maximumAlbumIndex.get(new Album(artist, DiscIndexHelper.formatDiscIndex(album, discIndex)));
}
public void checkIfMaximumAlbumIndex(String artist, String album, int discIndex, int albumIndex) {
Album key = new Album(artist, DiscIndexHelper.formatDiscIndex(DiscIndexHelper.removeDiscIndexPostfix(album), discIndex));
Integer maximum = maximumAlbumIndex.get(key);
if (maximum == null || maximum < albumIndex)
maximumAlbumIndex.put(key, albumIndex);
}
public Integer getMaximumDiscIndex(String artist, String album) {
return maximumDiscIndex.get(new Album(artist, DiscIndexHelper.removeDiscIndexPostfix(album)));
}
public void checkIfMaximumDiscIndex(String artist, String album, int discIndex) {
Album key = new Album(artist, DiscIndexHelper.removeDiscIndexPostfix(album));
Integer maximum = maximumDiscIndex.get(key);
if (maximum == null || maximum < discIndex)
maximumDiscIndex.put(key, discIndex);
}
}
private Map<File, Maxima> indexCountCache = new HashMap<File, Maxima>();
protected boolean addIndexCount(MP3File file) {
boolean result = false;
int discIndex = DiscIndexHelper.parseDiscIndex(file.getAlbum());
if (discIndex > 0) {
file.setPartOfSetIndex(discIndex);
result = true;
}
if (file.getIndex() > 0 || file.getPartOfSetIndex() > 0) {
// cache for the running of this JVM, locality of the cache should be really good
File directory = file.getFile().getParentFile();
Maxima maxima = indexCountCache.get(directory);
if (maxima == null) {
maxima = determineMaximumIndices(directory);
indexCountCache.put(directory, maxima);
}
Integer maximumAlbumIndex = maxima.getMaximumAlbumIndex(file.getArtist(), file.getAlbum(), file.getPartOfSetIndex());
if (maximumAlbumIndex != null && maximumAlbumIndex != file.getCount()) {
file.setCount(maximumAlbumIndex);
result = true;
}
Integer maximumDiscIndex = maxima.getMaximumDiscIndex(file.getArtist(), file.getAlbum());
if (maximumDiscIndex != null && maximumDiscIndex != file.getPartOfSetCount()) {
file.setPartOfSetCount(maximumDiscIndex);
result = true;
}
}
if (discIndex > 0) {
file.setAlbum(DiscIndexHelper.removeDiscIndexPostfix(file.getAlbum()));
}
return result;
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("slash.metamusic.mp3.tools.MP3Extender <file>");
System.exit(1);
}
File file = new File(args[0]);
MP3Extender extender = new MP3Extender();
extender.extend(file);
System.exit(0);
}
}
| gpl-2.0 |
Lythimus/lptv | apache-solr-3.6.0/solr/solrj/src/test/org/apache/solr/client/solrj/response/TermsResponseTest.java | 2427 | package org.apache.solr.client.solrj.response;
/**
* 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
*
* 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.
*/
import java.util.List;
import junit.framework.Assert;
import org.apache.solr.SolrJettyTestBase;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.TermsResponse.Term;
import org.apache.solr.util.ExternalPaths;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test for TermComponent's response in Solrj
*/
public class TermsResponseTest extends SolrJettyTestBase {
@BeforeClass
public static void beforeTest() throws Exception {
initCore(ExternalPaths.EXAMPLE_CONFIG, ExternalPaths.EXAMPLE_SCHEMA, ExternalPaths.EXAMPLE_HOME);
}
@Test
public void testTermsResponse() throws Exception {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", 1);
doc.setField("terms_s", "samsung");
getSolrServer().add(doc);
getSolrServer().commit(true, true);
SolrQuery query = new SolrQuery();
query.setQueryType("/terms");
query.setTerms(true);
query.setTermsLimit(5);
query.setTermsLower("s");
query.setTermsPrefix("s");
query.addTermsField("terms_s");
query.setTermsMinCount(1);
QueryRequest request = new QueryRequest(query);
List<Term> terms = request.process(getSolrServer()).getTermsResponse().getTerms("terms_s");
Assert.assertNotNull(terms);
Assert.assertEquals(terms.size(), 1);
Term term = terms.get(0);
Assert.assertEquals(term.getTerm(), "samsung");
Assert.assertEquals(term.getFrequency(), 1);
}
}
| gpl-2.0 |
cyberpython/java-gnome | generated/bindings/org/gnome/gdk/GdkDragContext.java | 11068 | /*
* java-gnome, a UI library for writing GTK and GNOME programs from Java!
*
* Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others
*
* The code in this file, and the program it is a part of, is made available
* to you by its authors as open source software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License version
* 2 ("GPL") 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 GPL for more details.
*
* You should have received a copy of the GPL along with this program. If not,
* see http://www.gnu.org/licenses/. The authors of this program may be
* contacted through http://java-gnome.sourceforge.net/.
*
* Linking this library statically or dynamically with other modules is making
* a combined work based on this library. Thus, the terms and conditions of
* the GPL cover the whole combination. As a special exception (the
* "Claspath Exception"), the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend the Classpath Exception to your
* version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*/
package org.gnome.gdk;
/*
* THIS FILE IS GENERATED CODE!
*
* To modify its contents or behaviour, either update the generation program,
* change the information in the source defs file, or implement an override for
* this class.
*/
import org.freedesktop.bindings.BlacklistedMethodError;
import org.freedesktop.bindings.FIXME;
import org.gnome.gdk.DragAction;
import org.gnome.gdk.DragContext;
import org.gnome.gdk.DragProtocol;
import org.gnome.gdk.Pixbuf;
import org.gnome.gdk.Plumbing;
import org.gnome.gdk.Screen;
import org.gnome.gdk.Window;
import org.gnome.gtk.Widget;
final class GdkDragContext extends Plumbing
{
private GdkDragContext() {}
static final void dragStatus(DragContext self, DragAction action, int time) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (action == null) {
throw new IllegalArgumentException("action can't be null");
}
synchronized (lock) {
gdk_drag_status(pointerOf(self), numOf(action), time);
}
}
private static native final void gdk_drag_status(long self, int action, int time);
static final void dropReply(DragContext self, boolean ok, int time) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
gdk_drop_reply(pointerOf(self), ok, time);
}
}
private static native final void gdk_drop_reply(long self, boolean ok, int time);
static final void dropFinish(DragContext self, boolean success, int time) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
gdk_drop_finish(pointerOf(self), success, time);
}
}
private static native final void gdk_drop_finish(long self, boolean success, int time);
@SuppressWarnings("unused")
static final FIXME dragGetSelection(DragContext self) throws BlacklistedMethodError {
throw new BlacklistedMethodError("GdkAtom");
}
static final void dragFindWindowForScreen(DragContext self, Window dragWindow, Screen screen, int xRoot, int yRoot, Window[] destWindow, DragProtocol[] protocol) {
long[] _destWindow;
int[] _protocol;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (dragWindow == null) {
throw new IllegalArgumentException("dragWindow can't be null");
}
if (screen == null) {
throw new IllegalArgumentException("screen can't be null");
}
if (destWindow == null) {
throw new IllegalArgumentException("destWindow can't be null");
}
if (protocol == null) {
throw new IllegalArgumentException("protocol can't be null");
}
_destWindow = pointersOf(destWindow);
_protocol = numsOf(protocol);
synchronized (lock) {
gdk_drag_find_window_for_screen(pointerOf(self), pointerOf(dragWindow), pointerOf(screen), xRoot, yRoot, _destWindow, _protocol);
fillObjectArray(destWindow, _destWindow);
fillEnumArray(DragProtocol.class, protocol, _protocol);
}
}
private static native final void gdk_drag_find_window_for_screen(long self, long dragWindow, long screen, int xRoot, int yRoot, long[] destWindow, int[] protocol);
static final boolean dragMotion(DragContext self, Window destWindow, DragProtocol protocol, int xRoot, int yRoot, DragAction suggestedAction, DragAction possibleActions, int time) {
boolean result;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (destWindow == null) {
throw new IllegalArgumentException("destWindow can't be null");
}
if (protocol == null) {
throw new IllegalArgumentException("protocol can't be null");
}
if (suggestedAction == null) {
throw new IllegalArgumentException("suggestedAction can't be null");
}
if (possibleActions == null) {
throw new IllegalArgumentException("possibleActions can't be null");
}
synchronized (lock) {
result = gdk_drag_motion(pointerOf(self), pointerOf(destWindow), numOf(protocol), xRoot, yRoot, numOf(suggestedAction), numOf(possibleActions), time);
return result;
}
}
private static native final boolean gdk_drag_motion(long self, long destWindow, int protocol, int xRoot, int yRoot, int suggestedAction, int possibleActions, int time);
static final void dragDrop(DragContext self, int time) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
gdk_drag_drop(pointerOf(self), time);
}
}
private static native final void gdk_drag_drop(long self, int time);
static final void dragAbort(DragContext self, int time) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
gdk_drag_abort(pointerOf(self), time);
}
}
private static native final void gdk_drag_abort(long self, int time);
static final boolean dragDropSucceeded(DragContext self) {
boolean result;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
result = gdk_drag_drop_succeeded(pointerOf(self));
return result;
}
}
private static native final boolean gdk_drag_drop_succeeded(long self);
static final void finish(DragContext self, boolean success, boolean del, int time) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
gtk_drag_finish(pointerOf(self), success, del, time);
}
}
private static native final void gtk_drag_finish(long self, boolean success, boolean del, int time);
static final Widget getSourceWidget(DragContext self) {
long result;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
result = gtk_drag_get_source_widget(pointerOf(self));
return (Widget) objectFor(result);
}
}
private static native final long gtk_drag_get_source_widget(long self);
static final void setIconWidget(DragContext self, Widget widget, int hotX, int hotY) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (widget == null) {
throw new IllegalArgumentException("widget can't be null");
}
synchronized (lock) {
gtk_drag_set_icon_widget(pointerOf(self), pointerOf(widget), hotX, hotY);
}
}
private static native final void gtk_drag_set_icon_widget(long self, long widget, int hotX, int hotY);
static final void setIconPixbuf(DragContext self, Pixbuf pixbuf, int hotX, int hotY) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (pixbuf == null) {
throw new IllegalArgumentException("pixbuf can't be null");
}
synchronized (lock) {
gtk_drag_set_icon_pixbuf(pointerOf(self), pointerOf(pixbuf), hotX, hotY);
}
}
private static native final void gtk_drag_set_icon_pixbuf(long self, long pixbuf, int hotX, int hotY);
static final void setIconStock(DragContext self, String stockId, int hotX, int hotY) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (stockId == null) {
throw new IllegalArgumentException("stockId can't be null");
}
synchronized (lock) {
gtk_drag_set_icon_stock(pointerOf(self), stockId, hotX, hotY);
}
}
private static native final void gtk_drag_set_icon_stock(long self, String stockId, int hotX, int hotY);
static final void setIconDefault(DragContext self) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
gtk_drag_set_icon_default(pointerOf(self));
}
}
private static native final void gtk_drag_set_icon_default(long self);
static final void setIconName(DragContext self, String iconName, int hotX, int hotY) {
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
if (iconName == null) {
throw new IllegalArgumentException("iconName can't be null");
}
synchronized (lock) {
gtk_drag_set_icon_name(pointerOf(self), iconName, hotX, hotY);
}
}
private static native final void gtk_drag_set_icon_name(long self, String iconName, int hotX, int hotY);
}
| gpl-2.0 |
mvehar/zanata-server | zanata-war/src/test/java/org/zanata/RestTest.java | 9201 | /*
* Copyright 2010, 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.zanata;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.deltaspike.core.api.exclude.Exclude;
import org.apache.deltaspike.core.api.projectstage.ProjectStage;
import org.apache.deltaspike.core.util.ProjectStageProducer;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.ext.h2.H2DataTypeFactory;
import org.dbunit.operation.DatabaseOperation;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.resteasy.client.ClientRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.zanata.arquillian.RemoteAfter;
import org.zanata.arquillian.RemoteBefore;
import org.zanata.provider.DBUnitProvider;
import org.zanata.rest.ResourceRequestEnvironment;
import org.zanata.util.ServiceLocator;
import com.google.common.collect.Lists;
/**
* Provides basic test utilities to test raw REST APIs and compatibility.
*
* @author Carlos Munoz <a
* href="mailto:camunoz@redhat.com">camunoz@redhat.com</a>
*/
@RunWith(Arquillian.class)
@Exclude
public abstract class RestTest {
// Admin credentials
protected static final String ADMIN = "admin";
protected static final String ADMIN_KEY =
"b6d7044e9ee3b2447c28fb7c50d86d98";
// Translator credentials
protected static final String TRANSLATOR = "demo";
protected static final String TRANSLATOR_KEY =
"23456789012345678901234567890123";
static {
// Tell DeltaSpike to give more warning messages
ProjectStageProducer.setProjectStage(ProjectStage.IntegrationTest);
}
// Authorized environment with valid credentials
private static final ResourceRequestEnvironment ENV_AUTHORIZED =
new ResourceRequestEnvironment() {
@Override
public Map<String, Object> getDefaultHeaders() {
return new HashMap<String, Object>() {
{
put("X-Auth-User", ADMIN);
put("X-Auth-Token", ADMIN_KEY);
}
};
}
};
private DBUnitProvider dbUnitProvider = new DBUnitProvider() {
@Override
protected IDatabaseConnection getConnection() {
return RestTest.getConnection();
}
};
@ArquillianResource
protected URL deploymentUrl;
/**
* Implement this in a subclass.
* <p/>
* Use it to stack DBUnit <tt>DataSetOperation</tt>'s with the
* <tt>beforeTestOperations</tt> and <tt>afterTestOperations</tt> lists.
*/
protected abstract void prepareDBUnitOperations();
public void
addBeforeTestOperation(DBUnitProvider.DataSetOperation operation) {
dbUnitProvider.addBeforeTestOperation(operation);
}
public void
addAfterTestOperation(DBUnitProvider.DataSetOperation operation) {
dbUnitProvider.addAfterTestOperation(operation);
}
/**
* Invoked on the arquillian container before the test is run.
*/
@RemoteBefore
public void prepareDataBeforeTest() {
addBeforeTestOperation(new DBUnitProvider.DataSetOperation(
"org/zanata/test/model/ClearAllTables.dbunit.xml",
DatabaseOperation.DELETE_ALL));
prepareDBUnitOperations();
addAfterTestOperation(new DBUnitProvider.DataSetOperation(
"org/zanata/test/model/ClearAllTables.dbunit.xml",
DatabaseOperation.DELETE_ALL));
dbUnitProvider.prepareDataBeforeTest();
// Clear the hibernate cache
ServiceLocator.instance().getEntityManagerFactory().getCache()
.evictAll();
}
/**
* Invoked in the arquillian container after the test is run.
*/
@RemoteAfter
public void cleanDataAfterTest() {
dbUnitProvider.cleanDataAfterTest();
}
@Rule
public final TestName testName = new TestName();
@Before
public void signalBeforeTest() {
ClientRequest clientRequest =
new ClientRequest(getRestEndpointUrl() + "test/remote/signal/before");
clientRequest.header("X-Auth-User", ADMIN);
clientRequest.header("X-Auth-Token", ADMIN_KEY);
try {
clientRequest
.queryParameter("c", this.getClass().getName())
.queryParameter("m", testName.getMethodName())
.post();
} catch (Exception e) {
e.printStackTrace();
}
}
@After
public void signalAfterTest() {
ClientRequest clientRequest =
new ClientRequest(getRestEndpointUrl() + "test/remote/signal/after");
clientRequest.header("X-Auth-User", ADMIN);
clientRequest.header("X-Auth-Token", ADMIN_KEY);
try {
clientRequest
.queryParameter("c", this.getClass().getName())
.queryParameter("m", testName.getMethodName())
.post();
} catch (Exception e) {
e.printStackTrace();
}
}
private static IDatabaseConnection getConnection() {
try {
DataSource dataSource =
(DataSource) new InitialContext().lookup(
"java:jboss/datasources/zanataDatasource");
DatabaseConnection dbConn =
new DatabaseConnection(dataSource.getConnection());
return dbConn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @return The artifact's base deployment Url.
*/
public String getDeploymentUrl() {
return deploymentUrl.toString();
}
/**
* Gets the full Url for a Rest endpoint.
*
* @param resourceUrl
* The relative resource url.
* @return The full absolute url of the deployed resource.
*/
public final String getRestEndpointUrl(String resourceUrl) {
StringBuilder fullUrl =
new StringBuilder(getDeploymentUrl() + "rest");
if (!resourceUrl.startsWith("/")) {
fullUrl.append("/");
}
return fullUrl.append(resourceUrl).toString();
}
/**
* Gets the artifact's deployed url for REST endpoints.
*
* @return The full absolute root url of the deployed artifact.
* @see RestTest#getRestEndpointUrl(String)
*/
public final String getRestEndpointUrl() {
return getRestEndpointUrl("/");
}
/**
* Gets a valid Authorized REST environment.
*
* @return A Resource Request execution environment with valid test
* credentials.
*/
public static final ResourceRequestEnvironment getAuthorizedEnvironment() {
return ENV_AUTHORIZED;
}
/**
* Gets an empty header for REST request.
*/
public static final ResourceRequestEnvironment getEmptyHeaderEnvironment() {
return new ResourceRequestEnvironment() {
@Override
public Map<String, Object> getDefaultHeaders() {
return new HashMap<String, Object>();
}
};
}
public static ResourceRequestEnvironment getTranslatorHeaders() {
return new ResourceRequestEnvironment() {
@Override
public Map<String, Object> getDefaultHeaders() {
return new HashMap<String, Object>() {
{
put("X-Auth-User", TRANSLATOR);
put("X-Auth-Token", TRANSLATOR_KEY);
}
};
}
};
}
protected void addExtensionToRequest(Set<String> extensions,
ClientRequest request) {
if (extensions != null) {
request.getQueryParameters().put("ext", Lists
.newArrayList(extensions));
}
}
}
| gpl-2.0 |
AutuanLiu/Code | MyJava/sourcecode/chapter05/src/Request.java | 3686 | import java.net.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.regex.*;
/* ´ú±í¿Í»§µÄHTTPÇëÇó */
public class Request {
static class Action { //ö¾ÙÀ࣬±íʾHTTPÇëÇó·½Ê½
private String name;
private Action(String name) { this.name = name; }
public String toString() { return name; }
static Action GET = new Action("GET");
static Action PUT = new Action("PUT");
static Action POST = new Action("POST");
static Action HEAD = new Action("HEAD");
public static Action parse(String s) {
if (s.equals("GET"))
return GET;
if (s.equals("PUT"))
return PUT;
if (s.equals("POST"))
return POST;
if (s.equals("HEAD"))
return HEAD;
throw new IllegalArgumentException(s);
}
}
private Action action;
private String version;
private URI uri;
public Action action() { return action; }
public String version() { return version; }
public URI uri() { return uri; }
private Request(Action a, String v, URI u) {
action = a;
version = v;
uri = u;
}
public String toString() {
return (action + " " + version + " " + uri);
}
private static Charset requestCharset = Charset.forName("GBK");
/* ÅжÏByteBufferÊÇ·ñ°üº¬ÁËHTTPÇëÇóµÄËùÓÐÊý¾Ý¡£
* HTTPÇëÇóÒÔ¡°\r\n\r\n¡±½áβ¡£
*/
public static boolean isComplete(ByteBuffer bb) {
ByteBuffer temp=bb.asReadOnlyBuffer();
temp.flip();
String data=requestCharset.decode(temp).toString();
if(data.indexOf("\r\n\r\n")!=-1){
return true;
}
return false;
}
/*
* ɾ³ýÇëÇóÕýÎÄ£¬±¾Àý×Ó½öÖ§³ÖGETºÍHEADÇëÇó·½Ê½£¬ºöÂÔHTTPÇëÇóÖеÄÕýÎIJ¿·Ö
*/
private static ByteBuffer deleteContent(ByteBuffer bb) {
ByteBuffer temp=bb.asReadOnlyBuffer();
String data=requestCharset.decode(temp).toString();
if(data.indexOf("\r\n\r\n")!=-1){
data=data.substring(0,data.indexOf("\r\n\r\n")+4);
return requestCharset.encode(data);
}
return bb;
}
/*
* É趨ÓÃÓÚ½âÎöHTTPÇëÇóµÄ×Ö·û´®Æ¥Åäģʽ¡£¶ÔÓÚÒÔÏÂÐÎʽµÄHTTPÇëÇó£º
*
* GET /dir/file HTTP/1.1
* Host: hostname
*
* ½«±»½âÎö³É:
*
* group[1] = "GET"
* group[2] = "/dir/file"
* group[3] = "1.1"
* group[4] = "hostname"
*/
private static Pattern requestPattern
= Pattern.compile("\\A([A-Z]+) +([^ ]+) +HTTP/([0-9\\.]+)$"
+ ".*^Host: ([^ ]+)$.*\r\n\r\n\\z",
Pattern.MULTILINE | Pattern.DOTALL);
/* ½âÎöHTTPÇëÇ󣬴´½¨ÏàÓ¦µÄRequest¶ÔÏó */
public static Request parse(ByteBuffer bb) throws MalformedRequestException {
bb=deleteContent(bb); //ɾ³ýÇëÇóÕýÎÄ
CharBuffer cb = requestCharset.decode(bb); //½âÂë
Matcher m = requestPattern.matcher(cb); //½øÐÐ×Ö·û´®Æ¥Åä
//Èç¹ûHTTPÇëÇóÓëÖ¸¶¨µÄ×Ö·û´®Ä£Ê½²»Æ¥Å䣬˵Ã÷ÇëÇóÊý¾Ý²»ÕýÈ·
if (!m.matches())
throw new MalformedRequestException();
Action a;
try { //»ñµÃÇëÇó·½Ê½
a = Action.parse(m.group(1));
} catch (IllegalArgumentException x) {
throw new MalformedRequestException();
}
URI u;
try { //»ñµÃURI
u = new URI("http://"
+ m.group(4)
+ m.group(2));
} catch (URISyntaxException x) {
throw new MalformedRequestException();
}
//´´½¨Ò»¸öRequest¶ÔÏ󣬲¢½«Æä·µ»Ø
return new Request(a, m.group(3), u);
}
}
/****************************************************
* ×÷ÕߣºËïÎÀÇÙ *
* À´Ô´£º<<JavaÍøÂç±à³Ì¾«½â>> *
* ¼¼ÊõÖ§³ÖÍøÖ·£ºwww.javathinker.org *
***************************************************/
| gpl-2.0 |
christianchristensen/resin | modules/kernel/src/com/caucho/config/bytecode/SerializationAdapter.java | 8936 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.config.bytecode;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import com.caucho.bytecode.CodeWriterAttribute;
import com.caucho.bytecode.ConstantPool;
import com.caucho.bytecode.JavaClass;
import com.caucho.bytecode.JavaClassLoader;
import com.caucho.bytecode.JavaField;
import com.caucho.bytecode.JavaMethod;
import com.caucho.config.ConfigException;
import com.caucho.config.inject.HandleAware;
import com.caucho.inject.Module;
import com.caucho.loader.ProxyClassLoader;
import com.caucho.vfs.Vfs;
import com.caucho.vfs.WriteStream;
/**
* interceptor generation
*/
@Module
public class SerializationAdapter<X> {
private final Class<X> _cl;
private Class<X> _proxyClass;
private SerializationAdapter(Class<X> cl)
{
_cl = cl;
}
public static <X> Class<X> gen(Class<X> cl)
{
if (Modifier.isFinal(cl.getModifiers()))
return cl;
if (HandleAware.class.isAssignableFrom(cl))
return cl;
SerializationAdapter<X> gen = new SerializationAdapter<X>(cl);
Class<X> proxyClass = gen.generateProxy();
return proxyClass;
}
public static void setHandle(Object obj, Object handle)
{
if (obj instanceof HandleAware) {
((HandleAware) obj).setSerializationHandle(handle);
}
else {
try {
Class cl = obj.getClass();
for (Field field : cl.getDeclaredFields()) {
if (field.getName().equals("__caucho_handle")) {
field.setAccessible(true);
field.set(obj, handle);
}
}
} catch (Exception e) {
throw ConfigException.create(e);
}
}
}
private Class generateProxy()
{
try {
JavaClassLoader jLoader = new JavaClassLoader(_cl.getClassLoader());
JavaClass jClass = new JavaClass(jLoader);
jClass.setAccessFlags(Modifier.PUBLIC);
ConstantPool cp = jClass.getConstantPool();
jClass.setWrite(true);
jClass.setMajor(49);
jClass.setMinor(0);
String superClassName = _cl.getName().replace('.', '/');
String thisClassName = superClassName + "$BeanProxy";
jClass.setSuperClass(superClassName);
jClass.setThisClass(thisClassName);
jClass.addInterface("java/io/Serializable");
jClass.addInterface("com/caucho/config/inject/HandleAware");
generateConstructors(jClass, superClassName);
generateWriteReplace(jClass);
generateSetHandle(jClass);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
WriteStream out = Vfs.openWrite(bos);
jClass.write(out);
out.close();
byte []buffer = bos.toByteArray();
if (false) {
out = Vfs.lookup("file:/tmp/caucho/qa/temp.class").openWrite();
out.write(buffer, 0, buffer.length);
out.close();
}
String cleanName = thisClassName.replace('/', '.');
_proxyClass = (Class<X>) new ProxyClassLoader().loadClass(cleanName, buffer);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
return _proxyClass;
}
private void generateConstructors(JavaClass jClass, String superClassName)
{
for (Constructor baseCtor : _cl.getDeclaredConstructors()) {
if (Modifier.isPrivate(baseCtor.getModifiers()))
continue;
generateConstructor(jClass, superClassName, baseCtor);
}
}
public static void generateConstructor(JavaClass jClass,
String superClassName,
Constructor baseCtor)
{
Class []types = baseCtor.getParameterTypes();
StringBuilder sb = new StringBuilder();
createDescriptor(sb, types);
sb.append("V");
String descriptor = sb.toString();
JavaMethod ctor = jClass.createMethod("<init>", descriptor);
ctor.setAccessFlags(Modifier.PUBLIC);
CodeWriterAttribute code = ctor.createCodeWriter();
code.setMaxLocals(5 + 2 * types.length);
code.setMaxStack(5 + 2 * types.length);
code.pushObjectVar(0);
marshal(code, types);
code.invokespecial(superClassName, "<init>", descriptor, 1, 0);
code.addReturn();
code.close();
}
private void generateWriteReplace(JavaClass jClass)
{
JavaField jField
= jClass.createField("__caucho_handle", "Ljava/lang/Object;");
jField.setAccessFlags(Modifier.PRIVATE);
JavaMethod jMethod
= jClass.createMethod("writeReplace", "()Ljava/lang/Object;");
jMethod.setAccessFlags(Modifier.PRIVATE);
CodeWriterAttribute code = jMethod.createCodeWriter();
code.setMaxLocals(5);
code.setMaxStack(5);
code.pushObjectVar(0);
code.getField(jClass.getThisClass(), "__caucho_handle",
"Ljava/lang/Object;");
code.addObjectReturn();
code.close();
}
private void generateSetHandle(JavaClass jClass)
{
/*
JavaField jField
= jClass.createField("__caucho_handle", "Ljava/lang/Object;");
jField.setAccessFlags(Modifier.PRIVATE);
*/
JavaMethod jMethod
= jClass.createMethod("setSerializationHandle", "(Ljava/lang/Object;)V");
jMethod.setAccessFlags(Modifier.PUBLIC);
CodeWriterAttribute code = jMethod.createCodeWriter();
code.setMaxLocals(5);
code.setMaxStack(5);
code.pushObjectVar(0);
code.pushObjectVar(1);
code.putField(jClass.getThisClass(), "__caucho_handle",
"Ljava/lang/Object;");
code.addReturn();
code.close();
}
public static void marshal(CodeWriterAttribute code, Class []param)
{
int stack = 1;
int index = 1;
for (int i = 0; i < param.length; i++) {
Class type = param[i];
if (boolean.class.equals(type)
|| byte.class.equals(type)
|| short.class.equals(type)
|| int.class.equals(type)) {
code.pushIntVar(index);
index += 1;
stack += 1;
}
else if (long.class.equals(type)) {
code.pushLongVar(index);
index += 2;
stack += 2;
}
else if (float.class.equals(type)) {
code.pushFloatVar(index);
index += 1;
stack += 1;
}
else if (double.class.equals(type)) {
code.pushDoubleVar(index);
index += 2;
stack += 2;
}
else {
code.pushObjectVar(index);
index += 1;
stack += 1;
}
}
}
private int parameterCount(Class []parameters)
{
int count = 0;
for (Class param : parameters) {
if (long.class.equals(param) || double.class.equals(param))
count += 2;
else
count += 1;
}
return count;
}
public static void createDescriptor(StringBuilder sb, Class []params)
{
sb.append("(");
for (Class param : params) {
sb.append(createDescriptor(param));
}
sb.append(")");
}
public static String createDescriptor(Class cl)
{
if (cl.isArray())
return "[" + createDescriptor(cl.getComponentType());
String primValue = _prim.get(cl);
if (primValue != null)
return primValue;
return "L" + cl.getName().replace('.', '/') + ";";
}
private static HashMap<Class,String> _prim = new HashMap<Class,String>();
private static HashMap<Class,String> _boxClass = new HashMap<Class,String>();
static {
_prim.put(boolean.class, "Z");
_prim.put(byte.class, "B");
_prim.put(char.class, "C");
_prim.put(short.class, "S");
_prim.put(int.class, "I");
_prim.put(long.class, "J");
_prim.put(float.class, "F");
_prim.put(double.class, "D");
_prim.put(void.class, "V");
_boxClass.put(boolean.class, "java/lang/Boolean");
_boxClass.put(byte.class, "java/lang/Byte");
_boxClass.put(char.class, "java/lang/Character");
_boxClass.put(short.class, "java/lang/Short");
_boxClass.put(int.class, "java/lang/Integer");
_boxClass.put(long.class, "java/lang/Long");
_boxClass.put(float.class, "java/lang/Float");
_boxClass.put(double.class, "java/lang/Double");
}
}
| gpl-2.0 |
rage/tmc-snapshot-api | src/test/java/fi/helsinki/cs/tmc/snapshot/api/spyware/model/SnapshotEventMetadataTest.java | 446 | package fi.helsinki.cs.tmc.snapshot.api.spyware.model;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public final class SnapshotEventMetadataTest {
@Test
public void constructorSetsValuesCorrectly() {
final SnapshotEventMetadata metadata = new SnapshotEventMetadata("myCause", "myFile");
assertEquals("myCause", metadata.getCause());
assertEquals("myFile", metadata.getFile());
}
}
| gpl-2.0 |
GLORIA-project/gloria-core | gloria-soap/gloria-commons/src/main/java/eu/gloria/gs/services/experiment/ExperimentInterface.java | 8355 | package eu.gloria.gs.services.experiment;
import java.util.List;
import java.util.Set;
import javax.jws.WebService;
import eu.gloria.gs.services.experiment.base.data.ExperimentInformation;
import eu.gloria.gs.services.experiment.base.data.ExperimentRuntimeInformation;
import eu.gloria.gs.services.experiment.base.data.ExperimentType;
import eu.gloria.gs.services.experiment.base.data.NoSuchExperimentException;
import eu.gloria.gs.services.experiment.base.data.OperationInformation;
import eu.gloria.gs.services.experiment.base.data.ParameterInformation;
import eu.gloria.gs.services.experiment.base.data.ReservationInformation;
import eu.gloria.gs.services.experiment.base.data.ResultInformation;
import eu.gloria.gs.services.experiment.base.data.TimeSlot;
import eu.gloria.gs.services.experiment.base.models.DuplicateExperimentException;
import eu.gloria.gs.services.experiment.base.models.InvalidUserContextException;
import eu.gloria.gs.services.experiment.base.operations.ExperimentOperation;
import eu.gloria.gs.services.experiment.base.operations.ExperimentOperationException;
import eu.gloria.gs.services.experiment.base.operations.NoSuchOperationException;
import eu.gloria.gs.services.experiment.base.parameters.ExperimentParameter;
import eu.gloria.gs.services.experiment.base.parameters.ExperimentParameterException;
import eu.gloria.gs.services.experiment.base.parameters.NoSuchParameterException;
import eu.gloria.gs.services.experiment.base.reservation.ExperimentNotInstantiatedException;
import eu.gloria.gs.services.experiment.base.reservation.ExperimentReservationArgumentException;
import eu.gloria.gs.services.experiment.base.reservation.MaxReservationTimeException;
import eu.gloria.gs.services.experiment.base.reservation.NoReservationsAvailableException;
import eu.gloria.gs.services.experiment.base.reservation.NoSuchReservationException;
import eu.gloria.gs.services.experiment.script.NoSuchScriptException;
import eu.gloria.gs.services.experiment.script.OverlapRTScriptException;
import eu.gloria.gs.services.experiment.script.data.RTScriptInformation;
import eu.gloria.gs.services.repository.user.InvalidUserException;
import eu.gloria.gs.services.utils.ObjectResponse;
@WebService(name = "ExperimentInterface", targetNamespace = "http://experiment.services.gs.gloria.eu/")
public interface ExperimentInterface {
public void createOnlineExperiment(String experiment)
throws ExperimentException, DuplicateExperimentException;
public void createOfflineExperiment(String experiment)
throws ExperimentException, DuplicateExperimentException;
public void deleteExperiment(String experiment) throws ExperimentException,
NoSuchExperimentException;
public void emptyExperiment(String experiment) throws ExperimentException,
NoSuchExperimentException;
public void deleteExperimentParameter(String experiment, String parameter)
throws ExperimentException, NoSuchExperimentException;
public void deleteExperimentOperation(String experiment, String operation)
throws ExperimentException, NoSuchExperimentException;
public void addExperimentOperation(String experiment,
OperationInformation operation) throws ExperimentException,
NoSuchExperimentException;
public void addExperimentParameter(String experiment,
ParameterInformation parameter) throws ExperimentException,
NoSuchExperimentException, NoSuchParameterException;
public ExperimentInformation getExperimentInformation(String experiment)
throws ExperimentException, NoSuchExperimentException;
public ParameterInformation getParameterInformation(String experiment,
String parameter) throws ExperimentException,
NoSuchExperimentException;
public void setExperimentDescription(String experiment, String description)
throws ExperimentException, NoSuchExperimentException;
public List<String> getAllExperiments(ExperimentType type)
throws ExperimentException;
public boolean containsExperiment(String experiment)
throws ExperimentException;
public List<ReservationInformation> getMyPendingReservations(
ExperimentType type) throws ExperimentException,
NoReservationsAvailableException;
public boolean anyReservationActiveNow(ExperimentType type)
throws ExperimentException;
public List<ReservationInformation> getMyCurrentReservations(
ExperimentType type) throws ExperimentException,
NoReservationsAvailableException;
public void reserveExperiment(String experiment, List<String> telescopes,
TimeSlot timeSlot) throws ExperimentException,
NoReservationsAvailableException,
ExperimentReservationArgumentException, MaxReservationTimeException;
public void applyForExperiment(String experiment)
throws ExperimentException, NoReservationsAvailableException,
NoSuchExperimentException;
public List<TimeSlot> getAvailableReservations(String experiment,
List<String> telescopes) throws ExperimentException,
ExperimentReservationArgumentException;
public void cancelExperimentReservation(int reservationId)
throws ExperimentException, NoSuchReservationException,
InvalidUserContextException;
public ReservationInformation getReservationInformation(int reservationId)
throws InvalidUserContextException, NoSuchReservationException,
ExperimentException;
public void executeExperimentOperation(int reservationId, String operation)
throws ExperimentOperationException, NoSuchOperationException,
ExperimentNotInstantiatedException, NoSuchReservationException,
InvalidUserContextException, ExperimentException;
public void setExperimentParameterValue(int reservationId,
String parameter, ObjectResponse value)
throws ExperimentParameterException, ExperimentException,
ExperimentNotInstantiatedException, NoSuchReservationException,
InvalidUserContextException, NoSuchParameterException;
public ObjectResponse getExperimentParameterValue(int reservationId,
String parameter) throws ExperimentParameterException,
ExperimentException, ExperimentNotInstantiatedException,
NoSuchReservationException, InvalidUserContextException,
NoSuchParameterException;
public List<ResultInformation> getContextResults(int reservationId)
throws ExperimentException, ExperimentNotInstantiatedException,
NoSuchReservationException;
public List<ResultInformation> getExperimentResults(String experiment)
throws ExperimentException;
public ExperimentRuntimeInformation getExperimentRuntimeInformation(
int reservationId) throws ExperimentException,
ExperimentNotInstantiatedException, NoSuchReservationException,
InvalidUserContextException;
public Set<String> getAllExperimentParameters() throws ExperimentException;
public Set<String> getAllExperimentOperations() throws ExperimentException;
public ExperimentParameter getExperimentParameter(String name)
throws ExperimentException, NoSuchParameterException;
public ExperimentOperation getExperimentOperation(String name)
throws ExperimentException, NoSuchOperationException;
public ObjectResponse getExperimentContext(int reservationId)
throws ExperimentException, ExperimentNotInstantiatedException,
NoSuchReservationException, InvalidUserContextException,
NoSuchParameterException;
public boolean isExperimentContextReady(int reservationId)
throws ExperimentException, NoSuchReservationException;
public void resetExperimentContext(int reservationId)
throws ExperimentException, NoSuchReservationException,
InvalidUserContextException, ExperimentNotInstantiatedException;
public int registerRTScript(String telescope, ScriptSlot slot,
String operation, String init, String result, boolean notify)
throws NoSuchExperimentException, ExperimentException,
OverlapRTScriptException, InvalidUserException;
public List<String> getRTScriptAvailableOperations(String telescope)
throws ExperimentException, NoSuchScriptException;
public RTScriptInformation getRTScriptInformation(int sid)
throws NoSuchScriptException, ExperimentException;
public List<Integer> getAllRTScripts(String rt) throws ExperimentException;
public void removeRTScript(int sid) throws NoSuchScriptException,
InvalidUserException, ExperimentException;
}
| gpl-2.0 |
omegavesko/KupujemProdajemAndroid | app/src/main/java/com/omegavesko/kupujemprodajem/ItemPageData.java | 575 | package com.omegavesko.kupujemprodajem;
import android.content.ClipData;
import android.graphics.Bitmap;
import java.util.List;
/**
* Created by omega_000 on 7/18/2014.
*/
public class ItemPageData
{
public String title;
public String price;
public String viewCount;
public String descriptionHTML;
public List<Bitmap> photos;
public String memberName;
public String memberYesVotes;
public String memberNoVotes;
public String memberLocation;
public Bitmap memberPhoneNumber;
public ItemPageData() {} // empty constructor
}
| gpl-2.0 |
csaldana/ReproductorAndroid | Reproductor/app/src/main/java/com/example/jonathan/reproductor/Cancion1.java | 1419 | package com.example.jonathan.reproductor;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Created by jonathan on 2/04/15.
*/
public class Cancion1 extends Activity {
MediaPlayer player = new MediaPlayer();
Button btnpause, btnstop;
private int Estado = 1;
private final int Reproducir = 1;
private final int Pausar = 2;
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.cancion1);
btnpause = (Button) findViewById(R.id.btnpause);
btnstop = (Button) findViewById(R.id.btnstop);
player = MediaPlayer.create(this, R.drawable.cancion1);
player.setLooping(true);
}
public void onclickpause(View view){
if(view == btnpause){
switch (Estado){
case Reproducir:
player.start();
Estado = Pausar;
btnpause.setText("Pause");
break;
case Pausar:
player.pause();
Estado = Reproducir;
btnpause.setText("Play");
break;
}
}
}
public void onclickstop(View view){
if(view == btnstop){
player.stop();
}
}
}
| gpl-2.0 |
flyingghost/KeepKeepClean | src/main/java/proguard/obfuscate/SimpleNameFactory.java | 4440 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2015 Eric Lafortune @ GuardSquare
*
* 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 proguard.obfuscate;
import java.util.*;
/**
* This <code>NameFactory</code> generates unique short names, using mixed-case
* characters or lower-case characters only.
*
* @author Eric Lafortune
*/
public class SimpleNameFactory implements NameFactory
{
private static final int CHARACTER_COUNT = 26;
private static final List cachedMixedCaseNames = new ArrayList();
private static final List cachedLowerCaseNames = new ArrayList();
private final boolean generateMixedCaseNames;
private int index = 0;
/**
* Creates a new <code>SimpleNameFactory</code> that generates mixed-case names.
*/
public SimpleNameFactory()
{
this(true);
}
/**
* Creates a new <code>SimpleNameFactory</code>.
* @param generateMixedCaseNames a flag to indicate whether the generated
* names will be mixed-case, or lower-case only.
*/
public SimpleNameFactory(boolean generateMixedCaseNames)
{
this.generateMixedCaseNames = generateMixedCaseNames;
}
// Implementations for NameFactory.
public void reset()
{
index = 0;
}
public String nextName()
{
return name(index++);
}
/**
* Returns the name at the given index.
*/
private String name(int index)
{
// Which cache do we need?
List cachedNames = generateMixedCaseNames ?
cachedMixedCaseNames :
cachedLowerCaseNames;
// Do we have the name in the cache?
if (index < cachedNames.size())
{
return (String)cachedNames.get(index);
}
// Create a new name and cache it.
String name = newName(index);
cachedNames.add(index, name);
return name;
}
/**
* Creates and returns the name at the given index.
*/
private String newName(int index)
{
// If we're allowed to generate mixed-case names, we can use twice as
// many characters.
int totalCharacterCount = generateMixedCaseNames ?
2 * CHARACTER_COUNT :
CHARACTER_COUNT;
int baseIndex = index / totalCharacterCount;
int offset = index % totalCharacterCount;
char newChar = charAt(offset);
String newName = baseIndex == 0 ?
new String(new char[] { newChar }) :
(name(baseIndex-1) + newChar);
return newName;
}
/**
* Returns the character with the given index, between 0 and the number of
* acceptable characters.
*/
private char charAt(int index)
{
return (char)((index < CHARACTER_COUNT ? 'a' - 0 :
'A' - CHARACTER_COUNT) + index);
}
public static void main(String[] args)
{
System.out.println("Some mixed-case names:");
printNameSamples(new SimpleNameFactory(true), 60);
System.out.println("Some lower-case names:");
printNameSamples(new SimpleNameFactory(false), 60);
System.out.println("Some more mixed-case names:");
printNameSamples(new SimpleNameFactory(true), 80);
System.out.println("Some more lower-case names:");
printNameSamples(new SimpleNameFactory(false), 80);
}
private static void printNameSamples(SimpleNameFactory factory, int count)
{
for (int counter = 0; counter < count; counter++)
{
System.out.println(" ["+factory.nextName()+"]");
}
}
}
| gpl-2.0 |
maximstewart/UDE | UFM/src/TabSystem/Icon.java | 7371 | package com.itdominator.ufm.TabSystem;
import com.itdominator.ufm.ThumbnailSystem.Thumbnail;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseEvent;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import java.util.Scanner;
import java.io.File;
import javafx.scene.layout.TilePane;
import javafx.scene.control.TextField;
public class Icon extends TabView {
// Class objects
private Thumbnail thumbnail = new Thumbnail();
// Generics
private TilePane tilePane = new TilePane();
private TextField txtDirPath = new TextField();
private VBox icon = new VBox();
private Image img;
private ImageView imgView = new ImageView();
private Label title = new Label("");
private Tooltip tooltip;
private Process pb; // Process runner
private Scanner scanner;
private File file;
private boolean isDir = false, isImage = false;
private String containsStr = System.getProperty("user.home")+ "/Desktop/",
toLaunch = "", runCommand = "", thumbImg = "",
toShellOut = "", toShellExec = "", line = "",
path = "", name = "";
private double orgSceneX, orgSceneY, orgTranslateX, orgTranslateY;
public VBox getIcon() {
return icon;
}
public void createIcon(String pth, String nme) {
icon.getStyleClass().add("icon");
path = pth;
name = nme;
// Creates Icon parts for desktop and sets click actions
getIconImg();
mergeIconParts();
setExecuteModel();
setIconEvents();
}
private void getIconImg() {
thumbnail.setIconImg(path, name);
thumbImg = thumbnail.getIconImg();
if (thumbImg.contains("systemFile.png")) {
if (name.matches("^.*?(doc|docx|odf).*$")) {
imgView.getStyleClass().add("icon-document");
} else if (name.matches("^.*?(pps|ppt|pptx).*$")) {
imgView.getStyleClass().add("icon-presentation");
} else if (name.matches("^.*?(xls|xlsx|csv).*$")) {
imgView.getStyleClass().add("icon-spreadsheet");
} else if (name.matches("^.*?(mp2|mp3|ogg).*$")) {
imgView.getStyleClass().add("icon-music");
} else if (name.matches("^.*?(txt|sh|link).*$")) {
imgView.getStyleClass().add("icon-text");
} else if (name.matches("^.*?(run|bin|jar).*$")) {
imgView.getStyleClass().add("icon-bin");
} else if (name.matches("^.*?(zip|7zip|rar|tar|tar.gz|gz).*$")) {
imgView.getStyleClass().add("icon-compressed");
} else if (name.matches("^.*?(html|xml|htm|css).*$")) {
imgView.getStyleClass().add("icon-web");
} else {
imgView.getStyleClass().add("icon-folder");
}
} else if (name.matches("^.*?(png|svg|jpg|jpeg|tiff|gif).*$")) {
placeImage();
isImage = true;
} else { placeImage(); }
imgView.setCache(true); // Improves responsiveness when there are many images
}
private void placeImage() {
img = new Image("file:" + thumbImg);
imgView.setImage(img);
imgView.setFitWidth(96.0);
imgView.setFitHeight(96.0);
}
private void mergeIconParts() {
title.setMaxWidth(150); // Based On Character Count??
title.setText(name);
tooltip = new Tooltip(name);
tooltip.minHeight(800);
tooltip.minWidth(800);
Tooltip.install(icon, tooltip);
icon.getChildren().addAll(imgView, title); // Insert image and name to icon VBox container
}
private void setExecuteModel() {
// Set file execution for .desktop files and directories else use xdg-open
toLaunch = path;
file = new File(path);
if (path.contains(".desktop")) {
try {
scanner = new Scanner(file);
while(scanner.hasNext()) {
line = scanner.nextLine();
if(line.contains("Exec=")) {
toShellOut = line;
break;
}
}
} catch(Throwable lineErr) {
System.out.println("Failed To Get Exec Info: " + lineErr);
}
if (toShellOut.contains("TryExec="))
toShellOut = toShellOut.replaceAll("TryExec=","");
else if (toShellOut.contains("Exec="))
toShellOut = toShellOut.replaceAll("Exec=","");
runCommand = toShellOut;
} else if (!file.isFile()) {
isDir = true;
}
else {
runCommand = "xdg-open " + toLaunch;
}
}
private void setIconEvents() {
icon.addEventFilter(MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent click) {
if (click.getClickCount() == 2) {
click.consume();
if (isDir == true) {
if (path.equals("..")) {
path = txtDirPath.getText();
int start = 0, end = path.length() - 1;
for (int i=end; i>0; i--) {
if (path.charAt(i) == '/') {
start = i;
break;
}
}
path = path.substring(0, start);
setTabView(path, tilePane, txtDirPath);
} else {
System.out.println(path);
setTabView(path, tilePane, txtDirPath);
}
} else if (isImage == true) {
openImage();
} else {
try {
System.out.println(runCommand);
pb = Runtime.getRuntime().exec(runCommand);
} catch(Throwable imgIOErr) {
System.out.println(imgIOErr);
}
}
}
}
});
}
private void openImage() {
Stage imagStage = new Stage();
Pane pane = new Pane();
ImageView iView = new ImageView(img);
pane.getChildren().add(iView);
iView.setLayoutX(0);
iView.setLayoutY(0);
iView.fitWidthProperty().bind(pane.widthProperty());
iView.fitHeightProperty().bind(pane.heightProperty());
iView.setPreserveRatio(true);
Scene scene = new Scene(pane, 800, 800);
imagStage.setTitle("" + img);
imagStage.setScene(scene);
imagStage.show();
}
protected void setWorkingTab(TilePane tP, TextField tF) {
this.tilePane = tP;
this.txtDirPath = tF;
}
}
| gpl-2.0 |
ntj/ComplexRapidMiner | src/de/tud/inf/operator/io/ComplexArffReader.java | 13853 | package de.tud.inf.operator.io;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.example.table.DataRow;
import com.rapidminer.example.table.DataRowFactory;
import com.rapidminer.example.table.DataRowReader;
import com.rapidminer.example.table.ExampleTable;
import com.rapidminer.example.table.MemoryExampleTable;
import com.rapidminer.operator.io.ArffExampleSource;
import com.rapidminer.operator.io.ArffReader;
import com.rapidminer.parameter.UndefinedParameterError;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.Tools;
import de.tud.inf.example.table.ComplexAttributeDescription;
import de.tud.inf.example.table.ComplexAttributeFactory;
import de.tud.inf.example.table.ComplexExampleTable;
import de.tud.inf.example.table.RelationalAttribute;
public class ComplexArffReader extends ArffReader{
public ComplexArffReader(StreamTokenizer tokenizer,
ArffExampleSource arffES, String parameter_sample_size,
String parameter_sample_ratio, String parameter_datamanagement,
String parameter_local_random_seed,
String parameter_decimal_point_character) {
super(tokenizer, arffES, parameter_sample_size, parameter_sample_ratio,
parameter_datamanagement, parameter_local_random_seed,
parameter_decimal_point_character);
}
/**
* builds two example tables, one with dependency information, one with data information, and merges them to create a complex example table
*/
@Override
public ComplexExampleTable read() throws IOException,UndefinedParameterError {
Tools.getFirstToken(tokenizer);
if(ComplexArffDescription.depAnnotation.equalsIgnoreCase(tokenizer.sval)) {
Tools.getNextToken(tokenizer);
Tools.getLastToken(tokenizer, false);
}
//extract dependency information from following attributes
List<Attribute> depAttributes = readAttributes(true);
if(depAttributes.size() == 0) new IOException("no attribute defintion for dependency relation found");
//check if dependency information only contains attribute names which are allowed in dependency part (recognize misspelled attribute names)
List<String> names = Arrays.asList(new String[]{ComplexArffDescription.depAttName,
ComplexArffDescription.depParamName,
ComplexArffDescription.depClassName,
ComplexArffDescription.depInnerAttributesName,
ComplexArffDescription.depHintName});
for(Attribute a: depAttributes)
if(!names.contains(a.getName()))
throw new IOException("attribute name '" +a.getName()+"' is not allowed in dependency section of complex arff file");
//terminates @data of dependency by checking if there is a @relation - Annotation (thats why additional function)
ExampleTable depEt = readDependencyData(depAttributes);
if("@relation".equalsIgnoreCase(tokenizer.sval)) {
Tools.getNextToken(tokenizer);
Tools.getLastToken(tokenizer, false);
}
List<Attribute> attributes = readAttributes(false);
//now check if dependency information is correct, if records of dependency table contain valid references to attribute names
//1. collect table indexes of attributes (not necessary if table attributes, but with names)
names = new LinkedList<String>();
for(Attribute a: attributes)
names.add(a.getName());
/*
String incorrAtt = "";
boolean corrDeps = true;
for(Attribute a : depEt.getAttributes())
//2. check if attribute could be valid (here: just check if possible nominal values are valid (no dependency information rows)
if(a.getName().equals(ComplexArffDescription.depInnerAttributesName)){
List<String> atts = ((RelationalAttribute)a).getInnerAttributes().get(0).getMapping().getValues();
for(String strA: atts)
if(!names.contains(strA)){
corrDeps = false;
incorrAtt = strA;
break;
}
}
if(corrDeps){ //indicates that dependency section does not contain innerAttriubte stuff, which is invalid (not really)
return buildTable(attributes, depEt);
}
else{
throw new IOException("dependency information attribute contains inncorrect attribute name "+incorrAtt+".");
}
*/
return buildTable(attributes, depEt);
}
/**
* read the data section of an ARFF - file
* @param attributes attribute information of attribute section in arff, which is already read
* @param depEt dependency information example table
* @return ComplexExampleTable which contains attributes + dependency information
* @throws UndefinedParameterError
* @throws IOException
*/
protected ComplexExampleTable buildTable(List<Attribute> attributes,ExampleTable depEt) throws UndefinedParameterError, IOException{
//read the "real" dataset
ExampleTable et = readData(attributes);
List<ComplexAttributeDescription> depList = createValidDependencyList(depEt,et);
try{
//ComplexAttributeConstraintChecker.checkConstraints(et, depList);
for(ComplexAttributeDescription desc : depList)
desc.checkConstraints(et);
}catch(RuntimeException e){
throw new IOException(e.getMessage());
}
return new ComplexExampleTable(et,depList);
}
/***
* @param tokenizer
* @param attributeName name of the relational Attribute
* @param depAttribute is true if relational attribute appears in dependency information of .arff file
* @return relational Attribute with wrapped innerAttributes
*/
@Override
protected Attribute readRelationalAttribute(StreamTokenizer tokenizer, String attributeName, boolean depAttribute) throws IOException{
RelationalAttribute attribute = null;
// get the name
Tools.getFirstToken(tokenizer);
if (tokenizer.ttype == StreamTokenizer.TT_EOF) {
throw new IOException("unexpected end of file in line " + tokenizer.lineno() + ", attribute description expected...");
}
ArrayList<Attribute> innerAttributes = createInnerAttributes(tokenizer,attributeName);
if(innerAttributes != null && innerAttributes.size()>0){
attribute = (RelationalAttribute)AttributeFactory.createAttribute(attributeName,Ontology.RELATIONAL);
attribute.setInnerAttributes(innerAttributes);
return attribute;
}
else throw new IOException("relational attributes should contain at least one inner attribute");
}
/***
* create list of inner attributes of a relational attribute
* @param tokenizer
* @param attributeName name of the relational Attribute
* @return innerAttributes
*/
private ArrayList<Attribute> createInnerAttributes(StreamTokenizer tokenizer, String attributeName) throws IOException{
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
while ("@attribute".equalsIgnoreCase(tokenizer.sval)) {
Attribute attribute = createAttribute(tokenizer,false);
attributes.add(attribute);
}
if("@end".equalsIgnoreCase(tokenizer.sval)){
tokenizer.nextToken();
if(attributeName.equalsIgnoreCase(tokenizer.sval))
return attributes;
else throw new IOException("relational attribute definition is false, should be '@end "+ attributeName +"'");
}
else throw new IOException("relational attribute end definition is false, should be '@end "+ attributeName +"'");
}
private ExampleTable readDependencyData(List<Attribute> depAttributes) throws IOException{
if (!"@data".equalsIgnoreCase(tokenizer.sval)) {
throw new IOException("expected keyword '@data' in line " + tokenizer.lineno());
}
// check attribute number
if (depAttributes.size() == 0) {
throw new IOException("no attributes were declared in the ARFF file, please declare attributes with the '@attribute' keyword.");
}
// fill data table
MemoryExampleTable table = new MemoryExampleTable(depAttributes);
Attribute[] attributeArray = table.getAttributes();
DataRowFactory factory = new DataRowFactory(DataRowFactory.TYPE_INT_ARRAY, '.');
DataRow dataRow = null;
while (((dataRow = createDataRow(tokenizer, true, factory, attributeArray)) != null)) {
table.addDataRow(dataRow);
}
return table;
}
/***
* creates the list of information about valid complex attributes from the two exampleTables
* @param depEt created from description section in ARFF file
* @param et created from relation section in ARFF file
* @return
* @throws IOException
*/
private List<ComplexAttributeDescription> createValidDependencyList(ExampleTable depEt, ExampleTable et) throws IOException{
//collect map String - TableIndexes from et
Map<String,Integer> nameIndexMap = new HashMap<String,Integer>();
for(int i=0;i<et.getNumberOfAttributes();i++)
if(et.getAttribute(i) != null)
nameIndexMap.put(et.getAttribute(i).getName(), et.getAttribute(i).getTableIndex());
List<ComplexAttributeDescription> etDependencies = new ArrayList<ComplexAttributeDescription>();
//name of the current dependency information attribute
String name;
//className, parameter tableIndex list and attribute table index list form a ExampleTableDependency
String symbol;
String attName = null;
String hint;
int[] params = null;
int[] attributes = null;
//identifies the attribute within a relational attribute -> in our case just one nominal attribute is necessary
//and should be the first (and only) innerAttribute in attributes and parameters description
Attribute innerA;
DataRowReader reader = depEt.getDataRowReader();
//example table dependency id = nr of datarow
//complex dataRow information for a concrete relational attribute
double[][] relValues;
int count =0;
Integer attIndex;
//read dataRows of dependency section
while(reader.hasNext()){
DataRow row = reader.next();
count++;
//find symbol
symbol = null; hint = null; params = null; attributes = null;
for(Attribute a1: depEt.getAttributes()){
name = a1.getName();
if(a1.getName().equals(ComplexArffDescription.depClassName) && a1.isNominal())
symbol = a1.getMapping().mapIndex((int)a1.getValue(row));
else if(a1.getName().equals(ComplexArffDescription.depHintName))
hint = a1.getMapping().mapIndex((int)a1.getValue(row));
else if(name.equals(ComplexArffDescription.depAttName)) {
attName = a1.getMapping().mapIndex((int)a1.getValue(row));
}else if( a1.isRelational() && (a1.getName().equals(ComplexArffDescription.depParamName))||(a1.getName().equals(ComplexArffDescription.depInnerAttributesName))){
relValues = row.getRelativeValuesFor(a1.getTableIndex());
if (((RelationalAttribute)a1).getInnerAttributeCount()!=1)
throw new IOException("relational attribute '"+a1.getName()+"' must contain exactly one inner attribute");
//the first (and only) innerAttribute should be a nominal one
innerA = ((RelationalAttribute)a1).getInnerAttributes().get(0);
if(innerA.isNominal()){
//fetch all table indexes of correlating attributes/parameters
if(name.equals(ComplexArffDescription.depParamName)){
//parameters must not be there
if((relValues!=null) && relValues.length>0){
params = new int[relValues.length];
for(int i=0;i<relValues.length;i++){
int tId = (int)relValues[i][0]; //relational parameter attribute just has ONE inner attribute
String tName = innerA.getMapping().mapIndex(tId);
attIndex = nameIndexMap.get(tName);
if(attIndex == null)
throw new IOException("parameter attribute "+ tName + " does not exist in the dataset");
else params[i] = nameIndexMap.get(tName).intValue();
}
}
}else if(name.equals(ComplexArffDescription.depInnerAttributesName))
if((relValues!=null) && relValues.length>0){
attributes = new int[relValues.length];
for(int i=0;i<relValues.length;i++){
int tId = (int)relValues[i][0]; //relational innerAttribute attribute just has ONE inner attribute
String tName = innerA.getMapping().mapIndex(tId);
attIndex = nameIndexMap.get(tName);
if(attIndex == null)
throw new IOException("dependency attribute "+ tName +" does not exist in the dataset");
else attributes[i] = nameIndexMap.get(tName).intValue();
}
}else throw new IOException("dependency data in row "+ count+" must contain at least one inner attribute");
}
else throw new IOException("inner attribute "+ innerA.getName() +" of attribute "+ name +" must be nominal");
}
}
//there should be at least information about correlating attributes
if(attributes != null)
//etDependencies.add(new ComplexAttributeDescription(attributes,params,symbol,attName,hint));
etDependencies.add(ComplexAttributeFactory.createAttributeDescription(attributes, params, symbol, attName, hint));
else throw new IOException("no correlating attributes defined for complex attribute "+ attName);
}
return etDependencies;
}
@Override
protected void findDataDefinitionEnd() throws IOException {
//maybe true is also working
Tools.getLastToken(tokenizer, false);
}
protected boolean AnnotationFound(){
if("@relation".equalsIgnoreCase(tokenizer.sval))
return true;
else return false;
}
}
| gpl-2.0 |
digolo/davmail-enterprise | davmail/src/main/java/davmail/exchange/ews/AttributeOption.java | 1563 | /*
* DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
* Copyright (C) 2010 Mickael Guessant
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package davmail.exchange.ews;
import java.io.IOException;
import java.io.Writer;
/**
* Generic attribute option.
*/
public class AttributeOption extends Option {
protected AttributeOption(String name, String value) {
super(name, value);
}
/**
* @inheritDoc
*/
public void appendTo(StringBuilder buffer) {
buffer.append(' ').append(name).append("=\"").append(value).append('"');
}
/**
* @inheritDoc
*/
@Override
public void write(Writer writer) throws IOException {
writer.write(" ");
writer.write(name);
writer.write("=\"");
writer.write(value);
writer.write("\"");
}
}
| gpl-2.0 |
humb1t/FairOfMinds | src/main/java/com/nipu/ui/model/AnswerModel.java | 740 | package com.nipu.ui.model;
import com.nipu.domain.Answer;
/**
* Created by humb1t on 16.02.14.
*/
public class AnswerModel
{
private String id;
private String text;
public AnswerModel(String text)
{
this.text = text;
}
public AnswerModel(Answer answer)
{
this.id = String.valueOf(answer.getId());
this.text = answer.getText();
}
public String getId()
{
return id;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
@Override
public String toString()
{
return "AnswerModel{" +
"text='" + text + '\'' +
'}';
}
}
| gpl-2.0 |
jefferssongalvao/AutoBoard | app/src/main/java/br/com/autoboard/autoboard/Configuracoes.java | 10728 | package br.com.autoboard.autoboard;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import java.util.List;
/**
* A {@link PreferenceActivity} that presents a set of application settings. On
* handset devices, settings are presented as a single list. On tablets,
* settings are split by category, with category headers shown to the left of
* the list of settings.
* <p/>
* See <a href="http://developer.android.com/design/patterns/settings.html">
* Android Design: Settings</a> for design guidelines and the <a
* href="http://developer.android.com/guide/topics/ui/settings.html">Settings
* API Guide</a> for more information on developing a Settings UI.
*/
public class Configuracoes extends PreferenceActivity {
/**
* Determines whether to always show the simplified settings UI, where
* settings are presented in a single list. When false, settings are shown
* as a master/detail two-pane view on tablets. When true, a single pane is
* shown on tablets.
*/
private static final boolean ALWAYS_SIMPLE_PREFS = false;
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSimplePreferencesScreen();
}
/**
* Shows the simplified settings UI if the device configuration if the
* device configuration dictates that a simplified, single-pane UI should be
* shown.
*/
private void setupSimplePreferencesScreen() {
if (!isSimplePreferences(this)) {
return;
}
// In the simplified UI, fragments are not used at all and we instead
// use the older PreferenceActivity APIs.
// Add 'general' preferences.
addPreferencesFromResource(R.xml.configuracoes);
// Add 'notifications' preferences, and a corresponding header.
PreferenceCategory fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_notifications);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_notification);
// Add 'data and sync' preferences, and a corresponding header.
fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_data_sync);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_data_sync);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
/**
* {@inheritDoc}
*/
@Override
public boolean onIsMultiPane() {
return isXLargeTablet(this) && !isSimplePreferences(this);
}
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Determines whether the simplified settings UI should be shown. This is
* true if this is forced via {@link #ALWAYS_SIMPLE_PREFS}, or the device
* doesn't have newer APIs like {@link PreferenceFragment}, or the device
* doesn't have an extra-large screen. In these cases, a single-pane
* "simplified" settings UI should be shown.
*/
private static boolean isSimplePreferences(Context context) {
return ALWAYS_SIMPLE_PREFS
|| Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
|| !isXLargeTablet(context);
}
/**
* {@inheritDoc}
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
if (!isSimplePreferences(this)) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
}
/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
}
}
/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
}
}
| gpl-2.0 |
langmo/youscope | plugins/show-measurement-information/src/main/java/org/youscope/plugin/showmeasurementinformation/ShowMeasurementInformationFactory.java | 2289 | /*******************************************************************************
* 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.plugin.showmeasurementinformation;
import java.awt.Desktop;
import org.youscope.addon.AddonException;
import org.youscope.addon.AddonMetadata;
import org.youscope.addon.AddonUI;
import org.youscope.addon.postprocessing.PostProcessorAddonFactory;
import org.youscope.clientinterfaces.YouScopeClient;
import org.youscope.common.saving.MeasurementFileLocations;
import org.youscope.serverinterfaces.YouScopeServer;
/**
* @author Moritz Lang
*
*/
public class ShowMeasurementInformationFactory implements PostProcessorAddonFactory
{
@Override
public AddonUI<? extends AddonMetadata> createPostProcessorUI(String typeIdentifier, YouScopeClient client,
YouScopeServer server, MeasurementFileLocations measurementFileLocations) throws AddonException {
if(ShowMeasurementInformation.TYPE_IDENTIFIER.equals(typeIdentifier))
{
return new ShowMeasurementInformation(client, server, measurementFileLocations.getHtmlInformationPath());
}
throw new AddonException("Type identifer "+typeIdentifier+" not supported by this factory.");
}
@Override
public String[] getSupportedTypeIdentifiers()
{
if(Desktop.isDesktopSupported())
return new String[]{ShowMeasurementInformation.TYPE_IDENTIFIER};
return new String[0];
}
@Override
public boolean isSupportingTypeIdentifier(String ID)
{
if(ShowMeasurementInformation.TYPE_IDENTIFIER.equals(ID))
return true;
return false;
}
@Override
public AddonMetadata getPostProcessorMetadata(String typeIdentifier) throws AddonException {
if(ShowMeasurementInformation.TYPE_IDENTIFIER.equals(typeIdentifier))
return ShowMeasurementInformation.getMetadata();
throw new AddonException("Type identifer "+typeIdentifier+" not supported by this factory.");
}
}
| gpl-2.0 |
bdheeman/jforex | Strategies/sto_rc2.java | 15360 | //
// Copyright (c) 2012, Balwinder S "bdheeman" Dheeman <bdheeman/AT/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 2 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc., 675
// Mass Ave, Cambridge, MA 02139, USA.
//
package jforex.strategies.bdheeman;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IIndicators.AppliedPrice;
import com.dukascopy.api.IIndicators.MaType;
import com.dukascopy.api.indicators.IIndicator;
public class sto_rc2 implements IStrategy {
private final String id = this.getClass().getName().substring(27, 31).toUpperCase();
private IAccount account;
private IConsole console;
private IEngine engine;
private IHistory history;
private IIndicators indicators;
private JFUtils utils;
@Configurable("Instrument")
public Instrument instrument = Instrument.EURUSD;
@Configurable("Time Frame")
public Period period = Period.ONE_HOUR;
@Configurable("Indicator Filter")
public Filter indicatorFilter = Filter.ALL_FLATS;
//@Configurable("Applied price")
public AppliedPrice appliedPrice = AppliedPrice.CLOSE;
//@Configurable("Offer side")
public OfferSide offerSide = OfferSide.BID;
@Configurable("STOCH Fast K period")
public int fastKPeriod = 3;
@Configurable("STOCH Slow K period")
public int slowKPeriod = 5;
@Configurable("STOCH K MA Type")
public MaType slowKMaType = MaType.SMA;
@Configurable("STOCH Slow D period")
public int slowDPeriod = 5;
@Configurable("STOCH D MA Type")
public MaType slowDMaType = MaType.SMA;
@Configurable(value="STOCH Short period", readOnly=true)
public Period shortPeriod = period;
@Configurable("STOCH Long period")
public Period longPeriod = Period.DAILY;
@Configurable("Swing High/Low period")
public int swingPeriod = 10;
@Configurable(value="Risk (percent)", stepSize=0.01)
public double riskPercent = 2.0;
//@Configurable("Amount")
//public double amount = 0.02;
@Configurable(value="Slippage (pips)", stepSize=0.1)
public double slippage = 0;
@Configurable(value="Minimal Take Profit (pips)", stepSize=0.5)
public int takeProfitPips = 10;
@Configurable(value="Minimal Stop Loss (pips)", stepSize=0.5)
public int stopLossPips = 10;
@Configurable(value="Close all on Stop? (No)")
public boolean closeAllOnStop = false;
//@Configurable(value="Verbose/Debug? (No)")
public boolean verbose = false;
@Configurable("Start Time (GMT)")
public String startAt = "00:00";
@Configurable("Stop Time (GMT)")
public String stopAt = "20:00";
private IOrder order = null, prevOrder = null;
private int counter = 0;
private final static double FACTOR = 0.236;
private final static double OVERBOUGHT = 80;
private final static double OVERSOLD = 20;
private int hourFrom = 0, minFrom = 0;
private int hourTo = 0, minTo = 0;
private long time;
@Override
public void onStart(IContext context) throws JFException {
account = context.getAccount();
console = context.getConsole();
engine = context.getEngine();
history = context.getHistory();
indicators = context.getIndicators();
utils = context.getUtils();
// re-evaluate configurables
hourFrom = Integer.valueOf(startAt.replaceAll("[:.][0-9]+$", ""));
minFrom = Integer.valueOf(startAt.replaceAll("^[0-9]+[:.]", ""));
hourTo = Integer.valueOf(stopAt.replaceAll("[:.][0-9]+$", ""));
minTo = Integer.valueOf(stopAt.replaceAll("^[0-9]+[:.]", ""));
shortPeriod = period;
// Add indicators for visual testing
IChart chart = context.getChart(instrument);
if (chart != null && engine.getType() == IEngine.Type.TEST) {
chart.addIndicator(indicators.getIndicator("STOCH"), new Object[] {fastKPeriod, slowKPeriod, slowKMaType.ordinal(), slowDPeriod, slowDMaType.ordinal()});
}
// Recall existing; last position, if any
this.order = null;
for (IOrder order : engine.getOrders(instrument)) {
if(order.getLabel().substring(0,id.length()).equals(id)) {
if (this.order != null) {
//console.getWarn().println(this.order.getLabel() +" Order IGNORED, manage it manually");
console.getOut().println(this.order.getLabel() +" <WARN> Order IGNORED, manage it manually");
}
this.order = order;
counter = Integer.valueOf(order.getLabel().replaceAll("^.{8,8}",""));
//console.getNotif().println(order.getLabel() +" Order FOUND, shall try handling it");
console.getOut().println(order.getLabel() +" <NOTICE> Order FOUND, shall try handling it");
}
}
if (isActive(order))
//console.getInfo().println(order.getLabel() +" ORDER_FOUND_OK");
console.getOut().println(order.getLabel() +" <INFO> ORDER_FOUND_OK");
}
@Override
public void onAccount(IAccount account) throws JFException {
}
@Override
public void onMessage(IMessage message) throws JFException {
// Print messages, but related to own orders
if (message.getOrder() != null && message.getOrder().getLabel().substring(0,id.length()).equals(id)) {
String orderLabel = message.getOrder().getLabel();
IMessage.Type messageType = message.getType();
switch (messageType) {
// Ignore the following
case ORDER_FILL_OK:
case ORDER_CHANGED_OK:
break;
case ORDER_SUBMIT_OK:
case ORDER_CLOSE_OK:
case ORDERS_MERGE_OK:
//console.getInfo().println(orderLabel +" "+ messageType);
console.getOut().println(orderLabel +" <INFO> "+ messageType);
break;
case NOTIFICATION:
//console.getNotif().println(orderLabel +" "+ message.getContent().replaceAll(".*-Order", "Order"));
console.getOut().println(orderLabel +" <NOTICE> "+ message.getContent().replaceAll(".*-Order", "Order"));
break;
case ORDER_CHANGED_REJECTED:
case ORDER_CLOSE_REJECTED:
case ORDER_FILL_REJECTED:
case ORDER_SUBMIT_REJECTED:
case ORDERS_MERGE_REJECTED:
//console.getWarn().println(orderLabel +" "+ messageType);
console.getOut().println(orderLabel +" <WARN> "+ messageType);
break;
default:
//console.getErr().println(orderLabel +" *"+ messageType +"* "+ message.getContent());
console.getOut().println(orderLabel +" *"+ messageType +"* "+ message.getContent());
break;
}
}
}
@Override
public void onStop() throws JFException {
if (!closeAllOnStop)
return;
// Close all orders
for (IOrder order : engine.getOrders(instrument)) {
if(order.getLabel().substring(0,id.length()).equals(id))
order.close();
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException {
if (instrument != this.instrument) {
return;
}
}
@Override
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if (instrument != this.instrument || period != this.period) {
return;
}
if (time == askBar.getTime()) {
return;
}
time = askBar.getTime();
if (!isActive(order)) {
order = null;
}
int K = 0;
int D = 1;
double[][] stochLong = indicators.stoch(instrument, longPeriod, offerSide, fastKPeriod, slowKPeriod, slowKMaType, slowDPeriod, slowDMaType, indicatorFilter, 2, askBar.getTime(), 0);
double[][] stochShort = indicators.stoch(instrument, shortPeriod, offerSide, fastKPeriod, slowKPeriod, slowKMaType, slowDPeriod, slowDMaType, indicatorFilter, 2, askBar.getTime(), 0);
double high = indicators.max(instrument, period, offerSide, AppliedPrice.HIGH, swingPeriod, indicatorFilter, 1, askBar.getTime(), 0)[0];
double low = indicators.min(instrument, period, offerSide, AppliedPrice.LOW, swingPeriod, indicatorFilter, 1, askBar.getTime(), 0)[0];
boolean isBuySignal = false;
boolean isSellSignal = false;
if (stochLong[K][0] > stochLong[D][0] && stochShort[K][0] > stochShort[D][0]
&& stochLong[K][0] < OVERBOUGHT && stochLong[D][0] < OVERBOUGHT && stochShort[K][0] < OVERBOUGHT && stochShort[D][0] < OVERBOUGHT) {
isBuySignal = true;
} else if (stochLong[K][0] < stochLong[D][0] && stochShort[K][0] < stochShort[D][0]
&& stochLong[K][0] > OVERSOLD && stochLong[D][0] > OVERSOLD && stochShort[K][0] > OVERSOLD && stochShort[D][0] > OVERSOLD) {
isSellSignal = true;
}
// BUY
if (isBuySignal) {
if (order == null || !order.isLong()) {
closeOrder(order);
if(isRightTime(askBar.getTime(), hourFrom, minFrom, hourTo, minTo)) {
double stopLoss = low;
double myStopLoss = bidBar.getOpen() - getPipPrice(stopLossPips);
double takeProfit = getRoundedPrice(bidBar.getOpen() + (high - low) * FACTOR);
double myTakeProfit = bidBar.getOpen() + getPipPrice(takeProfitPips);
stopLoss = Math.min(stopLoss, myStopLoss);
takeProfit = Math.max(takeProfit, myTakeProfit);
if (getPricePips(takeProfit - bidBar.getOpen()) >= FACTOR * 10) {
order = submitOrder(instrument, OrderCommand.BUY, stopLoss, takeProfit);
}
}
}
// SELL
} else if (isSellSignal) {
if (order == null || order.isLong()) {
closeOrder(order);
if(isRightTime(askBar.getTime(), hourFrom, minFrom, hourTo, minTo)) {
double stopLoss = high;
double myStopLoss = askBar.getOpen() + getPipPrice(stopLossPips);
double takeProfit = getRoundedPrice(askBar.getOpen() - (high - low) * FACTOR);
double myTakeProfit = askBar.getOpen() - getPipPrice(takeProfitPips);
stopLoss = Math.max(stopLoss, myStopLoss);
takeProfit = Math.min(takeProfit, myTakeProfit);
if (getPricePips(askBar.getOpen() - takeProfit) >= FACTOR * 10) {
order = submitOrder(instrument, OrderCommand.SELL, stopLoss, takeProfit);
}
}
}
}
if (prevOrder != null) {
//prevOrder.waitForUpdate(200, IOrder.State.CLOSED);
prevOrder.waitForUpdate(200);
switch (prevOrder.getState()) {
case CREATED:
case CLOSED:
this.prevOrder = null;
break;
default:
//console.getWarn().println(prevOrder.getLabel() +" Closed failed!");
console.getOut().println(prevOrder.getLabel() +" <WARN> Closed failed!");
}
}
}
private IOrder submitOrder(Instrument instrument, OrderCommand orderCommand, double stopLossPrice, double takeProfitPrice) throws JFException {
double amount = getAmount(account, instrument, riskPercent, getPipPrice(stopLossPips));
return engine.submitOrder(getLabel(instrument), instrument, orderCommand, amount, 0, slippage, stopLossPrice, takeProfitPrice);
}
protected void closeOrder(IOrder order) throws JFException {
if (order != null && isActive(order)) {
order.close();
prevOrder = order;
order = null;
}
}
protected boolean isActive(IOrder order) throws JFException {
if (order == null)
return false;
IOrder.State state = order.getState();
return state != IOrder.State.CLOSED && state != IOrder.State.CREATED && state != IOrder.State.CANCELED ? true : false;
}
protected boolean isRightTime(long time, int fromHour, int fromMin, int toHour, int toMin) {
Calendar start = new GregorianCalendar();
start.setTimeZone(TimeZone.getTimeZone("GMT"));
start.setTimeInMillis(time);
start.set(Calendar.HOUR_OF_DAY, fromHour);
start.set(Calendar.MINUTE, fromMin);
Calendar stop = new GregorianCalendar();
stop.setTimeZone(TimeZone.getTimeZone("GMT"));
stop.setTimeInMillis(time);
stop.set(Calendar.HOUR_OF_DAY, toHour);
stop.set(Calendar.MINUTE, toMin);
return start.getTimeInMillis() <= time && time <= stop.getTimeInMillis() ? true : false;
}
protected double getAmount(IAccount account, Instrument instrument, double riskPercent, double stopLossPrice) throws JFException {
double riskAmount = account.getEquity() * riskPercent / 100;
double pipQuote = utils.convertPipToCurrency(instrument, account.getCurrency());
double pipBase = instrument.getPipValue();
double factor = pipBase / pipQuote;
double riskPips = riskAmount * factor;
// volumeBase * stopLossPrice = riskPips
double volumeBase = riskPips / stopLossPrice;
double volumeBaseInMil = volumeBase / 1000000;
return getRoundedPrice(volumeBaseInMil);
}
protected String getLabel(Instrument instrument) {
return id + instrument.name().substring(0, 2) + instrument.name().substring(3, 5) + String.format("%8d", ++counter).replace(" ", "0");
}
protected double getPipPrice(double pips) {
return pips * this.instrument.getPipValue();
}
protected double getPricePips(double price) {
return price / this.instrument.getPipValue();
}
protected double getRoundedPips(double pips) {
BigDecimal bd = new BigDecimal(pips);
bd = bd.setScale(1, RoundingMode.HALF_UP);
return bd.doubleValue();
}
protected double getRoundedPrice(double price) {
BigDecimal bd = new BigDecimal(price);
bd = bd.setScale(this.instrument.getPipScale() + 1, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
| gpl-2.0 |
Buggaboo/xplatform | nl.sison.dsl.mobgen.JsonGen/src-gen/nl/sison/dsl/mobgen/serializer/JsonGenSemanticSequencer.java | 4276 | package nl.sison.dsl.mobgen.serializer;
import com.google.inject.Inject;
import com.google.inject.Provider;
import nl.sison.dsl.mobgen.jsonGen.ExJsonDateTime;
import nl.sison.dsl.mobgen.jsonGen.ExJsonEnum;
import nl.sison.dsl.mobgen.jsonGen.JsonArray;
import nl.sison.dsl.mobgen.jsonGen.JsonGenPackage;
import nl.sison.dsl.mobgen.jsonGen.JsonObject;
import nl.sison.dsl.mobgen.jsonGen.JsonValue;
import nl.sison.dsl.mobgen.jsonGen.Member;
import nl.sison.dsl.mobgen.services.JsonGenGrammarAccess;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.serializer.acceptor.ISemanticSequenceAcceptor;
import org.eclipse.xtext.serializer.diagnostic.ISemanticSequencerDiagnosticProvider;
import org.eclipse.xtext.serializer.diagnostic.ISerializationDiagnostic.Acceptor;
import org.eclipse.xtext.serializer.sequencer.AbstractDelegatingSemanticSequencer;
import org.eclipse.xtext.serializer.sequencer.GenericSequencer;
import org.eclipse.xtext.serializer.sequencer.ISemanticSequencer;
import org.eclipse.xtext.serializer.sequencer.ITransientValueService;
@SuppressWarnings("all")
public class JsonGenSemanticSequencer extends AbstractDelegatingSemanticSequencer {
@Inject
private JsonGenGrammarAccess grammarAccess;
public void createSequence(EObject context, EObject semanticObject) {
if(semanticObject.eClass().getEPackage() == JsonGenPackage.eINSTANCE) switch(semanticObject.eClass().getClassifierID()) {
case JsonGenPackage.EX_JSON_DATE_TIME:
if(context == grammarAccess.getExJsonDateTimeRule()) {
sequence_ExJsonDateTime(context, (ExJsonDateTime) semanticObject);
return;
}
else break;
case JsonGenPackage.EX_JSON_ENUM:
if(context == grammarAccess.getExJsonEnumRule()) {
sequence_ExJsonEnum(context, (ExJsonEnum) semanticObject);
return;
}
else break;
case JsonGenPackage.JSON_ARRAY:
if(context == grammarAccess.getJsonArrayRule()) {
sequence_JsonArray(context, (JsonArray) semanticObject);
return;
}
else break;
case JsonGenPackage.JSON_OBJECT:
if(context == grammarAccess.getJsonObjectRule()) {
sequence_JsonObject(context, (JsonObject) semanticObject);
return;
}
else break;
case JsonGenPackage.JSON_VALUE:
if(context == grammarAccess.getJsonValueRule()) {
sequence_JsonValue(context, (JsonValue) semanticObject);
return;
}
else break;
case JsonGenPackage.MEMBER:
if(context == grammarAccess.getMemberRule()) {
sequence_Member(context, (Member) semanticObject);
return;
}
else break;
}
if (errorAcceptor != null) errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context));
}
/**
* Constraint:
* (utc?='UTC' | format=STRING)
*/
protected void sequence_ExJsonDateTime(EObject context, ExJsonDateTime semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Constraint:
* (values+=STRING values+=STRING*)
*/
protected void sequence_ExJsonEnum(EObject context, ExJsonEnum semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Constraint:
* (values+=JsonValue values+=JsonValue*)
*/
protected void sequence_JsonArray(EObject context, JsonArray semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Constraint:
* (members+=Member members+=Member*)
*/
protected void sequence_JsonObject(EObject context, JsonObject semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Constraint:
* (
* obj=JsonObject |
* str=STRING |
* array=JsonArray |
* bool?=JSON_BOOLEAN |
* null?=JSON_NULL |
* int?=INT |
* float?=JSON_FLOAT |
* strFromEnum=ExJsonEnum |
* datetime=ExJsonDateTime
* )
*/
protected void sequence_JsonValue(EObject context, JsonValue semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Constraint:
* (optional?='?'? key=STRING value=JsonValue)
*/
protected void sequence_Member(EObject context, Member semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
}
| gpl-2.0 |
Sameer-Deswal/freetam | src/main/java/com/freetam/timetable/app/TimetableBenchmarkApp.java | 1272 | /*
* Copyright 2010 JBoss Inc
*
* 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.freetam.timetable.app;
import com.freetam.common.app.CommonBenchmarkApp;
public class TimetableBenchmarkApp extends CommonBenchmarkApp {
public static void main(final String[] args) {
new TimetableBenchmarkApp().buildAndBenchmark(args);
}
public TimetableBenchmarkApp() {
super(
new ArgOption("default",
"com/freetam/timetable/benchmark/curriculumCourseBenchmarkConfig.xml"),
new ArgOption("stepLimit",
"com/freetam/timetable/benchmark/curriculumCourseStepLimitBenchmarkConfig.xml"),
new ArgOption("template",
"com/freetam/timetable/benchmark/curriculumCourseBenchmarkConfigTemplate.xml.ftl", true)
);
}
}
| gpl-2.0 |
lamsfoundation/lams | lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieApplicationException.java | 1490 | /****************************************************************
* 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 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.scratchie.service;
public class ScratchieApplicationException extends Exception {
public ScratchieApplicationException() {
super();
}
public ScratchieApplicationException(String message, Throwable cause) {
super(message, cause);
}
public ScratchieApplicationException(String message) {
super(message);
}
public ScratchieApplicationException(Throwable cause) {
super(cause);
}
}
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/spring/org/springframework/web/servlet/mvc/support/ControllerClassNameHandlerMapping.java | 7037 | /*
* Copyright 2002-2012 the original author or 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.springframework.web.servlet.mvc.support;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Implementation of {@link org.springframework.web.servlet.HandlerMapping} that
* follows a simple convention for generating URL path mappings from the <i>class names</i>
* of registered {@link org.springframework.web.servlet.mvc.Controller} beans
* as well as {@code @Controller} annotated beans.
*
* <p>For simple {@link org.springframework.web.servlet.mvc.Controller} implementations
* (those that handle a single request type), the convention is to take the
* {@link ClassUtils#getShortName short name} of the {@code Class},
* remove the 'Controller' suffix if it exists and return the remaining text, lower-cased,
* as the mapping, with a leading {@code /}. For example:
* <ul>
* <li>{@code WelcomeController} -> {@code /welcome*}</li>
* <li>{@code HomeController} -> {@code /home*}</li>
* </ul>
*
* <p>For {@code MultiActionController MultiActionControllers} and {@code @Controller}
* beans, a similar mapping is registered, except that all sub-paths are registered
* using the trailing wildcard pattern {@code /*}. For example:
* <ul>
* <li>{@code WelcomeController} -> {@code /welcome}, {@code /welcome/*}</li>
* <li>{@code CatalogController} -> {@code /catalog}, {@code /catalog/*}</li>
* </ul>
*
* <p>For {@code MultiActionController} it is often useful to use
* this mapping strategy in conjunction with the
* {@link org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver}.
*
* <p>Thanks to Warren Oliver for suggesting the "caseSensitive", "pathPrefix"
* and "basePackage" properties which have been added in Spring 2.5.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
* @see org.springframework.web.servlet.mvc.Controller
* @see org.springframework.web.servlet.mvc.multiaction.MultiActionController
* @deprecated as of 4.3, in favor of annotation-driven handler methods
*/
@Deprecated
public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHandlerMapping {
/**
* Common suffix at the end of controller implementation classes.
* Removed when generating the URL path.
*/
private static final String CONTROLLER_SUFFIX = "Controller";
private boolean caseSensitive = false;
private String pathPrefix;
private String basePackage;
/**
* Set whether to apply case sensitivity to the generated paths,
* e.g. turning the class name "BuyForm" into "buyForm".
* <p>Default is "false", using pure lower case paths,
* e.g. turning the class name "BuyForm" into "buyform".
*/
public void setCaseSensitive(boolean caseSensitive) {
this.caseSensitive = caseSensitive;
}
/**
* Specify a prefix to prepend to the path generated from the controller name.
* <p>Default is a plain slash ("/"). A path like "/mymodule" can be specified
* in order to have controller path mappings prefixed with that path, e.g.
* "/mymodule/buyform" instead of "/buyform" for the class name "BuyForm".
*/
public void setPathPrefix(String prefixPath) {
this.pathPrefix = prefixPath;
if (StringUtils.hasLength(this.pathPrefix)) {
if (!this.pathPrefix.startsWith("/")) {
this.pathPrefix = "/" + this.pathPrefix;
}
if (this.pathPrefix.endsWith("/")) {
this.pathPrefix = this.pathPrefix.substring(0, this.pathPrefix.length() - 1);
}
}
}
/**
* Set the base package to be used for generating path mappings,
* including all subpackages underneath this packages as path elements.
* <p>Default is {@code null}, using the short class name for the
* generated path, with the controller's package not represented in the path.
* Specify a base package like "com.mycompany.myapp" to include subpackages
* within that base package as path elements, e.g. generating the path
* "/mymodule/buyform" for the class name "com.mycompany.myapp.mymodule.BuyForm".
* Subpackage hierarchies are represented as individual path elements,
* e.g. "/mymodule/mysubmodule/buyform" for the class name
* "com.mycompany.myapp.mymodule.mysubmodule.BuyForm".
*/
public void setBasePackage(String basePackage) {
this.basePackage = basePackage;
if (StringUtils.hasLength(this.basePackage) && !this.basePackage.endsWith(".")) {
this.basePackage = this.basePackage + ".";
}
}
@Override
protected String[] buildUrlsForHandler(String beanName, Class<?> beanClass) {
return generatePathMappings(beanClass);
}
/**
* Generate the actual URL paths for the given controller class.
* <p>Subclasses may choose to customize the paths that are generated
* by overriding this method.
* @param beanClass the controller bean class to generate a mapping for
* @return the URL path mappings for the given controller
*/
protected String[] generatePathMappings(Class<?> beanClass) {
StringBuilder pathMapping = buildPathPrefix(beanClass);
String className = ClassUtils.getShortName(beanClass);
String path = (className.endsWith(CONTROLLER_SUFFIX) ?
className.substring(0, className.lastIndexOf(CONTROLLER_SUFFIX)) : className);
if (path.length() > 0) {
if (this.caseSensitive) {
pathMapping.append(path.substring(0, 1).toLowerCase()).append(path.substring(1));
}
else {
pathMapping.append(path.toLowerCase());
}
}
if (isMultiActionControllerType(beanClass)) {
return new String[] {pathMapping.toString(), pathMapping.toString() + "/*"};
}
else {
return new String[] {pathMapping.toString() + "*"};
}
}
/**
* Build a path prefix for the given controller bean class.
* @param beanClass the controller bean class to generate a mapping for
* @return the path prefix, potentially including subpackage names as path elements
*/
private StringBuilder buildPathPrefix(Class<?> beanClass) {
StringBuilder pathMapping = new StringBuilder();
if (this.pathPrefix != null) {
pathMapping.append(this.pathPrefix);
pathMapping.append("/");
}
else {
pathMapping.append("/");
}
if (this.basePackage != null) {
String packageName = ClassUtils.getPackageName(beanClass);
if (packageName.startsWith(this.basePackage)) {
String subPackage = packageName.substring(this.basePackage.length()).replace('.', '/');
pathMapping.append(this.caseSensitive ? subPackage : subPackage.toLowerCase());
pathMapping.append("/");
}
}
return pathMapping;
}
}
| gpl-2.0 |
tud-stg-lang/caesar-compiler | src/org/caesarj/compiler/aspectj/CaesarSuperPointcut.java | 2344 | /*
* This source file is part of CaesarJ
* For the latest info, see http://caesarj.org/
*
* Copyright � 2003-2005
* Darmstadt University of Technology, Software Technology Group
* Also see acknowledgements in readme.txt
*
* 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
*
* $Id: CaesarSuperPointcut.java,v 1.1 2006-05-31 13:23:43 thiago Exp $
*/
package org.caesarj.compiler.aspectj;
import org.aspectj.bridge.IMessage;
import org.aspectj.weaver.TypeX;
import org.aspectj.weaver.patterns.Bindings;
import org.aspectj.weaver.patterns.IScope;
import org.aspectj.weaver.patterns.ReferencePointcut;
import org.aspectj.weaver.patterns.TypePatternList;
/**
* This class represents a reference to a pointcut in the super class.
*
* It is created by the parser when something like this is found :
*
* public cclass ClsB extends ClsA {
* pointcut p() : super.apointcut() || ...;
* }
*
* @author Thiago Tonelli Bartolomei <thiago.bartolomei@gmail.com>
*/
public class CaesarSuperPointcut extends ReferencePointcut {
public CaesarSuperPointcut(String name, TypePatternList arguments) {
super((TypeX) null, name, arguments);
}
/**
* Resolve the bindings. If we are in a caesar scope, we try to
* resolve the pointcut in the super type. Otherwise, we just use
* the regular resolving.
*/
public void resolveBindings(IScope scope, Bindings bindings) {
if (scope instanceof CaesarScope) {
onType = ((CaesarScope) scope).getSuperRegisterType();
}
try {
super.resolveBindings(scope, bindings);
} catch (Exception e) {
onType = null;
scope.message(IMessage.ERROR, this, "Can't find referenced pointcut");
return;
}
}
}
| gpl-2.0 |
lamsfoundation/lams | 3rdParty_sources/hibernate-core/org/hibernate/query/criteria/internal/predicate/BooleanStaticAssertionPredicate.java | 1310 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.query.criteria.internal.predicate;
import java.io.Serializable;
import org.hibernate.query.criteria.internal.CriteriaBuilderImpl;
import org.hibernate.query.criteria.internal.ParameterRegistry;
import org.hibernate.query.criteria.internal.compile.RenderingContext;
/**
* Predicate used to assert a static boolean condition.
*
* @author Steve Ebersole
*/
public class BooleanStaticAssertionPredicate
extends AbstractSimplePredicate
implements Serializable {
private final Boolean assertedValue;
public BooleanStaticAssertionPredicate(
CriteriaBuilderImpl criteriaBuilder,
Boolean assertedValue) {
super( criteriaBuilder );
this.assertedValue = assertedValue;
}
public Boolean getAssertedValue() {
return assertedValue;
}
@Override
public void registerParameters(ParameterRegistry registry) {
// nada
}
@Override
public String render(boolean isNegated, RenderingContext renderingContext) {
boolean isTrue = getAssertedValue();
if ( isNegated ) {
isTrue = !isTrue;
}
return isTrue ? "1=1" : "0=1";
}
}
| gpl-2.0 |
YuKitAs/battle-of-elements | src/test/java/xigua/battle/of/elements/logic/battle/BattleTest.java | 75 | package xigua.battle.of.elements.logic.battle;
public class BattleTest {
} | gpl-3.0 |
leapcode/bitmask_android | app/src/main/java/de/blinkt/openvpn/core/LogItem.java | 13036 | /*
* Copyright (c) 2012-2016 Arne Schwabe
* Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt
*/
package de.blinkt.openvpn.core;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources.NotFoundException;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.FormatFlagsConversionMismatchException;
import java.util.Locale;
import java.util.UnknownFormatConversionException;
import se.leap.bitmaskclient.R;
/**
* Created by arne on 24.04.16.
*/
public class LogItem implements Parcelable {
private Object[] mArgs = null;
private String mMessage = null;
private int mRessourceId;
// Default log priority
VpnStatus.LogLevel mLevel = VpnStatus.LogLevel.INFO;
private VpnStatus.ErrorType errorType = VpnStatus.ErrorType.UNKNOWN;
private long logtime = System.currentTimeMillis();
private int mVerbosityLevel = -1;
private LogItem(int ressourceId, Object[] args) {
mRessourceId = ressourceId;
mArgs = args;
}
public LogItem(VpnStatus.LogLevel level, int verblevel, String message) {
mMessage = message;
mLevel = level;
mVerbosityLevel = verblevel;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeArray(mArgs);
dest.writeString(mMessage);
dest.writeInt(mRessourceId);
dest.writeInt(mLevel.getInt());
dest.writeInt(mVerbosityLevel);
dest.writeLong(logtime);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof LogItem))
return obj.equals(this);
LogItem other = (LogItem) obj;
return Arrays.equals(mArgs, other.mArgs) &&
((other.mMessage == null && mMessage == other.mMessage) ||
mMessage.equals(other.mMessage)) &&
mRessourceId == other.mRessourceId &&
((mLevel == null && other.mLevel == mLevel) ||
other.mLevel.equals(mLevel)) &&
mVerbosityLevel == other.mVerbosityLevel &&
logtime == other.logtime;
}
public byte[] getMarschaledBytes() throws UnsupportedEncodingException, BufferOverflowException {
ByteBuffer bb = ByteBuffer.allocate(16384);
bb.put((byte) 0x0); //version
bb.putLong(logtime); //8
bb.putInt(mVerbosityLevel); //4
bb.putInt(mLevel.getInt());
bb.putInt(mRessourceId);
if (mMessage == null || mMessage.length() == 0) {
bb.putInt(0);
} else {
marschalString(mMessage, bb);
}
if (mArgs == null || mArgs.length == 0) {
bb.putInt(0);
} else {
bb.putInt(mArgs.length);
for (Object o : mArgs) {
if (o instanceof String) {
bb.putChar('s');
marschalString((String) o, bb);
} else if (o instanceof Integer) {
bb.putChar('i');
bb.putInt((Integer) o);
} else if (o instanceof Float) {
bb.putChar('f');
bb.putFloat((Float) o);
} else if (o instanceof Double) {
bb.putChar('d');
bb.putDouble((Double) o);
} else if (o instanceof Long) {
bb.putChar('l');
bb.putLong((Long) o);
} else if (o == null) {
bb.putChar('0');
} else {
VpnStatus.logDebug("Unknown object for LogItem marschaling " + o);
bb.putChar('s');
marschalString(o.toString(), bb);
}
}
}
int pos = bb.position();
bb.rewind();
return Arrays.copyOf(bb.array(), pos);
}
public LogItem(byte[] in, int length) throws UnsupportedEncodingException {
ByteBuffer bb = ByteBuffer.wrap(in, 0, length);
bb.get(); // ignore version
logtime = bb.getLong();
mVerbosityLevel = bb.getInt();
mLevel = VpnStatus.LogLevel.getEnumByValue(bb.getInt());
mRessourceId = bb.getInt();
int len = bb.getInt();
if (len == 0) {
mMessage = null;
} else {
if (len > bb.remaining())
throw new IndexOutOfBoundsException("String length " + len + " is bigger than remaining bytes " + bb.remaining());
byte[] utf8bytes = new byte[len];
bb.get(utf8bytes);
mMessage = new String(utf8bytes, "UTF-8");
}
int numArgs = bb.getInt();
if (numArgs > 30) {
throw new IndexOutOfBoundsException("Too many arguments for Logitem to unmarschal");
}
if (numArgs == 0) {
mArgs = null;
} else {
mArgs = new Object[numArgs];
for (int i = 0; i < numArgs; i++) {
char type = bb.getChar();
switch (type) {
case 's':
mArgs[i] = unmarschalString(bb);
break;
case 'i':
mArgs[i] = bb.getInt();
break;
case 'd':
mArgs[i] = bb.getDouble();
break;
case 'f':
mArgs[i] = bb.getFloat();
break;
case 'l':
mArgs[i] = bb.getLong();
break;
case '0':
mArgs[i] = null;
break;
default:
throw new UnsupportedEncodingException("Unknown format type: " + type);
}
}
}
if (bb.hasRemaining())
throw new UnsupportedEncodingException(bb.remaining() + " bytes left after unmarshaling everything");
}
private void marschalString(String str, ByteBuffer bb) throws UnsupportedEncodingException {
byte[] utf8bytes = str.getBytes("UTF-8");
bb.putInt(utf8bytes.length);
bb.put(utf8bytes);
}
private String unmarschalString(ByteBuffer bb) throws UnsupportedEncodingException {
int len = bb.getInt();
byte[] utf8bytes = new byte[len];
bb.get(utf8bytes);
return new String(utf8bytes, "UTF-8");
}
public LogItem(Parcel in) {
mArgs = in.readArray(Object.class.getClassLoader());
mMessage = in.readString();
mRessourceId = in.readInt();
mLevel = VpnStatus.LogLevel.getEnumByValue(in.readInt());
mVerbosityLevel = in.readInt();
logtime = in.readLong();
}
public static final Creator<LogItem> CREATOR
= new Creator<LogItem>() {
public LogItem createFromParcel(Parcel in) {
return new LogItem(in);
}
public LogItem[] newArray(int size) {
return new LogItem[size];
}
};
public LogItem(VpnStatus.LogLevel loglevel, int ressourceId, Object... args) {
mRessourceId = ressourceId;
mArgs = args;
mLevel = loglevel;
}
public LogItem(VpnStatus.LogLevel loglevel, String msg) {
mLevel = loglevel;
mMessage = msg;
}
public LogItem(VpnStatus.LogLevel loglevel, int ressourceId) {
mRessourceId = ressourceId;
mLevel = loglevel;
}
public LogItem(VpnStatus.ErrorType errorType) {
mLevel = VpnStatus.LogLevel.ERROR;
this.errorType = errorType;
}
public String getString(Context c) {
try {
if (mMessage != null) {
return mMessage;
} else {
if (c != null) {
if (mRessourceId == R.string.mobile_info)
return getMobileInfoString(c);
if (mArgs == null)
return c.getString(mRessourceId);
else
return c.getString(mRessourceId, mArgs);
} else {
String str = String.format(Locale.ENGLISH, "Log (no context) resid %d", mRessourceId);
if (mArgs != null)
str += join("|", mArgs);
return str;
}
}
} catch (NotFoundException e) {
String str = "Log resid not found: " + mRessourceId;
if (mArgs != null)
str += join("|", mArgs);
return str;
} catch (UnknownFormatConversionException e) {
if (c != null)
throw new UnknownFormatConversionException(e.getLocalizedMessage() + getString(null));
else
throw e;
} catch (java.util.FormatFlagsConversionMismatchException e) {
if (c != null)
throw new FormatFlagsConversionMismatchException(e.getLocalizedMessage() + getString(null), e.getConversion());
else
throw e;
}
}
// TextUtils.join will cause not macked exeception in tests ....
public static String join(CharSequence delimiter, Object[] tokens) {
StringBuilder sb = new StringBuilder();
boolean firstTime = true;
for (Object token : tokens) {
if (firstTime) {
firstTime = false;
} else {
sb.append(delimiter);
}
sb.append(token);
}
return sb.toString();
}
public VpnStatus.LogLevel getLogLevel() {
return mLevel;
}
public VpnStatus.ErrorType getErrorType() {
return errorType;
}
@Override
public String toString() {
return getString(null);
}
// The lint is wrong here
@SuppressLint("StringFormatMatches")
private String getMobileInfoString(Context c) {
c.getPackageManager();
String apksign = "error getting package signature";
String version = "error getting version";
try {
@SuppressLint("PackageManagerGetSignatures")
Signature raw = c.getPackageManager().getPackageInfo(c.getPackageName(), PackageManager.GET_SIGNATURES).signatures[0];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(raw.toByteArray()));
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
if (Arrays.equals(digest, VpnStatus.officalkey))
apksign = c.getString(R.string.official_build);
else if (Arrays.equals(digest, VpnStatus.officaldebugkey))
apksign = c.getString(R.string.debug_build);
else if (Arrays.equals(digest, VpnStatus.amazonkey))
apksign = "amazon version";
else if (Arrays.equals(digest, VpnStatus.fdroidkey))
apksign = "F-Droid built and signed version";
else
apksign = c.getString(R.string.built_by, cert.getSubjectX500Principal().getName());
PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
version = packageinfo.versionName;
} catch (PackageManager.NameNotFoundException | CertificateException |
NoSuchAlgorithmException ignored) {
}
Object[] argsext = Arrays.copyOf(mArgs, mArgs.length);
argsext[argsext.length - 1] = apksign;
argsext[argsext.length - 2] = version;
return c.getString(R.string.mobile_info, argsext);
}
public long getLogtime() {
return logtime;
}
public int getVerbosityLevel() {
if (mVerbosityLevel == -1) {
// Hack:
// For message not from OpenVPN, report the status level as log level
return mLevel.getInt();
}
return mVerbosityLevel;
}
public boolean verify() {
if (mLevel == null)
return false;
if (mMessage == null && mRessourceId == 0)
return false;
return true;
}
}
| gpl-3.0 |
bergerkiller/SpigotSource | src/main/java/net/minecraft/server/Block.java | 44774 | package net.minecraft.server;
import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.annotation.Nullable;
public class Block {
private static final MinecraftKey a = new MinecraftKey("air");
public static final RegistryBlocks<MinecraftKey, Block> REGISTRY = new RegistryBlocks(Block.a);
public static final RegistryBlockID<IBlockData> REGISTRY_ID = new RegistryBlockID();
public static final AxisAlignedBB j = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D);
public static final AxisAlignedBB k = null;
private CreativeModeTab creativeTab;
protected boolean l;
protected int m;
protected boolean n;
protected int o;
protected boolean p;
protected float strength;
protected float durability;
protected boolean s;
protected boolean t;
protected boolean isTileEntity;
protected SoundEffectType stepSound;
public float w;
protected final Material material;
protected final MaterialMapColor y;
public float frictionFactor;
protected final BlockStateList blockStateList;
private IBlockData blockData;
private String name;
public static int getId(Block block) {
return Block.REGISTRY.a(block); // CraftBukkit - decompile error
}
public static int getCombinedId(IBlockData iblockdata) {
Block block = iblockdata.getBlock();
return getId(block) + (block.toLegacyData(iblockdata) << 12);
}
public static Block getById(int i) {
return (Block) Block.REGISTRY.getId(i);
}
public static IBlockData getByCombinedId(int i) {
int j = i & 4095;
int k = i >> 12 & 15;
return getById(j).fromLegacyData(k);
}
public static Block asBlock(Item item) {
return item instanceof ItemBlock ? ((ItemBlock) item).d() : null;
}
@Nullable
public static Block getByName(String s) {
MinecraftKey minecraftkey = new MinecraftKey(s);
if (Block.REGISTRY.d(minecraftkey)) {
return (Block) Block.REGISTRY.get(minecraftkey);
} else {
try {
return (Block) Block.REGISTRY.getId(Integer.parseInt(s));
} catch (NumberFormatException numberformatexception) {
return null;
}
}
}
@Deprecated
public boolean k(IBlockData iblockdata) {
return iblockdata.getMaterial().k() && iblockdata.h();
}
@Deprecated
public boolean l(IBlockData iblockdata) {
return this.l;
}
@Deprecated
public int m(IBlockData iblockdata) {
return this.m;
}
@Deprecated
public int o(IBlockData iblockdata) {
return this.o;
}
@Deprecated
public boolean p(IBlockData iblockdata) {
return this.p;
}
@Deprecated
public Material q(IBlockData iblockdata) {
return this.material;
}
@Deprecated
public MaterialMapColor r(IBlockData iblockdata) {
return this.y;
}
@Deprecated
public IBlockData fromLegacyData(int i) {
return this.getBlockData();
}
public int toLegacyData(IBlockData iblockdata) {
if (iblockdata != null && !iblockdata.r().isEmpty()) {
throw new IllegalArgumentException("Don\'t know how to convert " + iblockdata + " back into data...");
} else {
return 0;
}
}
@Deprecated
public IBlockData updateState(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) {
return iblockdata;
}
@Deprecated
public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) {
return iblockdata;
}
@Deprecated
public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) {
return iblockdata;
}
public Block(Material material, MaterialMapColor materialmapcolor) {
this.s = true;
this.stepSound = SoundEffectType.d;
this.w = 1.0F;
this.frictionFactor = 0.6F;
this.material = material;
this.y = materialmapcolor;
this.blockStateList = this.getStateList();
this.w(this.blockStateList.getBlockData());
this.l = this.getBlockData().p();
this.m = this.l ? 255 : 0;
this.n = !material.blocksLight();
}
protected Block(Material material) {
this(material, material.r());
}
protected Block a(SoundEffectType soundeffecttype) {
this.stepSound = soundeffecttype;
return this;
}
protected Block d(int i) {
this.m = i;
return this;
}
protected Block a(float f) {
this.o = (int) (15.0F * f);
return this;
}
protected Block b(float f) {
this.durability = f * 3.0F;
return this;
}
@Deprecated
public boolean s(IBlockData iblockdata) {
return iblockdata.getMaterial().isSolid() && iblockdata.h();
}
@Deprecated
public boolean isOccluding(IBlockData iblockdata) {
return iblockdata.getMaterial().k() && iblockdata.h() && !iblockdata.m();
}
public boolean j() {
return this.material.isSolid() && this.getBlockData().h();
}
@Deprecated
public boolean c(IBlockData iblockdata) {
return true;
}
public boolean b(IBlockAccess iblockaccess, BlockPosition blockposition) {
return !this.material.isSolid();
}
@Deprecated
public EnumRenderType a(IBlockData iblockdata) {
return EnumRenderType.MODEL;
}
public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition) {
return false;
}
protected Block c(float f) {
this.strength = f;
if (this.durability < f * 5.0F) {
this.durability = f * 5.0F;
}
return this;
}
protected Block k() {
this.c(-1.0F);
return this;
}
@Deprecated
public float b(IBlockData iblockdata, World world, BlockPosition blockposition) {
return this.strength;
}
protected Block a(boolean flag) {
this.t = flag;
return this;
}
public boolean isTicking() {
return this.t;
}
public boolean isTileEntity() {
return this.isTileEntity;
}
@Deprecated
public AxisAlignedBB a(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition) {
return Block.j;
}
public boolean a(IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) {
return iblockaccess.getType(blockposition).getMaterial().isBuildable();
}
@Deprecated
public void a(IBlockData iblockdata, World world, BlockPosition blockposition, AxisAlignedBB axisalignedbb, List<AxisAlignedBB> list, @Nullable Entity entity) {
a(blockposition, axisalignedbb, list, iblockdata.d(world, blockposition));
}
protected static void a(BlockPosition blockposition, AxisAlignedBB axisalignedbb, List<AxisAlignedBB> list, @Nullable AxisAlignedBB axisalignedbb1) {
if (axisalignedbb1 != Block.k) {
AxisAlignedBB axisalignedbb2 = axisalignedbb1.a(blockposition);
if (axisalignedbb.b(axisalignedbb2)) {
list.add(axisalignedbb2);
}
}
}
@Deprecated
@Nullable
public AxisAlignedBB a(IBlockData iblockdata, World world, BlockPosition blockposition) {
return iblockdata.c(world, blockposition);
}
@Deprecated
public boolean b(IBlockData iblockdata) {
return true;
}
public boolean a(IBlockData iblockdata, boolean flag) {
return this.n();
}
public boolean n() {
return true;
}
public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) {
this.b(world, blockposition, iblockdata, random);
}
public void b(World world, BlockPosition blockposition, IBlockData iblockdata, Random random) {}
public void postBreak(World world, BlockPosition blockposition, IBlockData iblockdata) {}
@Deprecated
public void a(IBlockData iblockdata, World world, BlockPosition blockposition, Block block) {}
public int a(World world) {
return 10;
}
public void onPlace(World world, BlockPosition blockposition, IBlockData iblockdata) {
org.spigotmc.AsyncCatcher.catchOp( "block onPlace"); // Spigot
}
public void remove(World world, BlockPosition blockposition, IBlockData iblockdata) {
org.spigotmc.AsyncCatcher.catchOp( "block remove"); // Spigot
}
public int a(Random random) {
return 1;
}
@Nullable
public Item getDropType(IBlockData iblockdata, Random random, int i) {
return Item.getItemOf(this);
}
@Deprecated
public float getDamage(IBlockData iblockdata, EntityHuman entityhuman, World world, BlockPosition blockposition) {
float f = iblockdata.b(world, blockposition);
return f < 0.0F ? 0.0F : (!entityhuman.hasBlock(iblockdata) ? entityhuman.a(iblockdata) / f / 100.0F : entityhuman.a(iblockdata) / f / 30.0F);
}
public final void b(World world, BlockPosition blockposition, IBlockData iblockdata, int i) {
this.dropNaturally(world, blockposition, iblockdata, 1.0F, i);
}
public void dropNaturally(World world, BlockPosition blockposition, IBlockData iblockdata, float f, int i) {
if (!world.isClientSide) {
int j = this.getDropCount(i, world.random);
for (int k = 0; k < j; ++k) {
// CraftBukkit - <= to < to allow for plugins to completely disable block drops from explosions
if (world.random.nextFloat() < f) {
Item item = this.getDropType(iblockdata, world.random, i);
if (item != null) {
a(world, blockposition, new ItemStack(item, 1, this.getDropData(iblockdata)));
}
}
}
}
}
public static void a(World world, BlockPosition blockposition, ItemStack itemstack) {
if (!world.isClientSide && world.getGameRules().getBoolean("doTileDrops")) {
float f = 0.5F;
double d0 = (double) (world.random.nextFloat() * f) + (double) (1.0F - f) * 0.5D;
double d1 = (double) (world.random.nextFloat() * f) + (double) (1.0F - f) * 0.5D;
double d2 = (double) (world.random.nextFloat() * f) + (double) (1.0F - f) * 0.5D;
EntityItem entityitem = new EntityItem(world, (double) blockposition.getX() + d0, (double) blockposition.getY() + d1, (double) blockposition.getZ() + d2, itemstack);
entityitem.q();
world.addEntity(entityitem);
}
}
protected void dropExperience(World world, BlockPosition blockposition, int i) {
if (!world.isClientSide && world.getGameRules().getBoolean("doTileDrops")) {
while (i > 0) {
int j = EntityExperienceOrb.getOrbValue(i);
i -= j;
world.addEntity(new EntityExperienceOrb(world, (double) blockposition.getX() + 0.5D, (double) blockposition.getY() + 0.5D, (double) blockposition.getZ() + 0.5D, j));
}
}
}
public int getDropData(IBlockData iblockdata) {
return 0;
}
public float a(Entity entity) {
return this.durability / 5.0F;
}
@Deprecated
@Nullable
public MovingObjectPosition a(IBlockData iblockdata, World world, BlockPosition blockposition, Vec3D vec3d, Vec3D vec3d1) {
return this.a(blockposition, vec3d, vec3d1, iblockdata.c(world, blockposition));
}
@Nullable
protected MovingObjectPosition a(BlockPosition blockposition, Vec3D vec3d, Vec3D vec3d1, AxisAlignedBB axisalignedbb) {
Vec3D vec3d2 = vec3d.a((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ());
Vec3D vec3d3 = vec3d1.a((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ());
MovingObjectPosition movingobjectposition = axisalignedbb.a(vec3d2, vec3d3);
return movingobjectposition == null ? null : new MovingObjectPosition(movingobjectposition.pos.add((double) blockposition.getX(), (double) blockposition.getY(), (double) blockposition.getZ()), movingobjectposition.direction, blockposition);
}
public void wasExploded(World world, BlockPosition blockposition, Explosion explosion) {}
public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection, @Nullable ItemStack itemstack) {
return this.canPlace(world, blockposition, enumdirection);
}
public boolean canPlace(World world, BlockPosition blockposition, EnumDirection enumdirection) {
return this.canPlace(world, blockposition);
}
public boolean canPlace(World world, BlockPosition blockposition) {
return world.getType(blockposition).getBlock().material.isReplaceable();
}
public boolean interact(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman, EnumHand enumhand, @Nullable ItemStack itemstack, EnumDirection enumdirection, float f, float f1, float f2) {
return false;
}
public void stepOn(World world, BlockPosition blockposition, Entity entity) {}
public IBlockData getPlacedState(World world, BlockPosition blockposition, EnumDirection enumdirection, float f, float f1, float f2, int i, EntityLiving entityliving) {
return this.fromLegacyData(i);
}
public void attack(World world, BlockPosition blockposition, EntityHuman entityhuman) {}
public Vec3D a(World world, BlockPosition blockposition, Entity entity, Vec3D vec3d) {
return vec3d;
}
@Deprecated
public int b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) {
return 0;
}
@Deprecated
public boolean isPowerSource(IBlockData iblockdata) {
return false;
}
public void a(World world, BlockPosition blockposition, IBlockData iblockdata, Entity entity) {}
@Deprecated
public int c(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, EnumDirection enumdirection) {
return 0;
}
public void a(World world, EntityHuman entityhuman, BlockPosition blockposition, IBlockData iblockdata, @Nullable TileEntity tileentity, @Nullable ItemStack itemstack) {
entityhuman.b(StatisticList.a(this));
entityhuman.applyExhaustion(0.025F);
if (this.o() && EnchantmentManager.getEnchantmentLevel(Enchantments.SILK_TOUCH, itemstack) > 0) {
ItemStack itemstack1 = this.u(iblockdata);
if (itemstack1 != null) {
a(world, blockposition, itemstack1);
}
} else {
int i = EnchantmentManager.getEnchantmentLevel(Enchantments.LOOT_BONUS_BLOCKS, itemstack);
this.b(world, blockposition, iblockdata, i);
}
}
protected boolean o() {
return this.getBlockData().h() && !this.isTileEntity;
}
@Nullable
protected ItemStack u(IBlockData iblockdata) {
Item item = Item.getItemOf(this);
if (item == null) {
return null;
} else {
int i = 0;
if (item.k()) {
i = this.toLegacyData(iblockdata);
}
return new ItemStack(item, 1, i);
}
}
public int getDropCount(int i, Random random) {
return this.a(random);
}
public void postPlace(World world, BlockPosition blockposition, IBlockData iblockdata, EntityLiving entityliving, ItemStack itemstack) {}
public boolean d() {
return !this.material.isBuildable() && !this.material.isLiquid();
}
public Block c(String s) {
this.name = s;
return this;
}
public String getName() {
return LocaleI18n.get(this.a() + ".name");
}
public String a() {
return "tile." + this.name;
}
@Deprecated
public boolean a(IBlockData iblockdata, World world, BlockPosition blockposition, int i, int j) {
return false;
}
public boolean p() {
return this.s;
}
protected Block q() {
this.s = false;
return this;
}
@Deprecated
public EnumPistonReaction h(IBlockData iblockdata) {
return this.material.getPushReaction();
}
public void fallOn(World world, BlockPosition blockposition, Entity entity, float f) {
entity.e(f, 1.0F);
}
public void a(World world, Entity entity) {
entity.motY = 0.0D;
}
@Nullable
public ItemStack a(World world, BlockPosition blockposition, IBlockData iblockdata) {
return new ItemStack(Item.getItemOf(this), 1, this.getDropData(iblockdata));
}
public Block a(CreativeModeTab creativemodetab) {
this.creativeTab = creativemodetab;
return this;
}
public void a(World world, BlockPosition blockposition, IBlockData iblockdata, EntityHuman entityhuman) {}
public void h(World world, BlockPosition blockposition) {}
public boolean s() {
return true;
}
public boolean a(Explosion explosion) {
return true;
}
public boolean b(Block block) {
return this == block;
}
public static boolean a(Block block, Block block1) {
return block != null && block1 != null ? (block == block1 ? true : block.b(block1)) : false;
}
@Deprecated
public boolean isComplexRedstone(IBlockData iblockdata) {
return false;
}
@Deprecated
public int d(IBlockData iblockdata, World world, BlockPosition blockposition) {
return 0;
}
protected BlockStateList getStateList() {
return new BlockStateList(this, new IBlockState[0]);
}
public BlockStateList t() {
return this.blockStateList;
}
protected final void w(IBlockData iblockdata) {
this.blockData = iblockdata;
}
public final IBlockData getBlockData() {
return this.blockData;
}
public SoundEffectType w() {
return this.stepSound;
}
public String toString() {
return "Block{" + Block.REGISTRY.b(this) + "}";
}
public static void x() {
a(0, Block.a, (new BlockAir()).c("air"));
a(1, "stone", (new BlockStone()).c(1.5F).b(10.0F).a(SoundEffectType.d).c("stone"));
a(2, "grass", (new BlockGrass()).c(0.6F).a(SoundEffectType.c).c("grass"));
a(3, "dirt", (new BlockDirt()).c(0.5F).a(SoundEffectType.b).c("dirt"));
Block block = (new Block(Material.STONE)).c(2.0F).b(10.0F).a(SoundEffectType.d).c("stonebrick").a(CreativeModeTab.b);
a(4, "cobblestone", block);
Block block1 = (new BlockWood()).c(2.0F).b(5.0F).a(SoundEffectType.a).c("wood");
a(5, "planks", block1);
a(6, "sapling", (new BlockSapling()).c(0.0F).a(SoundEffectType.c).c("sapling"));
a(7, "bedrock", (new BlockNoDrop(Material.STONE)).k().b(6000000.0F).a(SoundEffectType.d).c("bedrock").q().a(CreativeModeTab.b));
a(8, "flowing_water", (new BlockFlowing(Material.WATER)).c(100.0F).d(3).c("water").q());
a(9, "water", (new BlockStationary(Material.WATER)).c(100.0F).d(3).c("water").q());
a(10, "flowing_lava", (new BlockFlowing(Material.LAVA)).c(100.0F).a(1.0F).c("lava").q());
a(11, "lava", (new BlockStationary(Material.LAVA)).c(100.0F).a(1.0F).c("lava").q());
a(12, "sand", (new BlockSand()).c(0.5F).a(SoundEffectType.h).c("sand"));
a(13, "gravel", (new BlockGravel()).c(0.6F).a(SoundEffectType.b).c("gravel"));
a(14, "gold_ore", (new BlockOre()).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreGold"));
a(15, "iron_ore", (new BlockOre()).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreIron"));
a(16, "coal_ore", (new BlockOre()).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreCoal"));
a(17, "log", (new BlockLog1()).c("log"));
a(18, "leaves", (new BlockLeaves1()).c("leaves"));
a(19, "sponge", (new BlockSponge()).c(0.6F).a(SoundEffectType.c).c("sponge"));
a(20, "glass", (new BlockGlass(Material.SHATTERABLE, false)).c(0.3F).a(SoundEffectType.f).c("glass"));
a(21, "lapis_ore", (new BlockOre()).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreLapis"));
a(22, "lapis_block", (new Block(Material.ORE, MaterialMapColor.H)).c(3.0F).b(5.0F).a(SoundEffectType.d).c("blockLapis").a(CreativeModeTab.b));
a(23, "dispenser", (new BlockDispenser()).c(3.5F).a(SoundEffectType.d).c("dispenser"));
Block block2 = (new BlockSandStone()).a(SoundEffectType.d).c(0.8F).c("sandStone");
a(24, "sandstone", block2);
a(25, "noteblock", (new BlockNote()).a(SoundEffectType.a).c(0.8F).c("musicBlock"));
a(26, "bed", (new BlockBed()).a(SoundEffectType.a).c(0.2F).c("bed").q());
a(27, "golden_rail", (new BlockPoweredRail()).c(0.7F).a(SoundEffectType.e).c("goldenRail"));
a(28, "detector_rail", (new BlockMinecartDetector()).c(0.7F).a(SoundEffectType.e).c("detectorRail"));
a(29, "sticky_piston", (new BlockPiston(true)).c("pistonStickyBase"));
a(30, "web", (new BlockWeb()).d(1).c(4.0F).c("web"));
a(31, "tallgrass", (new BlockLongGrass()).c(0.0F).a(SoundEffectType.c).c("tallgrass"));
a(32, "deadbush", (new BlockDeadBush()).c(0.0F).a(SoundEffectType.c).c("deadbush"));
a(33, "piston", (new BlockPiston(false)).c("pistonBase"));
a(34, "piston_head", (new BlockPistonExtension()).c("pistonBase"));
a(35, "wool", (new BlockCloth(Material.CLOTH)).c(0.8F).a(SoundEffectType.g).c("cloth"));
a(36, "piston_extension", new BlockPistonMoving());
a(37, "yellow_flower", (new BlockYellowFlowers()).c(0.0F).a(SoundEffectType.c).c("flower1"));
a(38, "red_flower", (new BlockRedFlowers()).c(0.0F).a(SoundEffectType.c).c("flower2"));
Block block3 = (new BlockMushroom()).c(0.0F).a(SoundEffectType.c).a(0.125F).c("mushroom");
a(39, "brown_mushroom", block3);
Block block4 = (new BlockMushroom()).c(0.0F).a(SoundEffectType.c).c("mushroom");
a(40, "red_mushroom", block4);
a(41, "gold_block", (new Block(Material.ORE, MaterialMapColor.F)).c(3.0F).b(10.0F).a(SoundEffectType.e).c("blockGold").a(CreativeModeTab.b));
a(42, "iron_block", (new Block(Material.ORE, MaterialMapColor.h)).c(5.0F).b(10.0F).a(SoundEffectType.e).c("blockIron").a(CreativeModeTab.b));
a(43, "double_stone_slab", (new BlockDoubleStep()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("stoneSlab"));
a(44, "stone_slab", (new BlockStep()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("stoneSlab"));
Block block5 = (new Block(Material.STONE, MaterialMapColor.D)).c(2.0F).b(10.0F).a(SoundEffectType.d).c("brick").a(CreativeModeTab.b);
a(45, "brick_block", block5);
a(46, "tnt", (new BlockTNT()).c(0.0F).a(SoundEffectType.c).c("tnt"));
a(47, "bookshelf", (new BlockBookshelf()).c(1.5F).a(SoundEffectType.a).c("bookshelf"));
a(48, "mossy_cobblestone", (new Block(Material.STONE)).c(2.0F).b(10.0F).a(SoundEffectType.d).c("stoneMoss").a(CreativeModeTab.b));
a(49, "obsidian", (new BlockObsidian()).c(50.0F).b(2000.0F).a(SoundEffectType.d).c("obsidian"));
a(50, "torch", (new BlockTorch()).c(0.0F).a(0.9375F).a(SoundEffectType.a).c("torch"));
a(51, "fire", (new BlockFire()).c(0.0F).a(1.0F).a(SoundEffectType.g).c("fire").q());
a(52, "mob_spawner", (new BlockMobSpawner()).c(5.0F).a(SoundEffectType.e).c("mobSpawner").q());
a(53, "oak_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.OAK))).c("stairsWood"));
a(54, "chest", (new BlockChest(BlockChest.Type.BASIC)).c(2.5F).a(SoundEffectType.a).c("chest"));
a(55, "redstone_wire", (new BlockRedstoneWire()).c(0.0F).a(SoundEffectType.d).c("redstoneDust").q());
a(56, "diamond_ore", (new BlockOre()).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreDiamond"));
a(57, "diamond_block", (new Block(Material.ORE, MaterialMapColor.G)).c(5.0F).b(10.0F).a(SoundEffectType.e).c("blockDiamond").a(CreativeModeTab.b));
a(58, "crafting_table", (new BlockWorkbench()).c(2.5F).a(SoundEffectType.a).c("workbench"));
a(59, "wheat", (new BlockCrops()).c("crops"));
Block block6 = (new BlockSoil()).c(0.6F).a(SoundEffectType.b).c("farmland");
a(60, "farmland", block6);
a(61, "furnace", (new BlockFurnace(false)).c(3.5F).a(SoundEffectType.d).c("furnace").a(CreativeModeTab.c));
a(62, "lit_furnace", (new BlockFurnace(true)).c(3.5F).a(SoundEffectType.d).a(0.875F).c("furnace"));
a(63, "standing_sign", (new BlockFloorSign()).c(1.0F).a(SoundEffectType.a).c("sign").q());
a(64, "wooden_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(SoundEffectType.a).c("doorOak").q());
a(65, "ladder", (new BlockLadder()).c(0.4F).a(SoundEffectType.j).c("ladder"));
a(66, "rail", (new BlockMinecartTrack()).c(0.7F).a(SoundEffectType.e).c("rail"));
a(67, "stone_stairs", (new BlockStairs(block.getBlockData())).c("stairsStone"));
a(68, "wall_sign", (new BlockWallSign()).c(1.0F).a(SoundEffectType.a).c("sign").q());
a(69, "lever", (new BlockLever()).c(0.5F).a(SoundEffectType.a).c("lever"));
a(70, "stone_pressure_plate", (new BlockPressurePlateBinary(Material.STONE, BlockPressurePlateBinary.EnumMobType.MOBS)).c(0.5F).a(SoundEffectType.d).c("pressurePlateStone"));
a(71, "iron_door", (new BlockDoor(Material.ORE)).c(5.0F).a(SoundEffectType.e).c("doorIron").q());
a(72, "wooden_pressure_plate", (new BlockPressurePlateBinary(Material.WOOD, BlockPressurePlateBinary.EnumMobType.EVERYTHING)).c(0.5F).a(SoundEffectType.a).c("pressurePlateWood"));
a(73, "redstone_ore", (new BlockRedstoneOre(false)).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreRedstone").a(CreativeModeTab.b));
a(74, "lit_redstone_ore", (new BlockRedstoneOre(true)).a(0.625F).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreRedstone"));
a(75, "unlit_redstone_torch", (new BlockRedstoneTorch(false)).c(0.0F).a(SoundEffectType.a).c("notGate"));
a(76, "redstone_torch", (new BlockRedstoneTorch(true)).c(0.0F).a(0.5F).a(SoundEffectType.a).c("notGate").a(CreativeModeTab.d));
a(77, "stone_button", (new BlockStoneButton()).c(0.5F).a(SoundEffectType.d).c("button"));
a(78, "snow_layer", (new BlockSnow()).c(0.1F).a(SoundEffectType.i).c("snow").d(0));
a(79, "ice", (new BlockIce()).c(0.5F).d(3).a(SoundEffectType.f).c("ice"));
a(80, "snow", (new BlockSnowBlock()).c(0.2F).a(SoundEffectType.i).c("snow"));
a(81, "cactus", (new BlockCactus()).c(0.4F).a(SoundEffectType.g).c("cactus"));
a(82, "clay", (new BlockClay()).c(0.6F).a(SoundEffectType.b).c("clay"));
a(83, "reeds", (new BlockReed()).c(0.0F).a(SoundEffectType.c).c("reeds").q());
a(84, "jukebox", (new BlockJukeBox()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("jukebox"));
a(85, "fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.OAK.c())).c(2.0F).b(5.0F).a(SoundEffectType.a).c("fence"));
Block block7 = (new BlockPumpkin()).c(1.0F).a(SoundEffectType.a).c("pumpkin");
a(86, "pumpkin", block7);
a(87, "netherrack", (new BlockBloodStone()).c(0.4F).a(SoundEffectType.d).c("hellrock"));
a(88, "soul_sand", (new BlockSlowSand()).c(0.5F).a(SoundEffectType.h).c("hellsand"));
a(89, "glowstone", (new BlockLightStone(Material.SHATTERABLE)).c(0.3F).a(SoundEffectType.f).a(1.0F).c("lightgem"));
a(90, "portal", (new BlockPortal()).c(-1.0F).a(SoundEffectType.f).a(0.75F).c("portal"));
a(91, "lit_pumpkin", (new BlockPumpkin()).c(1.0F).a(SoundEffectType.a).a(1.0F).c("litpumpkin"));
a(92, "cake", (new BlockCake()).c(0.5F).a(SoundEffectType.g).c("cake").q());
a(93, "unpowered_repeater", (new BlockRepeater(false)).c(0.0F).a(SoundEffectType.a).c("diode").q());
a(94, "powered_repeater", (new BlockRepeater(true)).c(0.0F).a(SoundEffectType.a).c("diode").q());
a(95, "stained_glass", (new BlockStainedGlass(Material.SHATTERABLE)).c(0.3F).a(SoundEffectType.f).c("stainedGlass"));
a(96, "trapdoor", (new BlockTrapdoor(Material.WOOD)).c(3.0F).a(SoundEffectType.a).c("trapdoor").q());
a(97, "monster_egg", (new BlockMonsterEggs()).c(0.75F).c("monsterStoneEgg"));
Block block8 = (new BlockSmoothBrick()).c(1.5F).b(10.0F).a(SoundEffectType.d).c("stonebricksmooth");
a(98, "stonebrick", block8);
a(99, "brown_mushroom_block", (new BlockHugeMushroom(Material.WOOD, MaterialMapColor.l, block3)).c(0.2F).a(SoundEffectType.a).c("mushroom"));
a(100, "red_mushroom_block", (new BlockHugeMushroom(Material.WOOD, MaterialMapColor.D, block4)).c(0.2F).a(SoundEffectType.a).c("mushroom"));
a(101, "iron_bars", (new BlockThin(Material.ORE, true)).c(5.0F).b(10.0F).a(SoundEffectType.e).c("fenceIron"));
a(102, "glass_pane", (new BlockThin(Material.SHATTERABLE, false)).c(0.3F).a(SoundEffectType.f).c("thinGlass"));
Block block9 = (new BlockMelon()).c(1.0F).a(SoundEffectType.a).c("melon");
a(103, "melon_block", block9);
a(104, "pumpkin_stem", (new BlockStem(block7)).c(0.0F).a(SoundEffectType.a).c("pumpkinStem"));
a(105, "melon_stem", (new BlockStem(block9)).c(0.0F).a(SoundEffectType.a).c("pumpkinStem"));
a(106, "vine", (new BlockVine()).c(0.2F).a(SoundEffectType.c).c("vine"));
a(107, "fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.OAK)).c(2.0F).b(5.0F).a(SoundEffectType.a).c("fenceGate"));
a(108, "brick_stairs", (new BlockStairs(block5.getBlockData())).c("stairsBrick"));
a(109, "stone_brick_stairs", (new BlockStairs(block8.getBlockData().set(BlockSmoothBrick.VARIANT, BlockSmoothBrick.EnumStonebrickType.DEFAULT))).c("stairsStoneBrickSmooth"));
a(110, "mycelium", (new BlockMycel()).c(0.6F).a(SoundEffectType.c).c("mycel"));
a(111, "waterlily", (new BlockWaterLily()).c(0.0F).a(SoundEffectType.c).c("waterlily"));
Block block10 = (new BlockNetherbrick()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("netherBrick").a(CreativeModeTab.b);
a(112, "nether_brick", block10);
a(113, "nether_brick_fence", (new BlockFence(Material.STONE, MaterialMapColor.K)).c(2.0F).b(10.0F).a(SoundEffectType.d).c("netherFence"));
a(114, "nether_brick_stairs", (new BlockStairs(block10.getBlockData())).c("stairsNetherBrick"));
a(115, "nether_wart", (new BlockNetherWart()).c("netherStalk"));
a(116, "enchanting_table", (new BlockEnchantmentTable()).c(5.0F).b(2000.0F).c("enchantmentTable"));
a(117, "brewing_stand", (new BlockBrewingStand()).c(0.5F).a(0.125F).c("brewingStand"));
a(118, "cauldron", (new BlockCauldron()).c(2.0F).c("cauldron"));
a(119, "end_portal", (new BlockEnderPortal(Material.PORTAL)).c(-1.0F).b(6000000.0F));
a(120, "end_portal_frame", (new BlockEnderPortalFrame()).a(SoundEffectType.f).a(0.125F).c(-1.0F).c("endPortalFrame").b(6000000.0F).a(CreativeModeTab.c));
a(121, "end_stone", (new Block(Material.STONE, MaterialMapColor.d)).c(3.0F).b(15.0F).a(SoundEffectType.d).c("whiteStone").a(CreativeModeTab.b));
a(122, "dragon_egg", (new BlockDragonEgg()).c(3.0F).b(15.0F).a(SoundEffectType.d).a(0.125F).c("dragonEgg"));
a(123, "redstone_lamp", (new BlockRedstoneLamp(false)).c(0.3F).a(SoundEffectType.f).c("redstoneLight").a(CreativeModeTab.d));
a(124, "lit_redstone_lamp", (new BlockRedstoneLamp(true)).c(0.3F).a(SoundEffectType.f).c("redstoneLight"));
a(125, "double_wooden_slab", (new BlockDoubleWoodStep()).c(2.0F).b(5.0F).a(SoundEffectType.a).c("woodSlab"));
a(126, "wooden_slab", (new BlockWoodStep()).c(2.0F).b(5.0F).a(SoundEffectType.a).c("woodSlab"));
a(127, "cocoa", (new BlockCocoa()).c(0.2F).b(5.0F).a(SoundEffectType.a).c("cocoa"));
a(128, "sandstone_stairs", (new BlockStairs(block2.getBlockData().set(BlockSandStone.TYPE, BlockSandStone.EnumSandstoneVariant.SMOOTH))).c("stairsSandStone"));
a(129, "emerald_ore", (new BlockOre()).c(3.0F).b(5.0F).a(SoundEffectType.d).c("oreEmerald"));
a(130, "ender_chest", (new BlockEnderChest()).c(22.5F).b(1000.0F).a(SoundEffectType.d).c("enderChest").a(0.5F));
a(131, "tripwire_hook", (new BlockTripwireHook()).c("tripWireSource"));
a(132, "tripwire", (new BlockTripwire()).c("tripWire"));
a(133, "emerald_block", (new Block(Material.ORE, MaterialMapColor.I)).c(5.0F).b(10.0F).a(SoundEffectType.e).c("blockEmerald").a(CreativeModeTab.b));
a(134, "spruce_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.SPRUCE))).c("stairsWoodSpruce"));
a(135, "birch_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.BIRCH))).c("stairsWoodBirch"));
a(136, "jungle_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.JUNGLE))).c("stairsWoodJungle"));
a(137, "command_block", (new BlockCommand(MaterialMapColor.B)).k().b(6000000.0F).c("commandBlock"));
a(138, "beacon", (new BlockBeacon()).c("beacon").a(1.0F));
a(139, "cobblestone_wall", (new BlockCobbleWall(block)).c("cobbleWall"));
a(140, "flower_pot", (new BlockFlowerPot()).c(0.0F).a(SoundEffectType.d).c("flowerPot"));
a(141, "carrots", (new BlockCarrots()).c("carrots"));
a(142, "potatoes", (new BlockPotatoes()).c("potatoes"));
a(143, "wooden_button", (new BlockWoodButton()).c(0.5F).a(SoundEffectType.a).c("button"));
a(144, "skull", (new BlockSkull()).c(1.0F).a(SoundEffectType.d).c("skull"));
a(145, "anvil", (new BlockAnvil()).c(5.0F).a(SoundEffectType.k).b(2000.0F).c("anvil"));
a(146, "trapped_chest", (new BlockChest(BlockChest.Type.TRAP)).c(2.5F).a(SoundEffectType.a).c("chestTrap"));
a(147, "light_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.ORE, 15, MaterialMapColor.F)).c(0.5F).a(SoundEffectType.a).c("weightedPlate_light"));
a(148, "heavy_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.ORE, 150)).c(0.5F).a(SoundEffectType.a).c("weightedPlate_heavy"));
a(149, "unpowered_comparator", (new BlockRedstoneComparator(false)).c(0.0F).a(SoundEffectType.a).c("comparator").q());
a(150, "powered_comparator", (new BlockRedstoneComparator(true)).c(0.0F).a(0.625F).a(SoundEffectType.a).c("comparator").q());
a(151, "daylight_detector", new BlockDaylightDetector(false));
a(152, "redstone_block", (new BlockPowered(Material.ORE, MaterialMapColor.f)).c(5.0F).b(10.0F).a(SoundEffectType.e).c("blockRedstone").a(CreativeModeTab.d));
a(153, "quartz_ore", (new BlockOre(MaterialMapColor.K)).c(3.0F).b(5.0F).a(SoundEffectType.d).c("netherquartz"));
a(154, "hopper", (new BlockHopper()).c(3.0F).b(8.0F).a(SoundEffectType.e).c("hopper"));
Block block11 = (new BlockQuartz()).a(SoundEffectType.d).c(0.8F).c("quartzBlock");
a(155, "quartz_block", block11);
a(156, "quartz_stairs", (new BlockStairs(block11.getBlockData().set(BlockQuartz.VARIANT, BlockQuartz.EnumQuartzVariant.DEFAULT))).c("stairsQuartz"));
a(157, "activator_rail", (new BlockPoweredRail()).c(0.7F).a(SoundEffectType.e).c("activatorRail"));
a(158, "dropper", (new BlockDropper()).c(3.5F).a(SoundEffectType.d).c("dropper"));
a(159, "stained_hardened_clay", (new BlockCloth(Material.STONE)).c(1.25F).b(7.0F).a(SoundEffectType.d).c("clayHardenedStained"));
a(160, "stained_glass_pane", (new BlockStainedGlassPane()).c(0.3F).a(SoundEffectType.f).c("thinStainedGlass"));
a(161, "leaves2", (new BlockLeaves2()).c("leaves"));
a(162, "log2", (new BlockLog2()).c("log"));
a(163, "acacia_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.ACACIA))).c("stairsWoodAcacia"));
a(164, "dark_oak_stairs", (new BlockStairs(block1.getBlockData().set(BlockWood.VARIANT, BlockWood.EnumLogVariant.DARK_OAK))).c("stairsWoodDarkOak"));
a(165, "slime", (new BlockSlime()).c("slime").a(SoundEffectType.l));
a(166, "barrier", (new BlockBarrier()).c("barrier"));
a(167, "iron_trapdoor", (new BlockTrapdoor(Material.ORE)).c(5.0F).a(SoundEffectType.e).c("ironTrapdoor").q());
a(168, "prismarine", (new BlockPrismarine()).c(1.5F).b(10.0F).a(SoundEffectType.d).c("prismarine"));
a(169, "sea_lantern", (new BlockSeaLantern(Material.SHATTERABLE)).c(0.3F).a(SoundEffectType.f).a(1.0F).c("seaLantern"));
a(170, "hay_block", (new BlockHay()).c(0.5F).a(SoundEffectType.c).c("hayBlock").a(CreativeModeTab.b));
a(171, "carpet", (new BlockCarpet()).c(0.1F).a(SoundEffectType.g).c("woolCarpet").d(0));
a(172, "hardened_clay", (new BlockHardenedClay()).c(1.25F).b(7.0F).a(SoundEffectType.d).c("clayHardened"));
a(173, "coal_block", (new Block(Material.STONE, MaterialMapColor.E)).c(5.0F).b(10.0F).a(SoundEffectType.d).c("blockCoal").a(CreativeModeTab.b));
a(174, "packed_ice", (new BlockPackedIce()).c(0.5F).a(SoundEffectType.f).c("icePacked"));
a(175, "double_plant", new BlockTallPlant());
a(176, "standing_banner", (new BlockBanner.BlockStandingBanner()).c(1.0F).a(SoundEffectType.a).c("banner").q());
a(177, "wall_banner", (new BlockBanner.BlockWallBanner()).c(1.0F).a(SoundEffectType.a).c("banner").q());
a(178, "daylight_detector_inverted", new BlockDaylightDetector(true));
Block block12 = (new BlockRedSandstone()).a(SoundEffectType.d).c(0.8F).c("redSandStone");
a(179, "red_sandstone", block12);
a(180, "red_sandstone_stairs", (new BlockStairs(block12.getBlockData().set(BlockRedSandstone.TYPE, BlockRedSandstone.EnumRedSandstoneVariant.SMOOTH))).c("stairsRedSandStone"));
a(181, "double_stone_slab2", (new BlockDoubleStoneStep2()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("stoneSlab2"));
a(182, "stone_slab2", (new BlockStoneStep2()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("stoneSlab2"));
a(183, "spruce_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.SPRUCE)).c(2.0F).b(5.0F).a(SoundEffectType.a).c("spruceFenceGate"));
a(184, "birch_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.BIRCH)).c(2.0F).b(5.0F).a(SoundEffectType.a).c("birchFenceGate"));
a(185, "jungle_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.JUNGLE)).c(2.0F).b(5.0F).a(SoundEffectType.a).c("jungleFenceGate"));
a(186, "dark_oak_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.DARK_OAK)).c(2.0F).b(5.0F).a(SoundEffectType.a).c("darkOakFenceGate"));
a(187, "acacia_fence_gate", (new BlockFenceGate(BlockWood.EnumLogVariant.ACACIA)).c(2.0F).b(5.0F).a(SoundEffectType.a).c("acaciaFenceGate"));
a(188, "spruce_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.SPRUCE.c())).c(2.0F).b(5.0F).a(SoundEffectType.a).c("spruceFence"));
a(189, "birch_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.BIRCH.c())).c(2.0F).b(5.0F).a(SoundEffectType.a).c("birchFence"));
a(190, "jungle_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.JUNGLE.c())).c(2.0F).b(5.0F).a(SoundEffectType.a).c("jungleFence"));
a(191, "dark_oak_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.DARK_OAK.c())).c(2.0F).b(5.0F).a(SoundEffectType.a).c("darkOakFence"));
a(192, "acacia_fence", (new BlockFence(Material.WOOD, BlockWood.EnumLogVariant.ACACIA.c())).c(2.0F).b(5.0F).a(SoundEffectType.a).c("acaciaFence"));
a(193, "spruce_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(SoundEffectType.a).c("doorSpruce").q());
a(194, "birch_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(SoundEffectType.a).c("doorBirch").q());
a(195, "jungle_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(SoundEffectType.a).c("doorJungle").q());
a(196, "acacia_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(SoundEffectType.a).c("doorAcacia").q());
a(197, "dark_oak_door", (new BlockDoor(Material.WOOD)).c(3.0F).a(SoundEffectType.a).c("doorDarkOak").q());
a(198, "end_rod", (new BlockEndRod()).c(0.0F).a(0.9375F).a(SoundEffectType.a).c("endRod"));
a(199, "chorus_plant", (new BlockChorusFruit()).c(0.4F).a(SoundEffectType.a).c("chorusPlant"));
a(200, "chorus_flower", (new BlockChorusFlower()).c(0.4F).a(SoundEffectType.a).c("chorusFlower"));
Block block13 = (new Block(Material.STONE)).c(1.5F).b(10.0F).a(SoundEffectType.d).a(CreativeModeTab.b).c("purpurBlock");
a(201, "purpur_block", block13);
a(202, "purpur_pillar", (new BlockRotatable(Material.STONE)).c(1.5F).b(10.0F).a(SoundEffectType.d).a(CreativeModeTab.b).c("purpurPillar"));
a(203, "purpur_stairs", (new BlockStairs(block13.getBlockData())).c("stairsPurpur"));
a(204, "purpur_double_slab", (new BlockPurpurSlab.Default()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("purpurSlab"));
a(205, "purpur_slab", (new BlockPurpurSlab.Half()).c(2.0F).b(10.0F).a(SoundEffectType.d).c("purpurSlab"));
a(206, "end_bricks", (new Block(Material.STONE)).a(SoundEffectType.d).c(0.8F).a(CreativeModeTab.b).c("endBricks"));
a(207, "beetroots", (new BlockBeetroot()).c("beetroots"));
Block block14 = (new BlockGrassPath()).c(0.65F).a(SoundEffectType.c).c("grassPath").q();
a(208, "grass_path", block14);
a(209, "end_gateway", (new BlockEndGateway(Material.PORTAL)).c(-1.0F).b(6000000.0F));
a(210, "repeating_command_block", (new BlockCommand(MaterialMapColor.z)).k().b(6000000.0F).c("repeatingCommandBlock"));
a(211, "chain_command_block", (new BlockCommand(MaterialMapColor.C)).k().b(6000000.0F).c("chainCommandBlock"));
a(212, "frosted_ice", (new BlockIceFrost()).c(0.5F).d(3).a(SoundEffectType.f).c("frostedIce"));
a(255, "structure_block", (new BlockStructure()).k().b(6000000.0F).c("structureBlock").a(1.0F));
Block.REGISTRY.a();
Iterator iterator = Block.REGISTRY.iterator();
while (iterator.hasNext()) {
Block block15 = (Block) iterator.next();
if (block15.material == Material.AIR) {
block15.p = false;
} else {
boolean flag = false;
boolean flag1 = block15 instanceof BlockStairs;
boolean flag2 = block15 instanceof BlockStepAbstract;
boolean flag3 = block15 == block6 || block15 == block14;
boolean flag4 = block15.n;
boolean flag5 = block15.m == 0;
if (flag1 || flag2 || flag3 || flag4 || flag5) {
flag = true;
}
block15.p = flag;
}
}
HashSet hashset = Sets.newHashSet(new Block[] { (Block) Block.REGISTRY.get(new MinecraftKey("tripwire"))});
Iterator iterator1 = Block.REGISTRY.iterator();
while (iterator1.hasNext()) {
Block block16 = (Block) iterator1.next();
if (hashset.contains(block16)) {
for (int i = 0; i < 15; ++i) {
int j = Block.REGISTRY.a(block16) << 4 | i; // CraftBukkit - decompile error
Block.REGISTRY_ID.a(block16.fromLegacyData(i), j);
}
} else {
Iterator iterator2 = block16.t().a().iterator();
while (iterator2.hasNext()) {
IBlockData iblockdata = (IBlockData) iterator2.next();
int k = Block.REGISTRY.a(block16) << 4 | block16.toLegacyData(iblockdata); // CraftBukkit - decompile error
Block.REGISTRY_ID.a(iblockdata, k);
}
}
}
}
// CraftBukkit start
public int getExpDrop(World world, IBlockData data, int enchantmentLevel) {
return 0;
}
// CraftBukkit end
private static void a(int i, MinecraftKey minecraftkey, Block block) {
Block.REGISTRY.a(i, minecraftkey, block);
}
private static void a(int i, String s, Block block) {
a(i, new MinecraftKey(s), block);
}
// Spigot start
public static float range(float min, float value, float max) {
if (value < min) {
return min;
}
if (value > max) {
return max;
}
return value;
}
// Spigot end
}
| gpl-3.0 |
gtenham/magnolia-templating | magnolia-templating-foundation/src/main/java/nl/gertontenham/magnolia/templating/rendering/ResultsRenderingModel.java | 475 | package nl.gertontenham.magnolia.templating.rendering;
import info.magnolia.rendering.model.RenderingModel;
import info.magnolia.rendering.template.RenderableDefinition;
import nl.gertontenham.magnolia.templating.search.SearchResult;
/**
* Created by gtenham on 2015-04-07.
*/
public interface ResultsRenderingModel<RD extends RenderableDefinition> extends RenderingModel<RD> {
void executeSearch();
String getSubtitle();
SearchResult getSearchResult();
}
| gpl-3.0 |
hypereddie/GGS-Plugin-Pack | src/com/ep/ggs/mb/blocks/CommandBlock.java | 1543 | /*******************************************************************************
* Copyright (c) 2012 MCForge.
* 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 com.ep.ggs.mb.blocks;
import com.ep.ggs.API.plugin.Command;
import com.ep.ggs.server.Server;
import com.ep.ggs.world.blocks.classicmodel.ClassicBlock;
public class CommandBlock extends ClassicBlock {
private static final long serialVersionUID = 1808391182561161713L;
private String message;
private boolean canWalk;
public CommandBlock() { super(); }
public CommandBlock(byte ID, String name) {
super(ID, name);
}
public CommandBlock(String message, ClassicBlock placed) {
this(placed.getVisibleBlock(), placed.name);
this.message = message;
this.canWalk = placed.canWalkThrough();
}
/**
* Get the full message without the / at the beginning
* @return
*/
public String getMessage() {
return message.substring(1);
}
/**
* Get the command this commandblock holds
* @param server
* The server with the commandhandler
* @return
* The command
*/
public Command getCommand(Server server) {
return server.getCommandHandler().find(getMessage().split("\\ ")[0]);
}
@Override
public boolean canWalkThrough() {
return canWalk;
}
}
| gpl-3.0 |
mothma/Limited-Game | src/me/mothma/limitedgame/Zone.java | 792 | package me.mothma.limitedgame;
import java.io.Serializable;
import org.bukkit.Location;
public class Zone implements Serializable{
private static final long serialVersionUID = 8908067227624482698L;
String name;
double x1;
double z1;
double x2;
double z2;
public Zone(String name, Location a, Location b) {
this.name = name;
x1 = Math.min(a.getX(), b.getX());
z1 = Math.min(a.getZ(), b.getZ());
x2 = Math.max(a.getX(), b.getX());
z2 = Math.max(a.getZ(), b.getZ());
}
public boolean contains(Location l) {
double x = l.getX();
double z = l.getZ();
if (x > x1 && x < x2) {
if (z > z1 && z < z2) {
return true;
}
}
return false;
}
public boolean equals(Zone z) {
if (z.name.equals(this.name)) {
return true;
}
return false;
}
}
| gpl-3.0 |
Minecolonies/minecolonies | src/api/java/com/minecolonies/api/util/Pond.java | 6616 | package com.minecolonies.api.util;
import com.minecolonies.api.entity.pathfinding.WaterPathResult;
import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorldReader;
import org.jetbrains.annotations.NotNull;
/**
* Utility class to search for fisher ponds.
*/
public final class Pond
{
/**
* The minimum pond requirements.
*/
private static final int WATER_POOL_WIDTH_REQUIREMENT = 6;
private static final int WATER_POOL_LENGTH_REQUIREMENT = 3;
/**
* Checks if on position "water" really is water, if the water is connected to land and if the pond is big enough (bigger then 20).
*
* @param world The world the player is in.
* @param water The coordinate to check.
* @param result the water path result.
* @return true if water.
*/
public static boolean checkWater(@NotNull final IWorldReader world, @NotNull final BlockPos water, final WaterPathResult result)
{
if (checkWater(world, water, WATER_POOL_WIDTH_REQUIREMENT, WATER_POOL_LENGTH_REQUIREMENT))
{
result.pond = water;
return true;
}
return false;
}
/**
* Checks if on position "water" really is water, if the water is connected to land and if the pond is big enough (bigger then 20).
*
* @param world The world the player is in.
* @param water The coordinate to check.
* @param width which has to be water.
* @param length which has to be water.
* @return true if water.
*/
public static boolean checkWater(@NotNull final IWorldReader world, @NotNull final BlockPos water, final int width, final int length)
{
if (world.getBlockState(water).getBlock() != Blocks.WATER || !world.isAirBlock(water.up()))
{
return false;
}
final int x = water.getX();
final int y = water.getY();
final int z = water.getZ();
//If not one direction contains a pool with length at least 6 and width 7
return checkWaterPoolInDirectionXThenZ(world, x, y, z, 1, width, length)
|| checkWaterPoolInDirectionXThenZ(world, x, y, z, -1, width, length)
|| checkWaterPoolInDirectionZThenX(world, x, y, z, 1, width, length)
|| checkWaterPoolInDirectionZThenX(world, x, y, z, -1, width, length);
}
/**
* Checks if all blocks in direction X are water and if yes from the middle to both sides in. direction Z all blocks are also water.
*
* @param world World.
* @param x posX.
* @param y posY.
* @param z posZ.
* @param vector direction.
* @param width which has to be water.
* @param length length has to be water.
* @return true if all blocks are water, else false.
*/
private static boolean checkWaterPoolInDirectionXThenZ(
@NotNull final IWorldReader world,
final int x,
final int y,
final int z,
final int vector,
final int width,
final int length)
{
//Check 6 blocks in direction +/- x
for (int dx = x + width * vector; dx <= x + width * vector; dx++)
{
if (world.getBlockState(new BlockPos(dx, y, z)).getBlock() != Blocks.WATER)
{
return false;
}
}
//Takes the middle x block and searches 3 water blocks to both sides
return checkWaterPoolInDirectionZ(world, x + length * vector, y, z, 1) && checkWaterPoolInDirectionZ(world, x + length
* vector, y, z, -1);
}
/**
* Checks if all blocks in direction Z are water and if yes from the middle to both sides in direction X all blocks are also water.
*
* @param world World.
* @param x posX.
* @param y posY.
* @param z posZ.
* @param vector direction.
* @param width which has to be water.
* @param length length has to be water.
* @return true if all blocks are water, else false.
*/
private static boolean checkWaterPoolInDirectionZThenX(
@NotNull final IWorldReader world,
final int x,
final int y,
final int z,
final int vector,
final int width,
final int length)
{
//Check 6 blocks in direction +/- z
for (int dz = z + width * vector; dz <= z + width * vector; dz++)
{
if (world.getBlockState(new BlockPos(x, y, dz)).getBlock() != Blocks.WATER)
{
return false;
}
}
//Takes the middle z block and searches 3 water blocks to both sides
return checkWaterPoolInDirectionX(world, x, y, z + length * vector, 1) && checkWaterPoolInDirectionX(world, x, y, z + length
* vector, -1);
}
/**
* Checks if all blocks in direction Z are Pond.
*
* @param world World.
* @param x posX.
* @param y posY.
* @param z posZ.
* @param vector direction.
* @return true if all blocks are water, else false.
*/
private static boolean checkWaterPoolInDirectionZ(@NotNull final IWorldReader world, final int x, final int y, final int z, final int vector)
{
//Check 3 blocks in direction +/- z
for (int dz = z + WATER_POOL_LENGTH_REQUIREMENT * vector; dz <= z + WATER_POOL_LENGTH_REQUIREMENT * vector; dz++)
{
if (world.getBlockState(new BlockPos(x, y, dz)).getBlock() != Blocks.WATER)
{
return false;
}
}
return true;
}
/**
* Checks if all blocks in direction X are Pond.
*
* @param world World.
* @param x posX.
* @param y posY.
* @param z posZ.
* @param vector direction.
* @return true if all blocks are water, else false.
*/
private static boolean checkWaterPoolInDirectionX(@NotNull final IWorldReader world, final int x, final int y, final int z, final int vector)
{
//Check 3 blocks in direction +/- x
for (int dx = x + WATER_POOL_LENGTH_REQUIREMENT * vector; dx <= x + WATER_POOL_LENGTH_REQUIREMENT * vector; dx++)
{
if (world.getBlockState(new BlockPos(dx, y, z)).getBlock() != Blocks.WATER)
{
return false;
}
}
return true;
}
}
| gpl-3.0 |
renatocf/MAC0434-PROJECT | external/sablecc-3.7/src/org/sablecc/sablecc/GenParser.java | 28167 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* This file is part of SableCC. *
* See the file "LICENSE" for copyright information and the *
* terms and conditions for copying, distribution and *
* modification of SableCC. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
package org.sablecc.sablecc;
import java.io.*;
import java.util.*;
import org.sablecc.sablecc.analysis.*;
import org.sablecc.sablecc.node.*;
/*
* GenParser
*
* This class is the responsible of generation of the parser.
* It calls another classes which will do internal transformations
* to the grammar in order to made it support by BNF parser generator
* algorithm whereas SableCC3.x.x grammars can be written with some
* operators of the EBNF form.
* It can also call an appropriate Tree-Walker which in case of conflict
* will try to inline productions involved in the conflict with the aim of
* resolving it.
*/
@SuppressWarnings({"rawtypes","unchecked"})
public class GenParser extends DepthFirstAdapter
{
//This is the tree-walker field which made internal transformations("EBNF"->BNF) to the grammar
InternalTransformationsToGrammar bnf_and_CST_AST_Transformations;
//tree-walker field which construct data structures for generating of parsing tables.
ConstructParserGenerationDatas genParserAdapter;
private MacroExpander macros;
private ResolveIds ids;
private ResolveAltIds altIds;
private ResolveTransformIds transformIds;
// This class reference variable fills the map "altsElemTypes" from class AlternativeElementTypes. It associates
// the name of elements with its types
private AlternativeElementTypes AET;
//This computes variables declarations position and type for parser generation.
//In fact it helps to determine how many elements are needed to pop from the stack
private ComputeCGNomenclature CG;
//This helps to compute alternative transformations code generation.
private ComputeSimpleTermPosition CTP;
private File pkgDir;
private String pkgName;
private boolean hasProductions;
private String firstProductionName;
private boolean processInlining;
private boolean prettyPrinting;
private boolean grammarHasTransformations;
// This boolean is used to check weither the filter() method in class Parser.java
// should be present or not.
private boolean activateFilter = true;
//This tree-walker field generate the code of parsing and construction of the AST.
GenerateAlternativeCodeForParser aParsedAltAdapter;
private LinkedList listSimpleTermTransform = new LinkedList();
public final Map simpleTermTransform =
new TypedHashMap(NodeCast.instance,
StringCast.instance);
//This map contains Productions which were explicitely transformed in the grammar
//Those transformations was specified by the grammar-writer.
private final Map mapProductionTransformations =
new TypedHashMap(StringCast.instance,
ListCast.instance);
private Map alts;
public GenParser(ResolveIds ids, ResolveAltIds altIds, ResolveTransformIds transformIds,
String firstProductionName, boolean processInlining, boolean prettyPrinting,
boolean grammarHasTransformations)
{
this.ids = ids;
this.altIds = altIds;
this.transformIds = transformIds;
this.processInlining = processInlining;
this.prettyPrinting = prettyPrinting;
this.grammarHasTransformations = grammarHasTransformations;
AET = new AlternativeElementTypes(ids);
CG = new ComputeCGNomenclature(ids, transformIds.getProdTransformIds());
CTP = new ComputeSimpleTermPosition(ids);
this.firstProductionName = firstProductionName;
try
{
macros = new MacroExpander(
new InputStreamReader(
getClass().getResourceAsStream("parser.txt")));
}
catch(IOException e)
{
throw new RuntimeException("unable to open parser.txt.");
}
pkgDir = new File(ids.pkgDir, "parser");
pkgName = ids.pkgName.equals("") ? "parser" : ids.pkgName + ".parser";
if(!pkgDir.exists())
{
if(!pkgDir.mkdir())
{
throw new RuntimeException("Unable to create " + pkgDir.getAbsolutePath());
}
}
}
@Override
public void caseStart(Start tree)
{
tree.getPGrammar().apply(new DepthFirstAdapter()
{
@Override
public void caseAProd(AProd node)
{
hasProductions = true;
if(node.getProdTransform() != null)
{
mapProductionTransformations.put("P"+ResolveIds.name(node.getId().getText()),
node.getProdTransform().clone() );
}
}
}
);
if(!hasProductions)
{
return;
}
//Performing internal transformations
bnf_and_CST_AST_Transformations =
new InternalTransformationsToGrammar(ids, altIds, transformIds,
listSimpleTermTransform,
simpleTermTransform,
mapProductionTransformations,
transformIds.simpleTermOrsimpleListTermTypes);
//apply internal transformations to the grammar.
tree.getPGrammar().apply(bnf_and_CST_AST_Transformations);
if(prettyPrinting)
{
tree.apply(new PrettyPrinter());
return;
}
ConstructProdsMap mapOfProds = new ConstructProdsMap();
tree.apply(mapOfProds);
boolean computeLALR = false;
//This do-while loop is managing the inlining process.
do
{
//Initialization of parsing tables and some symbol tables
//names and elemTypes from ResolveIds.
reinit();
reConstructSymbolTables(tree);
tree.apply(new DepthFirstAdapter()
{
private boolean hasAlternative;
@Override
public void caseATokenDef(ATokenDef node)
{
String name = (String) ids.names.get(node);
String errorName = (String) ids.errorNames.get(node);
if(!ids.ignTokens.containsKey(name))
{
Grammar.addTerminal(name, errorName);
}
}
@Override
public void inAProd(AProd node)
{
hasAlternative = false;
}
@Override
public void inAAlt(AAlt node)
{
hasAlternative = true;
}
@Override
public void outAProd(AProd node)
{
if(hasAlternative)
{
Grammar.addNonterminal((String) ids.names.get(node));
}
}
}
);
//Construct all necessary informations for generation of the parser.
//This map contains all the alternatives of the transformed final grammar
alts = new TypedHashMap(StringCast.instance, NodeCast.instance);
tree.getPGrammar().apply(new ConstructParserGenerationDatas(ids, alts));
try
{
//Generation of parsing symbol tables
Grammar.computeLALR();
computeLALR = true;
}
catch(ConflictException ce)
{
if(activateFilter)
{
activateFilter = false;
}
//Here, we are trying to inline the grammar with production imply in the conflict.
if(processInlining)
{
ComputeInlining grammarToBeInlinedWithConflictualProductions = new ComputeInlining(ce.getConflictualProductions(),
mapOfProds.productionsMap,
tree);
if(!grammarToBeInlinedWithConflictualProductions.computeInlining())
{
System.out.println("\nA previous conflict that we've tried to solve by inline some productions inside the grammars cannot be solved that way. The transformed grammar is : ");
tree.apply(new PrettyPrinter());
throw new RuntimeException(ce.getMessage());
}
System.out.println();
System.out.println("Inlining.");
}
else
{
throw new RuntimeException(ce.getMessage());
}
}
}
while(!computeLALR);
tree.getPGrammar().apply(AET);
CG.setAltElemTypes(AET.getMapOfAltElemType());
tree.getPGrammar().apply(CG);
tree.getPGrammar().apply(CTP);
createParser();
createParserException();
createState();
createTokenIndex();
}
public void reinit()
{
// re-initialize all static structures in the engine
LR0Collection.reinit();
Symbol.reinit();
Production.reinit();
Grammar.reinit();
ids.reinit();
}
private String currentProd;
private String currentAlt;
//reconstruction of map names of class ResolveIds
public void reConstructSymbolTables(Start tree)
{
tree.apply(new DepthFirstAdapter()
{
@Override
public void caseAProd(AProd node)
{
currentProd = ResolveIds.name(node.getId().getText());
String name = "P" + currentProd;
ids.names.put(node, name);
//list of inAAlt code.
Object []list_alt = (Object [])node.getAlts().toArray();
for(int i = 0; i< list_alt.length; i++)
{
((PAlt)list_alt[i]).apply(this);
}
}
@Override
public void outAHelperDef(AHelperDef node)
{
String name = node.getId().getText();
ids.names.put(node, name);
}
@Override
public void outATokenDef(ATokenDef node)
{
String name = "T" + ResolveIds.name(node.getId().getText());
ids.names.put(node, name);
}
@Override
public void caseAAlt(final AAlt alt)
{
if(alt.getAltName() != null)
{
currentAlt =
"A" +
ResolveIds.name(alt.getAltName().getText()) +
currentProd;
ids.names.put(alt, currentAlt);
}
else
{
currentAlt = "A" + currentProd;
ids.names.put(alt, currentAlt);
}
AElem list_elem[] = (AElem[]) alt.getElems().toArray(new AElem[0]);
for(int i=0; i<list_elem.length;i++)
{
list_elem[i].apply(this);
}
}
@Override
public void caseAAst(AAst node)
{}
@Override
public void caseAElem(final AElem elem)
{
if(elem.getElemName() != null)
{
ids.names.put(elem, ResolveIds.name(elem.getElemName().getText()) );
}
else
{
ids.names.put(elem, ResolveIds.name(elem.getId().getText()));
}
}
}
);
}
//Parser.java Generation
private void createParser()
{
BufferedWriter file;
try
{
file = new BufferedWriter(
new FileWriter(
new File(pkgDir, "Parser.java")));
}
catch(IOException e)
{
throw new RuntimeException("Unable to create " + new File(pkgDir, "Parser.java").getAbsolutePath());
}
try
{
// Symbol[] terminals = Symbol.terminals();
Symbol[] nonterminals = Symbol.nonterminals();
Production[] productions = Production.productions();
macros.apply(file, "ParserHeader", new String[] {pkgName,
ids.pkgName.equals("") ? "lexer" : ids.pkgName + ".lexer",
ids.pkgName.equals("") ? "node" : ids.pkgName + ".node",
ids.pkgName.equals("") ? "analysis" : ids.pkgName + ".analysis"});
if(activateFilter && !grammarHasTransformations)
{
macros.apply(file, "ParserNoInliningPushHeader");
macros.apply(file, "ParserCommon", new String[] {", true", ", false"});
}
else
{
macros.apply(file, "ParserInliningPushHeader");
macros.apply(file, "ParserCommon", new String[] {"", ""});
}
for(int i = 500; i < (productions.length - 1); i += 500) {
macros.apply(file, "ParseReduceElseIf", new String[] {"" + (i + 500), "" + i});
}
macros.apply(file, "ParserParseTail", new String[] {firstProductionName});
macros.apply(file, "ParserReduceHead", new String[] {"0"});
//this loop generates the code for all possible reductions and the type of
//the node needed to be created at a local point.
for(int i = 0; i < (productions.length - 1); i++)
{
// Node node = (Node) alts.get(productions[i].name);
if(i % 500 == 0 && i != 0) {
macros.apply(file, "ParserReduceTail", new String[] {});
macros.apply(file, "ParserReduceHead", new String[] {"" + i});
}
if(activateFilter && !grammarHasTransformations)
{
macros.apply(file, "ParserNoInliningReduce", new String[] {
"" + productions[i].index,
"" + productions[i].leftside,
"" + (productions[i].name.startsWith("ANonTerminal$") ||
productions[i].name.startsWith("ATerminal$")),
productions[i].name});
}
else
{
macros.apply(file, "ParserInliningReduce", new String[] {
"" + productions[i].index,
"" + productions[i].leftside,
productions[i].name});
}
}
macros.apply(file, "ParserReduceTail", new String[] {});
//the node creation code. Reduce methods definitions are done here
for(int i = 0; i < (productions.length - 1); i++)
{
macros.apply(file, "ParserNewHeader", new String[] {
"" + productions[i].index,
productions[i].name});
final Node node = (Node) alts.get(productions[i].name);
// final BufferedWriter finalFile = file;
final LinkedList stack = new LinkedList();
node.apply(new DepthFirstAdapter()
{
private int current;
@Override
public void caseAElem(AElem elem)
{
current++;
stack.addFirst(new Element("ParserNewBodyDecl",
new String[] {"" + current}));
}
}
);
try
{
for(Iterator it = stack.iterator(); it.hasNext();)
{
Element e = (Element) it.next();
macros.apply(file, e.macro, e.arguments);
}
}
catch(IOException e)
{
throw new RuntimeException("An error occured while writing to " +
new File(pkgDir, "Parser.java").getAbsolutePath());
}
String nodeName = (String)ids.names.get(node);
String realnodeName = (String)ids.names.get(node);
aParsedAltAdapter =
new GenerateAlternativeCodeForParser(pkgDir, nodeName, realnodeName,
file, transformIds, CG, CTP,
simpleTermTransform, macros,
listSimpleTermTransform,
transformIds.simpleTermOrsimpleListTermTypes);
node.apply(aParsedAltAdapter);
}
macros.apply(file, "ParserActionHeader");
StringBuffer table = new StringBuffer();
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(
new File(pkgDir, "parser.dat"))));
Vector outerArray = new Vector();
//Generating of paring tables
for(int i = 0; i < Grammar.action_.length; i++)
{
Vector innerArray = new Vector();
String mostFrequentAction = "ERROR";
int mostFrequentDestination = i;
int frequence = 0;
Map map = new TreeMap(IntegerComparator.instance);
for(int j = 0; j < Grammar.action_[i].length; j++)
{
if(Grammar.action_[i][j] != null)
{
if(Grammar.action_[i][j][0] == 1)
{
Integer index = new Integer(Grammar.action_[i][j][1]);
Integer count = (Integer) map.get(index);
int freq = count == null ? 0 : count.intValue();
map.put(index, new Integer(++freq));
if(freq > frequence)
{
frequence = freq;
mostFrequentAction = "REDUCE";
mostFrequentDestination = Grammar.action_[i][j][1];
}
}
}
}
table.append("\t\t\t{");
table.append("{" + -1 + ", " +
mostFrequentAction + ", " +
mostFrequentDestination + "}, ");
innerArray.addElement(
new int[] {-1,
mostFrequentAction.equals("ERROR") ? 3 : 1,
mostFrequentDestination});
for(int j = 0; j < Grammar.action_[i].length; j++)
{
if(Grammar.action_[i][j] != null)
{
switch(Grammar.action_[i][j][0])
{
case 0:
table.append("{" + j + ", SHIFT, " + Grammar.action_[i][j][1] + "}, ");
innerArray.addElement(new int[] {j, 0, Grammar.action_[i][j][1]});
break;
case 1:
if(Grammar.action_[i][j][1] != mostFrequentDestination)
{
table.append("{" + j + ", REDUCE, " + Grammar.action_[i][j][1] + "}, ");
innerArray.addElement(new int[] {j, 1, Grammar.action_[i][j][1]});
}
break;
case 2:
table.append("{" + j + ", ACCEPT, -1}, ");
innerArray.addElement(new int[] {j, 2, -1});
break;
}
}
}
table.append("}," + System.getProperty("line.separator"));
outerArray.addElement(innerArray);
}
file.write("" + table);
out.writeInt(outerArray.size());
for(Enumeration e = outerArray.elements(); e.hasMoreElements();)
{
Vector innerArray = (Vector) e.nextElement();
out.writeInt(innerArray.size());
for(Enumeration n = innerArray.elements(); n.hasMoreElements();)
{
int[] array = (int[]) n.nextElement();
for(int i = 0; i < 3; i++)
{
out.writeInt(array[i]);
}
}
}
macros.apply(file, "ParserActionTail");
macros.apply(file, "ParserGotoHeader");
table = new StringBuffer();
outerArray = new Vector();
for(int j = 0; j < nonterminals.length - 1; j++)
{
Vector innerArray = new Vector();
int mostFrequent = -1;
int frequence = 0;
Map map = new TreeMap(IntegerComparator.instance);
for(int i = 0; i < Grammar.goto_.length; i++)
{
if(Grammar.goto_[i][j] != -1)
{
Integer index = new Integer(Grammar.goto_[i][j]);
Integer count = (Integer) map.get(index);
int freq = count == null ? 0 : count.intValue();
map.put(index, new Integer(++freq));
if(freq > frequence)
{
frequence = freq;
mostFrequent = Grammar.goto_[i][j];
}
}
}
table.append("\t\t\t{");
table.append("{" + (-1) + ", " + mostFrequent + "}, ");
innerArray.addElement(new int[] {-1, mostFrequent});
for(int i = 0; i < Grammar.goto_.length; i++)
{
if((Grammar.goto_[i][j] != -1) &&
(Grammar.goto_[i][j] != mostFrequent))
{
table.append("{" + i + ", " + Grammar.goto_[i][j] + "}, ");
innerArray.addElement(new int[] {i, Grammar.goto_[i][j]});
}
}
table.append("}," + System.getProperty("line.separator"));
outerArray.addElement(innerArray);
}
file.write("" + table);
out.writeInt(outerArray.size());
for(Enumeration e = outerArray.elements(); e.hasMoreElements();)
{
Vector innerArray = (Vector) e.nextElement();
out.writeInt(innerArray.size());
for(Enumeration n = innerArray.elements(); n.hasMoreElements();)
{
int[] array = (int[]) n.nextElement();
for(int i = 0; i < 2; i++)
{
out.writeInt(array[i]);
}
}
}
macros.apply(file, "ParserGotoTail");
macros.apply(file, "ParserErrorsHeader");
table = new StringBuffer();
StringBuffer index = new StringBuffer();
int nextIndex = 0;
Map errorIndex = new TypedTreeMap(
StringComparator.instance,
StringCast.instance,
IntegerCast.instance);
outerArray = new Vector();
Vector indexArray = new Vector();
index.append("\t\t\t");
for(int i = 0; i < Grammar.action_.length; i++)
{
StringBuffer s = new StringBuffer();
s.append("expecting: ");
boolean comma = false;
for(int j = 0; j < Grammar.action_[i].length; j++)
{
if(Grammar.action_[i][j] != null)
{
if(comma)
{
s.append(", ");
}
else
{
comma = true;
}
s.append(Symbol.symbol(j, true).errorName);
}
}
if(errorIndex.containsKey(s.toString()))
{
index.append(errorIndex.get(s.toString()) + ", ");
indexArray.addElement(errorIndex.get(s.toString()));
}
else
{
table.append("\t\t\t\"" + s + "\"," + System.getProperty("line.separator"));
outerArray.addElement(s.toString());
errorIndex.put(s.toString(), new Integer(nextIndex));
indexArray.addElement(new Integer(nextIndex));
index.append(nextIndex++ + ", ");
}
}
file.write("" + table);
out.writeInt(outerArray.size());
for(Enumeration e = outerArray.elements(); e.hasMoreElements();)
{
String s = (String) e.nextElement();
out.writeInt(s.length());
int length = s.length();
for(int i = 0; i < length; i++)
{
out.writeChar(s.charAt(i));
}
}
out.writeInt(indexArray.size());
for(Enumeration e = indexArray.elements(); e.hasMoreElements();)
{
Integer n = (Integer) e.nextElement();
out.writeInt(n.intValue());
}
out.close();
macros.apply(file, "ParserErrorsTail");
macros.apply(file, "ParserErrorIndexHeader");
file.write("" + index);
macros.apply(file, "ParserErrorIndexTail");
macros.apply(file, "ParserTail");
}
catch(IOException e)
{
throw new RuntimeException("An error occured while writing to " +
new File(pkgDir, "Parser.java").getAbsolutePath());
}
try
{
file.close();
}
catch(IOException e)
{}
}
private void createTokenIndex()
{
BufferedWriter file;
try
{
file = new BufferedWriter(
new FileWriter(
new File(pkgDir, "TokenIndex.java")));
}
catch(IOException e)
{
throw new RuntimeException("Unable to create " + new File(pkgDir, "TokenIndex.java").getAbsolutePath());
}
try
{
Symbol[] terminals = Symbol.terminals();
macros.apply(file, "TokenIndexHeader", new String[] {pkgName,
ids.pkgName.equals("") ? "node" : ids.pkgName + ".node",
ids.pkgName.equals("") ? "analysis" : ids.pkgName + ".analysis"});
for(int i = 0; i < (terminals.length - 2); i++)
{
macros.apply(file, "TokenIndexBody", new String[] {terminals[i].name, "" + i});
}
macros.apply(file, "TokenIndexTail", new String[] {"" + (terminals.length - 2)});
}
catch(IOException e)
{
throw new RuntimeException("An error occured while writing to " +
new File(pkgDir, "TokenIndex.java").getAbsolutePath());
}
try
{
file.close();
}
catch(IOException e)
{}
}
private void createParserException()
{
BufferedWriter file;
try
{
file = new BufferedWriter(
new FileWriter(
new File(pkgDir, "ParserException.java")));
}
catch(IOException e)
{
throw new RuntimeException("Unable to create " + new File(pkgDir, "ParserException.java").getAbsolutePath());
}
try
{
macros.apply(file, "ParserException", new String[] {pkgName,
ids.pkgName.equals("") ? "node" : ids.pkgName + ".node"});
}
catch(IOException e)
{
throw new RuntimeException("An error occured while writing to " +
new File(pkgDir, "ParserException.java").getAbsolutePath());
}
try
{
file.close();
}
catch(IOException e)
{}
}
private void createState()
{
BufferedWriter file;
try
{
file = new BufferedWriter(
new FileWriter(
new File(pkgDir, "State.java")));
}
catch(IOException e)
{
throw new RuntimeException("Unable to create " + new File(pkgDir, "State.java").getAbsolutePath());
}
try
{
macros.apply(file, "State", new String[] {pkgName});
}
catch(IOException e)
{
throw new RuntimeException("An error occured while writing to " +
new File(pkgDir, "State.java").getAbsolutePath());
}
try
{
file.close();
}
catch(IOException e)
{}
}
/*
private int count(String name)
{
if(name.charAt(0) != 'X')
{
return 0;
}
StringBuffer s = new StringBuffer();
int i = 1;
while((i < name.length()) &&
(name.charAt(i) >= '0') &&
(name.charAt(i) <= '9'))
{
s.append(name.charAt(i++));
}
return Integer.parseInt(s.toString());
}
*/
/*
private String name(String name)
{
if(name.charAt(0) != 'X')
{
return name;
}
int i = 1;
while((i < name.length()) &&
(name.charAt(i) >= '0') &&
(name.charAt(i) <= '9'))
{
i++;
}
return name.substring(i);
}
*/
static class Element
{
String macro;
String[] arguments;
Element(String macro, String[] arguments)
{
this.macro = macro;
this.arguments = arguments;
}
}
}
| gpl-3.0 |
vbisbest/ShadowOS | ModifiedFiles/HttpRequestExecutor.java | 15000 | /*
* $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/module-main/src/main/java/org/apache/http/protocol/HttpRequestExecutor.java $
* $Revision: 576073 $
* $Date: 2007-09-16 03:53:13 -0700 (Sun, 16 Sep 2007) $
*
* ====================================================================
* 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
*
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.protocol;
import java.io.IOException;
import java.net.ProtocolException;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.params.CoreProtocolPNames;
// ShadowOS
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
/**
* Sends HTTP requests and receives the responses.
* Takes care of request preprocessing and response postprocessing
* by the respective interceptors.
*
* @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
*
* @version $Revision: 576073 $
*
* @since 4.0
*
* @deprecated Please use {@link java.net.URL#openConnection} instead.
* Please visit <a href="http://android-developers.blogspot.com/2011/09/androids-http-clients.html">this webpage</a>
* for further details.
*/
@Deprecated
public class HttpRequestExecutor {
/**
* Create a new request executor.
*/
public HttpRequestExecutor() {
super();
}
/**
* Decide whether a response comes with an entity.
* The implementation in this class is based on RFC 2616.
* Unknown methods and response codes are supposed to
* indicate responses with an entity.
* <br/>
* Derived executors can override this method to handle
* methods and response codes not specified in RFC 2616.
*
* @param request the request, to obtain the executed method
* @param response the response, to obtain the status code
*/
protected boolean canResponseHaveBody(final HttpRequest request,
final HttpResponse response) {
if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) {
return false;
}
int status = response.getStatusLine().getStatusCode();
return status >= HttpStatus.SC_OK
&& status != HttpStatus.SC_NO_CONTENT
&& status != HttpStatus.SC_NOT_MODIFIED
&& status != HttpStatus.SC_RESET_CONTENT;
}
/**
* Synchronously send a request and obtain the response.
*
* @param request the request to send. It will be preprocessed.
* @param conn the open connection over which to send
*
* @return the response to the request, postprocessed
*
* @throws HttpException in case of a protocol or processing problem
* @throws IOException in case of an I/O problem
*/
public HttpResponse execute(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("Client connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
try {
HttpResponse response = doSendRequest(request, conn, context);
if (response == null) {
response = doReceiveResponse(request, conn, context);
}
return response;
} catch (IOException ex) {
conn.close();
throw ex;
} catch (HttpException ex) {
conn.close();
throw ex;
} catch (RuntimeException ex) {
conn.close();
throw ex;
}
}
/**
* Prepare a request for sending.
*
* @param request the request to prepare
* @param processor the processor to use
* @param context the context for sending the request
*
* @throws HttpException in case of a protocol or processing problem
* @throws IOException in case of an I/O problem
*/
public void preProcess(
final HttpRequest request,
final HttpProcessor processor,
final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
// ShadowOS
shadowLog(request, context);
processor.process(request, context);
}
/**
* Send a request over a connection.
* This method also handles the expect-continue handshake if necessary.
* If it does not have to handle an expect-continue handshake, it will
* not use the connection for reading or anything else that depends on
* data coming in over the connection.
*
* @param request the request to send, already
* {@link #preProcess preprocessed}
* @param conn the connection over which to send the request,
* already established
* @param context the context for sending the request
*
* @return a terminal response received as part of an expect-continue
* handshake, or
* <code>null</code> if the expect-continue handshake is not used
*
* @throws HttpException in case of a protocol or processing problem
* @throws IOException in case of an I/O problem
*/
protected HttpResponse doSendRequest(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws IOException, HttpException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("HTTP connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpResponse response = null;
context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.FALSE);
conn.sendRequestHeader(request);
if (request instanceof HttpEntityEnclosingRequest) {
// Check for expect-continue handshake. We have to flush the
// headers and wait for an 100-continue response to handle it.
// If we get a different response, we must not send the entity.
boolean sendentity = true;
final ProtocolVersion ver =
request.getRequestLine().getProtocolVersion();
if (((HttpEntityEnclosingRequest) request).expectContinue() &&
!ver.lessEquals(HttpVersion.HTTP_1_0)) {
conn.flush();
// As suggested by RFC 2616 section 8.2.3, we don't wait for a
// 100-continue response forever. On timeout, send the entity.
int tms = request.getParams().getIntParameter(
CoreProtocolPNames.WAIT_FOR_CONTINUE, 2000);
if (conn.isResponseAvailable(tms)) {
response = conn.receiveResponseHeader();
if (canResponseHaveBody(request, response)) {
conn.receiveResponseEntity(response);
}
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
if (status != HttpStatus.SC_CONTINUE) {
throw new ProtocolException(
"Unexpected response: " + response.getStatusLine());
}
// discard 100-continue
response = null;
} else {
sendentity = false;
}
}
}
if (sendentity) {
conn.sendRequestEntity((HttpEntityEnclosingRequest) request);
}
}
conn.flush();
context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.TRUE);
return response;
}
/**
* Wait for and receive a response.
* This method will automatically ignore intermediate responses
* with status code 1xx.
*
* @param request the request for which to obtain the response
* @param conn the connection over which the request was sent
* @param context the context for receiving the response
*
* @return the final response, not yet post-processed
*
* @throws HttpException in case of a protocol or processing problem
* @throws IOException in case of an I/O problem
*/
protected HttpResponse doReceiveResponse(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("HTTP connection may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
HttpResponse response = null;
int statuscode = 0;
while (response == null || statuscode < HttpStatus.SC_OK) {
response = conn.receiveResponseHeader();
if (canResponseHaveBody(request, response)) {
conn.receiveResponseEntity(response);
}
statuscode = response.getStatusLine().getStatusCode();
} // while intermediate response
return response;
}
/**
* Finish a response.
* This includes post-processing of the response object.
* It does <i>not</i> read the response entity, if any.
* It does <i>not</i> allow for immediate re-use of the
* connection over which the response is coming in.
*
* @param response the response object to finish
* @param processor the processor to use
* @param context the context for post-processing the response
*
* @throws HttpException in case of a protocol or processing problem
* @throws IOException in case of an I/O problem
*/
public void postProcess(
final HttpResponse response,
final HttpProcessor processor,
final HttpContext context)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (processor == null) {
throw new IllegalArgumentException("HTTP processor may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
processor.process(response, context);
}
private void shadowLog(HttpRequest request, HttpContext context)
{
try
{
String shadowHeaders = "";
String shadowPostData = "";
String shadowHost = "";
// Grab the URL
HttpHost target = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
shadowHost = target.toURI();
// Grab the headers
Header[] headers = request.getAllHeaders();
for (Header header : headers) {
shadowHeaders += header.getName() + ":" + header.getValue() + "\r\n";
}
// Grab the post data
if (request instanceof HttpEntityEnclosingRequest) { //test if request is a POST
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
shadowPostData = org.apache.http.util.EntityUtils.toString(entity); //here you have the POST body
}
// ShadowOS
//java.util.logging.Logger.getLogger("ShadowOS").info("Http request: " + shadowHost + "/" + request.getRequestLine());
//shadowOS.shadowLogHTTP(shadowHost, request.getRequestLine().toString(), shadowHeaders, shadowPostData, getClass().getName());
org.json.JSONObject shadowData = new org.json.JSONObject();
org.json.JSONObject shadowCategory = new org.json.JSONObject();
shadowData.put("class", "HttpRequestExecutor");
shadowData.put("url", shadowHost);
shadowData.put("method", "");
shadowData.put("headers", shadowHeaders);
shadowData.put("scheme", "");
shadowData.put("uri", target.toURI());
shadowCategory.put("http", shadowData);
java.util.logging.Logger.getLogger("ShadowOS").info(shadowCategory.toString());
}
catch(Exception e)
{
java.util.logging.Logger.getLogger("ShadowOS").info("Error " + getClass().getName() + ": " + e.getMessage());
}
}
} // class HttpRequestExecutor
| gpl-3.0 |
Laton95/Rune-Mysteries | src/main/java/com/laton95/runemysteries/capability/RejectedCapability.java | 2460 | package com.laton95.runemysteries.capability;
import com.laton95.runemysteries.RuneMysteries;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.IntNBT;
import net.minecraft.util.Direction;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
public class RejectedCapability {
@CapabilityInject(Rejected.class)
public static Capability<Rejected> REJECTED = null;
public static void register() {
CapabilityManager.INSTANCE.register(Rejected.class, new Capability.IStorage<Rejected>() {
@Override
public INBT writeNBT(Capability<Rejected> capability, Rejected instance, Direction direction) {
return IntNBT.valueOf(instance.isRejected() ? 1 : 0);
}
@Override
public void readNBT(Capability<Rejected> capability, Rejected instance, Direction direction, INBT nbt) {
if(((IntNBT) nbt).getInt() == 1) {
instance.setRejected();
}
}
}, () -> null);
MinecraftForge.EVENT_BUS.register(new EventHandlers());
}
public static class Rejected {
private boolean rejected = false;
public void setRejected() {
rejected = true;
}
public boolean isRejected() {
return rejected;
}
}
public static Rejected get(ItemEntity item) {
return item.getCapability(RejectedCapability.REJECTED).orElseThrow(() -> new RuntimeException("Did not find capability"));
}
static class EventHandlers {
@SubscribeEvent
public void attach(AttachCapabilitiesEvent<Entity> event) {
if(event.getObject() instanceof ItemEntity) {
event.addCapability(new ResourceLocation(RuneMysteries.MOD_ID, ""), new ICapabilityProvider() {
final Rejected rejected = new Rejected();
final LazyOptional<Rejected> rejectedInstance = LazyOptional.of(() -> rejected);
@Override
public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
return REJECTED.orEmpty(cap, rejectedInstance);
}
});
}
}
}
}
| gpl-3.0 |
schuylernathaniel/PixelDungeon2--edited | src/com/watabou/input/Touchscreen.java | 2813 | /*
* Copyright (C) 2012-2014 Oleg Dolya
*
* 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.watabou.input;
import java.util.ArrayList;
import java.util.HashMap;
import com.watabou.pixeldungeon.utils.PointF;
import com.watabou.pixeldungeon.utils.Signal;
import android.view.MotionEvent;
public class Touchscreen {
public static Signal<Touch> event = new Signal<Touch>( true );
public static HashMap<Integer,Touch> pointers = new HashMap<Integer, Touch>();
public static float x;
public static float y;
public static boolean touched;
public static void processTouchEvents( ArrayList<MotionEvent> events ) {
int size = events.size();
for (int i=0; i < size; i++) {
MotionEvent e = events.get( i );
Touch touch;
switch (e.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
touched = true;
touch = new Touch( e, 0 );
pointers.put( e.getPointerId( 0 ), touch );
event.dispatch( touch );
break;
case MotionEvent.ACTION_POINTER_DOWN:
int index = e.getActionIndex();
touch = new Touch( e, index );
pointers.put( e.getPointerId( index ), touch );
event.dispatch( touch );
break;
case MotionEvent.ACTION_MOVE:
int count = e.getPointerCount();
for (int j=0; j < count; j++) {
pointers.get( e.getPointerId( j ) ).update( e, j );
}
event.dispatch( null );
break;
case MotionEvent.ACTION_POINTER_UP:
event.dispatch( pointers.remove( e.getPointerId( e.getActionIndex() ) ).up() );
break;
case MotionEvent.ACTION_UP:
touched = false;
event.dispatch( pointers.remove( e.getPointerId( 0 ) ).up() );
break;
}
e.recycle();
}
}
public static class Touch {
public PointF start;
public PointF current;
public boolean down;
public Touch( MotionEvent e, int index ) {
float x = e.getX( index );
float y = e.getY( index );
start = new PointF( x, y );
current = new PointF( x, y );
down = true;
}
public void update( MotionEvent e, int index ) {
current.set( e.getX( index ), e.getY( index ) );
}
public Touch up() {
down = false;
return this;
}
}
}
| gpl-3.0 |
sophalkim/Reddit_is_Fun_Practice | src/com/andrewshu/android/reddit/submit/SubmitLinkActivity2.java | 8594 | package com.andrewshu.android.reddit.submit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.client.HttpClient;
import android.app.TabActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import com.andrewshu.android.reddit.R;
import com.andrewshu.android.reddit.captcha.CaptchaCheckRequiredTask;
import com.andrewshu.android.reddit.common.Constants;
import com.andrewshu.android.reddit.common.RedditIsFunHttpClientFactory;
import com.andrewshu.android.reddit.common.util.StringUtils;
import com.andrewshu.android.reddit.common.util.Util;
import com.andrewshu.android.reddit.login.LoginTask;
import com.andrewshu.android.reddit.settings.RedditSettings;
import com.andrewshu.android.reddit.things.ThingInfo;
public class SubmitLinkActivity2 extends TabActivity {
public static final String TAG = "SubmitLinkActivity2";
// Group 1: Subreddit. Group 2: thread id (no t3_prefix)
private final Pattern NEW_THREAD_PATTERN = Pattern.compile(Constants.COMMENT_PATH_PATTERN_STRING);
// Group1: whole error. Group 2: the time part
private final Pattern RATELIMIT_RETRY_PATTERN = Pattern.compile("(you are trying to submit too fast. try again in (.+?)\\.)");
//Group 1 Subreddit
private final Pattern SUBMIT_PATH_PATTERN = Pattern.compile("/(?:r/([^/]+)/)?submit/?");
TabHost mTabHost;
private RedditSettings mSettings = new RedditSettings();
private final HttpClient mClient = RedditIsFunHttpClientFactory.getGzipHttpClient();
private String mSubmitUrl;
private volatile String mCaptchaIden = null;
private volatile String mCaptchaUrl = null;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
CookieSyncManager.createInstance(getApplicationContext());
mSettings.loadRedditPreferences(this, mClient);
setRequestedOrientation(mSettings.getRotation());
setTheme(mSettings.getTheme());
setContentView(R.layout.submit_link_main);
final FrameLayout fl = (FrameLayout) findViewById(android.R.id.tabcontent);
if (Util.isLightTheme(mSettings.getTheme())) {
fl.setBackgroundResource(R.color.gray_75);
} else {
fl.setBackgroundResource(R.color.black);
}
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec(Constants.TAB_LINK).setIndicator("link").setContent(R.id.submit_link_view));
mTabHost.addTab(mTabHost.newTabSpec(Constants.TAB_TEXT).setIndicator("text").setContent(R.id.submit_text_view));
mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
// Copy everything (except url and text) from old tab to new tab.
final EditText submitLinkTitle = (EditText) findViewById(R.id.submit_link_title);
final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
final EditText submitTextTitle = (EditText) findViewById(R.id.submit_text_title);
final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
if (Constants.TAB_LINK.equals(tabId)) {
submitLinkTitle.setText(submitTextTitle.getText());
submitLinkReddit.setText(submitTextReddit.getText());
} else {
submitTextTitle.setText(submitLinkTitle.getText());
submitTextReddit.setText(submitLinkReddit.getText());
}
}
});
mTabHost.setCurrentTab(0);
if (mSettings.isLoggedIn()) {
start();
} else {
showDialog(Constants.DIALOG_LOGIN);
}
}
@Override
public void onResume() {
super.onResume();
mSettings.saveRedditPreferences(this);
CookieSyncManager.getInstance().stopSync();
}
@Override
protected void onPause() {
super.onPause();
mSettings.saveRedditPreferences(this);
CookieSyncManager.getInstance().stopSync();
}
/**
* Enable the UI after user is logged in.
*/
public void start() {
// Intents can be external (browser share page) or from Reddit is fun.
String intentAction = getIntent().getAction();
if (Intent.ACTION_SEND.equals(intentAction)) {
// Share
Bundle extras = getIntent().getExtras();
if (extras != null) {
String url = extras.getString(Intent.EXTRA_TEXT);
final EditText submitLinkUrl = (EditText) findViewById(R.id.submit_link_url);
final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
submitLinkUrl.setText(url);
submitLinkReddit.setText("");
submitTextReddit.setText("");
mSubmitUrl = Constants.REDDIT_BASE_URL + "/submit";
}
} else {
String submitPath = null;
Uri data = getIntent().getData();
if (data != null && Util.isRedditUri(data))
submitPath = data.getPath();
if (submitPath == null)
submitPath = "/submit";
// the URL to do HTTP POST to
mSubmitUrl = Util.absolutePathToURL(submitPath);
// Put the subreddit in the text field
final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
Matcher m = SUBMIT_PATH_PATTERN.matcher(submitPath);
if (m.matches()) {
String subreddit = m.group(1);
if (StringUtils.isEmpty(subreddit)) {
submitLinkReddit.setText("");
submitTextReddit.setText("");
} else {
submitLinkReddit.setText(subreddit);
submitTextReddit.setText(subreddit);
}
}
}
final Button submitLinkButton = (Button) findViewById(R.id.submit_link_button);
submitLinkButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (validateLinkForm()) {
final EditText submitLinkTitle = (EditText) findViewById(R.id.submit_link_title);
final EditText submitLinkUrl = (EditText) findViewById(R.id.submit_link_url);
final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
final EditText submitLinkCaptcha = (EditText) findViewById(R.id.submit_link_captcha);
new SubmitLinkTask(submitLinkTitle.getText().toString(),
submitLinkUrl.getText().toString(),
submitLinkReddit.getText().toString(),
Constants.SUBMIT_KIND_LINK,
submitLinkCaptcha.getText().toString()).execute();
}
}
});
final Button submitTextButton = (Button) findViewById(R.id.submit_text_button);
submitTextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (validateTextForm()) {
final EditText submitTextTitle = (EditText) findViewById(R.id.submit_text_title);
final EditText submitTextText = (EditText) findViewById(R.id.submit_text_text);
final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
final EditText submitTextCaptcha = (EditText) findViewById(R.id.submit_text_captcha);
new SubmitLinkTask(submitTextTitle.getText().toString(),
submitTextText.getText().toString(),
submitTextReddit.getText().toString(),
Constants.SUBMIT_KIND_SELF,
submitTextCaptcha.getText().toString()).execute();
}
}
});
// Check the CAPTCHA
new MyCaptchaCheckRequiredTask().execute();
}
private void returnStatus(int status) {
Intent i = new Intent();
setResult(status, i);
finish();
}
private class MyLoginTask extends LoginTask {
public MyLoginTask(String username, String password) {
super(username, password, mSettings, mClient, getApplicationContext());
}
}
public boolean validateTextForm() {
return true;
}
public boolean validateLinkForm() {
return true;
}
private class SubmitLinkTask extends AsyncTask<Void, Void, ThingInfo> {
String _mTitle, _mUrlOrText, _mSubreddit, _mKind, _mCaptcha;
String _mUserError = "Error creating submission. Please try again.";
SubmitLinkTask(String title, String urlOrText, String subreddit, String kind, String captcha) {
_mTitle = title;
_mUrlOrText = urlOrText;
_mSubreddit = subreddit;
_mKind = kind;
_mCaptcha = captcha;
}
@Override
protected ThingInfo doInBackground(Void... arg0) {
return null;
}
}
private class MyCaptchaCheckRequiredTask extends CaptchaCheckRequiredTask {
public MyCaptchaCheckRequiredTask() {
super(mSubmitUrl, mClient);
}
@Override
protected void saveState() {
}
}
}
| gpl-3.0 |
Gliby/VoiceChat-Base | src/net/gliby/minecraft/voicechat/VoiceChatClient.java | 2433 | package net.gliby.minecraft.voicechat;
import java.io.File;
import javax.net.ssl.KeyManager;
import org.apache.logging.log4j.Logger;
import com.esotericsoftware.kryo.Kryo;
import net.gliby.minecraft.base.keybindings.Keybind;
import net.gliby.minecraft.base.keybindings.KeybindManager;
import net.gliby.minecraft.voicechat.audio.AudioManager;
import net.gliby.minecraft.voicechat.gui.overlay.WidgetManager;
import net.gliby.minecraft.voicechat.keybindings.EnumKeybinds;
import net.gliby.minecraft.voicechat.keybindings.KeyOpenGui;
import net.gliby.minecraft.voicechat.network.client.ClientConnectionHandler;
import net.gliby.minecraft.voicechat.network.client.IClient;
import net.gliby.minecraft.voicechat.settings.ClientSettings;
import net.gliby.minecraft.voicechat.settings.SharedSettings;
public class VoiceChatClient extends VoiceChatShared {
public VoiceChatClient(Logger logger) {
super(logger);
}
AudioManager audioManager;
WidgetManager widgetManager;
KeybindManager keyManager;
@Override
public void preInit(File configDir) {
super.preInit(configDir);
settings = (ClientSettings) load(ClientSettings.class);
save(settings);
keyManager = new KeybindManager();
widgetManager = new WidgetManager();
// TODO server supposed to SharedSettings data to client
for (int i = 0; i < EnumKeybinds.values().length; i++) {
EnumKeybinds enumKey = EnumKeybinds.values()[i];
keyManager.registerKeybind(new Keybind(enumKey.getName(), enumKey.getKeyCode()));
}
eventBus.register(new KeyOpenGui(this));
audioManager = new AudioManager(this);
Kryo kryo = new Kryo();
getEventBus().register(new ClientConnectionHandler.Connect(this, kryo));
getLogger().info("Started client side Voice Chat.");
}
public WidgetManager getWidgetManager() {
return widgetManager;
}
@Override
public void init() {
super.init();
}
/** Key bindings should be registered before init() is called! **/
public KeybindManager getKeyManager() {
return keyManager;
}
public AudioManager getAudioManager() {
return audioManager;
}
// TODO implement client(network handle)
public IClient getClient() {
return client;
}
// TODO CONTINUE: make a container for this, so null pointer exceptions
// aren't thrown.
private IClient client;
public void setClient(IClient client) {
this.client = client;
}
public ClientSettings getClientSettings() {
return (ClientSettings) settings;
}
}
| gpl-3.0 |
Moony22/Compact_Crafting | src/main/java/moony/compactcrafting/items/ItemC1StoneAxe.java | 566 | package moony.compactcrafting.items;
import moony.compactcrafting.CCMain;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemAxe;
public class ItemC1StoneAxe extends ItemAxe {
public ItemC1StoneAxe(ToolMaterial enumToolMaterial) {
super(enumToolMaterial);
this.setCreativeTab(CreativeTabs.tabTools);
}
@Override
public void registerIcons(IIconRegister par1IconRegister)
{
this.itemIcon = par1IconRegister.registerIcon(CCMain.modid + ":" + "C1StoneAxe");
}
}
| gpl-3.0 |
rferreira/uva-core | src/com/uvasoftware/core/primitives/PrincipalInfo.java | 2545 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.1-b01-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2006.07.07 at 09:44:38 PM MST
//
package com.uvasoftware.core.primitives;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.sifinfo.org/infrastructure/1.x}ContactName" minOccurs="0"/>
* <element ref="{http://www.sifinfo.org/infrastructure/1.x}ContactTitle" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"contactName",
"contactTitle"
})
@XmlRootElement(name = "PrincipalInfo")
public class PrincipalInfo {
@XmlElement(name = "ContactName")
protected String contactName;
@XmlElement(name = "ContactTitle")
protected String contactTitle;
/**
* Gets the value of the contactName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContactName() {
return contactName;
}
/**
* Sets the value of the contactName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContactName(String value) {
this.contactName = value;
}
/**
* Gets the value of the contactTitle property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContactTitle() {
return contactTitle;
}
/**
* Sets the value of the contactTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContactTitle(String value) {
this.contactTitle = value;
}
}
| gpl-3.0 |
SiLeBAT/FSK-Lab | de.bund.bfr.knime.pmm.nodes/src/de/bund/bfr/knime/pmm/js/common/MiscList.java | 3243 | /*******************************************************************************
* Copyright (c) 2015 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.pmm.js.common;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* List of PmmLab Misc.
*
* @see Misc
* @author Miguel de Alba
*/
@JsonAutoDetect
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public class MiscList {
private int numMiscs;
private Misc[] miscs;
/**
* Returns an array with the miscs in the list.
*
* If not set returns null.
*
* @return an array with the miscs in the list
*/
public Misc[] getMiscs() {
return miscs;
}
/**
* Sets the miscs in the list.
*
* @param miscs
* array of miscs to be set
*/
public void setMiscs(final Misc[] miscs) {
numMiscs = miscs.length;
this.miscs = miscs;
}
/**
* Saves the list of miscs into a {@link NodeSettingsWO} with properties:
* <ul>
* <li>Integer "numMiscs"
* <li>Variable number of settings with key "miscs" and a suffix. E.g. "miscs0",
* "miscs1", etc.
* </ul>
*
* @param settings
* settings where to save the {@link MiscList} properties
*/
public void saveToNodeSettings(NodeSettingsWO settings) {
SettingsHelper.addInt("numMiscs", numMiscs, settings);
for (int i = 0; i < numMiscs; i++) {
miscs[i].saveToNodeSettings(settings.addNodeSettings("miscs" + i));
}
}
/**
* Load properties of the matrix list from a {@link NodeSettingsRO}.
*
* @param settings
* with properties:
* <ul>
* <li>Integer "numMiscs"
* <li>Variable number of settings with key "miscs" and a suffix.
* E.g. "miscs0", "miscs1", etc.
* </ul>
*/
public void loadFromNodeSettings(NodeSettingsRO settings) {
try {
numMiscs = settings.getInt("numMiscs");
miscs = new Misc[numMiscs];
for (int i = 0; i < numMiscs; i++) {
miscs[i] = new Misc();
miscs[i].loadFromNodeSettings(settings.getNodeSettings("miscs" + i));
}
} catch (InvalidSettingsException e) {
}
}
}
| gpl-3.0 |
Meldanor/RMITest | src/main/java/library/ServerInterface.java | 949 | /*
* Copyright (C) 2013 Kilian Gaertner
*
* This file is part of RMITest.
*
* RMITest is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* RMITest 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 RMITest. If not, see <http://www.gnu.org/licenses/>.
*/
package library;
import java.rmi.Remote;
import java.rmi.RemoteException;
/*
* Interface shared by server and client
*/
public interface ServerInterface extends Remote {
public void count() throws RemoteException;
public int getCounter() throws RemoteException;
}
| gpl-3.0 |
atiro/PPP | src/uk/org/tiro/android/PPP/PoliticsFeedDBHelper.java | 22078 | package uk.org.tiro.android.PPP;
import android.app.Application;
import android.app.Activity;
import android.content.Context;
import android.content.ContentValues;
import android.database.SQLException;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import java.util.Date;
import java.util.Calendar;
import android.util.Log;
class PoliticsFeedDBHelper {
static final String MATCH="match";
static final String TRIGGER_ID="trigger_id";
static final String TRIGGER_TYPE="trigger_type";
static final String ITEM_ID="item_id";
static final String HOUSE="house";
static final String HIGHLIGHT="highlight"; // Alert coming debate
static final String READ="read"; // 2 - readable&new, 1 = unread,0-old
static final String NEW="new"; // 2 - new, 1 = unread, 0 - old
static final String DATE="date"; // Date of debate
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private ActsDBHelper actshelper;
private BillsDBHelper billshelper;
private CommonsDBHelper commonshelper;
private LordsDBHelper lordshelper;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DBAdaptor.DATABASE_NAME, null, DBAdaptor.DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO
}
}
public PoliticsFeedDBHelper(Context ctx) {
this.mCtx = ctx;
}
public PoliticsFeedDBHelper open() throws SQLException {
Log.v("PPP", "Creating PoliticsFeedDB Helper");
this.mDbHelper = new DatabaseHelper(this.mCtx);
this.mDb = this.mDbHelper.getWritableDatabase();
// PPPApp pppApp = (PPPApp)((Activity)this.mCtx).getApplication();
// this.mDb = ((PPPApp)(((Activity)this.mCtx).getApplication())).dbadaptor.mDb;
// this.mDb = pppApp.dbadaptor.mDb;
return this;
}
public void close() {
Log.v("PPP", "Closing PoliticsFeedDB Helper");
if(this.mDb != null) {
this.mDb.close();
}
if(this.mDbHelper != null) {
this.mDbHelper.close();
}
}
public boolean checkExists(Integer item_id, House house) {
String [] args = {item_id.toString(), house.toOrdinal()};
Cursor c = this.mDb.rawQuery("SELECT _id FROM politicsfeed WHERE item_id = ? AND house = ?", args);
if(c.getCount() > 0) {
c.close();
return true;
} else {
c.close();
return false;
}
}
public void insert_bill(String trigger, long trigger_id, Integer bill_id, boolean new_trigger) {
ContentValues cv = new ContentValues();
/*
BillsDBHelper billshelper = new BillsDBHelper(this.mCtx).open();
Cursor c = billshelper.getBill(bill_id);
c.moveToFirst(); // TODO check got result
Create message
New bill ' ' matched trigger' '
Bill ' ' matching trigger' ' has moved to stage ''
Bill ' ' matching trigger' ' has moved to house ''
*/
if(checkExists(bill_id, House.NEITHER) == false) {
//Log.v("PPP", "Adding feed entry for bill : " + bill_id.toString());
// TODO Check trigger doesn't already exist
cv.put(MATCH, trigger);
// cv.put(BILL_ID, bill.getID());
cv.put(ITEM_ID, bill_id);
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
cv.put(DATE, c.getTimeInMillis() / 1000);
cv.put(TRIGGER_ID, trigger_id);
cv.put(TRIGGER_TYPE, Trigger.BILL.ordinal());
cv.put(HOUSE, House.NEITHER.ordinal());
c = Calendar.getInstance();
cv.put(HIGHLIGHT, c.getTimeInMillis() / 1000);
cv.put(READ, 0);
if(new_trigger) {
cv.put(NEW, 2);
} else {
cv.put(NEW, 0);
}
// ADDED - getdate
this.mDb.insert("politicsfeed", MATCH , cv);
} else {
//Log.v("PPP", "Entry already exists, skipping");
}
}
public void insert_act(String trigger, long trigger_id, Integer act_id, boolean new_trigger) {
ContentValues cv = new ContentValues();
/*
ActsDBHelper actshelper = new ActsDBHelper(this.mCtx).open();
Log.v("PPP", "Adding feed entry for act : " + act_id.toString());
Cursor curs = actshelper.getAct(act_id);
curs.moveToFirst();
*/
// TODO Check trigger doesn't already exist
if(checkExists(act_id, House.NEITHER) == false) {
cv.put(MATCH, trigger);
cv.put(ITEM_ID, act_id);
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
cv.put(DATE, c.getTimeInMillis() / 1000);
cv.put(TRIGGER_ID, trigger_id);
cv.put(TRIGGER_TYPE, Trigger.ACT.ordinal());
cv.put(HOUSE, House.NEITHER.ordinal());
c = Calendar.getInstance();
cv.put(HIGHLIGHT, c.getTimeInMillis() / 1000);
cv.put(READ, 0);
if(new_trigger) {
cv.put(NEW, 2);
} else {
cv.put(NEW, 0);
}
// ADDED - getdate
this.mDb.insert("politicsfeed", MATCH, cv);
}
}
public void insert_commons_debate(String trigger, long trigger_id, Integer commons_id, boolean new_trigger) {
if(checkExists(commons_id, House.COMMONS) == false) {
Trigger trigger_type;
ContentValues cv = new ContentValues();
CommonsDBHelper commonshelper = new CommonsDBHelper(this.mCtx).open();
//Log.v("PPP", "Adding feed entry for debate : " + commons_id.toString());
Cursor curs = commonshelper.getDebate(commons_id);
curs.moveToFirst(); // TODO check got result
/* Create message
New bill ' ' matched trigger ' '
Bill ' ' matching trigger ' ' has moved to stage ''
Bill ' ' matching trigger' ' has moved to house ''
*/
Chamber chamber = commonshelper.getChamber(curs);
if(chamber == Chamber.MAIN) {
trigger_type = Trigger.MAIN;
} else if(chamber == Chamber.SELECT) {
trigger_type = Trigger.SELECT;
} else if(chamber == Chamber.WESTMINSTER) {
trigger_type = Trigger.WESTMINSTER;
} else {
trigger_type = Trigger.GENERAL;
}
// TODO Check trigger doesn't already exist
cv.put(MATCH, trigger);
// c.set(Calendar.HOUR, 0);
// c.set(Calendar.MINUTE, 0);
// c.set(Calendar.SECOND, 0);
// c.set(Calendar.MILLISECOND, 0);
cv.put(DATE, commonshelper.getDateLong(curs));
cv.put(TRIGGER_ID, trigger_id);
cv.put(TRIGGER_TYPE, trigger_type.ordinal());
cv.put(ITEM_ID, commons_id);
cv.put(HOUSE, House.COMMONS.ordinal());
Calendar c = Calendar.getInstance();
cv.put(HIGHLIGHT, c.getTimeInMillis() / 1000);
cv.put(READ, 0);
if(new_trigger) {
cv.put(NEW, 2);
} else {
cv.put(NEW, 0);
}
// ADDED - getdate
this.mDb.insert("politicsfeed", MATCH, cv);
curs.close();
commonshelper.close();
} else {
//Log.v("PPP", "ALready in feed");
}
}
public void insert_lords_debate(String trigger, long trigger_id, Integer lords_id, boolean new_trigger) {
if(checkExists(lords_id, House.LORDS) == false) {
Trigger trigger_type;
ContentValues cv = new ContentValues();
lordshelper = new LordsDBHelper(this.mCtx).open();
//Log.v("PPP", "Adding feed entry for debate : " + lords_id.toString());
Cursor curs = lordshelper.getDebate(lords_id);
curs.moveToFirst(); // TODO check got result
/* Create message
New bill ' ' matched trigger ' '
Bill ' ' matching trigger ' ' has moved to stage ''
Bill ' ' matching trigger ' ' has moved to house ''
*/
Chamber chamber = lordshelper.getChamber(curs);
if(chamber == Chamber.MAIN) {
trigger_type = Trigger.MAIN;
} else if(chamber == Chamber.SELECT) {
trigger_type = Trigger.SELECT;
} else {
trigger_type = Trigger.GRAND;
}
// TODO Check trigger doesn't already exist
cv.put(MATCH, trigger);
cv.put(TRIGGER_ID, trigger_id);
cv.put(TRIGGER_TYPE, trigger_type.ordinal());
cv.put(ITEM_ID, lords_id);
cv.put(HOUSE, House.LORDS.ordinal());
// Calendar c = Calendar.getInstance();
// c.set(Calendar.HOUR, 0);
// c.set(Calendar.MINUTE, 0);
// c.set(Calendar.SECOND, 0);
// c.set(Calendar.MILLISECOND, 0);
// cv.put(DATE, c.getTimeInMillis() / 1000);
cv.put(DATE, lordshelper.getDateLong(curs));
Calendar c = Calendar.getInstance();
cv.put(HIGHLIGHT, c.getTimeInMillis() / 1000);
cv.put(READ, 0);
if(new_trigger) {
cv.put(NEW, 2);
} else {
cv.put(NEW, 0);
}
this.mDb.insert("politicsfeed", MATCH, cv);
curs.close();
lordshelper.close();
} else {
//Log.v("PPP", "Already exists, skipping");
}
}
public Cursor getPoliticsFeed(Integer days_ahead, Boolean is_new) {
// Calendar c = Calendar.getInstance();
// c.set(Calendar.HOUR, 0);
// c.set(Calendar.MINUTE, 0);
// c.set(Calendar.SECOND, 0);
// c.set(Calendar.MILLISECOND, 0);
// Try to ensure we include bills/acts with today's
// date by adding half-day leeway.
// Long today = (c.getTimeInMillis() / 1000) - 43200;
// Long ahead = today + (days_ahead * 24 * 60 * 60);
// String[] args = {today.toString()};
String date_clause = "date >= strftime('%s', strftime('%Y-%m-%d', 'now')) and date <= strftime('%s', strftime('%Y-%m-%d', 'now', '+" + days_ahead + " days'))";
if(is_new == true) {
date_clause += " AND new = 1";
}
return(this.mDb.rawQuery("SELECT _id, match, trigger_id, trigger_type, item_id, house, highlight, read, new, date from politicsfeed WHERE " + date_clause + " ORDER BY DATE asc, _id asc", null));
}
public Integer getPoliticsFeedCount(House house, Integer days_ahead, Boolean is_new) {
String [] args = {house.toOrdinal()};
Integer nf_count = -1;
Cursor c;
String date_clause = "date >= strftime('%s', strftime('%Y-%m-%d', 'now')) and date <= strftime('%s', strftime('%Y-%m-%d', 'now', '+" + days_ahead + " days'))";
if(is_new == true) {
date_clause += " AND new = 1";
}
if(house == House.COMMONS) {
c = this.mDb.rawQuery("SELECT COUNT(*) from politicsfeed WHERE " + date_clause + " AND house = ?", args);
} else if(house == House.LORDS) {
c = this.mDb.rawQuery("SELECT COUNT(*) from politicsfeed WHERE " + date_clause + " AND house = ?", args);
} else {
c = this.mDb.rawQuery("SELECT COUNT(*) from politicsfeed WHERE " + date_clause, null);
}
c.moveToFirst();
nf_count = c.getInt(0);
c.close();
return nf_count ;
}
public Cursor getPoliticsToday() {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// Try to ensure we include bills/acts with today's
// date by adding half-day leeway.
Long today = (c.getTimeInMillis() / 1000);
Long tomorrow = today + 86399;
String[] args = {today.toString(), tomorrow.toString()};
return(this.mDb.rawQuery("SELECT _id, match, trigger_id, trigger_type, item_id, house, highlight, read, new, date from politicsfeed WHERE date >= ? AND date < ? ORDER BY DATE asc, _id asc", args));
}
public Integer getPoliticsTodayCount() {
Integer nf_count = -1;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Long today = (cal.getTimeInMillis() / 1000);
Long tomorrow = today + 86399;
String[] args = {today.toString(), tomorrow.toString()};
// Try to ensure we include bills/acts with today's
// date by adding half-day leeway.
Cursor c = this.mDb.rawQuery("SELECT COUNT(*) from politicsfeed WHERE date >= ? AND date < ?", args);
c.moveToFirst();
nf_count = c.getInt(0);
c.close();
return nf_count ;
}
public Cursor getPoliticsLatest() {
return(this.mDb.rawQuery("SELECT _id, match, trigger_id, trigger_type, item_id, house, highlight, read, new, date from politicsfeed ORDER BY date desc, _id asc LIMIT 20", null));
}
public Integer getPoliticsLatestCount() {
Integer nf_count = -1;
Cursor c= this.mDb.rawQuery("SELECT COUNT(*) from politicsfeed WHERE new > 0", null);
c.moveToFirst();
nf_count = c.getInt(0);
c.close();
return nf_count;
}
/*
public Cursor getpoliticsfeedFiltered(String match) {
String filter = new String('%' + match + '%');
String [] args = {filter};
return(this.mDb.rawQuery("SELECT _id,title from triggers WHERE match LIKE ? ORDER BY date desc", args));
}
private boolean checkTriggerByMatch(String match) {
String [] args = {match};
Log.v("PPP", "Checking existence of trigger with match: " + match);
Cursor r = this.mDb.rawQuery("SELECT _id from triggers WHERE match = ?", args);
if(r.getCount() > 0) {
r.close();
return true;
} else {
r.close();
return false;
}
}
*/
public String getURL(Cursor c) {
Trigger trigger = getTriggerType(c);
String url = "";
Cursor d = null;
if(trigger == Trigger.ACT) {
actshelper = new ActsDBHelper(this.mCtx).open();
d = actshelper.getAct(getItemID(c));
d.moveToFirst(); // TODO check got result
url = actshelper.getURL(d);
d.close();
actshelper.close();
} else if (trigger == Trigger.BILL) {
billshelper = new BillsDBHelper(this.mCtx).open();
d = billshelper.getBill(getItemID(c));
d.moveToFirst(); // TODO check got result
url = billshelper.getURL(d);
d.close();
billshelper.close();
} else if (trigger == Trigger.MAIN) {
House house = getHouseRaw(c);
if(house == House.COMMONS) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
url = commonshelper.getURL(d);
d.close();
commonshelper.close();
} else {
lordshelper = new LordsDBHelper(this.mCtx).open();
d = lordshelper.getDebate(getItemID(c));
d.moveToFirst();
url = lordshelper.getURL(d);
d.close();
lordshelper.close();
}
} else if (trigger == Trigger.SELECT) {
// Need to get house
House house = getHouseRaw(c);
if(house == House.COMMONS) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
url = commonshelper.getURL(d);
d.close();
commonshelper.close();
} else {
lordshelper = new LordsDBHelper(this.mCtx).open();
d = lordshelper.getDebate(getItemID(c));
d.moveToFirst();
url = lordshelper.getURL(d);
d.close();
lordshelper.close();
}
} else if (trigger == Trigger.WESTMINSTER) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
url = commonshelper.getURL(d);
d.close();
commonshelper.close();
} else if (trigger == Trigger.GRAND) {
lordshelper = new LordsDBHelper(this.mCtx).open();
d = lordshelper.getDebate(getItemID(c));
d = lordshelper.getDebate(getItemID(c));
d.moveToFirst();
url = lordshelper.getURL(d);
d.close();
lordshelper.close();
} else if (trigger == Trigger.GENERAL) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
url = commonshelper.getURL(d);
d.close();
commonshelper.close();
}
if(d != null) {
d.close();
}
return url;
}
public String getMessage(Cursor c) {
// Need to do some work here
Trigger trigger = getTriggerType(c);
String msg = "";
Cursor d = null;
if(trigger == Trigger.ACT) {
actshelper = new ActsDBHelper(this.mCtx).open();
d = actshelper.getAct(getItemID(c));
d.moveToFirst(); // TODO check got result
msg = actshelper.getTitle(d) + " is now an Act.";
d.close();
actshelper.close();
} else if (trigger == Trigger.BILL) {
billshelper = new BillsDBHelper(this.mCtx).open();
d = billshelper.getBill(getItemID(c));
d.moveToFirst(); // TODO check got result
msg = "'" + billshelper.getTitle(d) + "' now at " + billshelper.getStage(d).toString() + " stage.";
d.close();
billshelper.close();
} else if (trigger == Trigger.MAIN) {
// Need to get house
House house = getHouseRaw(c);
if(house == House.COMMONS) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
msg = "'" + commonshelper.getSubject(d) + "'";
msg += " will be debated at ";
msg += "'" + commonshelper.getTitle(d) + "'.";
d.close();
commonshelper.close();
} else {
lordshelper = new LordsDBHelper(this.mCtx).open();
d = lordshelper.getDebate(getItemID(c));
d.moveToFirst();
msg = "'" + lordshelper.getSubject(d) + "'";
msg += " will be debated at ";
msg += "'" + lordshelper.getTitle(d) + "'.";
d.close();
lordshelper.close();
}
} else if (trigger == Trigger.SELECT) {
// Need to get house
House house = getHouseRaw(c);
String subject;
if(house == House.COMMONS) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
subject = commonshelper.getSubject(d).trim();
if(subject == null || "".equals(subject)) {
msg = "Meeting of the ";
} else {
msg = "'" + commonshelper.getSubject(d) + "'";
msg += " will be discussed at the ";
}
msg += commonshelper.getTitle(d) + " committee.";
d.close();
commonshelper.close();
} else {
lordshelper = new LordsDBHelper(this.mCtx).open();
d = lordshelper.getDebate(getItemID(c));
d.moveToFirst();
subject = lordshelper.getSubject(d).trim();
if(subject == null || "".equals(subject)) {
msg = "Meeting of the ";
} else {
msg = "'" + lordshelper.getSubject(d) + "'";
msg += " will be discussed at the ";
}
msg += lordshelper.getTitle(d) + " committee.";
d.close();
lordshelper.close();
}
} else if (trigger == Trigger.WESTMINSTER) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
msg = "'" + commonshelper.getSubject(d) + "'";
msg += " will be debated.";
d.close();
commonshelper.close();
} else if (trigger == Trigger.GRAND) {
lordshelper = new LordsDBHelper(this.mCtx).open();
d = lordshelper.getDebate(getItemID(c));
d.moveToFirst();
msg = "'" + lordshelper.getTitle(d) + "'";
msg += " will be debated.";
d.close();
lordshelper.close();
} else if (trigger == Trigger.GENERAL) {
commonshelper = new CommonsDBHelper(this.mCtx).open();
d = commonshelper.getDebate(getItemID(c));
d.moveToFirst();
msg = "'" + commonshelper.getSubject(d) + "'";
msg += " will be discussed by the ";
msg += commonshelper.getCommittee(d) + ".";
d.close();
commonshelper.close();
}
if(d != null) {
d.close();
}
// SI, Draft SI, Reports...
return msg;
}
public void clearTrigger(String trigger_id) {
String [] args = {trigger_id};
//Log.v("PPP", "Clearing feed of trigger: " + trigger_id);
this.mDb.delete("politicsfeed", "trigger_id = ?", args);
}
public Cursor getReadable(Integer days_back) {
// Get all talks marked as wanted to be read and older than yesterday
String date_query = "read > 0 AND date < strftime('%s', 'now', '-1 day') AND date > strftime('%s', 'now', '-" + days_back.toString() + " day')";
return(this.mDb.rawQuery("SELECT _id, match, trigger_id, trigger_type, item_id, house, highlight, read, new, date from politicsfeed WHERE " + date_query + " ORDER BY date desc LIMIT 100", null));
}
// Show talks from yesterday that are marked as wanting to be read
public Integer getReadableCount(House house, Integer days_back) {
String [] args = {house.toOrdinal()};
Integer ready_count = -1;
Cursor c;
if(house == House.COMMONS || house == House.LORDS) {
c = this.mDb.rawQuery("SELECT COUNT(*) from politicsfeed WHERE read > 0 AND date < strftime('%s', 'now') and date > strftime('%s', 'now', '-" + days_back.toString() + " day') AND house = ? LIMIT 50", args);
} else {
c = this.mDb.rawQuery("SELECT COUNT(*) from politicsfeed WHERE read > 0 AND date < strftime('%s', 'now') and date > strftime('%s', 'now', '-" + days_back.toString() + " day') LIMIT 50", null);
}
c.moveToFirst();
ready_count = c.getInt(0);
c.close();
return ready_count ;
}
public void markToRead(Integer debate_id) {
String [] args = {debate_id.toString()};
this.mDb.execSQL("UPDATE politicsfeed SET read = 2 WHERE _id = " + debate_id.toString());
}
public void markFeedUnread() {
this.mDb.execSQL("UPDATE politicsfeed SET read = 1 WHERE read = 2");
}
public void markFeedStale() { // Searching for the right word...
this.mDb.execSQL("UPDATE politicsfeed SET new = 1 WHERE new = 2");
}
public void markFeedOld() {
this.mDb.execSQL("UPDATE politicsfeed SET new = 0 WHERE new = 1");
}
public int getId(Cursor c) {
return(c.getInt(0));
}
public String getMatch(Cursor c) {
return(c.getString(1));
}
public int getTriggerID(Cursor c) {
return(c.getInt(2));
}
public Trigger getTriggerType(Cursor c) {
int type = c.getInt(3);
return(Trigger.values()[type]);
}
public int getItemID(Cursor c) {
return(c.getInt(4));
}
public House getHouseRaw(Cursor c) {
return(House.values()[c.getInt(5)]);
}
public String getHouse(Cursor c) {
int house = c.getInt(5);
String name;
if(House.values()[house] != House.NEITHER) {
name = "(" + House.values()[house].toShort() + ")";
} else {
name = "";
}
return(name);
}
public int getHighlight(Cursor c) {
return(c.getInt(6));
}
public int getRead(Cursor c) {
return(c.getInt(7));
}
public int getNew(Cursor c) {
return(c.getInt(8));
}
public int getDate(Cursor c) {
return(c.getInt(9));
}
public Date getDateLong(Cursor c) {
Long timestamp = c.getLong(9) * 1000;
return(new Date(timestamp));
}
public void onDestroy() {
actshelper.close();
billshelper.close();
commonshelper.close();
lordshelper.close();
this.mDb.close();
this.mDbHelper.close();
}
}
| gpl-3.0 |
hpclab/TheMatrixProject | src/it/cnr/isti/thematrix/scripting/modules/MatrixSort.java | 20600 | /*
* Copyright (c) 2010-2014 "HPCLab at ISTI-CNR"
*
* This file is part of TheMatrix.
*
* TheMatrix 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 it.cnr.isti.thematrix.scripting.modules;
import it.cnr.isti.thematrix.configuration.Dynamic;
import it.cnr.isti.thematrix.configuration.LogST;
import it.cnr.isti.thematrix.mapping.utils.CSVFile;
import it.cnr.isti.thematrix.mapping.utils.TempFileManager;
import it.cnr.isti.thematrix.scripting.sys.MatrixModule;
import it.cnr.isti.thematrix.scripting.sys.Symbol;
import it.cnr.isti.thematrix.scripting.sys.TheMatrixSys;
import it.cnr.isti.thematrix.scripting.utils.StringUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;
import org.erasmusmc.utilities.NewFileSort;
/* WRONG plan -- setup creates the sorting thread in waiting, registers it in a global list. First read access wakes the
* thread, which then goes on by itself; at end of batch, it goes to sleep and wakes the next sorting thread from the
* list (1 the original method still being suspended) (2 since we are in the running phase, all thread have been
* properly initialized already). As the reading job is done, the sorting thread removes itself from the list and starts
* the actual sorting, then unlocks the caller. No: it needs to be done via thread. Not implemented now.
*/
/**
* This class implements the SortModule functionality using the Jerboa on-disk
* FileSorter, with some caveats about concurrency. Class initialization reads
* the data from the input and stages it to disk in order to sort it. Sorting
* requires all the data and some time, and data pull requests for MatrixSort
* cannot return until the data is there. <br>
* All calls to MatrixSort that needs actual data (
* <code>hasmore() next() attributes() get()</code> ) are protected by the
* semaphore <code>phase</code> (mutual exclusion of those methods) and will
* call the sort() function if data is not yet there. Only once the sorting is
* done (see <code>sort()</code>) the specific primitive is processed, the
* semaphore is released and other data-accessing method are enabled. Class
* relies on buffering: there is no need for semaphore fairness as we only
* expect a single thread to be able to call us at a time (otherwise there would
* be a buffer in between).<br>
*
* FIXME This class creates a FileInputModule on the fly, thus possibly creating
* an issue with postprocessing and linking other modules; I'm trying to creat
* the InputModule a bit earlier.
*
* TODO in case of a shortcut with a MatrixFileInput, use the tempfile to do a
* raw copy of the input, which is then passed to the file sorter; this is to
* avoid touching the original input file, which may be a shared or a permanent
* one.
*
* @author edoardovacchi massimo
*
*/
public class MatrixSort extends MatrixModule
{
private static final long serialVersionUID = -5414034925146978819L;
private final List<String> sortFieldNames;
private MatrixModule inputTable; // this is our input module
//
/**
* temporary file full absolute pathname; it sits in the iad directory
*/
private String tempFileName;
/**
* temporary file name stripped off of path and csv suffix
*/
private String tempBaseName;
/**
* temporary file where the sorting happens
*/
private File tempFile;
// these are initialized in setup()
/**
* reader module that gets back the sorted data from disc
*/
private MatrixModule readSortedModule;
/**
* FIXME write module YET UNUSED ; should rewrite the data stream to disc
*/
private MatrixModule writeUnsortedModule;
private String schemaName;
/**
* The writer for the intermediate file.
*/
private CSVFile tempCSV = null;
/**
* prevent any data read method before the sorting phase is complete
*/
private Semaphore phase = new Semaphore(1); // a semaphore with one permit
/**
* true as soon as we enter the sort routine
*/
private boolean sorted = false;
/**
* still unused: disable creation of the input temporary file (we need to
* get the file from somewhere!)
*/
private boolean skipInputFileCreation = false;
private String readyFileName;
public MatrixSort(String name, String inputTable, String schema,
List<String> fieldNames) {
super(name);
this.inputTable = TheMatrixSys.getModule(inputTable);
this.inputTable.schemaMatches(schema);
this.schemaName = schema; // TODO save for setup(); do we really need to
// save it?
this.inputTable.addConsumer(this);
this.sortFieldNames = fieldNames;
// try { // initially we acquire the lock, no reading out until the file
// is sorted
// this.phase.acquire();
// } catch (InterruptedException e) {
// throw new Error("MatrixSort.MatrixSort exception " + e.toString());
// }
}
/**
* setup the sort module.
*/
@Override
@SuppressWarnings("unchecked")
public void setup() {
/**
* should initialize everything needed by sort.
*
* FIXME maybe initializations shall be delayed as much as possible?
*
* TODO the code creating the temporary file should be skipped if we
* already have a temp file at hand; since we cannot do that (we are
* inside setup, we don't know yet) most of the changes will have to be
* undone in that case.
*/
this.setSchema(inputTable.getSchema());
// we will use fieldNames.toArray() as the column list; Jerboa
// Comparator wants either a single column index or
// a String[] of names.
if (sortFieldNames.isEmpty())
throw new Error("MatrixSort.setup() no fields to sort with!");
/*
* check disabled, should take final / into account, to check we are in
* the right dir? let's do that only once in the program
*
* File baseDir = new File(System.getProperty("user.dir")); // should
* check this if
* (!baseDir.getAbsolutePath().equals(Dynamic.getBasePath())) { throw
* new Error( "MatrixSort.setup() -- Wrong Directory " +
* baseDir.getAbsolutePath() + " expected " + Dynamic.getBasePath()); }
*/
// take temp file for copying data
this.tempFile = TempFileManager.newTempFile();
tempFileName = tempFile.getAbsolutePath();
tempBaseName = tempFile.getName();
if (tempBaseName.endsWith(".csv")) {
tempBaseName = tempBaseName.substring(0, tempBaseName.length() - 4);
}
// create file writer
LogST.logP(2, "MatrixSort.setup() -- using header "+ this.getSchema().fieldNames().toString());
tempCSV = new CSVFile(this.tempFile.getParentFile().getAbsolutePath()+File.separator, tempBaseName, "");
tempCSV.setHeader(this.getSchema().fieldNames());
// /*** this is created later on **/
// if (true){
// // we will use a FileInput for reading; check that it doesn't try to
// start reading too soon, otherwise move it
// // to exec()
// this.readSortedModule = new MatrixFileInput(this.name,
// tempFile.getName(), this.getSchema(),
// (List<String>) Collections.EMPTY_LIST);
// readSortedModule.setup();
// }
// /*****/
// changes to apply: use FileUtils.copyFile or Java 7 Files.copy
LogST.logP(1, "MatrixSort.setup() done : " + this);
}
/************************************* POSTPROCESSING SUPPORT ****************************/
/**
* UNTESTED set the sort module for using an already existing input file; we
* need this as the condition is detected after class creation. The method
* shall be called after setup, this is a bit of a problem later on.
* @param fullname
*/
public void overrideInputFile(String fullname) {
LogST.logP(0, "MatrixSort:overrideInputFile() changing input to "
+ fullname);
// TODO check that it exists?
readyFileName = fullname;
skipInputFileCreation = true;
};
public void changeInput (MatrixModule m)
{
this.inputTable.schemaMatches(m.getSchema().name);
this.inputTable = m;
this.schemaName = m.getSchema().name;
}
/**
* Get the input module, needed for postprocessing the graph. Use with great
* care.
*
* @return the input module
*/
public MatrixModule getInput() {
return inputTable;
}
/************************************** EXECUTION ****************************************/
public void exec() {}
/**
* Starts the sorting algorithm. Receive all the data; dump it to disc
* (possibly in batches); at data end, call the File Sorter; when sorted,
* open the file for reading; enable the hasMore(), next() and get methods
*
* TODO: need the documentation about branches
*/
private void sort()
{
sorted = true;
LogST.logP(0, this.getClass().getSimpleName()+".sort() is sorting the following attributes: "+
inputTable.attributes()+ " with fields "+sortFieldNames.toString());
if (!skipInputFileCreation)
{
/***
* In this branch of the if we create the file
***/
LogST.logP(0, "MatrixSort.sort() " + this.name + " in tempfile creation branch");
// fixing for large files : I should really build and call a
// FileOutput module
// TODO this could be done in the graph modification phase,
// simplifying code here
LogST.logP(2, "MatrixSort.sort() -- before reading data into the CSVFile object "+ this.name);
// read all the data and save it
int rowsInBatch = 0;
int rows = 0;
boolean appending = false;
while (inputTable.hasMore())
{
inputTable.next(); // let's really go to the next row
// manage writing to tempfile
int columnCount = 0;
for (Symbol<?> field : inputTable.attributes()) {
// System.out.println(field.name +" " + field.type);
tempCSV.setValue(columnCount,
StringUtil.symbolToString(field));
columnCount++;
// maybe add some checks here? if one column skips we mangle
// all the data
}
rows++;
rowsInBatch++;
if (rowsInBatch == Dynamic.writeCSVBatchSize) {
// cut&paste! make it a function? in CSVFile?
try {
LogST.logP(2, "MatrixSort before saving to disc File");
tempCSV.save(appending);
appending = true;
LogST.logP(2, "MatrixSort after save");
} catch (Exception e) {
throw new Error(e.toString());
}
// cute&paste END
rowsInBatch = 0;
}
}
LogST.logP(2, "MatrixSort after reading " + rows + " rows");
// save the last batch, if it's not empty
// note: if the whole file was empty we need to save anyway to
// create the header
// I will need to check that FileSorter is ok with that case
if (rowsInBatch > 0 || rows == 0) {
try {
LogST.logP(1,
"MatrixSort before saving last batch to disc File");
tempCSV.save(appending);
LogST.logP(1, "MatrixSort after last batch save");
} catch (Exception e) {
throw new Error(e.toString());
}
;
// TODO write out the number of written rows
}
}
else {
/***
* In this branch of the if we skip temp file creation, and copy the
* source file
***/
LogST.logP(0, "MatrixSort.sort() " + this.name +" in stolen file branch");
// check the Symbol fields
/*
* for (Symbol<?> field : inputTable.attributes()) { Object
* symbolName = (Object) field.name; System.out.println(field.name
* +" " + this.inputTable.getSchema().get(symbolName)); }
*/
// undo setup() arrangements
// - destroy the file writer, we don't need it
tempCSV = null;
/**
* this will maybe needed some day; currently the close routine
* breaks if file was not open at all try { // it was never written
* to, but we need to close it (may be a zip/gzip)
* tempCSV.closeFile(); } catch (IOException e) { throw new
* Error("MatrixSort:sort() deleting tempCSV for file "
* +tempFileName+"got Exception"+e); }
**/
/*
* // - destroy the old tempfile, remove it from the bookkeeper if
* needed TempFileManager.deleteTempFileQuietly(tempFileName); // -
* modify the sorting routine call to target the new file name
*/
// TODO we actually need to make a copy of the file as the sort will
// write to it in the end
// TODO this will be the basename for temp names in FileSorter,
// check for any issue there
// *****************************************************************
// this becomes a file copy
// tempFileName = readyFileName;
File source = new File(readyFileName);
File dest = new File(tempFileName);
LogST.logP(0, this.getClass().getSimpleName()+".sort() copying "+source+" to "+dest);
try {
copyFile(source, dest);
} catch (IOException e) {
LogST.logException(e);
throw new Error(e.toString());
}
}
/***** file is ready either way : we actually call sort it ********/
// FIXME we don't know how the FileSorter comparator will handle the
// various TheMatrix types
//
File f = new File(tempFileName);
long MB = f.length() / 1024 / 1024;
LogST.logP(0, "MatrixSort.sort() calling sorter with " + f.getName() +
"with size "+MB+"MB on fields " + sortFieldNames.toString());
// sorting
long before = System.currentTimeMillis();
NewFileSort.sort(tempFileName, sortFieldNames.toArray(new String[0]), inputTable.getSchema());
long after = System.currentTimeMillis();
long duration_sec = (after - before) / 1000;
LogST.logP(0, "MatrixSort.sort() lasted "+duration_sec);
/******* complete the initialization of the reader module *****/
// we will use a FileInput for reading
this.readSortedModule = new MatrixFileInput(this.name, tempFile.getName(), this.getSchema(),
(List<String>) Collections.EMPTY_LIST, true);
readSortedModule.setup();
LogST.logP(1, "MatrixSort.sort() created reader : "+ this.readSortedModule);
/***
* This is needed if we want the following modules to refer the new
* inputModule directly. If they refer to the sort module instead (the
* inputModule is hidden) then we shall not fiddle with the consumer
* list here.
*
* migrateOnlyConsumer(this,readSortedModule);
***/
// release lock
phase.release();
}
/**
* Returns true if there are more lines to read from the sorted data.
* hasMore() of Sort is actually reading from the sorted file after it has
* been sorted on disk. It has to<br>
* stall until all the data is collected, then<br>
* trigger the sorting code<br>
* trigger the initialization of a FileInput Module from the sorted output<br>
* from then, piggyback on the hasMore of the FileInput.<br>
* Eventually, it'll need to check that there are more receivers for the
* same input (maybe create more FileInput modules ?)
*/
@Override
public boolean hasMore() {
phase.acquireUninterruptibly(); // if data is not there, wait until exec
// will unlock us
if (!sorted)
this.sort();
boolean result = this.readSortedModule.hasMore();
if (!result) {
LogST.logP(1, "MatrixSort.hasmore() for module " + this.name
+ " end of sorted file");
if (Dynamic.keepTemporaryFiles) {
// FIXME unimplemented
LogST.logP(1, "MatrixSort.hasmore() for module " + this.name
+ " _should_ delete temporary file" + this.tempFileName);
}
}
phase.release();
return result;
// TODO on EOF, write out the number of read rows and of discarder rows
}
/**
* Skips to the next row of the sorted data. next() of Sort is actually
* reading from the sorted file after it has been sorted on disk. It has to<br>
* stall until all the data is collected, then<br>
* trigger the sorting code<br>
* trigger the initialization of a FileInput Module from the sorted output<br>
* from then, piggyback on the hasMore of the FileInput.<br>
* Eventually, it'll need to check that there are more receivers for the
* same input (maybe create more FileInput modules ?)
*/
@Override
public void next() {
phase.acquireUninterruptibly(); // if data is not there, wait until exec
// will unlock us
if (!sorted)
this.sort();
this.readSortedModule.next();
this.setAll(readSortedModule);
phase.release();
// throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Forwards the data access to the actual reading module
*/
@Override
public List<Symbol<?>> attributes() {
phase.acquireUninterruptibly(); // if data is not there, wait until exec
// will unlock us
// never happened so far, but this may actually be a potential error
if (!sorted)
LogST.logP(0,"Warning : MatrixSort.attributes() called before sort");
// throw new Error ("MatrixSort.attributes() called before sort");
phase.release();
return this.readSortedModule.attributes();
}
/**
* Forwards the data access to the actual reading module
*/
// public Symbol<?> get(Object name) {
// phase.acquireUninterruptibly(); // if data is not there, wait until exec
// will unlock us
// // never happened so far, but this may actually be a potential error
// if(!sorted)
// LogST.logP(0, "Warning : MatrixSort.get() called before sort");
// //throw new Error ("MatrixSort.get() called before sort");
// //we ignore the error for now
// phase.release();
// return this.readSortedModule.get(name);
// }
/********************************************** SUPPORT METHODS *******************/
@Override
public String toString() {
return String
.format("SortModule named '%s'\n with parameters:\n %s\n sort field names: %s\n\n",
name, inputTable.name, sortFieldNames);
}
/**
* likely not going to be supported, but may be
*/
@Override
public void reset() {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Utility function to manage copying a large file either via the OS native
* IO (quickest, on 64bit JVM) or via standard Java streams. On a 32bit JVM,
* the slower method works for files larger than the available address
* space, that cannot be memory-mapped.
*
* FIXME this function and the related imports (NIO, InputStream and
* OutputStream) should be moved to an utility class. There should also be
* some logging of runtime info.
*
* @param sourceFile
* @param destFile
* @throws IOException
*/
private static void copyFile(File sourceFile, File destFile)
throws IOException {
LogST.logP(1, "copyFile() " + sourceFile + " " + destFile);
// check if 64 bit or not
if (Dynamic.getDynamicInfo().isJvm64bit()) {
// 64 bit java = NIO is ok
if (!destFile.exists()) {
LogST.logP(1,
"copyFile, 64bit NIO mode, Creating destination file");
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
LogST.logP(1, "copyFile 64bit finally");
if (source == null && destination == null)
LogST.logP(0, "copyFile error");
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
} else {
// if 32 bit Java, no NIO
LogST.logP(1, "copyFile, 32bit FileI/OStream mode, creating buffer");
InputStream input = null;
OutputStream output = null;
try {
// create a buffer of 1 MB in size; here, so that
byte[] buf = new byte[1024 * 1024];
input = new FileInputStream(sourceFile);
output = new FileOutputStream(destFile);
// byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
LogST.logP(1, "copyFile 32bit finally");
if (input == null && output == null)
LogST.logP(0, "copyFile error");
if (input != null)
input.close();
if (output != null)
output.close();
}
}
LogST.logP(1, "copyFile copy done, exiting");
}
}
| gpl-3.0 |
iCarto/siga | extCAD/src/com/iver/cit/gvsig/project/documents/view/snapping/snappers/TangentPointSnapper.java | 3534 | package com.iver.cit.gvsig.project.documents.view.snapping.snappers;
import java.awt.Graphics;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import com.iver.andami.PluginServices;
import com.iver.cit.gvsig.fmap.core.FArc2D;
import com.iver.cit.gvsig.fmap.core.FCircle2D;
import com.iver.cit.gvsig.fmap.core.FEllipse2D;
import com.iver.cit.gvsig.fmap.core.FSpline2D;
import com.iver.cit.gvsig.fmap.core.IGeometry;
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
import com.iver.cit.gvsig.project.documents.view.snapping.AbstractSnapper;
import com.iver.cit.gvsig.project.documents.view.snapping.ISnapperVectorial;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LineSegment;
/**
* Tangent point snapper.
*
* @author Vicente Caballero Navarro
*/
public class TangentPointSnapper extends AbstractSnapper implements
ISnapperVectorial {
/*
* (non-Javadoc)
*
* @see com.iver.cit.gvsig.gui.cad.snapping.ISnapper#getSnapPoint(Point2D
* point, IGeometry geom,double tolerance, Point2D lastPointEntered)
*/
@Override
public Point2D getSnapPoint(Point2D point, IGeometry geom,
double tolerance, Point2D lastPointEntered) {
if (!(geom.getInternalShape() instanceof FCircle2D
|| geom.getInternalShape() instanceof FArc2D
|| geom.getInternalShape() instanceof FEllipse2D || geom
.getInternalShape() instanceof FSpline2D)) {
return null;
}
Point2D resul = null;
Coordinate c = new Coordinate(point.getX(), point.getY());
PathIterator theIterator = geom.getPathIterator(null,
FConverter.FLATNESS);
double[] theData = new double[6];
double minDist = tolerance;
Coordinate from = null;
Coordinate first = null;
while (!theIterator.isDone()) {
// while not done
int theType = theIterator.currentSegment(theData);
switch (theType) {
case PathIterator.SEG_MOVETO:
from = new Coordinate(theData[0], theData[1]);
first = from;
break;
case PathIterator.SEG_LINETO:
// System.out.println("SEG_LINETO");
Coordinate to = new Coordinate(theData[0], theData[1]);
LineSegment line = new LineSegment(from, to);
Coordinate closestPoint = line.closestPoint(c);
double dist = c.distance(closestPoint);
if ((dist < minDist)) {
resul = new Point2D.Double(closestPoint.x, closestPoint.y);
minDist = dist;
}
from = to;
break;
case PathIterator.SEG_CLOSE:
line = new LineSegment(from, first);
closestPoint = line.closestPoint(c);
dist = c.distance(closestPoint);
if ((dist < minDist)) {
resul = new Point2D.Double(closestPoint.x, closestPoint.y);
minDist = dist;
}
from = first;
break;
} // end switch
theIterator.next();
}
return resul;
}
/*
* (non-Javadoc)
*
* @see com.iver.cit.gvsig.gui.cad.snapping.ISnapper#getToolTipText()
*/
@Override
public String getToolTipText() {
return PluginServices.getText(this, "tangent_point");
}
/*
* (non-Javadoc)
*
* @see com.iver.cit.gvsig.gui.cad.snapping.ISnapper#draw(java.awt.Graphics,
* java.awt.geom.Point2D)
*/
@Override
public void draw(Graphics g, Point2D pPixels) {
g.setColor(getColor());
int half = getSizePixels() / 2;
g.drawLine((int) (pPixels.getX() - half),
(int) (pPixels.getY() - half), (int) (pPixels.getX() + half),
(int) (pPixels.getY() - half));
g.drawOval((int) (pPixels.getX() - half),
(int) (pPixels.getY() - half), getSizePixels(), getSizePixels());
}
}
| gpl-3.0 |
theprogrammingchronicles/tpc-tdd-exercises | tdd-lesson-4/tdd-4-7-tdd-iteration/src/test/java/com/programmingchronicles/tdd/addressbook/TestGlobalAddressBook.java | 11486 | /*
* Copyright (C) 2010-2011, Pedro Ballesteros <pedro@theprogrammingchronicles.com>
*
* This file is part of The Programming Chronicles Test-Driven Development
* Exercises(http://theprogrammingchronicles.com/)
*
* This copyrighted material 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 material 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 material. This copy is available in LICENSE-GPL.txt
* file. If not, see <http://www.gnu.org/licenses/>.
*/
package com.programmingchronicles.tdd.addressbook;
import com.programmingchronicles.tdd.domain.Contact;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.junit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Test de GlobalAddressBook.
*
* <p>
* Ejemplo importante en {@link #testAddDuplicateSurname() }.</p>
*
* @author Pedro Ballesteros <pedro@theprogrammingchronicles.com>
*/
public class TestGlobalAddressBook {
private static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
private Contact expectedContact;
private GlobalAddressBook addressBook;
private IdGenerator generatorMock;
@Before
public void setUp() {
expectedContact = new Contact();
addressBook = new GlobalAddressBook();
// Se crea el mock automaticamente usando mockito
generatorMock = mock(IdGenerator.class);
// Se programa una respuesta por defecto para nextId. Se configuran
// varias respuestas ya que algunos tests necesitan más de un contacto.
// Cada llamada devolverá la siguiente respuesta.
when(generatorMock.newId()).thenReturn("0", "1", "2", "3", "4");
addressBook.setIdGenerator(generatorMock);
}
/**
* Test que añade un contacto y se verifica obteniendo el contenido
* actual de la agenda.
*/
@Test
public void testAddContact() {
expectedContact.setFirstName("Pedro");
// Test.
addressBook.addContact(expectedContact);
// Verifica que la agenda contiene el contacto que se acaba de añadir.
List<Contact> contacts = addressBook.getAll();
assertEquals(1, contacts.size());
assertEquals("Pedro", contacts.get(0).getFirstName());
}
@Test
public void testGetContact() {
expectedContact.setFirstName("Pedro");
// Inicialización de la agenda con los datos de prueba.
String expectedId = addressBook.addContact(expectedContact);
// Ejecución del test
Contact actual = addressBook.getContact(expectedId);
// Verificación
assertEquals(expectedId, actual.getId());
assertEquals("Pedro", actual.getFirstName());
}
@Test
public void testGetContactInvalidId() {
try {
addressBook.getContact("INVALID");
fail("testGetContactInvalidId: Expected Exception");
} catch (InvalidIdException ex) {
// No es necesario, pero ayuda a la legibilidad de test,
// vemos el objetivo de este test.
assertTrue(true);
}
}
@Test
public void testAddFullContact() throws ParseException {
expectedContact.setFirstName("Pedro");
expectedContact.setSurname("Ballesteros");
Date actualBirthday = dateFormat.parse("8/1/1974");
expectedContact.setBirthday(actualBirthday);
expectedContact.setPhone("610101010");
addressBook.addContact(expectedContact);
List<Contact> contacts = addressBook.getAll();
assertEquals(1, contacts.size());
assertEquals("Pedro", contacts.get(0).getFirstName());
assertEquals("Ballesteros", contacts.get(0).getSurname());
assertEquals(actualBirthday, contacts.get(0).getBirthday());
assertEquals("610101010", contacts.get(0).getPhone());
}
@Test(expected=InvalidContactException.class)
public void testAddWithoutFirstName() {
expectedContact.setSurname("Ballesteros");
addressBook.addContact(expectedContact);
}
@Test(expected=InvalidContactException.class)
public void testAddBlankFirstName() {
expectedContact.setFirstName(" ");
expectedContact.setSurname("Ballesteros");
addressBook.addContact(expectedContact);
}
@Test(expected=InvalidContactException.class)
public void testAddEmptyFirstName() {
expectedContact.setFirstName("");
expectedContact.setSurname("Ballesteros");
addressBook.addContact(expectedContact);
}
@Test
public void testAddDuplicateFirstName() {
Contact c1 = new Contact();
c1.setFirstName("Pedro");
Contact c2 = new Contact();
c2.setFirstName("Pedro");
addressBook.addContact(c1);
try {
addressBook.addContact(c2);
fail("Expected InvalidContactException");
} catch(InvalidContactException ex) {
List<Contact> contacts = addressBook.getAll();
assertEquals(1, contacts.size());
assertEquals("Pedro", contacts.get(0).getFirstName());
}
}
@Test
public void testAddDuplicateNameWithCapital() {
Contact c1 = new Contact();
c1.setFirstName("Pedro");
Contact c2 = new Contact();
c2.setFirstName("PEDRO");
addressBook.addContact(c1);
try {
addressBook.addContact(c2);
fail("Expected InvalidContactException");
} catch(InvalidContactException ex) {
List<Contact> contacts = addressBook.getAll();
assertEquals(1, contacts.size());
assertEquals("Pedro", contacts.get(0).getFirstName());
}
}
@Test
public void testAddDuplicateNameWithBlanks() {
Contact c1 = new Contact();
c1.setFirstName(" Pedro "); // Un espacio
Contact c2 = new Contact();
c2.setFirstName(" PEDRO "); // Mas de un espacio
addressBook.addContact(c1);
try {
addressBook.addContact(c2);
fail("Expected InvalidContactException");
} catch(InvalidContactException ex) {
List<Contact> contacts = addressBook.getAll();
assertEquals(1, contacts.size());
// Decidimos que mejor almacenar los nombres sin espacios
// y con esto también queda testeado.
assertEquals("Pedro", contacts.get(0).getFirstName());
}
}
/**
* Se implementa el test que valida que un contacto con el mismo
* nombre y el mismo apellido debe provocar un error.
* <p/>
*
* Se observa que no se trata de un buen test unitario ya que no
* podemos hacerlo fallar. Los test anteriores impiden que se pueda
* añadir un contacto con el mismo nombre sin validar el apellido.
*
* <p/>
* Para codificar esta funcionalidad se necesita por tanto añadir
* el test contrario, que un contacto con el mismo nombre y diferente
* apellido si se puede añadir.
*/
@Test
public void testAddDuplicateSurname() {
Contact c1 = new Contact();
c1.setFirstName("Pedro");
c1.setSurname("Ballesteros");
Contact c2 = new Contact();
c2.setFirstName("Pedro");
c2.setSurname("Ballesteros");
addressBook.addContact(c1);
try {
addressBook.addContact(c2);
fail("Expected InvalidContactException");
} catch(InvalidContactException ex) {
List<Contact> contacts = addressBook.getAll();
assertEquals(1, contacts.size());
assertEquals("Pedro", contacts.get(0).getFirstName());
assertEquals("Ballesteros", contacts.get(0).getSurname());
}
}
/**
* Test para validar que un contacto con el mismo nombre pero
* diferente apellido si se puede añadir.
* <p/>
*
* El test anterior no se puede hacer fallar por lo que no ayuda
* a la codificación de la funcionalidad, no dirigue el desarrollo.
*/
@Test
public void testAddDuplicateNameDifferentSurname() {
Contact c1 = new Contact();
c1.setFirstName("Pedro");
c1.setSurname("Herranz");
Contact c2 = new Contact();
c2.setFirstName("Pedro");
c2.setSurname("Ballesteros");
String actualId1 = addressBook.addContact(c1);
String actualId2 = addressBook.addContact(c2);
List<Contact> contacts = addressBook.getAll();
assertEquals(2, contacts.size());
Contact expectedC1 = addressBook.getContact(actualId1);
assertEquals("Pedro", expectedC1.getFirstName());
assertEquals("Herranz", expectedC1.getSurname());
Contact expectedC2 = addressBook.getContact(actualId2);
assertEquals("Pedro", expectedC2.getFirstName());
assertEquals("Ballesteros", expectedC2.getSurname());
}
/**
* Este test lo hemos descubierto mientras desarrollabamos la funcionalidad
* que exigia el test anterior "testAddDuplicateSurname".
*/
@Test
public void testAddDuplicateNameWithNullSurname() {
Contact c1 = new Contact();
c1.setFirstName("Pedro");
c1.setSurname("Ballesteros");
Contact c2 = new Contact();
c2.setFirstName("Pedro");
c2.setSurname(null);
String actualId1 = addressBook.addContact(c1);
// Test
String actualId2 = addressBook.addContact(c2);
// Verify
List<Contact> contacts = addressBook.getAll();
assertEquals(2, contacts.size());
Contact expectedC1 = addressBook.getContact(actualId1);
assertEquals("Pedro", expectedC1.getFirstName());
assertEquals("Ballesteros", expectedC1.getSurname());
Contact expectedC2 = addressBook.getContact(actualId2);
assertEquals("Pedro", expectedC2.getFirstName());
assertNull(expectedC2.getSurname());
}
/**
* Este test es el complementario del anterior, en este caso es el contacto
* existente el que tiene el apellido a null, no el nuevo.
*/
@Test
public void testAddDuplicateNameFirstContactWithoutSurname() {
Contact c1 = new Contact();
c1.setFirstName("Pedro");
c1.setSurname(null);
Contact c2 = new Contact();
c2.setFirstName("Pedro");
c2.setSurname("Ballesteros");
String actualId1 = addressBook.addContact(c1);
String actualId2 = addressBook.addContact(c2);
List<Contact> contacts = addressBook.getAll();
assertEquals(2, contacts.size());
Contact expectedC1 = addressBook.getContact(actualId1);
assertEquals("Pedro", expectedC1.getFirstName());
assertNull(expectedC1.getSurname());
Contact expectedC2 = addressBook.getContact(actualId2);
assertEquals("Pedro", expectedC2.getFirstName());
assertEquals("Ballesteros", expectedC2.getSurname());
}
}
| gpl-3.0 |
xuesong123/finder-web | src/main/java/com/skin/finder/config/Config.java | 14884 | /*
* $RCSfile: Config.java,v $
* $Revision: 1.1 $
*
* Copyright (C) 2008 Skin, Inc. All rights reserved.
*
* This software is the proprietary information of Skin, Inc.
* Use is subject to license terms.
*/
package com.skin.finder.config;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* <p>Title: Config</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* @author xuesong.net
* @version 1.0
*/
public class Config {
private Map<String, String> parameters = new ConcurrentHashMap<String, String>();
/**
* new instance
*/
public Config() {
}
/**
* @param map
*/
public Config(Map<String, String> map) {
this.parameters.putAll(map);
}
/**
* @param properties
*/
public Config(Properties properties) {
Set<Map.Entry<Object, Object>> set = properties.entrySet();
for(Map.Entry<Object, Object> entry : set) {
Object key = entry.getKey();
Object value = entry.getValue();
if(key != null && value != null) {
this.parameters.put(key.toString(), value.toString());
}
}
}
/**
* @param name
* @param value
*/
public void setValue(String name, String value) {
if(name == null) {
return;
}
if(value != null) {
this.parameters.put(name, value);
}
else {
this.parameters.put(name, "");
}
}
/**
* @param name
* @return String
*/
public String getValue(String name) {
return this.parameters.get(name);
}
/**
* @param name
* @param defaultValue
* @return String
*/
public String getValue(String name, String defaultValue) {
String value = this.parameters.get(name);
if(value != null) {
value = value.trim();
}
if(value != null && value.length() > 0) {
return value;
}
return defaultValue;
}
/**
* @param name
* @return String
*/
public String getString(String name) {
return this.getValue(name, null);
}
/**
* @param name
* @param defaultValue
* @return String
*/
public String getString(String name, String defaultValue) {
return this.getValue(name, defaultValue);
}
/**
* @param name
* @return Character
*/
public Character getCharacter(String name) {
return getCharacter(name, null);
}
/**
* @param name
* @param defaultValue
* @return Character
*/
public Character getCharacter(String name, Character defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseCharacter(value, defaultValue);
}
/**
* @param name
* @return Boolean
*/
public Boolean getBoolean(String name) {
return this.getBoolean(name, Boolean.FALSE);
}
/**
* @param name
* @param defaultValue
* @return Boolean
*/
public Boolean getBoolean(String name, Boolean defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseBoolean(value, defaultValue);
}
/**
* @param name
* @return Byte
*/
public Byte getByte(String name) {
return getByte(name, null);
}
/**
* @param name
* @param defaultValue
* @return Byte
*/
public Byte getByte(String name, Byte defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseByte(value, defaultValue);
}
/**
* @param name
* @return Short
*/
public Short getShort(String name) {
return getShort(name, null);
}
/**
* @param name
* @param defaultValue
* @return Short
*/
public Short getShort(String name, Short defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseShort(value, defaultValue);
}
/**
* @param name
* @return Integer
*/
public Integer getInteger(String name) {
return getInteger(name, null);
}
/**
* @param name
* @param defaultValue
* @return Integer
*/
public Integer getInteger(String name, Integer defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseInt(value, defaultValue);
}
/**
* @param name
* @return Float
*/
public Float getFloat(String name) {
return getFloat(name, null);
}
/**
* @param name
* @param defaultValue
* @return Float
*/
public Float getFloat(String name, Float defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseFloat(value, defaultValue);
}
/**
* @param name
* @return Double
*/
public Double getDouble(String name) {
return getDouble(name, null);
}
/**
* @param name
* @param defaultValue
* @return Double
*/
public Double getDouble(String name, Double defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseDouble(value, defaultValue);
}
/**
* @param name
* @return Long
*/
public Long getLong(String name) {
return getLong(name, null);
}
/**
* @param name
* @param defaultValue
* @return Long
*/
public Long getLong(String name, Long defaultValue) {
String value = this.getValue(name);
if(value == null) {
return defaultValue;
}
return parseLong(value, defaultValue);
}
/**
* @param name
* @param pattern
* @return java.util.Date
*/
public java.util.Date getDate(String name, String pattern) {
String value = this.getValue(name);
if(value == null) {
return null;
}
return parseDate(value, pattern);
}
/**
* @param value
* @return Character
*/
public Character parseCharacter(String value) {
return parseCharacter(value, null);
}
/**
* @param value
* @return Boolean
*/
public Boolean parseBoolean(String value) {
return parseBoolean(value, null);
}
/**
* @param value
* @return Byte
*/
public Byte parseByte(String value) {
return parseByte(value, null);
}
/**
* @param value
* @return Short
*/
public Short parseShort(String value) {
return parseShort(value, null);
}
/**
* @param value
* @return Integer
*/
public Integer parseInt(String value) {
return parseInt(value, null);
}
/**
* @param value
* @return Float
*/
public Float parseFloat(String value) {
return parseFloat(value, null);
}
/**
* @param value
* @return Double
*/
public Double parseDouble(String value) {
return parseDouble(value, null);
}
/**
* @param value
* @return Long
*/
public Long parseLong(String value) {
return parseLong(value, null);
}
/**
* @param value
* @param defaultValue
* @return Character
*/
public Character parseCharacter(String value, Character defaultValue) {
Character result = defaultValue;
if(value != null && value.trim().length() > 0) {
try {
char c = Character.valueOf(value.trim().charAt(0));
result = Character.valueOf(c);
}
catch(Exception e) {
}
}
return result;
}
/**
* @param value
* @param defaultValue
* @return Boolean
*/
public Boolean parseBoolean(String value, Boolean defaultValue) {
if(value != null) {
return (value.equalsIgnoreCase("true") ? Boolean.TRUE : Boolean.FALSE);
}
return defaultValue;
}
/**
* @param value
* @param defaultValue
* @return Byte
*/
public Byte parseByte(String value, Byte defaultValue) {
Byte result = defaultValue;
if(value != null) {
try {
byte b = Byte.parseByte(value);
result = Byte.valueOf(b);
}
catch(NumberFormatException e) {
}
}
return result;
}
/**
* @param value
* @param defaultValue
* @return parseShort
*/
public Short parseShort(String value, Short defaultValue) {
Short result = defaultValue;
if(value != null) {
try {
short s = Short.parseShort(value);
result = Short.valueOf(s);
}
catch(NumberFormatException e) {
}
}
return result;
}
/**
* @param value
* @param defaultValue
* @return Integer
*/
public Integer parseInt(String value, Integer defaultValue) {
Integer result = defaultValue;
if(value != null) {
try {
int i = Integer.parseInt(value);
result = Integer.valueOf(i);
}
catch(NumberFormatException e) {
}
}
return result;
}
/**
* @param value
* @param defaultValue
* @return Float
*/
public Float parseFloat(String value, Float defaultValue) {
Float result = defaultValue;
if(value != null) {
try {
float f = Float.parseFloat(value);
result = new Float(f);
}
catch(NumberFormatException e) {
}
}
return result;
}
/**
* @param value
* @param defaultValue
* @return Double
*/
public Double parseDouble(String value, Double defaultValue) {
Double result = defaultValue;
if(value != null) {
try {
double d = Double.parseDouble(value);
result = new Double(d);
}
catch(NumberFormatException e) {
}
}
return result;
}
/**
* @param value
* @param defaultValue
* @return Long
*/
public Long parseLong(String value, Long defaultValue) {
Long result = defaultValue;
if(value != null) {
try {
long l = Long.parseLong(value);
result = Long.valueOf(l);
}
catch(NumberFormatException e) {
}
}
return result;
}
/**
* @param value
* @param format
* @return java.util.Date
*/
public java.util.Date parseDate(String value, String format) {
java.util.Date date = null;
if(value != null) {
try {
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
date = df.parse(value);
}
catch(java.text.ParseException e) {
}
}
return date;
}
/**
* @param <T>
* @param name
* @param type
* @return T
*/
@SuppressWarnings("unchecked")
public <T> T getObject(String name, Class<T> type) {
Object value = null;
String className = type.getName();
if(className.equals("char") || className.equals("java.lang.Character")) {
value = getCharacter(name);
}
else if(className.equals("boolean") || className.equals("java.lang.Boolean")) {
value = getBoolean(name);
}
else if(className.equals("byte") || className.equals("java.lang.Byte")) {
value = getByte(name);
}
else if(className.equals("short") || className.equals("java.lang.Short")) {
value = getShort(name);
}
else if(className.equals("int") || className.equals("java.lang.Integer")) {
value = getInteger(name);
}
else if(className.equals("float") || className.equals("java.lang.Float")) {
value = getFloat(name);
}
else if(className.equals("double") || className.equals("java.lang.Double")) {
value = getDouble(name);
}
else if(className.equals("long") || className.equals("java.lang.Long")) {
value = getLong(name);
}
else if(className.equals("java.lang.String")) {
value = getString(name);
}
else if(className.equals("java.util.Date")) {
value = getDate(name, "yyyy-MM-dd hh:mm:ss");
}
return (T)value;
}
/**
* @param name
* @return boolean
*/
public boolean has(String name) {
return this.parameters.containsKey(name);
}
/**
* @param name
* @param value
* @return boolean
*/
public boolean contains(String name, String value) {
String content = this.getString(name);
if(content != null) {
if(content.trim().equals("*")) {
return true;
}
String[] array = content.split(",");
for(int i = 0; i < array.length; i++) {
array[i] = array[i].trim();
if(array[i].equals(value)) {
return true;
}
}
}
return false;
}
/**
* @return Set<String>
*/
public Set<String> getNames() {
return this.parameters.keySet();
}
/**
* @param map
*/
public void extend(Map<String, String> map) {
this.parameters.putAll(map);
}
/**
* @param config
*/
public void extend(Config config) {
this.parameters.putAll(config.parameters);
}
/**
* @param config
*/
public void copy(Config config) {
this.parameters.putAll(config.parameters);
}
/**
* @return int
*/
public int size() {
return this.parameters.size();
}
/**
*
*/
public void clear() {
this.parameters.clear();
}
/**
* @return Map<String, String>
*/
public Map<String, String> getMap() {
Map<String, String> map = new HashMap<String, String>();
map.putAll(this.parameters);
return map;
}
}
| gpl-3.0 |
thevpc/upa | upa-api/src/main/java/net/thevpc/upa/PersistenceUnit.java | 19113 | /**
* ====================================================================
* UPA (Unstructured Persistence API)
* Yet another ORM Framework
* ++++++++++++++++++++++++++++++++++
* Unstructured Persistence API, referred to as UPA, is a genuine effort
* to raise programming language frameworks managing relational data in
* applications using Java Platform, Standard Edition and Java Platform,
* Enterprise Edition and Dot Net Framework equally to the next level of
* handling ORM for mutable data structures. UPA is intended to provide
* a solid reflection mechanisms to the mapped data structures while
* affording to make changes at runtime of those data structures.
* Besides, UPA has learned considerably of the leading ORM
* (JPA, Hibernate/NHibernate, MyBatis and Entity Framework to name a few)
* failures to satisfy very common even known to be trivial requirement in
* enterprise applications.
* <p>
* Copyright (C) 2014-2015 Taha BEN SALAH
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* ====================================================================
*/
package net.thevpc.upa;
import net.thevpc.upa.persistence.*;
import net.thevpc.upa.bulk.ImportExportManager;
import net.thevpc.upa.events.DefinitionListener;
import net.thevpc.upa.events.EntityInterceptor;
import net.thevpc.upa.events.PersistenceUnitListener;
import net.thevpc.upa.events.Trigger;
import net.thevpc.upa.config.ScanFilter;
import net.thevpc.upa.config.ScanSource;
import net.thevpc.upa.expressions.EntityStatement;
import net.thevpc.upa.expressions.Expression;
import net.thevpc.upa.expressions.QLParameterProcessor;
import net.thevpc.upa.filters.EntityFilter;
import net.thevpc.upa.types.I18NString;
import java.beans.PropertyChangeListener;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* Persistence Unit is this template use File | Settings | File Templates.
*/
public interface PersistenceUnit extends Closeable {
boolean isAutoStart();
void setAutoStart(boolean value);
/**
* if true, when no scan filter is specified will scan all class-path
*
* @return true if auto scan is enabled
*/
boolean isAutoScan();
void setAutoScan(boolean autoScan);
boolean isInheritScanFilters();
void setInheritScanFilters(boolean inheritScanFilters);
Session openSession();
ObjectFactory getFactory();
PersistenceGroup getPersistenceGroup();
// void setPersistenceGroup(PersistenceGroup persistenceGroup) ;
I18NString getTitle();
// void add(PersistenceUnitItem part);
// void remove(int index) ;
// void move(int index, int newIndex) ;
// void move(int index, int newIndex, int count) ;
// void invalidate() ;
// List<PersistenceUnitItem> getChildren() ;
// int indexOf(PersistenceUnitItem child) ;
// int indexOf(String childName) ;
Package addPackage(String name, String parentPath);
Package addPackage(String name, String parentPath, int index);
Package addPackage(String name);
Package addPackage(String name, int index);
/**
* add all modules
*
* @param path
* @param missingStrategy
* @return
*/
Package getPackage(String path, MissingStrategy missingStrategy);
Package getPackage(String path);
Package getDefaultPackage();
// DatabaseResources getResources();
boolean isReadOnly();
void setReadOnly(boolean enable);
// void declareInternEntities();
// void declareEntities();
// String getDefaultAdapterString();
//
// void setDefaultConnectionString(String defaultAdapterString);
String getName();
String getAbsoluteName();
// void setName(String name) ;
boolean isLastStartSucceeded();
void setLastStartSucceeded(boolean success);
boolean isRecurseRemove();
boolean isLockablePersistenceUnit();
PersistenceStore getPersistenceStore();
/**
* descriptor may be
* <ul>
* <li> an instance of EntityDescriptor </li>
* <li> an instance of Class in which case it is considered as an annotated
* class </li>
* <li> Any other instance in which case it is considered as an annotated
* class also</li>
* </ul>
*
* @param descriptor
* @return
* @
*/
Entity addEntity(Object descriptor);
// Index addIndex(String indexName, String entityName, boolean unique, List<String> fieldNames) ;
List<Index> getIndexes();
List<Index> getIndexes(String entityName);
boolean containsEntity(String entityName);
/**
*
* example :
* <pre>
* UPA.getPersistenceUnit().scan(UPA.getContext().getFactory().createClassScanSource(new Class[]{
* Client.class,
* ClientView.class,
* ClientOrder.class
* }), null, true);
* </pre>
*
* @param source source to be parsed
* @param listener listener to track scanned items or null
* @param configure if true process configuration (add entities,
* functions...)
* @
*/
void scan(ScanSource source, ScanListener listener, boolean configure);
/**
* true if the entity <code>entityName</code> exists AND it contains the
* field <code>fieldName</code>.
*
* @param entityName
* @param fieldName
* @return
*/
boolean containsField(String entityName, String fieldName);
Entity getEntity(String entityName);
boolean containsEntity(Class entityType);
Entity findEntity(Class entityType);
List<Entity> findEntities(Class entityType);
Entity findEntity(String entityName);
Entity getEntity(Class entityType);
// int getExplicitEntitiesCount() ;
void addRelationship(RelationshipDescriptor relationDescriptor);
// Relationship addRelation(String name, RelationType type, String detailEntityName, String masterEntityName, String detailFieldName, String masterfieldName, RelationUpdateType detailUpdateType, RelationUpdateType masterUpdateType, String[] detailFieldNames, boolean nullable, Expression filter) ;
void reset();
void reset(Map<String, Object> hints);
/**
* return all entities. same as
* <pre>getEntities(true)</pre>
*
* @return all entities.
*/
List<Entity> getEntities();
/**
* when includeAll is true will return all entities (all packages included),
* otherwise will return root only entities.
*
* @param includeAll when true will return all entities (all packages
* included), otherwise
* @return
*/
List<Entity> getEntities(boolean includeAll);
List<Package> getPackages();
List<Package> getPackages(boolean includeAll);
List<Entity> getEntities(EntityFilter entityFilter);
List<Relationship> getRelationships();
Relationship getRelationship(String name);
boolean containsRelationship(String relationName);
List<Relationship> getRelationshipsByTarget(Entity entity);
List<Relationship> getRelationshipsBySource(Entity entity);
void installDemoData();
void start();
boolean isSystemSession(Session s);
String getPersistenceName();
void setPersistenceName(String persistenceName);
boolean isValidPersistenceUnit();
void clear(String name, Map<String, Object> hints);
void clear(Class entity, Map<String, Object> hints);
void clear(EntityFilter entityFilter, Map<String, Object> hints);
/**
* clears all entities by removing all information (rows, except special
* rows if any)
*/
void clear();
void flush();
@Deprecated
void addPropertyChangeListener(String propertyName, PropertyChangeListener listener);
@Deprecated
void addPropertyChangeListener(PropertyChangeListener listener);
@Deprecated
void removePropertyChangeListener(String propertyName, PropertyChangeListener listener);
@Deprecated
void removePropertyChangeListener(PropertyChangeListener listener);
PropertyChangeListener[] getPropertyChangeListeners();
PropertyChangeListener[] getPropertyChangeListeners(String propertyName);
int getStatus();
void setStatus(int status);
//--------------------------- PROPERTIES SUPPORT
Properties getProperties();
boolean isAskOnCheckCreatedPersistenceUnit();
void setAskOnCheckCreatedPersistenceUnit(boolean askOnCheckCreatedPersistenceUnit);
Class getEntityExtensionSupportType(Class entityExtensionType);
UPASecurityManager getSecurityManager();
/**
* @param definitionListener
* @param trackSystem when true system entities are also tracked
*/
void addDefinitionListener(DefinitionListener definitionListener, boolean trackSystem);
/**
* @param entityName
* @param definitionListener
* @param trackSystem when true system entities are also tracked
*/
void addDefinitionListener(String entityName, DefinitionListener definitionListener, boolean trackSystem);
void addDefinitionListener(Class entityType, DefinitionListener definitionListener, boolean trackSystem);
/**
* system entities are not tracked
*
* @param definitionListener
*/
void addDefinitionListener(DefinitionListener definitionListener);
/**
* system entities are not tracked
*
* @param entityName
* @param definitionListener
*/
void addDefinitionListener(String entityName, DefinitionListener definitionListener);
void removeDefinitionListener(DefinitionListener definitionListener);
void removeDefinitionListener(String entityName, DefinitionListener definitionListener);
void removeDefinitionListener(Class entityType, DefinitionListener definitionListener);
void addPersistenceUnitListener(PersistenceUnitListener listener);
void removePersistenceUnitListener(PersistenceUnitListener listener);
List<PersistenceUnitListener> getPersistenceUnitListeners();
PersistenceStoreFactory getPersistenceStoreFactory();
void addSQLParameterProcessor(QLParameterProcessor p);
void removeSQLParameterProcessor(QLParameterProcessor p);
I18NStringStrategy getI18NStringStrategy();
LockInfo getPersistenceUnitLockingInfo();
void lockPersistenceUnit(String id);
void unlockPersistenceUnit(String id);
LockInfo getLockingInfo(Entity entity);
void lockEntity(Entity entity, String id);
void unlockEntity(Entity entity, String id);
List<LockInfo> getLockingInfo(Entity entity, Expression expression);
void lockEntities(Entity entity, Expression expression, String id);
void unlockEntities(Entity entity, Expression expression, String id);
////////////////////////////////////////
// LISTENERS
//////////////////////////////////////////////////////////////////
//
// Triggers
//
//////////////////////////////////////////////////////////////////
/**
* if entityNamePattern is a simple Entity name of an existing name call
* entity.addTrigger if not postpone creation for all entities verifying
* triggerName with are (or are not) system entities
*
* @param triggerName
* @param interceptor
* @param entityNamePattern
* @param system if true include system entities
* @
*/
void addTrigger(String triggerName, EntityInterceptor interceptor, String entityNamePattern, boolean system);
void dropTrigger(String entityName, String triggerName);
List<Trigger> getTriggers(String entityName);
boolean isTriggersEnabled();
void setTriggersEnabled(boolean triggersEnabled);
//////////////////////////////////////////////////////////////////////
ConnectionProfile getConnectionProfile();
void persist(String entityName, Object objectOrDocument);
void persist(String entity, Object objectOrDocument, Map<String, Object> hints);
void persist(Object objectOrDocument);
RemoveTrace remove(String entityName, Object objectOrDocument);
RemoveTrace remove(Object objectOrDocument);
UpdateQuery createUpdateQuery(String entityName);
UpdateQuery createUpdateQuery(Class type);
UpdateQuery createUpdateQuery(Object object);
void merge(String entityName, Object objectOrDocument);
void merge(Class entityType, Object objectOrDocument);
void merge(Object objectOrDocument);
void update(Object objectOrDocument);
boolean save(Object objectOrDocument);
boolean save(Class entityType, Object objectOrDocument);
boolean save(String entityName, Object objectOrDocument);
void update(Class entityType, Object objectOrDocument);
void update(String entityName, Object objectOrDocument);
void updateAllFormulas();
void updateAllFormulas(EntityFilter entityFilter, Map<String, Object> hints);
//////// REMOVE
RemoveTrace remove(Class entityType, Object object);
RemoveTrace remove(Class entityType, RemoveOptions options);
RemoveTrace remove(String entityName, RemoveOptions options);
<T> List<T> findAll(Class entityType);
<T> List<T> findAll(String entityName);
<T> List<T> findAllIds(String entityName);
<T> T findByMainField(Class entityType, Object mainFieldValue);
<T> T findByMainField(String entityName, Object mainFieldValue);
<T> T findByField(Class entityType, String fieldName, Object mainFieldValue);
<T> T findByField(String entityName, String fieldName, Object mainFieldValue);
<T> T findById(Class entityType, Object id);
<T> T findById(String entityName, Object id);
<T> T reloadObject(T object);
<T> T reloadObject(String entityName, Object object);
Document reloadDocument(String entityName, Object object);
Document reloadDocument(Class entityType, Object object);
boolean existsById(String entityName, Object id);
List<Document> findAllDocuments(Class entityType);
List<Document> findAllDocuments(String entityName);
Document findDocumentById(Class entityType, Object id);
Document findDocumentById(String entityName, Object id);
QueryBuilder createQueryBuilder(Class entityType);
QueryBuilder createQueryBuilder(String entityName);
Query createQuery(EntityStatement query);
Query createQuery(String query);
/**
* @param transactionType transactionType
* @return true if a transaction has been created
* @
*/
boolean beginTransaction(TransactionType transactionType);
void commitTransaction();
void rollbackTransaction();
boolean isStarted();
boolean isValidStructureModificationContext();
boolean isStructureModification();
void beginStructureModification();
void commitStructureModification();
boolean isClosed();
ExpressionManager getExpressionManager();
ImportExportManager getImportExportManager();
DataTypeTransformFactory getTypeTransformFactory();
void setTypeTransformFactory(DataTypeTransformFactory typeTransformFactory);
ConnectionConfig[] getConnectionConfigs();
ConnectionConfig[] getRootConnectionConfigs();
void addConnectionConfig(ConnectionConfig connectionConfig);
void removeConnectionConfig(int index);
void addRootConnectionConfig(ConnectionConfig connectionConfig);
void removeRootConnectionConfig(int index);
void addScanFilter(ScanFilter filter);
void removeScanFilter(ScanFilter filter);
ScanFilter[] getScanFilters();
UserPrincipal getUserPrincipal();
UserPrincipal getUserPrincipal(Session session);
/**
* push new user context if login and credentials are valid
*
* @param login login
* @param credentials credentials
* @param force force when false and the login is the same, no login
* @return true if a new login context is created
*/
boolean login(String login, String credentials,boolean force);
/**
*
* @param login login
* @param force force when false and the login is the same, no login
* @return true if a new login context is created
*/
boolean loginPrivileged(String login,boolean force);
/**
* logout from previous login. should be valid only if login succeeded
*/
void logout();
boolean currentSessionExists();
Session getCurrentSession();
Key createKey(Object... keyValues);
Callback addCallback(MethodCallback methodCallback);
void addCallback(Callback callback);
void removeCallback(Callback callback);
Callback[] getCallbacks(EventType eventType, ObjectType objectType, String name, boolean system, boolean preparedOnly, EventPhase phase);
UConnection getConnection();
void setIdentityConstraintsEnabled(Entity entity, boolean enable);
<T> T invoke(Action<T> action, InvokeContext invokeContext);
<T> T invoke(Action<T> action);
<T> T invokePrivileged(Action<T> action, InvokeContext invokeContext);
<T> T invokePrivileged(Action<T> action);
void invoke(VoidAction action, InvokeContext invokeContext);
void invoke(VoidAction action);
void invokePrivileged(VoidAction action, InvokeContext invokeContext);
void invokePrivileged(VoidAction action);
Comparator<Entity> getDependencyComparator();
<T> T copyObject(T r);
<T> T copyObject(String entityName, T r);
<T> T copyObject(Class entityType, T r);
boolean isEmpty(String entityName);
boolean isEmpty(Class entityType);
long getEntityCount(String entityName);
long getEntityCount(Class entityType);
PersistenceUnitInfo getInfo();
NamedFormulaDefinition[] getNamedFormulas();
NamedFormulaDefinition getNamedFormula(String name);
void addNamedFormula(String name, Formula formula);
void removeNamedFormula(String name);
boolean isCaseSensitiveIdentifiers();
void setCaseSensitiveIdentifiers(boolean caseSensitiveIdentifiers);
PersistenceNameStrategy getPersistenceNameStrategy();
void invalidateCache();
void invalidateCache(String entityName);
void invalidateCacheByKey(String entityName, Key id);
void invalidateCacheById(String entityName, Object id);
boolean updateFormulas(String entityName, Object id);
boolean updateFormulas(Class entityType, Object id);
<T> List<T> findAllByField(String name, String field, Object value);
<T> List<T> findAllByField(Class type, String field, Object value);
}
| gpl-3.0 |
lighthouse64/Random-Dungeon | src/com/lh64/randomdungeon/ui/HealthIndicator.java | 2024 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* 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.lh64.randomdungeon.ui;
import com.lh64.gltextures.TextureCache;
import com.lh64.noosa.Image;
import com.lh64.noosa.ui.Component;
import com.lh64.randomdungeon.actors.Char;
import com.lh64.randomdungeon.sprites.CharSprite;
public class HealthIndicator extends Component {
private static final float HEIGHT = 2;
public static HealthIndicator instance;
private Char target;
private Image bg;
private Image level;
public HealthIndicator() {
super();
instance = this;
}
@Override
protected void createChildren() {
bg = new Image( TextureCache.createSolid( 0xFFcc0000 ) );
bg.scale.y = HEIGHT;
add( bg );
level = new Image( TextureCache.createSolid( 0xFF00cc00 ) );
level.scale.y = HEIGHT;
add( level );
}
@Override
public void update() {
super.update();
if (target != null && target.isAlive() && target.sprite.visible) {
CharSprite sprite = target.sprite;
bg.scale.x = sprite.width;
level.scale.x = sprite.width * target.HP / target.HT;
bg.x = level.x = sprite.x;
bg.y = level.y = sprite.y - HEIGHT - 1;
visible = true;
} else {
visible = false;
}
}
public void target( Char ch ) {
if (ch != null && ch.isAlive()) {
target = ch;
} else {
target = null;
}
}
public Char target() {
return target;
}
}
| gpl-3.0 |
SaferMobile/InTheClear | projects/blackberry/src/org/j4me/util/MathFunc.java | 11189 | package org.j4me.util;
/**
* Implements the methods which are in the standard J2SE's <code>Math</code> class,
* but are not in in J2ME's.
* <p>
* The following methods are still missing from the implementation:
* <ul>
* <li><code>public static double exp (double a)</code>
* <li><code>public static double log (double a)</code>
* <li><code>public static double pow (double a, double b)</code>
* <li><code>public static double random ()</code>
* <li><code>public static double rint()</code>
* </ul>
*
* @see java.lang.Math
*/
public final class MathFunc
{
/**
* Constant for PI divided by 2.
*/
private static final double PIover2 = Math.PI / 2;
/**
* Constant for PI divided by 4.
*/
private static final double PIover4 = Math.PI / 4;
/**
* Constant for PI divided by 6.
*/
private static final double PIover6 = Math.PI / 6;
/**
* Constant for PI divided by 12.
*/
private static final double PIover12 = Math.PI / 12;
/**
* Constant used in the <code>atan</code> calculation.
*/
private static final double ATAN_CONSTANT = 1.732050807569;
/**
* Returns the arc cosine of an angle, in the range of 0.0 through <code>Math.PI</code>.
* Special case:
* <ul>
* <li>If the argument is <code>NaN</code> or its absolute value is greater than 1,
* then the result is <code>NaN</code>.
* </ul>
*
* @param a - the value whose arc cosine is to be returned.
* @return the arc cosine of the argument.
*/
public static double acos (double a)
{
// Special case.
if ( Double.isNaN(a) || Math.abs(a) > 1.0 )
{
return Double.NaN;
}
// Calculate the arc cosine.
double aSquared = a * a;
double arcCosine = atan2( Math.sqrt(1 - aSquared), a );
return arcCosine;
}
/**
* Returns the arc sine of an angle, in the range of <code>-Math.PI/2</code> through
* <code>Math.PI/2</code>. Special cases:
* <ul>
* <li>If the argument is <code>NaN</code> or its absolute value is greater than 1,
* then the result is <code>NaN</code>.
* <li>If the argument is zero, then the result is a zero with the same sign
* as the argument.
* </ul>
*
* @param a - the value whose arc sine is to be returned.
* @return the arc sine of the argument.
*/
public static double asin (double a)
{
// Special cases.
if ( Double.isNaN(a) || Math.abs(a) > 1.0 )
{
return Double.NaN;
}
if ( a == 0.0 )
{
return a;
}
// Calculate the arc sine.
double aSquared = a * a;
double arcSine = atan2( a, Math.sqrt(1 - aSquared) );
return arcSine;
}
/**
* Returns the arc tangent of an angle, in the range of <code>-Math.PI/2</code>
* through <code>Math.PI/2</code>. Special cases:
* <ul>
* <li>If the argument is <code>NaN</code>, then the result is <code>NaN</code>.
* <li>If the argument is zero, then the result is a zero with the same
* sign as the argument.
* </ul>
* <p>
* A result must be within 1 ulp of the correctly rounded result. Results
* must be semi-monotonic.
*
* @param a - the value whose arc tangent is to be returned.
* @return the arc tangent of the argument.
*/
public static double atan (double a)
{
// Special cases.
if ( Double.isNaN(a) )
{
return Double.NaN;
}
if ( a == 0.0 )
{
return a;
}
// Compute the arc tangent.
boolean negative = false;
boolean greaterThanOne = false;
int i = 0;
if ( a < 0.0 )
{
a = -a;
negative = true;
}
if ( a > 1.0 )
{
a = 1.0 / a;
greaterThanOne = true;
}
double t;
for ( ; a > PIover12; a *= t )
{
i++;
t = a + ATAN_CONSTANT;
t = 1.0 / t;
a *= ATAN_CONSTANT;
a--;
}
double aSquared = a * a;
double arcTangent = aSquared + 1.4087812;
arcTangent = 0.55913709 / arcTangent;
arcTangent += 0.60310578999999997;
arcTangent -= 0.051604539999999997 * aSquared;
arcTangent *= a;
for ( ; i > 0; i-- )
{
arcTangent += PIover6;
}
if ( greaterThanOne )
{
arcTangent = PIover2 - arcTangent;
}
if ( negative )
{
arcTangent = -arcTangent;
}
return arcTangent;
}
/**
* Converts rectangular coordinates (x, y) to polar (r, <i>theta</i>). This method
* computes the phase <i>theta</i> by computing an arc tangent of y/x in the range
* of <i>-pi</i> to <i>pi</i>. Special cases:
* <ul>
* <li>If either argument is <code>NaN</code>, then the result is <code>NaN</code>.
* <li>If the first argument is positive zero and the second argument is
* positive, or the first argument is positive and finite and the second
* argument is positive infinity, then the result is positive zero.
* <li>If the first argument is negative zero and the second argument is
* positive, or the first argument is negative and finite and the second
* argument is positive infinity, then the result is negative zero.
* <li>If the first argument is positive zero and the second argument is
* negative, or the first argument is positive and finite and the second
* argument is negative infinity, then the result is the <code>double</code> value
* closest to <i>pi</i>.
* <li>If the first argument is negative zero and the second argument is
* negative, or the first argument is negative and finite and the second
* argument is negative infinity, then the result is the <code>double</code> value
* closest to <i>-pi</i>.
* <li>If the first argument is positive and the second argument is positive
* zero or negative zero, or the first argument is positive infinity and
* the second argument is finite, then the result is the <code>double</code> value
* closest to <i>pi</i>/2.
* <li>If the first argument is negative and the second argument is positive
* zero or negative zero, or the first argument is negative infinity and
* the second argument is finite, then the result is the <code>double</code> value
* closest to <i>-pi</i>/2.
* <li>If both arguments are positive infinity, then the result is the double
* value closest to <i>pi</i>/4.
* <li>If the first argument is positive infinity and the second argument is
* negative infinity, then the result is the double value closest to 3*<i>pi</i>/4.
* <li>If the first argument is negative infinity and the second argument is
* positive infinity, then the result is the double value closest to -<i>pi</i>/4.
* <li>If both arguments are negative infinity, then the result is the double
* value closest to -3*<i>pi</i>/4.
* </ul>
* <p>
* A result must be within 2 ulps of the correctly rounded result. Results
* must be semi-monotonic.
*
* @param y - the ordinate coordinate
* @param x - the abscissa coordinate
* @return the <i>theta</i> component of the point (r, <i>theta</i>) in polar
* coordinates that corresponds to the point (x, y) in Cartesian coordinates.
*/
public static double atan2 (double y, double x)
{
// Special cases.
if ( Double.isNaN(y) || Double.isNaN(x) )
{
return Double.NaN;
}
else if ( Double.isInfinite(y) )
{
if ( y > 0.0 ) // Positive infinity
{
if ( Double.isInfinite(x) )
{
if ( x > 0.0 )
{
return PIover4;
}
else
{
return 3.0 * PIover4;
}
}
else if ( x != 0.0 )
{
return PIover2;
}
}
else // Negative infinity
{
if ( Double.isInfinite(x) )
{
if ( x > 0.0 )
{
return -PIover4;
}
else
{
return -3.0 * PIover4;
}
}
else if ( x != 0.0 )
{
return -PIover2;
}
}
}
else if ( y == 0.0 )
{
if ( x > 0.0 )
{
return y;
}
else if ( x < 0.0 )
{
return Math.PI;
}
}
else if ( Double.isInfinite(x) )
{
if ( x > 0.0 ) // Positive infinity
{
if ( y > 0.0 )
{
return 0.0;
}
else if ( y < 0.0 )
{
return -0.0;
}
}
else // Negative infinity
{
if ( y > 0.0 )
{
return Math.PI;
}
else if ( y < 0.0 )
{
return -Math.PI;
}
}
}
else if ( x == 0.0 )
{
if ( y > 0.0 )
{
return PIover2;
}
else if ( y < 0.0 )
{
return -PIover2;
}
}
// Implementation a simple version ported from a PASCAL implementation:
// http://everything2.com/index.pl?node_id=1008481
double arcTangent;
// Use arctan() avoiding division by zero.
if ( Math.abs(x) > Math.abs(y) )
{
arcTangent = atan(y / x);
}
else
{
arcTangent = atan(x / y); // -PI/4 <= a <= PI/4
if ( arcTangent < 0 )
{
arcTangent = -PIover2 - arcTangent; // a is negative, so we're adding
}
else
{
arcTangent = PIover2 - arcTangent;
}
}
// Adjust result to be from [-PI, PI]
if ( x < 0 )
{
if ( y < 0 )
{
arcTangent = arcTangent - Math.PI;
}
else
{
arcTangent = arcTangent + Math.PI;
}
}
return arcTangent;
}
/**
* Returns the closest <code>int</code> to the argument. The
* result is rounded to an integer by adding 1/2, taking the
* floor of the result, and casting the result to type <code>int</code>.
* In other words, the result is equal to the value of the expression:
* <p>
* <pre>(int)Math.floor(a + 0.5f)</pre>
* <p>
* Special cases:
* <ul>
* <li>If the argument is NaN, the result is 0.
* <li>If the argument is negative infinity or any value less than or
* equal to the value of <code>Integer.MIN_VALUE</code>, the result is
* equal to the value of <code>Integer.MIN_VALUE</code>.
* <li>If the argument is positive infinity or any value greater than or
* equal to the value of <code>Integer.MAX_VALUE</code>, the result is
* equal to the value of <code>Integer.MAX_VALUE</code>.
* </ul>
*
* @param a - a floating-point value to be rounded to an integer.
* @return the value of the argument rounded to the nearest <code>int</code> value.
*/
public static int round (float a)
{
return (int)Math.floor( a + 0.5f );
}
/**
* Returns the closest <code>long</code> to the argument. The result
* is rounded to an integer by adding 1/2, taking the floor of the
* result, and casting the result to type <code>long</code>. In other
* words, the result is equal to the value of the expression:
* <p>
* <pre>(long)Math.floor(a + 0.5d)</pre>
* <p>
* Special cases:
* <ul>
* <li>If the argument is NaN, the result is 0.
* <li>If the argument is negative infinity or any value less than or
* equal to the value of <code>Long.MIN_VALUE</code>, the result is
* equal to the value of <code>Long.MIN_VALUE</code>.
* <li>If the argument is positive infinity or any value greater than or
* equal to the value of <code>Long.MAX_VALUE</code>, the result is
* equal to the value of <code>Long.MAX_VALUE</code>.
* </ul>
*
* @param a - a floating-point value to be rounded to a <code>long</code>.
* @return the value of the argument rounded to the nearest <code>long</code> value.
*/
public static long round (double a)
{
return (long)Math.floor( a + 0.5 );
}
}
| gpl-3.0 |
patrick-winter-knime/misc | de.unikonstanz.winter.util/src/de/unikonstanz/winter/util/Activator.java | 1045 | package de.unikonstanz.winter.util;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "de.unikn.knime.stud.winter.util"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| gpl-3.0 |
iCarto/siga | libFMap/src/com/iver/cit/gvsig/fmap/drivers/dgn/DGNElemColorTable.java | 1889 | /*
* Created on 17-jul-2003
*
* Copyright (c) 2003
* Francisco José Peñarrubia MartÃnez
* IVER TecnologÃas de la Información S.A.
* Salamanca 50
* 46005 Valencia ( SPAIN )
* +34 963163400
* mailto:fran@iver.es
* http://www.iver.es
*/
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* 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.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* gvsig@gva.es
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* dac@iver.es
*/
package com.iver.cit.gvsig.fmap.drivers.dgn;
/**
* Clase utilizada para guardar un elemento de tipo ColorTable.
*
* @author Vicente Caballero Navarro
*/
public class DGNElemColorTable extends DGNElemCore {
//DGNElemCore core=new DGNElemCore();
public int screen_flag;
public byte[][] color_info = new byte[256][3];
//256 3 /*!< Color table, 256 colors by red (0), green(1) and blue(2) component. */
}
| gpl-3.0 |
Muzietto/funky-java-gym | src/main/java/net/faustinelli/funkyJavaGym/ch3/_04_EmailValidation_office/EmailValidation.java | 1349 | /*
* Project: funky-java-gym
* Author: Marco Faustinelli - Muzietto (contacts@faustinelli.net)
* Web: http://faustinelli.wordpress.com/, http://www.github.com/muzietto, http://faustinelli.net/
* Version: 1.0
* The GPL 3.0 License - Copyright (c) 2015-2016 - The funky-java-gym Project
*/
package net.faustinelli.funkyJavaGym.ch3._04_EmailValidation_office;
import java.util.regex.Pattern;
/**
* Created by Marco Faustinelli - Muzietto on 4/12/2016.
*/
public class EmailValidation {
static Pattern emailPattern = Pattern.compile("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$");
public static void main(String[] args) {
validate("this.is@my.email");
validate(null);
validate("");
validate("john.doe@acme.com");
}
private static void validate(String address) {
Caze.match(
new Caze.DefaultCaze(new ValidationRezzult.Suzzess(address + " is valid")),
new Caze(new Predizzate(address, s -> (s == null)), new ValidationRezzult.Faizzure("address is null")),
new Caze(new Predizzate(address, s -> (s == "")), new ValidationRezzult.Faizzure("address is empty")),
new Caze(new Predizzate(address, s -> emailPattern.matcher((CharSequence) s).matches()), new ValidationRezzult.Faizzure(address + " is null"))
);
}
}
| gpl-3.0 |
wandora-team/wandora | src/org/wandora/query2/Static.java | 2551 | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2016 Wandora Team
*
* 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/>.
*
*
*
*
* Static.java
*
*
*/
package org.wandora.query2;
import java.util.*;
/**
*
* @author olli
*/
public class Static extends Directive implements DirectiveUIHints.Provider {
private ArrayList<ResultRow> result;
public Static(){
this.result=new ArrayList<ResultRow>();
}
public Static(ArrayList<ResultRow> result){
this.result=result;
}
public Static(ResultRow result){
this.result=new ArrayList<ResultRow>();
this.result.add(result);
}
public Static(ResultRow[] result){
this.result=new ArrayList<ResultRow>();
this.result.addAll(Arrays.asList(result));
}
@Override
public DirectiveUIHints getUIHints() {
DirectiveUIHints ret=new DirectiveUIHints(Static.class,new DirectiveUIHints.Constructor[]{
new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{}, "")
// result row type is not yet supported
// new DirectiveUIHints.Constructor(new DirectiveUIHints.Parameter[]{
// new DirectiveUIHints.Parameter(ResultRow.class, true, "row")
// }, "")
},
Directive.getStandardAddonHints(),
"Static",
"Primitive");
return ret;
}
@Override
public ArrayList<ResultRow> query(QueryContext context, ResultRow input) throws QueryException {
return result;
}
@Override
public ResultIterator queryIterator(QueryContext context, ResultRow input) throws QueryException {
if(result.size()==1) return result.get(0).toIterator();
else return super.queryIterator(context, input);
}
@Override
public boolean isStatic(){
return true;
}
}
| gpl-3.0 |
zpxocivuby/freetong_mobile | ItafMobileDto/src/itaf/framework/base/dto/WsPageResult.java | 2496 | package itaf.framework.base.dto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/**
*
* WS返回结果统一类
*
* @author
*
* @UpdateDate 2014年10月28日
*/
public class WsPageResult<T> implements Serializable {
private static final long serialVersionUID = 6303037874842719163L;
public static final String STATUS_SUCCESS = "1";
public static final String STATUS_ERROR = "-1";
// WS调用是否成功 1为成功 -1为失败
private String status;
// 错误信息(抛给用户的信息)
private String errorMsg;
// 状态代码
private String statusCode;
// 当前记录索引
private int currentIndex = 0;
// 每页显示的记录数,默认为20条记录 如果要显示全部记录数,可以设定每页记录数为 0
private int pageSize = 20;
// 总记录数
private int totalCount = 0;
// 当前页面
private int currentPage = 1;
// 总记录的页面数
private int totalPage = 0;
// 内容
private Collection<T> content = new ArrayList<T>();
private HashMap<String, Object> params = new HashMap<String, Object>();
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public int getCurrentIndex() {
return currentIndex;
}
public void setCurrentIndex(int currentIndex) {
this.currentIndex = currentIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public Collection<T> getContent() {
return content;
}
public void setContent(Collection<T> content) {
this.content = content;
}
public HashMap<String, Object> getParams() {
return params;
}
public void setParams(HashMap<String, Object> params) {
this.params = params;
}
}
| gpl-3.0 |
ThiagoGarciaAlves/ForestryMC | src/main/java/forestry/energy/gadgets/EngineClockwork.java | 4197 | /*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.energy.gadgets;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ICrafting;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.FakePlayer;
import forestry.core.TemperatureState;
import forestry.core.config.Defaults;
import forestry.core.gadgets.Engine;
import forestry.core.utils.DamageSourceForestry;
public class EngineClockwork extends Engine {
private final static float WIND_EXHAUSTION = 0.05f;
private final static float WIND_TENSION_BASE = 0.5f;
private final static int WIND_DELAY = 10;
private static final int ENGINE_CLOCKWORK_HEAT_MAX = 300000;
private static final int ENGINE_CLOCKWORK_ENERGY_PER_CYCLE = 2;
private static final float ENGINE_CLOCKWORK_WIND_MAX = 8f;
private static final DamageSourceForestry damageSourceEngineClockwork = new DamageSourceForestry("engine.clockwork");
private float tension = 0.0f;
private short delay = 0;
public EngineClockwork() {
super(ENGINE_CLOCKWORK_HEAT_MAX, 10000);
}
@Override
public void openGui(EntityPlayer player) {
if (!(player instanceof EntityPlayerMP)) {
return;
}
if (player instanceof FakePlayer) {
return;
}
if (tension <= 0) {
tension = WIND_TENSION_BASE;
} else if (tension < ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) {
tension += (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE - tension) / (ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE) * WIND_TENSION_BASE;
} else {
return;
}
player.addExhaustion(WIND_EXHAUSTION);
if (tension > ENGINE_CLOCKWORK_WIND_MAX + (0.1 * WIND_TENSION_BASE)) {
player.attackEntityFrom(damageSourceEngineClockwork, 6);
}
tension = tension > ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE ? ENGINE_CLOCKWORK_WIND_MAX + WIND_TENSION_BASE : tension;
delay = WIND_DELAY;
setNeedsNetworkUpdate();
}
/* LOADING & SAVING */
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {
super.readFromNBT(nbttagcompound);
tension = nbttagcompound.getFloat("Wound");
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {
super.writeToNBT(nbttagcompound);
nbttagcompound.setFloat("Wound", tension);
}
@Override
public boolean isRedstoneActivated() {
return true;
}
@Override
public int dissipateHeat() {
return 0;
}
@Override
public int generateHeat() {
return 0;
}
@Override
public boolean mayBurn() {
return true;
}
@Override
public void burn() {
heat = (int) (tension * 10000);
if (delay > 0) {
delay--;
return;
}
if (!isBurning()) {
return;
}
if (tension > 0.01f) {
tension *= 0.9995f;
} else {
tension = 0;
}
energyManager.generateEnergy(ENGINE_CLOCKWORK_ENERGY_PER_CYCLE * (int) tension);
}
@Override
protected boolean isBurning() {
return tension > 0;
}
@Override
public TemperatureState getTemperatureState() {
TemperatureState state = TemperatureState.getState(heat / 10000, ENGINE_CLOCKWORK_WIND_MAX);
if (state == TemperatureState.MELTING) {
state = TemperatureState.OVERHEATING;
}
return state;
}
@Override
public float getPistonSpeed() {
if (delay > 0) {
return 0;
}
float fromClockwork = (tension / ENGINE_CLOCKWORK_WIND_MAX) * Defaults.ENGINE_PISTON_SPEED_MAX;
fromClockwork = Math.round(fromClockwork * 100f) / 100f;
return fromClockwork;
}
@Override
public void getGUINetworkData(int i, int j) {
}
@Override
public void sendGUINetworkData(Container containerEngine, ICrafting iCrafting) {
}
}
| gpl-3.0 |
Moony22/Compact_Crafting | src/main/java/moony/compactcrafting/core/handler/EventListener.java | 1164 | package moony.compactcrafting.core.handler;
import moony.compactcrafting.CCMain;
import net.minecraft.item.Item;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.ItemCraftedEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.ItemSmeltedEvent;
public class EventListener
{
@SubscribeEvent
public void onCrafted(ItemCraftedEvent craft)
{
if (craft.crafting.getItem() == Item.getItemFromBlock(CCMain.CompactCobblestone)
|| craft.crafting.getItem() == Item.getItemFromBlock(CCMain.CompactDirt)
|| craft.crafting.getItem() == Item.getItemFromBlock(CCMain.CompactNetherrack)
|| craft.crafting.getItem() == Item.getItemFromBlock(CCMain.CompactCoalBlock)
|| craft.crafting.getItem() == CCMain.CompactCoal
|| craft.crafting.getItem() == Item.getItemFromBlock(CCMain.CompactSand))
{
craft.player.addStat(CCMain.achievements.compactBlockAchieve, 1);
}
}
@SubscribeEvent
public void onSmelted(ItemSmeltedEvent smelt)
{
if(smelt.smelting.getItem() == Item.getItemFromBlock(CCMain.CompactGlass))
smelt.player.addStat(CCMain.achievements.compactGlassAchieve, 1);
}
}
| gpl-3.0 |
LQTZ/Global-Domination | src/com/lqtz/globaldomination/graphics/GameScreen.java | 6652 | /*******************************************************************************
* Global Domination is a strategy game.
* Copyright (C) 2014, 2015 LQTZ 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 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.lqtz.globaldomination.graphics;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.MouseInputListener;
import com.lqtz.globaldomination.gameplay.Nationality;
import com.lqtz.globaldomination.gameplay.Soldier;
import com.lqtz.globaldomination.io.Utils;
public class GameScreen extends JPanel implements MouseInputListener {
private static final long serialVersionUID = 1L;
private Utils utils;
private Font tileFont;
/**
* All the {@code Tile}s on the map
*/
public Tile[][] tiles;
/**
* {@code Tile} currently being moused over
*/
public Tile highlightedTile;
/**
* Map {@code JPanel} to draw {@code Tile}s on
*
* @param utils
* GD {@code Utils} utility
*/
public GameScreen(Utils utils) {
super();
this.utils = utils;
addMouseListener(this);
addMouseMotionListener(this);
}
/**
* Add all the {@code Hexagon}s
*
* @param width
* width of the {@code GameScreen}
* @param height
* height of the {@code GameScreen}
* @param addTiles
* whether or not to add new {@code Tile}s
*/
public void init(int width, int height, boolean addTiles) {
final int DIM = utils.DIM;
// Size needed to fit tiles horizontally / 8
double sizeFitX = width / (3 * DIM - 1) / 7.0;
// Size needed to fit tiles vertically / 8
double sizeFitY = height / (1.5 * DIM + 0.5) / 8.0;
// Best size for tiles
int sizeFit = 8 * (int) Math.min(sizeFitX, sizeFitY);
// Create font size
tileFont = utils.fonts.sourcesans.deriveFont(Font.PLAIN, sizeFit / 6);
if (addTiles) {
// Center tiles
int xOffset = (width - sizeFit * (3 * DIM - 1) * 7 / 8) / 2;
int yOffset = (int) ((height - sizeFit * (1.5 * DIM + 0.5)) / 2);
tiles = new Tile[DIM][DIM];
// Add tiles
for (int i = 0; i < DIM; i++) {
for (int j = 0; j < DIM; j++) {
tiles[i][j] = new Tile(i, j, sizeFit * (1 + 2 * i + j) * 7
/ 8 + xOffset, height
- (sizeFit * (3 * j + 2) / 2 + yOffset), sizeFit,
Math.abs(utils.random.nextInt(5) + 5),
Math.abs(utils.random.nextInt(5) + 5), utils);
}
}
}
}
@Override
/**
* Paints all the {@code Hexagon}s in the {@code GameScreen}
*
* @param g
* graphics device for painting
*/
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Tile[] tileList : tiles) {
for (Tile tile : tileList) {
tile.paint(g, tileFont);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
mouseMoved(e);
utils.game.selectTile(highlightedTile);
// If move
if (utils.game.moveSelected && utils.game.selectedTile != null
&& utils.game.selectedUnit != null) {
if (!utils.game.selectedTile.settlers.isEmpty()
&& !utils.game.selectedTile.soldiers.isEmpty()
&& utils.game.selectedTile.nat != utils.game.selectedUnit.nation.nationality) {
JOptionPane.showMessageDialog(utils.gw,
"You cannot move to an enemy tile.", "Bad Tile",
JOptionPane.ERROR_MESSAGE);
}
else {
int moveStatus = utils.game.selectedUnit
.move(utils.game.selectedTile);
switch (moveStatus) {
case -1: {
JOptionPane.showMessageDialog(utils.gw,
"You cannot move to a non-adjacent tile.",
"Bad Tile", JOptionPane.ERROR_MESSAGE);
break;
}
case -2: {
JOptionPane.showMessageDialog(utils.gw,
"This unit is exhausted, you cannot move it.",
"Too Much Moving", JOptionPane.ERROR_MESSAGE);
break;
}
case -3: {
JOptionPane.showMessageDialog(utils.gw,
"This Settler is building, you "
+ "cannot interupt its building.",
"Building", JOptionPane.ERROR_MESSAGE);
break;
}
}
}
utils.game.moveSelected = false;
utils.game.selectUnit(null);
}
// If attack
if (utils.game.attackSelected && utils.game.selectedTile != null) {
if (utils.game.selectedTile.nat == utils.game.selectedUnit.nation.nationality
|| utils.game.selectedTile.nat == Nationality.NEUTRAL) {
JOptionPane.showMessageDialog(utils.gw,
"You cannot attack a friendly tile.", "Bad Tile",
JOptionPane.ERROR_MESSAGE);
}
else {
int attackStatus = ((Soldier) utils.game.selectedUnit)
.attackTile(utils.game.selectedTile);
switch (attackStatus) {
case -1: {
JOptionPane.showMessageDialog(utils.gw,
"You cannot attack a non adjacent tile.",
"Bad Tile", JOptionPane.ERROR_MESSAGE);
break;
}
}
utils.game.attackSelected = false;
utils.game.selectUnit(null);
}
}
utils.game.selectedUnit = null;
utils.game.updateWindow();
}
@Override
public void mouseMoved(MouseEvent e) {
// Highlight tile being moused over
if (highlightedTile != null) {
if (highlightedTile.hexagon.contains(e.getPoint())) {
return;
} else {
highlightedTile.isHighlighted = false;
highlightedTile = null;
}
}
for (Tile[] t0 : tiles) {
for (Tile t1 : t0) {
if (t1.hexagon.contains(e.getPoint())) {
highlightedTile = t1;
highlightedTile.isHighlighted = true;
}
}
}
utils.game.updateWindow();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent arg0) {
}
}
| gpl-3.0 |
robbyn/easyguest | src/org/tastefuljava/ezguest/data/Room.java | 1258 | package org.tastefuljava.ezguest.data;
public class Room implements Comparable<Room> {
private int id;
private Hotel hotel;
private int number;
private RoomType type;
public int getId() {
return id;
}
public void setId(int newValue) {
id = newValue;
}
public Hotel getHotel() {
return hotel;
}
void setHotel(Hotel newValue) {
hotel = newValue;
}
public int getNumber() {
return number;
}
public void setNumber(int newValue) {
number = newValue;
}
public RoomType getType() {
return type;
}
public void setType(RoomType newValue) {
if (type != null) {
type.getRooms().remove(this);
}
type = newValue;
if (type != null) {
type.getRooms().add(this);
}
}
@Override
public int compareTo(Room other) {
if (hotel.getId() < other.hotel.getId()) {
return -1;
} else if (hotel.getId() > other.hotel.getId()) {
return 1;
} else if (number < other.number) {
return -1;
} else if (number > other.number) {
return 1;
} else {
return 0;
}
}
}
| gpl-3.0 |
wiki2014/Learning-Summary | alps/cts/tests/tests/renderscript/src/android/renderscript/cts/generated/TestAtan.java | 30490 | /*
* Copyright (C) 2016 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.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh.
package android.renderscript.cts;
import android.renderscript.Allocation;
import android.renderscript.RSRuntimeException;
import android.renderscript.Element;
import android.renderscript.cts.Target;
import java.util.Arrays;
public class TestAtan extends RSBaseCompute {
private ScriptC_TestAtan script;
private ScriptC_TestAtanRelaxed scriptRelaxed;
@Override
protected void setUp() throws Exception {
super.setUp();
script = new ScriptC_TestAtan(mRS);
scriptRelaxed = new ScriptC_TestAtanRelaxed(mRS);
}
public class ArgumentsFloatFloat {
public float inV;
public Target.Floaty out;
}
private void checkAtanFloatFloat() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 1, 0x92004c8dl, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE);
script.forEach_testAtanFloatFloat(inV, out);
verifyResultsAtanFloatFloat(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloatFloat: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE);
scriptRelaxed.forEach_testAtanFloatFloat(inV, out);
verifyResultsAtanFloatFloat(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloatFloat: " + e.toString());
}
}
private void verifyResultsAtanFloatFloat(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 1];
Arrays.fill(arrayInV, (float) 42);
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 1];
Arrays.fill(arrayOut, (float) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 1 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i];
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.FLOAT, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 1 + j])) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 1 + j]);
if (!args.out.couldBe(arrayOut[i * 1 + j])) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanFloatFloat" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
private void checkAtanFloat2Float2() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 2, 0x48a32749l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE);
script.forEach_testAtanFloat2Float2(inV, out);
verifyResultsAtanFloat2Float2(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloat2Float2: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE);
scriptRelaxed.forEach_testAtanFloat2Float2(inV, out);
verifyResultsAtanFloat2Float2(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloat2Float2: " + e.toString());
}
}
private void verifyResultsAtanFloat2Float2(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 2];
Arrays.fill(arrayInV, (float) 42);
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 2];
Arrays.fill(arrayOut, (float) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 2 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 2 + j];
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.FLOAT, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 2 + j])) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 2 + j]);
if (!args.out.couldBe(arrayOut[i * 2 + j])) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanFloat2Float2" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
private void checkAtanFloat3Float3() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 3, 0x3ebe4827l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE);
script.forEach_testAtanFloat3Float3(inV, out);
verifyResultsAtanFloat3Float3(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloat3Float3: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE);
scriptRelaxed.forEach_testAtanFloat3Float3(inV, out);
verifyResultsAtanFloat3Float3(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloat3Float3: " + e.toString());
}
}
private void verifyResultsAtanFloat3Float3(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 4];
Arrays.fill(arrayInV, (float) 42);
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 4];
Arrays.fill(arrayOut, (float) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 3 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 4 + j];
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.FLOAT, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 4 + j]);
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanFloat3Float3" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
private void checkAtanFloat4Float4() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 4, 0x34d96905l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE);
script.forEach_testAtanFloat4Float4(inV, out);
verifyResultsAtanFloat4Float4(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloat4Float4: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE);
scriptRelaxed.forEach_testAtanFloat4Float4(inV, out);
verifyResultsAtanFloat4Float4(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanFloat4Float4: " + e.toString());
}
}
private void verifyResultsAtanFloat4Float4(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 4];
Arrays.fill(arrayInV, (float) 42);
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 4];
Arrays.fill(arrayOut, (float) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 4 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 4 + j];
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.FLOAT, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 4 + j]);
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanFloat4Float4" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
public class ArgumentsHalfHalf {
public short inV;
public double inVDouble;
public Target.Floaty out;
}
private void checkAtanHalfHalf() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_16, 1, 0xfa1813dfl, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 1), INPUTSIZE);
script.forEach_testAtanHalfHalf(inV, out);
verifyResultsAtanHalfHalf(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalfHalf: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 1), INPUTSIZE);
scriptRelaxed.forEach_testAtanHalfHalf(inV, out);
verifyResultsAtanHalfHalf(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalfHalf: " + e.toString());
}
}
private void verifyResultsAtanHalfHalf(Allocation inV, Allocation out, boolean relaxed) {
short[] arrayInV = new short[INPUTSIZE * 1];
Arrays.fill(arrayInV, (short) 42);
inV.copyTo(arrayInV);
short[] arrayOut = new short[INPUTSIZE * 1];
Arrays.fill(arrayOut, (short) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 1 ; j++) {
// Extract the inputs.
ArgumentsHalfHalf args = new ArgumentsHalfHalf();
args.inV = arrayInV[i];
args.inVDouble = Float16Utils.convertFloat16ToDouble(args.inV);
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.HALF, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 1 + j]))) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 1 + j]);
message.append("\n");
message.append("Actual output out (in double): ");
appendVariableToMessage(message, Float16Utils.convertFloat16ToDouble(arrayOut[i * 1 + j]));
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 1 + j]))) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanHalfHalf" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
private void checkAtanHalf2Half2() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_16, 2, 0xff1e93c9l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 2), INPUTSIZE);
script.forEach_testAtanHalf2Half2(inV, out);
verifyResultsAtanHalf2Half2(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalf2Half2: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 2), INPUTSIZE);
scriptRelaxed.forEach_testAtanHalf2Half2(inV, out);
verifyResultsAtanHalf2Half2(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalf2Half2: " + e.toString());
}
}
private void verifyResultsAtanHalf2Half2(Allocation inV, Allocation out, boolean relaxed) {
short[] arrayInV = new short[INPUTSIZE * 2];
Arrays.fill(arrayInV, (short) 42);
inV.copyTo(arrayInV);
short[] arrayOut = new short[INPUTSIZE * 2];
Arrays.fill(arrayOut, (short) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 2 ; j++) {
// Extract the inputs.
ArgumentsHalfHalf args = new ArgumentsHalfHalf();
args.inV = arrayInV[i * 2 + j];
args.inVDouble = Float16Utils.convertFloat16ToDouble(args.inV);
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.HALF, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 2 + j]))) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 2 + j]);
message.append("\n");
message.append("Actual output out (in double): ");
appendVariableToMessage(message, Float16Utils.convertFloat16ToDouble(arrayOut[i * 2 + j]));
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 2 + j]))) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanHalf2Half2" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
private void checkAtanHalf3Half3() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_16, 3, 0x5e2658bdl, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 3), INPUTSIZE);
script.forEach_testAtanHalf3Half3(inV, out);
verifyResultsAtanHalf3Half3(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalf3Half3: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 3), INPUTSIZE);
scriptRelaxed.forEach_testAtanHalf3Half3(inV, out);
verifyResultsAtanHalf3Half3(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalf3Half3: " + e.toString());
}
}
private void verifyResultsAtanHalf3Half3(Allocation inV, Allocation out, boolean relaxed) {
short[] arrayInV = new short[INPUTSIZE * 4];
Arrays.fill(arrayInV, (short) 42);
inV.copyTo(arrayInV);
short[] arrayOut = new short[INPUTSIZE * 4];
Arrays.fill(arrayOut, (short) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 3 ; j++) {
// Extract the inputs.
ArgumentsHalfHalf args = new ArgumentsHalfHalf();
args.inV = arrayInV[i * 4 + j];
args.inVDouble = Float16Utils.convertFloat16ToDouble(args.inV);
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.HALF, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 4 + j]))) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 4 + j]);
message.append("\n");
message.append("Actual output out (in double): ");
appendVariableToMessage(message, Float16Utils.convertFloat16ToDouble(arrayOut[i * 4 + j]));
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 4 + j]))) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanHalf3Half3" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
private void checkAtanHalf4Half4() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_16, 4, 0xbd2e1db1l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 4), INPUTSIZE);
script.forEach_testAtanHalf4Half4(inV, out);
verifyResultsAtanHalf4Half4(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalf4Half4: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_16, 4), INPUTSIZE);
scriptRelaxed.forEach_testAtanHalf4Half4(inV, out);
verifyResultsAtanHalf4Half4(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAtanHalf4Half4: " + e.toString());
}
}
private void verifyResultsAtanHalf4Half4(Allocation inV, Allocation out, boolean relaxed) {
short[] arrayInV = new short[INPUTSIZE * 4];
Arrays.fill(arrayInV, (short) 42);
inV.copyTo(arrayInV);
short[] arrayOut = new short[INPUTSIZE * 4];
Arrays.fill(arrayOut, (short) 42);
out.copyTo(arrayOut);
StringBuilder message = new StringBuilder();
boolean errorFound = false;
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 4 ; j++) {
// Extract the inputs.
ArgumentsHalfHalf args = new ArgumentsHalfHalf();
args.inV = arrayInV[i * 4 + j];
args.inVDouble = Float16Utils.convertFloat16ToDouble(args.inV);
// Figure out what the outputs should have been.
Target target = new Target(Target.FunctionType.NORMAL, Target.ReturnType.HALF, relaxed);
CoreMathVerifier.computeAtan(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 4 + j]))) {
valid = false;
}
if (!valid) {
if (!errorFound) {
errorFound = true;
message.append("Input inV: ");
appendVariableToMessage(message, args.inV);
message.append("\n");
message.append("Expected output out: ");
appendVariableToMessage(message, args.out);
message.append("\n");
message.append("Actual output out: ");
appendVariableToMessage(message, arrayOut[i * 4 + j]);
message.append("\n");
message.append("Actual output out (in double): ");
appendVariableToMessage(message, Float16Utils.convertFloat16ToDouble(arrayOut[i * 4 + j]));
if (!args.out.couldBe(Float16Utils.convertFloat16ToDouble(arrayOut[i * 4 + j]))) {
message.append(" FAIL");
}
message.append("\n");
message.append("Errors at");
}
message.append(" [");
message.append(Integer.toString(i));
message.append(", ");
message.append(Integer.toString(j));
message.append("]");
}
}
}
assertFalse("Incorrect output for checkAtanHalf4Half4" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), errorFound);
}
public void testAtan() {
checkAtanFloatFloat();
checkAtanFloat2Float2();
checkAtanFloat3Float3();
checkAtanFloat4Float4();
checkAtanHalfHalf();
checkAtanHalf2Half2();
checkAtanHalf3Half3();
checkAtanHalf4Half4();
}
}
| gpl-3.0 |
LinEvil/Nukkit | src/main/java/cn/nukkit/block/StoneBricks.java | 1981 | package cn.nukkit.block;
import cn.nukkit.item.Item;
import cn.nukkit.item.Tool;
import cn.nukkit.math.AxisAlignedBB;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class StoneBricks extends Solid {
public static final int NORMAL = 0;
public static final int MOSSY = 1;
public static final int CRACKED = 2;
public static final int CHISELED = 3;
public StoneBricks() {
this(0);
}
public StoneBricks(int meta) {
super(meta);
}
@Override
public int getId() {
return STONE_BRICKS;
}
@Override
public double getHardness() {
return 1.5;
}
@Override
public double getResistance() {
return 30;
}
@Override
public String getName() {
String[] names = new String[]{
"Stone Bricks",
"Mossy Stone Bricks",
"Cracked Stone Bricks",
"Chiseled Stone Bricks"
};
return names[this.meta & 0x03];
}
@Override
protected AxisAlignedBB recalculateBoundingBox() {
if ((this.meta & 0x08) > 0) {
return new AxisAlignedBB(
this.x,
this.y + 0.5,
this.z,
this.x + 1,
this.y + 1,
this.z + 1
);
} else {
return new AxisAlignedBB(
this.x,
this.y,
this.z,
this.x + 1,
this.y + 0.5,
this.z + 1
);
}
}
@Override
public int[][] getDrops(Item item) {
if (item.isPickaxe() && item.getTier() >= Tool.TIER_WOODEN) {
return new int[][]{new int[]{Item.STONE_BRICKS, this.meta & 0x03, 1}};
} else {
return new int[0][];
}
}
@Override
public int getToolType() {
return Tool.TYPE_PICKAXE;
}
}
| gpl-3.0 |