repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
nrv/BASToD | bastod-gui/src/main/java/name/herve/bastod/gui/components/UnitInfoBox.java | 2409 | /*
* Copyright 2012, 2020 Nicolas HERVE
*
* This file is part of BASToD.
*
* BASToD 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.
*
* BASToD 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 BASToD. If not, see <http://www.gnu.org/licenses/>.
*/
package name.herve.bastod.gui.components;
import java.util.List;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Blending;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import name.herve.bastod.engine.Unit;
import name.herve.game.gui.AbstractComponent;
import name.herve.game.gui.GUIResources;
/**
* @author Nicolas HERVE - n.herve@laposte.net
*/
public class UnitInfoBox extends AbstractComponent {
public static final String INFOBOX_FONT = "ibxfont";
private Unit unit;
private BitmapFont font;
public UnitInfoBox(Unit u) {
super(u.getName() + "-InfoBox", -1, -1, 200, 100);
unit = u;
setNeedUpdate(false);
font = GUIResources.getInstance().getFont(INFOBOX_FONT);
Pixmap p = new Pixmap(getWidth(), getHeight(), Pixmap.Format.RGBA8888);
p.setBlending(Blending.None);
Color c1 = Color.YELLOW;
c1.a = 1f;
p.setColor(c1);
p.drawRectangle(0, 0, getWidth(), getHeight());
c1 = Color.BLACK;
c1.a = 0.5f;
p.setColor(c1);
p.fillRectangle(1, 1, getWidth() - 2, getHeight() - 2);
setBackground(new Texture(p));
p.dispose();
}
@Override
public void drawText() {
List<String> infos = unit.getInfos();
if ((infos != null) && (!infos.isEmpty())) {
float h = getBounds(font, infos.get(0)).height;
float spacer = getHeight() / (float) infos.size();
float y = 0;
for (String s : infos) {
draw(font, s, getX(), getY() + y + h + SMALL_SPACER);
y += spacer;
}
}
}
@Override
public Texture updateComponent() {
return null;
}
}
| gpl-3.0 |
chvink/kilomek | megamek/src/megamek/client/commands/ShowEntityCommand.java | 2233 | /**
*
*/
package megamek.client.commands;
import megamek.client.Client;
import megamek.common.Entity;
/**
* @author dirk
* This command exists to print entity information to the chat
* window, it's primarily intended for vissually impaired users.
*/
public class ShowEntityCommand extends ClientCommand {
public ShowEntityCommand(Client client) {
super(
client,
"entity",
"print the information about a entity into the chat window. Ussage: #entity 5 whih would show the details for the entity numbered 5. Also #entity 5 0 would show location 0 of entity 5.");
// to be extended by adding /entity unit# loc# to list details on
// locations.
}
/**
* Run this command with the arguments supplied
*
* @see megamek.server.commands.ServerCommand#run(int, java.lang.String[])
*/
@Override
public String run(String[] args) {
// is this nessesary to prevent cheating?
if (getClient().getGame().getOptions().booleanOption("double_blind")) {
return "Sorry, this command is disabled during double blind.";
}
if (args.length == 1) {
String list = "List of all entities.\n";
for (Entity ent : getClient().getEntitiesVector()) {
list += ent.getId() + " " + ent.getOwner().getName() + "'s "
+ ent.getDisplayName() + "\n";
}
return list;
}
try {
int id = Integer.parseInt(args[1]);
Entity ent = getClient().getEntity(id);
if (ent != null) {
if (args.length > 2) {
String str = "";
for (int i = 2; i < args.length; i++) {
str += ent.statusToString(args[i]);
}
return str;
}
return ent.statusToString();
} else {
return "No such entity.";
}
} catch (NumberFormatException nfe) {
} catch (NullPointerException npe) {
} catch (IndexOutOfBoundsException ioobe) {
}
return "Error parsing the command.";
}
}
| gpl-3.0 |
k-kojak/yako | src/hu/rgai/yako/workers/ThreadContentGetter.java | 3754 | package hu.rgai.yako.workers;
import android.content.Context;
import android.util.Log;
import hu.rgai.yako.beens.Account;
import hu.rgai.yako.beens.FullSimpleMessage;
import hu.rgai.yako.beens.FullThreadMessage;
import hu.rgai.yako.beens.Person;
import hu.rgai.yako.config.Settings;
import hu.rgai.yako.handlers.ThreadContentGetterHandler;
import hu.rgai.yako.messageproviders.MessageProvider;
import hu.rgai.yako.messageproviders.ThreadMessageProvider;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ThreadContentGetter extends TimeoutAsyncTask<String, Integer, FullThreadMessage> {
private final Context context;
private final boolean mLoadQuickAnswers;
private final ThreadContentGetterHandler mHandler;
private final Account account;
private int offset = 0;
private boolean scrollBottomAfterLoad = false;
public ThreadContentGetter(Context context, boolean loadQuickAnswers, ThreadContentGetterHandler handler,
Account account, boolean scrollBottomAfterLoad) {
super(handler);
this.context = context;
mLoadQuickAnswers = loadQuickAnswers;
this.mHandler = handler;
this.account = account;
this.scrollBottomAfterLoad = scrollBottomAfterLoad;
}
public void setOffset(int offset) {
this.offset = offset;
}
@Override
protected FullThreadMessage doInBackground(String... params) {
FullThreadMessage threadMessage = null;
try {
if (account == null) {
Log.d("rgai", "instance is NULL @ threadContentGetter");
} else {
// Log.d("rgai", "Getting thread messages...");
Class providerClass = Settings.getAccountTypeToMessageProvider().get(account.getAccountType());
Class accountClass = Settings.getAccountTypeToAccountClass().get(account.getAccountType());
Constructor constructor = null;
if (providerClass == null) {
throw new RuntimeException("Provider class is null, " + account.getAccountType() + " is not a valid TYPE.");
}
ThreadMessageProvider mp = null;
if (account.getAccountType().equals(MessageProvider.Type.SMS)) {
constructor = providerClass.getConstructor(Context.class);
mp = (ThreadMessageProvider) constructor.newInstance(context);
} else {
constructor = providerClass.getConstructor(accountClass);
mp = (ThreadMessageProvider) constructor.newInstance(account);
}
// cast result to ThreadMessage, since this is a thread displayer
threadMessage = (FullThreadMessage) mp.getMessage(params[0], offset, Settings.MESSAGE_QUERY_LIMIT);
for (FullSimpleMessage fsm : threadMessage.getMessages()) {
fsm.setFrom(Person.searchPersonAndr(context, fsm.getFrom()));
}
}
// TODO: handle exceptions
} catch (NoSuchMethodException ex) {
Log.d("rgai", "", ex);
} catch (InstantiationException ex) {
Log.d("rgai", "", ex);
} catch (IllegalAccessException ex) {
Log.d("rgai", "", ex);
} catch (IllegalArgumentException ex) {
Log.d("rgai", "", ex);
} catch (InvocationTargetException ex) {
Log.d("rgai", "", ex);
} catch (NoSuchProviderException ex) {
Log.d("rgai", "", ex);
} catch (MessagingException ex) {
Log.d("rgai", "", ex);
} catch (IOException ex) {
Log.d("rgai", "", ex);
}
return threadMessage;
}
@Override
protected void onPostExecute(FullThreadMessage result) {
mHandler.onComplete(mLoadQuickAnswers, account.isInternetNeededForLoad(), true, result, scrollBottomAfterLoad);
}
} | gpl-3.0 |
brasse18/Maze | Code/src/main/java/model/Mpc.java | 502 | package model;
import java.awt.Image;
import java.awt.Point;
import model.Enhet;
public class Mpc extends Enhet
{
public Mpc(Point point, int damage, Image imageEnheterArr, Image imageEnheterArr2){
super(point, damage, imageEnheterArr, imageEnheterArr2);
//setImage(Objekt.Enemy);
}
public Mpc(Point position)
{
super(position, 5);
}
public Mpc(Point position, int damage)
{
super(position, damage);
}
@Override
public boolean isFriendly(Enhet enhet) {
return true;
}
}
| gpl-3.0 |
siwells/monkeypuzzle | src/org/simonwells/monkeypuzzle/ToulminFullSizePanel.java | 6152 | package org.simonwells.monkeypuzzle;
import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
/*
* Created on Nov 16, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
/**
* @author growe
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ToulminFullSizePanel extends ToulminFullTextPanel
{
/**
*
*/
public ToulminFullSizePanel()
{
super();
// TODO Auto-generated constructor stub
textWidth = 25;
}
public void drawVertex(Graphics2D gg, TreeVertex vertex, Color color)
{
// Draw the box around the node's text
Point corner = new Point(vertex.toulminX, vertex.toulminY);
Dimension totalLayoutSize = vertex.totalLayoutSize;
Paint textColor;
if (vertex.isMissing()) {
gg.setStroke(dashStroke);
textColor = DiagramBase.missingColor;
} else {
gg.setStroke(solidStroke);
textColor = textBackground;
}
gg.setPaint(textColor);
Shape textBox = vertex.getShape(this);
gg.fill(textBox);
drawText(gg, vertex, textColor, corner);
gg.setPaint(color);
if (vertex.isSelected())
{
if (vertex.isMissing())
{
gg.setStroke(selectDashStroke);
} else {
gg.setStroke(selectStroke);
}
}
gg.draw(textBox);
if (vertex.hidingChildren)
{
gg.setFont(labelFont2);
gg.setPaint(Color.blue);
Rectangle bounds = vertex.getShape(this).getBounds();
gg.drawString("+", corner.x + bounds.width - 10,
corner.y + bounds.height - 5);
gg.setPaint(Color.black);
return;
}
// Draw vertexes and edges arising from current vertex
drawEdges(vertex.toulminDataEdges, gg, dataColor);
drawEdges(vertex.toulminWarrantEdges, gg, warrantColor);
drawEdges(vertex.toulminQualifierEdges, gg, qualifierColor);
drawEdges(vertex.toulminRebuttalEdges, gg, rebuttalColor);
drawEdges(vertex.toulminBackingEdges, gg, backingColor);
}
public void paint(Graphics g)
{
super.paintComponent(g);
Graphics2D gg = (Graphics2D)g;
gg.setPaint(getDiagramBackground());
gg.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
drawTree(gg);
if (displayText) {
drawText(gg);
}
getDisplayFrame().getMainScrollPane().getViewport().setBackground(getDiagramBackground());
}
public void calcTextLayout(TreeVertex vertex)
{
int height;
int layoutHeight = 0;
if (vertex.m_nodeLabel != null && argument.isShowSupportLabels()) {
vertex.nodeLabelLayout = calcLayout(vertex.m_nodeLabel, boldMap);
height = getLayoutHeight(vertex.nodeLabelLayout);
layoutHeight += height;
vertex.nodeLabelLayoutSize = new Dimension(textWidth, height);
}
// Get layout for the Toulmin role for this vertex
String role = (String)vertex.roles.get("toulmin");
// Layout for main text label
String text = (String)vertex.getShortLabelString();
// If the vertex is not to be shown, use ? as its text
if (vertex.isHiddenTable.get("toulmin").equals("true"))
{
text = "?";
}
else if (role.equals("qualifier"))
{
text = (String)vertex.getLabel();
if (text.length() > 3)
text = text.substring(0, 3);
}
vertex.textLayout = calcLayout(text, plainMap);
height = getLayoutHeight(vertex.textLayout);
layoutHeight += height;
vertex.textLayoutSize = new Dimension(textWidth, height);
vertex.ownersLayout = null;
// Allow for separate arrows from each data node to be connected to the
// text box
int arrowHeight = 0;
if (vertex.toulminDataEdges.size() > 0)
{
arrowHeight = dcArrowTop + (vertex.toulminDataEdges.size() - 1) * dcArrowHeadSpacing;
}
if (layoutHeight < arrowHeight)
{
layoutHeight = arrowHeight;
}
vertex.totalLayoutSize = new Dimension(textWidth, layoutHeight);
}
public void assignVertexShape(TreeVertex vertex, int x, int y, int width, int height)
{
String role = (String)vertex.roles.get("toulmin");
Shape shape;
if (role.equals("rebuttal"))
{
shape = new Ellipse2D.Double(x, y, width, height);
} else if (role.equals("qualifier")) {
GeneralPath path = new GeneralPath();
path.moveTo(x + width/2, y);
path.lineTo(x + width, y + height);
path.lineTo(x, y + height);
path.closePath();
shape = path;
} else {
shape = new Rectangle2D.Double(x, y, width, height);
}
vertex.setShape(shape, this);
}
public void drawText(Graphics2D gg, TreeVertex vertex, Paint textColor, Point corner)
{
int y = corner.y;
String role = (String)vertex.roles.get("toulmin");
TextLayout textLayout = ((TextLine)vertex.textLayout.elementAt(0)).getLayout();
Rectangle2D textBounds = textLayout.getBounds();
Rectangle2D boundingBox = vertex.getShape(this).getBounds2D();
int startX = vertex.toulminX + (int)(boundingBox.getWidth() - textBounds.getWidth())/2;
int startY;
// For rebuttals & data nodes, centre the text in the shape
if (role.equals("qualifier"))
{
startY = vertex.toulminY + (int)(boundingBox.getHeight() - textBounds.getHeight())
- textBorderMargin;
} else {
startY = vertex.toulminY + (int)(boundingBox.getHeight() - textBounds.getHeight())/2
- textBorderMargin;
}
Shape currentClip = gg.getClip();
if (currentClip == null)
{
gg.setClip(new Rectangle(0, 0, getWidth(), getHeight()));
currentClip = gg.getClip();
}
Area backgroundArea = new Area(currentClip);
backgroundArea.intersect(new Area(vertex.getShape(this)));
gg.setClip(backgroundArea);
drawLayout(gg, vertex.textLayout, startX, startY,
textColor, vertex.textLayoutSize);
gg.setClip(currentClip);
}
}
| gpl-3.0 |
derekberube/wildstar-foundation-architecture | src/main/java/com/wildstartech/wfa/document/DocumentNameTooLongException.java | 4467 | /*
* Copyright (c) 2001 - 2016 Wildstar Technologies, LLC.
*
* This file is part of Wildstar Foundation Architecture.
*
* Wildstar Foundation Architecture 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.
*
* Wildstar Foundation Architecture 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
* Wildstar Foundation Architecture. If not, see
* <http://www.gnu.org/licenses/>.
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the
* GNU General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module, the
* terms and conditions of the license of that module. An independent module is
* a module which is not derived from or based on this library. If you modify
* this library, you may extend this exception to your version of the library,
* but you are not obliged to do so. If you do not wish to do so, delete this
* exception statement from your version.
*
* If you need additional information or have any questions, please contact:
*
* Wildstar Technologies, LLC.
* 63 The Greenway Loop
* Panama City Beach, FL 32413
* USA
*
* derek.berube@wildstartech.com
* www.wildstartech.com
*/
package com.wildstartech.wfa.document;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.wildstartech.wfa.WFARuntimeException;
import com.wildstartech.wfa.dao.document.DocumentResources;
public class DocumentNameTooLongException extends WFARuntimeException {
private static final String _CLASS=
DocumentNameTooLongException.class.getName();
private static final Logger logger=Logger.getLogger(_CLASS);
/**
* Unique class version id used in serialization/deserialization.
*/
private static final long serialVersionUID = -4827090381303564613L;
/**
* Identifies the resource bundle used to format the message.
* This field should be over-ridden by all subclassing object
* identifying a valid ResourceBundle key.
*/
private static final String RESOURCE_BUNDLE_KEY =
DocumentResources.class.getName();
private int maxDocumentNameLength = 0;
private String documentName = null;
public DocumentNameTooLongException(String name, int maxLength) {
super(RESOURCE_BUNDLE_KEY);
if (logger.isLoggable(Level.FINEST)) {
logger.entering(_CLASS,"DocumentNameTooLongException(String,int)",
new Object[] {name, maxLength});
} // END if (logger.isLoggable(Level.FINEST))
this.documentName = name;
this.maxDocumentNameLength = maxLength;
localizeMessage("DocumentNameTooLongException", new Object[]{
name,
maxLength
});
if (logger.isLoggable(Level.FINEST)) {
logger.exiting(_CLASS,"DocumentNameTooLongException(String,int)");
} // END if (logger.isLoggable(Level.FINEST))
}
public String getDocumentName() {
if (logger.isLoggable(Level.FINEST)) {
logger.entering(_CLASS,"getDocumentName()");
logger.exiting(_CLASS,"getDocumentName()",this.documentName);
} // END if (logger.isLoggable(Level.FINEST))
return this.documentName;
}
public int getDocumentNameMaxLength() {
if (logger.isLoggable(Level.FINEST)) {
logger.entering(_CLASS,"getDocumentNameMaxLength()");
logger.exiting(_CLASS,"getDocumentNameMaxLength()",
this.maxDocumentNameLength);
} // END if (logger.isLoggable(Level.FINEST))
return this.maxDocumentNameLength;
}
}
| gpl-3.0 |
piyell/NeteaseCloudMusic | app/src/main/java/com/zsorg/neteasecloudmusic/widgets/PlaylistDialog.java | 7203 | package com.zsorg.neteasecloudmusic.widgets;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;
import com.zsorg.neteasecloudmusic.adapters.BaseAdapter;
import com.zsorg.neteasecloudmusic.BaseHolder;
import com.zsorg.neteasecloudmusic.callbacks.OnItemCLickListener;
import com.zsorg.neteasecloudmusic.callbacks.OnItemCloseListener;
import com.zsorg.neteasecloudmusic.R;
import com.zsorg.neteasecloudmusic.models.PlayerManager;
import com.zsorg.neteasecloudmusic.models.beans.MusicBean;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Project:NeteaseCloudMusic
*
* @Author: piyel_000
* Created on 2017/1/28.
* E-mail:piyell@qq.com
*/
public class PlaylistDialog extends BaseBottomSheetDialog implements OnItemCLickListener, OnItemCloseListener, View.OnClickListener {
private TextView tvTitle;
private TextView tvClear;
private List<MusicBean> mList;
private PlaylistAdapter mAdapter;
private int mPosition;
private PlayerManager mPlayer;
public PlaylistDialog(@NonNull Context context) {
super(context);
initPlaylist();
}
public PlaylistDialog(@NonNull Context context, @StyleRes int theme) {
super(context, theme);
initPlaylist();
}
public PlaylistDialog(@NonNull Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
initPlaylist();
}
@Override
public void onItemClick(View view, int position) {
mPlayer.setCurrentPosition(position);
mPlayer.playMusic(getContext());
setCurrentPlayPosition(position);
}
@Override
public void onClick(View view) {
new AlertDialog.Builder(getContext())
.setMessage(R.string.confirm_to_clear_playlist)
.setPositiveButton(R.string.clear, new OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mList.clear();
mAdapter.notifyDataSetChanged();
mPlayer.stop();
mPlayer.setCurrentPositionOnly(0);
PlaylistDialog.this.cancel();
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
@Override
public void onClose(int position) {
mList.remove(position);
mAdapter.notifyItemRemoved(position);
if (mList.size() > 0) {
if (mPosition > position) {
mPlayer.setCurrentPositionOnly(--mPosition);
} else if (mPosition == position) {
mPosition = mPosition % mList.size();
mPlayer.setCurrentPosition(mPosition);
// mAdapter.notifyItemChanged(mPosition);
}
// setCurrentPlayPosition(mPosition);
} else {
mAdapter.notifyDataSetChanged();
mPlayer.stop();
}
tvTitle.setText(getContext().getString(R.string.play_list_count, String.valueOf(mList != null ? mList.size() : 0)));
}
public void setPlaylist(List<MusicBean> list) {
mList = list;
tvTitle.setText(getContext().getString(R.string.play_list_count, String.valueOf(list != null ? list.size() : 0)));
mAdapter.notifyDataSetChanged();
}
public void setCurrentPlayPosition(int position) {
int lastPosition = this.mPosition;
this.mPosition = position;
mAdapter.notifyItemChanged(lastPosition);
mAdapter.notifyItemChanged(position);
tvTitle.setText(getContext().getString(R.string.play_list_count, String.valueOf(mList != null ? mList.size() : 0)));
}
private void initPlaylist() {
View view = setHeaderView(R.layout.dialog_playlist_header);
tvTitle = (TextView) findViewById(R.id.tv_title);
tvClear = (TextView) findViewById(R.id.tv_clear);
tvClear.setOnClickListener(this);
mPlayer = PlayerManager.getInstance(getContext());
mAdapter = new PlaylistAdapter(getLayoutInflater());
mAdapter.setOnItemClickListener(this);
mAdapter.setOnItemCloseListener(this);
setListAdapter(mAdapter);
}
private class PlaylistAdapter extends BaseAdapter<MyHolder> {
private final String unknown;
private OnItemCloseListener onItemCloseListener;
public PlaylistAdapter(@NonNull LayoutInflater inflater) {
super(inflater);
unknown = getContext().getString(R.string.unknown);
}
@Override
public MyHolder onCreateHolder(ViewGroup parent, int viewType) {
return new MyHolder(mInflater.inflate(R.layout.dialog_play_list_item, parent, false));
}
@Override
public void onBindHolder(MyHolder holder, int position) {
holder.setOnItemCloseListener(onItemCloseListener);
MusicBean bean = mList.get(position);
holder.tvName.setText(bean.getName());
String singer = bean.getSinger() == null ? unknown : bean.getSinger();
singer = " - " + singer;
holder.tvSinger.setText(singer);
holder.setHighlight(mPosition == position);
}
@Override
public int getDataCount() {
return null == mList ? 0 : mList.size();
}
public void setOnItemCloseListener(OnItemCloseListener onItemCloseListener) {
this.onItemCloseListener = onItemCloseListener;
}
}
class MyHolder extends BaseHolder {
@BindView(R.id.tv_name)
CheckedTextView tvName;
@BindView(R.id.tv_singer)
CheckedTextView tvSinger;
@BindView(R.id.iv_close)
ImageView ivClose;
@BindView(R.id.iv_voice)
ImageView ivVoice;
private OnItemCloseListener onItemCloseListener;
public MyHolder(View itemView) {
super(itemView);
ButterKnife.bind(MyHolder.this, itemView);
ivClose.setOnClickListener(this);
}
public void setOnItemCloseListener(OnItemCloseListener onItemCloseListener) {
this.onItemCloseListener = onItemCloseListener;
}
public void setHighlight(boolean isHighlight) {
tvName.setChecked(isHighlight);
tvSinger.setChecked(isHighlight);
ivVoice.setVisibility(isHighlight ? View.VISIBLE : View.GONE);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.iv_close) {
if (null != onItemCloseListener) {
onItemCloseListener.onClose(getAdapterPosition());
}
} else {
super.onClick(view);
}
}
}
}
| gpl-3.0 |
mozartframework/cms | src/com/mozartframework/db/base/StringDBValue.java | 2271 | package com.mozartframework.db.base;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mozartframework.logger.TLogger;
public class StringDBValue extends DBValue {
public StringDBValue(int type, Object value) throws DBCastException {
super(type, value);
}
/**
* Зачитывает значение из {@link ResultSet}
* @param rs
* @param position
* @return value для метода {@link #set}
* @throws SQLException
* @see #getFrom
*/
protected Object readFromResultSet(ResultSet rs, int position) throws SQLException {
return rs.getString(position);
}
/**
* Проверяет значение, приводит его к необходимому виду
* @throws DBCastException неправильное значение
* @see DBValue#set
*/
protected Object customizeValue(Object value) throws DBCastException {
return MCast.toString(value);
}
/**
* Пустое значение всегда преобразуется в {@link Null}
* @see #set
* @return
*/
protected boolean isEmptyValueAllwaysNull() {
return false;
}
/**
* Читает из потока только значение объекта {@link #set}
* @param input
*/
public void readFromStream(ObjectInputStream input) throws IOException, DBCastException {
int len = input.readInt();
StringBuffer buff = new StringBuffer(len);
for (int i = 0; i < len; ++i) {
buff.append(input.readChar());
}
set(buff.toString());
}
/**
* Записывает только значение объекта {@link #get} в поток
* @param output
*/
public void writeToStream(ObjectOutputStream output) throws IOException {
try {
String tmp = (String) get();
output.writeInt(tmp.length());
output.writeChars(tmp);
}catch(IOException e){
TLogger.error(this.getClass(),"Can't write value='"+get()+"'");
throw e;
}
}
public boolean isString() {
return true;
}
}
| gpl-3.0 |
ContextQuickie/ContextQuickie | Plugin/src/contextquickie/tortoise/git/entries/BisectBad.java | 544 | package contextquickie.tortoise.git.entries;
public class BisectBad extends AbstractTortoiseGitBisectEntry
{
/**
* The menu text identifier for this class.
*/
public static final int MenuTextIdentifier = 163;
/**
* Constructor.
*
* @param iconPath
* The path containing the icon for this instance.
*/
public BisectBad(String iconPath, String iconExtension)
{
super(MenuTextIdentifier, "Bisect bad");
this.setIconPath(iconPath + "thumb_down" + iconExtension);
this.setParameter1("/bad");
}
}
| gpl-3.0 |
Effervex/CycDAG | src/graph/inference/module/GenlPredTransitiveWorker.java | 3214 | /*******************************************************************************
* Copyright (C) 2013 University of Waikato, Hamilton, New Zealand.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Sam Sarjant - initial API and implementation
******************************************************************************/
package graph.inference.module;
import graph.core.CommonConcepts;
import graph.core.DAGNode;
import graph.core.Edge;
import graph.core.EdgeModifier;
import graph.core.Node;
import graph.inference.QueryObject;
import graph.inference.QueryResult;
import graph.inference.QueryWorker;
import graph.inference.Substitution;
import graph.inference.VariableNode;
import graph.module.QueryModule;
import java.util.ArrayList;
import java.util.Collection;
public class GenlPredTransitiveWorker extends QueryWorker {
public GenlPredTransitiveWorker(QueryModule queryModule) {
super(queryModule);
}
private static final long serialVersionUID = -7782457322494540617L;
@Override
public void queryInternal(QueryObject queryObj)
throws IllegalArgumentException {
// Find related edges for args
Node[] nodes = queryObj.getNodes();
boolean isSymmetric = querier_.prove(false,
CommonConcepts.ISA.getNode(dag_), nodes[0],
CommonConcepts.SYMMETRIC_BINARY.getNode(dag_)) == QueryResult.TRUE;
Object[] nodeArgs = asArgs(nodes, isSymmetric);
// Sub preds
VariableNode varNode = new VariableNode("?SUB_PREDS");
Collection<Substitution> subPreds = querier_
.executeQuery(new QueryObject(false, false, QueryResult.TRUE,
CommonConcepts.GENLPREDS.getNode(dag_), varNode,
queryObj.getNode(0)));
if (subPreds.isEmpty())
subPreds.add(new Substitution(varNode, (DAGNode) queryObj
.getNode(0)));
// Try the subs
for (Substitution sub : subPreds) {
Node subPred = sub.getSubstitution(varNode);
Object[] predArgs = new Object[nodeArgs.length + 2];
System.arraycopy(nodeArgs, 0, predArgs, 2, nodeArgs.length);
predArgs[0] = subPred;
predArgs[1] = 1;
Collection<Edge> intersect = relatedModule_.execute(predArgs);
for (Edge interEdge : intersect) {
if (EdgeModifier.isRemoved(interEdge, dag_))
continue;
Node[] edgeNodes = EdgeModifier.getUnmodNodes(interEdge, dag_);
if (queryObj.addResult(
!EdgeModifier.isNegated(interEdge, dag_), edgeNodes))
return;
if (isSymmetric
&& queryObj.addResult(
!EdgeModifier.isNegated(interEdge, dag_),
new Node[] { edgeNodes[0], edgeNodes[2],
edgeNodes[1] }))
return;
}
}
}
private Object[] asArgs(Node[] nodes, boolean isSymmetric) {
ArrayList<Object> nodeArgs = new ArrayList<>();
for (int i = 1; i < nodes.length; i++) {
if (!(nodes[i] instanceof VariableNode)) {
nodeArgs.add(nodes[i]);
if (!isSymmetric)
nodeArgs.add(i + 1);
}
}
return nodeArgs.toArray(new Object[nodeArgs.size()]);
}
}
| gpl-3.0 |
Estada1401/anuwhscript | GameServer/src/com/aionemu/gameserver/model/actions/CreatureActions.java | 1236 | /*
* This file is part of Encom. **ENCOM FUCK OTHER SVN**
*
* Encom is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Encom 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Encom. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.actions;
import com.aionemu.gameserver.model.gameobjects.Creature;
/****/
/** Author Rinzler (Encom)
/****/
public class CreatureActions
{
public static String getName(Creature creature) {
return creature.getName();
}
public static boolean isAlreadyDead(Creature creature) {
return creature.getLifeStats().isAlreadyDead();
}
public static void delete(Creature creature) {
if (creature != null) {
creature.getController().onDelete();
}
}
} | gpl-3.0 |
andune/anduneCommonBukkitLib | src/main/java/com/andune/minecraft/commonlib/server/bukkit/BukkitScheduler.java | 2178 | /**
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (c) 2013 Andune (andune.alleria@gmail.com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
/**
*
*/
package com.andune.minecraft.commonlib.server.bukkit;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.bukkit.Server;
import com.andune.minecraft.commonlib.server.api.Scheduler;
/**
* @author andune
*
*/
@Singleton
public class BukkitScheduler implements Scheduler {
private org.bukkit.plugin.Plugin plugin;
private Server bukkitServer;
@Inject
public BukkitScheduler(org.bukkit.plugin.Plugin plugin, Server bukkitServer) {
this.plugin = plugin;
this.bukkitServer = bukkitServer;
}
@Override
public int scheduleSyncDelayedTask(Runnable task, long delay) {
return bukkitServer.getScheduler().scheduleSyncDelayedTask(plugin, task, delay);
}
@Override
public int scheduleAsyncDelayedTask(Runnable task, long delay) {
return bukkitServer.getScheduler().runTaskLaterAsynchronously(plugin, task, delay).getTaskId();
}
}
| gpl-3.0 |
ytongshang/Commons | rxjava/src/main/java/cradle/rancune/commons/rxjava/rxbus/finder/AnnotatedFinder.java | 10328 | package cradle.rancune.commons.rxjava.rxbus.finder;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import cradle.rancune.commons.rxjava.rxbus.annotation.Produce;
import cradle.rancune.commons.rxjava.rxbus.annotation.Subscribe;
import cradle.rancune.commons.rxjava.rxbus.annotation.Tag;
import cradle.rancune.commons.rxjava.rxbus.entity.EventType;
import cradle.rancune.commons.rxjava.rxbus.entity.ProducerEvent;
import cradle.rancune.commons.rxjava.rxbus.entity.SubscriberEvent;
import cradle.rancune.commons.rxjava.rxbus.thread.EventThread;
/**
* Helper methods for finding methods annotated with {@link Produce} and {@link Subscribe}.
*/
public final class AnnotatedFinder {
/**
* Cache event bus producer methods for each class.
*/
private static final ConcurrentMap<Class<?>, Map<EventType, SourceMethod>> PRODUCERS_CACHE =
new ConcurrentHashMap<>();
/**
* Cache event bus subscriber methods for each class.
*/
private static final ConcurrentMap<Class<?>, Map<EventType, Set<SourceMethod>>> SUBSCRIBERS_CACHE =
new ConcurrentHashMap<>();
private static void loadAnnotatedProducerMethods(Class<?> listenerClass,
Map<EventType, SourceMethod> producerMethods) {
Map<EventType, Set<SourceMethod>> subscriberMethods = new HashMap<>();
loadAnnotatedMethods(listenerClass, producerMethods, subscriberMethods);
}
private static void loadAnnotatedSubscriberMethods(Class<?> listenerClass,
Map<EventType, Set<SourceMethod>> subscriberMethods) {
Map<EventType, SourceMethod> producerMethods = new HashMap<>();
loadAnnotatedMethods(listenerClass, producerMethods, subscriberMethods);
}
/**
* Load all methods annotated with {@link Produce} or {@link Subscribe} into their respective caches for the
* specified class.
*/
private static void loadAnnotatedMethods(Class<?> listenerClass,
Map<EventType, SourceMethod> producerMethods, Map<EventType, Set<SourceMethod>> subscriberMethods) {
// KasLog.d("guohe", "into loadAnnotatedMethods");
for (Method method : listenerClass.getDeclaredMethods()) {
// KasLog.d("guohe", "method.name = " + method.getName());
// The compiler sometimes creates synthetic bridge methods as part of the
// type erasure process. As of JDK8 these methods now include the same
// annotations as the original declarations. They should be ignored for
// subscribe/produce.
if (method.isBridge()) {
// KasLog.d("guohe", "method continue..... ");
continue;
}
if (method.isAnnotationPresent(Subscribe.class)) {
// KasLog.d("guohe", "method isAnnotationPresent..... ");
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1) {
throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation but requires "
+ parameterTypes.length + " arguments. Methods must require a single argument.");
}
Class<?> parameterClazz = parameterTypes[0];
if (parameterClazz.isInterface()) {
throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation on " + parameterClazz
+ " which is an interface. Subscription must be on a concrete class type.");
}
if ((method.getModifiers() & Modifier.PUBLIC) == 0) {
throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation on " + parameterClazz
+ " but is not 'public'.");
}
Subscribe annotation = method.getAnnotation(Subscribe.class);
EventThread thread = annotation.thread();
Tag[] tags = annotation.tags();
// KasLog.d("guohe", "tags = " + tags.toString());
int tagLength = (tags == null ? 0 : tags.length);
do {
String tag = Tag.DEFAULT;
if (tagLength > 0) {
tag = tags[tagLength - 1].value();
}
EventType type = new EventType(tag, parameterClazz);
Set<SourceMethod> methods = subscriberMethods.get(type);
// KasLog.d("guohe", "1111,,, methods = " + methods);
if (methods == null) {
methods = new HashSet<>();
subscriberMethods.put(type, methods);
}
methods.add(new SourceMethod(thread, method));
tagLength--;
} while (tagLength > 0);
} else if (method.isAnnotationPresent(Produce.class)) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 0) {
throw new IllegalArgumentException("Method " + method + "has @Produce annotation but requires "
+ parameterTypes.length + " arguments. Methods must require zero arguments.");
}
if (method.getReturnType() == Void.class) {
throw new IllegalArgumentException("Method " + method
+ " has a return type of void. Must declare a non-void type.");
}
Class<?> parameterClazz = method.getReturnType();
if (parameterClazz.isInterface()) {
throw new IllegalArgumentException("Method " + method + " has @Produce annotation on " + parameterClazz
+ " which is an interface. Producers must return a concrete class type.");
}
if (parameterClazz.equals(Void.TYPE)) {
throw new IllegalArgumentException("Method " + method + " has @Produce annotation but has no return type.");
}
if ((method.getModifiers() & Modifier.PUBLIC) == 0) {
throw new IllegalArgumentException("Method " + method + " has @Produce annotation on " + parameterClazz
+ " but is not 'public'.");
}
Produce annotation = method.getAnnotation(Produce.class);
EventThread thread = annotation.thread();
Tag[] tags = annotation.tags();
int tagLength = (tags == null ? 0 : tags.length);
do {
String tag = Tag.DEFAULT;
if (tagLength > 0) {
tag = tags[tagLength - 1].value();
}
EventType type = new EventType(tag, parameterClazz);
if (producerMethods.containsKey(type)) {
throw new IllegalArgumentException("Producer for type " + type + " has already been registered.");
}
producerMethods.put(type, new SourceMethod(thread, method));
tagLength--;
} while (tagLength > 0);
}
}
// KasLog.d("guohe", "producerMethods = " + producerMethods);
PRODUCERS_CACHE.put(listenerClass, producerMethods);
// KasLog.d("guohe", "subscriberMethods = " + subscriberMethods);
SUBSCRIBERS_CACHE.put(listenerClass, subscriberMethods);
}
/**
* This implementation finds all methods marked with a {@link Produce} annotation.
*/
static Map<EventType, ProducerEvent> findAllProducers(Object listener) {
final Class<?> listenerClass = listener.getClass();
Map<EventType, ProducerEvent> producersInMethod = new HashMap<>();
Map<EventType, SourceMethod> methods = PRODUCERS_CACHE.get(listenerClass);
// KasLog.d("guohe", "22222,,, methods = " + methods);
if (null == methods) {
methods = new HashMap<>();
loadAnnotatedProducerMethods(listenerClass, methods);
}
if (!methods.isEmpty()) {
for (Map.Entry<EventType, SourceMethod> e : methods.entrySet()) {
ProducerEvent producer = new ProducerEvent(listener, e.getValue().method, e.getValue().thread);
producersInMethod.put(e.getKey(), producer);
}
}
return producersInMethod;
}
/**
* This implementation finds all methods marked with a {@link Subscribe} annotation.
*/
static Map<EventType, Set<SubscriberEvent>> findAllSubscribers(Object listener) {
Class<?> listenerClass = listener.getClass();
Map<EventType, Set<SubscriberEvent>> subscribersInMethod = new HashMap<>();
Map<EventType, Set<SourceMethod>> methods = SUBSCRIBERS_CACHE.get(listenerClass);
// KasLog.d("guohe", "methods = " + methods);
if (null == methods) {
methods = new HashMap<>();
loadAnnotatedSubscriberMethods(listenerClass, methods);
}
// KasLog.d("guohe", "methods.size = " + methods.size());
if (!methods.isEmpty()) {
for (Map.Entry<EventType, Set<SourceMethod>> e : methods.entrySet()) {
Set<SubscriberEvent> subscribers = new HashSet<>();
for (SourceMethod m : e.getValue()) {
subscribers.add(new SubscriberEvent(listener, m.method, m.thread));
}
subscribersInMethod.put(e.getKey(), subscribers);
}
}
return subscribersInMethod;
}
private AnnotatedFinder() {
// No instances.
}
private static class SourceMethod {
private EventThread thread;
private Method method;
private SourceMethod(EventThread thread, Method method) {
this.thread = thread;
this.method = method;
}
}
}
| gpl-3.0 |
ieugen/Teachingbox | src/org/hswgt/teachingbox/core/rl/env/WindyGridworld.java | 5657 | /**
* \file WindyGridworld.java
*
* $Id: WindyGridworld.java 677 2010-06-17 08:12:19Z twanschik $ $URL: https://teachingbox.svn.sourceforge.net/svnroot/teachingbox/trunk/src/org/hswgt/teachingbox/core/rl/env/WindyGridworld.java $
*
* \version $Rev: 677 $ \author Markus Schneider \date Sep 23, 2008
*
*/
package org.hswgt.teachingbox.core.rl.env;
import java.util.HashMap;
import org.hswgt.teachingbox.core.rl.datastructures.ActionFilter;
import org.hswgt.teachingbox.core.rl.datastructures.ActionSet;
import org.hswgt.teachingbox.core.rl.datastructures.StateSet;
import org.hswgt.teachingbox.core.rl.policy.GreedyPolicy;
import org.hswgt.teachingbox.core.rl.valuefunctions.QFunction;
import cern.colt.matrix.linalg.SeqBlas;
import cern.jet.random.Uniform;
/**
*
*/
public class WindyGridworld implements Environment
{
private static final long serialVersionUID = -7693368441937761196L;
public static final Action LEFT = new Action(new double[] { -1, 0 });
public static final Action RIGHT = new Action(new double[] { +1, 0 });
public static final Action UP = new Action(new double[] { 0, +1 });
public static final Action DOWN = new Action(new double[] { 0, -1 });
public static final Action RIGHT_UP = new Action(new double[] { +1, +1 });
public static final Action RIGHT_DOWN = new Action(new double[] { +1, -1 });
public static final Action LEFT_UP = new Action(new double[] { -1, +1 });
public static final Action LEFT_DOWN = new Action(new double[] { -1, -1 });
/**
* The ActionSet contains all possible standard actions
*/
public static final ActionSet STANDARD_MOVES = new ActionSet();
/**
* The ActionSet contains all possible standard actions + 4 moves
*/
public static final ActionSet KINGS_MOVES = new ActionSet();
/**
* Defines the wind
*/
public static final int[] WIND = { 0, 0, 0, 1, 1, 1, 2, 2, 1, 0 };
/**
* Gridworld has a width of 10
*/
public static int MAX_X_POSITION = 9;
/**
* Gridworld has a height of 7
*/
public static int MAX_Y_POSITION = 6;
/**
* The StateSet contains all 6 states
*/
public static final StateSet STATE_SET = new StateSet();
/**
* StartState
*/
public static final State START = new State(new double[] { 0, 3 });
/**
* GoalState
*/
public static final State GOAL = new State(new double[] { 7, 3 });
/**
* The agent is not allowed to cross the borders
*/
public static final ActionFilter FILTER = new ActionFilter()
{
private static final long serialVersionUID = -5057734785625735742L;
public boolean isPermitted(final State s, final Action a)
{
State sn = s.copy();
// s = s + a;
SeqBlas.seqBlas.daxpy(1, a, sn);
if (sn.get(0) < 0)
return false;
if (sn.get(0) > MAX_X_POSITION)
return false;
if (sn.get(1) < 0)
return false;
if (sn.get(1) > MAX_Y_POSITION)
return false;
return true;
}
};
// init actionsets
static {
STANDARD_MOVES.add(LEFT);
STANDARD_MOVES.add(RIGHT);
STANDARD_MOVES.add(UP);
STANDARD_MOVES.add(DOWN);
KINGS_MOVES.add(LEFT);
KINGS_MOVES.add(RIGHT);
KINGS_MOVES.add(UP);
KINGS_MOVES.add(DOWN);
KINGS_MOVES.add(LEFT_DOWN);
KINGS_MOVES.add(LEFT_UP);
KINGS_MOVES.add(RIGHT_DOWN);
KINGS_MOVES.add(RIGHT_UP);
STANDARD_MOVES.addFilter(FILTER);
KINGS_MOVES.addFilter(FILTER);
}
// init stateset
static {
for (int x = 0; x <= MAX_X_POSITION; x++) {
for (int y = 0; y <= MAX_Y_POSITION; y++) {
STATE_SET.add(new State(new double[] { x, y }));
}
}
}
/**
* Internal state
*/
protected State s = new State(2);
/*
* (non-Javadoc)
* @see
* org.hswgt.teachingbox.env.Environment#doAction(org.hswgt.teachingbox.
* env.Action)
*/
public double doAction(Action a)
{
// s = s + a;
SeqBlas.seqBlas.daxpy(1, a, s);
// add wind
s.set(1, s.get(1) + WIND[(int) s.get(0)]);
// check range
s.set(0, Math.min(s.get(0), MAX_X_POSITION));
s.set(0, Math.max(s.get(0), 0));
s.set(1, Math.min(s.get(1), MAX_Y_POSITION));
s.set(1, Math.max(s.get(1), 0));
if (isTerminalState())
return 0;
else
return -1;
}
/*
* (non-Javadoc)
* @see org.hswgt.teachingbox.env.Environment#getState()
*/
public State getState()
{
return s.copy();
}
/*
* (non-Javadoc)
* @see
* org.hswgt.teachingbox.env.Environment#init(org.hswgt.teachingbox.env.
* State)
*/
public void init(State s)
{
this.s = s.copy();
}
/*
* (non-Javadoc)
* @see org.hswgt.teachingbox.env.Environment#initRandom()
*/
public void initRandom()
{
this.s.set(0, Uniform.staticNextIntFromTo(0, MAX_X_POSITION));
this.s.set(1, Uniform.staticNextIntFromTo(0, MAX_Y_POSITION));
}
/*
* (non-Javadoc)
* @see org.hswgt.teachingbox.env.Environment#isTerminalState()
*/
public boolean isTerminalState()
{
// if( ((int) s.get(0)) == 7 && ((int) s.get(1)) == 3)
if (s.equals(GOAL))
return true;
return false;
}
/**
* @param q
*/
public static void Display(QFunction Q, ActionSet as)
{
HashMap<Action, String> symbols = new HashMap<Action, String>();
symbols.put(DOWN, "V");
symbols.put(UP, "^");
symbols.put(LEFT, "<");
symbols.put(RIGHT, ">");
GreedyPolicy pi = new GreedyPolicy(Q, as);
for (int y = MAX_Y_POSITION; y >= 0; y--) {
System.out.println("+---+---+---+---+---+---+---+---+---+---+");
System.out.print("| ");
for (int x = 0; x <= MAX_X_POSITION; x++) {
State s = new State(new double[] { x, y });
Action best = pi.getBestAction(s);
System.out.print(symbols.get(best) + " | ");
}
System.out.println("");
}
System.out.println("+---+---+---+---+---+---+---+---+---+---+");
}
}
| gpl-3.0 |
TeamDmfMM/Extra-Food | src/main/java/dmf444/ExtraFood/Common/blocks/Machines/AutoCutter.java | 1833 | package dmf444.ExtraFood.Common.blocks.Machines;
import dmf444.ExtraFood.Common.blocks.BlockContainerRotate;
import dmf444.ExtraFood.Common.blocks.tileentity.AutoCutterTileEntity;
import dmf444.ExtraFood.ExtraFood;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class AutoCutter extends BlockContainerRotate {
public AutoCutter() {
super(Material.WOOD);
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
TileEntity tileEntity = world.getTileEntity(pos);
if (tileEntity == null || player.isSneaking()) {
return false;
}
//code to open gui explained later
player.openGui(ExtraFood.instance, 1, world, pos.getX(), pos.getY(), pos.getZ());
return true;
}
//Make sure you set this as your TileEntity class relevant for the block!
@Override
public TileEntity createNewTileEntity(World world, int i) {
return new AutoCutterTileEntity();
}
//You don't want the normal render type, or it wont render properly.
@Override
public EnumBlockRenderType getRenderType(IBlockState state) {
return EnumBlockRenderType.INVISIBLE;
}
//It's not an opaque cube, so you need this.
@Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
}
| gpl-3.0 |
Matt529/Argus-Installer2 | src/com/mattc/argus2/gui/ArchiveChooser.java | 1571 | package com.mattc.argus2.gui;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import com.mattc.argus2.Ref;
import com.mattc.argus2.concurrent.Decompressors;
import com.mattc.argus2.io.ArchiveFile;
/**
* A Convenience Class for creating a {@link JFileChooser} with an Archive File
* filter based on registered formats and files not already included. It also
* automatically sets up any settings for us such as FileSelectionMode and
* MultiSelectionMode.
*
* @author Matthew
*
*/
public class ArchiveChooser extends JFileChooser {
private static final long serialVersionUID = -6360065333434189746L;
private static final String title = "Archive Selector";
public ArchiveChooser() {
super(Ref.getArchivesDir());
setFileFilter(getFilter());
setFileHidingEnabled(true);
setDialogTitle(title);
setDialogType(JFileChooser.OPEN_DIALOG);
setApproveButtonText("Confirm");
setFileSelectionMode(JFileChooser.FILES_ONLY);
setMultiSelectionEnabled(true);
}
private FileFilter getFilter() {
return new FileFilter() {
@Override
public String getDescription() {
return "Archive Files";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) return true;
final ArchiveFile[] files = ArchiveFile.getCurrentArchives();
// If already included then don't include.
for (final ArchiveFile aFile : files)
if (aFile.equals(f)) return false;
// Only show if it is a valid Archive File
return Decompressors.isAcceptableArchive(f);
}
};
}
}
| gpl-3.0 |
oswetto/LoboEvolution | LoboHtml/src/main/java/org/loboevolution/html/dom/svgimpl/SVGSVGElementImpl.java | 15542 | /*
* GNU GENERAL LICENSE
* Copyright (C) 2014 - 2021 Lobo Evolution
*
* 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
* verion 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 License for more details.
*
* You should have received a copy of the GNU General Public
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact info: ivan.difrancesco@yahoo.it
*/
package org.loboevolution.html.dom.svgimpl;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import org.loboevolution.html.dom.filter.IdFilter;
import org.loboevolution.html.dom.nodeimpl.NodeListImpl;
import org.loboevolution.html.dom.svg.Drawable;
import org.loboevolution.html.dom.svg.SVGAngle;
import org.loboevolution.html.dom.svg.SVGAnimatedLength;
import org.loboevolution.html.dom.svg.SVGAnimatedPreserveAspectRatio;
import org.loboevolution.html.dom.svg.SVGAnimatedRect;
import org.loboevolution.html.dom.svg.SVGAnimatedTransformList;
import org.loboevolution.html.dom.svg.SVGElement;
import org.loboevolution.html.dom.svg.SVGImageElement;
import org.loboevolution.html.dom.svg.SVGLength;
import org.loboevolution.html.dom.svg.SVGMatrix;
import org.loboevolution.html.dom.svg.SVGNumber;
import org.loboevolution.html.dom.svg.SVGPoint;
import org.loboevolution.html.dom.svg.SVGRect;
import org.loboevolution.html.dom.svg.SVGSVGElement;
import org.loboevolution.html.dom.svg.SVGTransform;
import org.loboevolution.html.dom.svg.SVGTransformable;
import org.loboevolution.html.dom.svg.SVGUseElement;
import org.loboevolution.html.dom.svg.SVGViewSpec;
import org.loboevolution.html.js.events.EventFactory;
import org.loboevolution.html.node.Element;
import org.loboevolution.html.node.Node;
import org.loboevolution.html.node.NodeList;
import org.loboevolution.html.node.events.Event;
/**
* <p>SVGSVGElementImpl class.</p>
*
*
*
*/
public class SVGSVGElementImpl extends SVGLocatableImpl implements SVGSVGElement, Drawable {
private final SVGRect viewport;
private SVGViewSpec currentView;
private SVGAnimatedRect viewBox;
private SVGPoint currentTranslate;
private AffineTransform viewboxToViewportTransform;
private float currentScale;
private boolean useCurrentView = false;
private boolean painted;
/**
* <p>isPainted.</p>
*
* @return the painted
*/
public boolean isPainted() {
return painted;
}
/**
* <p>Setter for the field painted.</p>
*
* @param painted the painted to set
*/
public void setPainted(boolean painted) {
this.painted = painted;
}
/**
* <p>Constructor for SVGSVGElementImpl.</p>
*
* @param name a {@link java.lang.String} object.
*/
public SVGSVGElementImpl(String name) {
super(name);
currentTranslate = new SVGPointImpl();
float x = getX().getBaseVal().getValue();
float y = getY().getBaseVal().getValue();
float width = getWidth().getBaseVal().getValue();
float height = getHeight().getBaseVal().getValue();
viewport = new SVGRectImpl(x, y, width, height);
}
/** {@inheritDoc} */
@Override
public SVGAnimatedRect getViewBox() {
if (viewBox == null) {
final float width = getWidth().getBaseVal().getValue();
final float height = getHeight().getBaseVal().getValue();
viewBox = new SVGAnimatedRectImpl(new SVGRectImpl(0, 0, width, height));
}
return viewBox;
}
/** {@inheritDoc} */
@Override
public SVGAnimatedPreserveAspectRatio getPreserveAspectRatio() {
// TODO Auto-generated method stub
return null;
}
/** {@inheritDoc} */
@Override
public short getZoomAndPan() {
// TODO Auto-generated method stub
return 0;
}
/** {@inheritDoc} */
@Override
public void setZoomAndPan(short zoomAndPan) {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public Event createEvent(String eventType) {
return EventFactory.createEvent(eventType);
}
/** {@inheritDoc} */
@Override
public SVGAnimatedLength getX() {
return new SVGAnimatedLengthImpl(new SVGLengthImpl(this.getAttribute("x")));
}
/** {@inheritDoc} */
@Override
public SVGAnimatedLength getY() {
return new SVGAnimatedLengthImpl(new SVGLengthImpl(this.getAttribute("y")));
}
/** {@inheritDoc} */
@Override
public SVGAnimatedLength getWidth() {
return new SVGAnimatedLengthImpl(new SVGLengthImpl(this.getAttribute("width")));
}
/** {@inheritDoc} */
@Override
public SVGAnimatedLength getHeight() {
return new SVGAnimatedLengthImpl(new SVGLengthImpl(this.getAttribute("height")));
}
/** {@inheritDoc} */
@Override
public SVGRect getViewport() {
float x = getX().getBaseVal().getValue();
float y = getY().getBaseVal().getValue();
float width = getWidth().getBaseVal().getValue();
float height = getHeight().getBaseVal().getValue();
return new SVGRectImpl(x, y, width, height);
}
/** {@inheritDoc} */
@Override
public float getPixelUnitToMillimeterX() {
return (float) 0.28;
}
/** {@inheritDoc} */
@Override
public float getPixelUnitToMillimeterY() {
return (float) 0.28;
}
/** {@inheritDoc} */
@Override
public float getScreenPixelToMillimeterX() {
return (float) 0.28;
}
/** {@inheritDoc} */
@Override
public float getScreenPixelToMillimeterY() {
return (float) 0.28;
}
/** {@inheritDoc} */
@Override
public boolean getUseCurrentView() {
return useCurrentView;
}
/** {@inheritDoc} */
@Override
public void setUseCurrentView(boolean useCurrentView) {
this.useCurrentView = useCurrentView;
}
/** {@inheritDoc} */
@Override
public SVGViewSpec getCurrentView() {
return currentView;
}
/** {@inheritDoc} */
@Override
public float getCurrentScale() {
return currentScale;
}
/** {@inheritDoc} */
@Override
public void setCurrentScale(float currentScale) {
this.currentScale = currentScale;
}
/** {@inheritDoc} */
@Override
public SVGPoint getCurrentTranslate() {
return currentTranslate;
}
/**
* <p>Setter for the field currentTranslate.</p>
*
* @param currentTranslate a {@link org.loboevolution.html.dom.svg.SVGPoint} object.
* @throws org.w3c.dom.DOMException if any.
*/
public void setCurrentTranslate(SVGPoint currentTranslate) {
this.currentTranslate = currentTranslate;
}
/** {@inheritDoc} */
@Override
public int suspendRedraw(int max_wait_milliseconds) {
// TODO Auto-generated method stub
return 0;
}
/** {@inheritDoc} */
@Override
public void unsuspendRedraw(int suspend_handle_id) {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public void unsuspendRedrawAll() {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public void forceRedraw() {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public void pauseAnimations() {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public void unpauseAnimations() {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public boolean animationsPaused() {
// TODO Auto-generated method stub
return false;
}
/** {@inheritDoc} */
@Override
public float getCurrentTime() {
// TODO Auto-generated method stub
return 0;
}
/** {@inheritDoc} */
@Override
public void setCurrentTime(float seconds) {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public NodeList getIntersectionList(SVGRect rect, SVGElement referenceElement) {
// TODO Auto-generated method stub
return null;
}
/** {@inheritDoc} */
@Override
public NodeList getEnclosureList(SVGRect rect, SVGElement referenceElement) {
// TODO Auto-generated method stub
return null;
}
/** {@inheritDoc} */
@Override
public boolean checkIntersection(SVGElement element, SVGRect rect) {
// TODO Auto-generated method stub
return false;
}
/** {@inheritDoc} */
@Override
public boolean checkEnclosure(SVGElement element, SVGRect rect) {
// TODO Auto-generated method stub
return false;
}
/** {@inheritDoc} */
@Override
public void deselectAll() {
// TODO Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public SVGLength createSVGLength() {
return new SVGLengthImpl();
}
/** {@inheritDoc} */
@Override
public SVGAngle createSVGAngle() {
return new SVGAngleImpl();
}
/** {@inheritDoc} */
@Override
public SVGPoint createSVGPoint() {
return new SVGPointImpl();
}
/** {@inheritDoc} */
@Override
public SVGMatrix createSVGMatrix() {
return new SVGMatrixImpl();
}
/** {@inheritDoc} */
@Override
public SVGNumber createSVGNumber() {
return new SVGNumberImpl();
}
/** {@inheritDoc} */
@Override
public SVGRect createSVGRect() {
float x = getX().getBaseVal().getValue();
float y = getY().getBaseVal().getValue();
float width = getWidth().getBaseVal().getValue();
float height = getHeight().getBaseVal().getValue();
return new SVGRectImpl(x, y, width, height);
}
/** {@inheritDoc} */
@Override
public SVGTransform createSVGTransform() {
return new SVGTransformImpl();
}
/** {@inheritDoc} */
@Override
public SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix) {
SVGTransform transform = new SVGTransformImpl();
transform.setMatrix(matrix);
return transform;
}
/** {@inheritDoc} */
@Override
public Element getElementById(String elementId) {
NodeList nodeList = getNodeList(new IdFilter(elementId));
return nodeList != null && nodeList.getLength() > 0 ? (Element)nodeList.item(0) : null;
}
/** {@inheritDoc} */
@Override
public void draw(Graphics2D graphics) {
boolean display = getDisplay();
float opacity = getOpacity();
if (display && opacity > 0) {
AffineTransform oldGraphicsTransform = graphics.getTransform();
Shape oldClip = graphics.getClip();
graphics.translate(viewport.getX(), viewport.getY());
if (opacity < 1) {
SVGSVGElement root = this;
float currentScale = root.getCurrentScale();
SVGPoint currentTranslate = root.getCurrentTranslate();
if (currentTranslate == null) {
currentTranslate = new SVGPointImpl();
}
// create buffer to draw on
Shape shape = createShape(null);
AffineTransform screenCTM = getScreenCTM().getAffineTransform();
Shape transformedShape = screenCTM.createTransformedShape(shape);
Rectangle2D bounds = transformedShape.getBounds2D();
double xInc = bounds.getWidth() / 5;
double yInc = bounds.getHeight() / 5;
bounds.setRect(bounds.getX() - xInc, bounds.getY() - yInc, bounds.getWidth() + 2 * xInc, bounds.getHeight() + 2 * yInc);
int imageWidth = (int) (bounds.getWidth() * currentScale);
int imageHeight = (int) (bounds.getHeight() * currentScale);
if (imageWidth > 0 && imageHeight > 0) {
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D offGraphics = (Graphics2D) image.getGraphics();
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
offGraphics.setRenderingHints(hints);
if (currentScale != 1) {
offGraphics.scale(currentScale, currentScale);
}
offGraphics.translate(-bounds.getX(), -bounds.getY());
offGraphics.transform(screenCTM);
drawChildren(offGraphics);
Composite oldComposite = graphics.getComposite();
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity);
graphics.setComposite(ac);
AffineTransform imageTransform = AffineTransform.getTranslateInstance(bounds.getX(), bounds.getY());
imageTransform.scale(1 / currentScale, 1 / currentScale);
try {
imageTransform.preConcatenate(screenCTM.createInverse());
} catch (NoninvertibleTransformException e) {
}
graphics.drawImage(image, imageTransform, null);
graphics.setComposite(oldComposite);
image.flush();
}
} else {
drawChildren(graphics);
}
graphics.setTransform(oldGraphicsTransform);
graphics.setClip(oldClip);
}
}
/** {@inheritDoc} */
@Override
public Shape createShape(AffineTransform transform) {
GeneralPath path = new GeneralPath();
if (hasChildNodes()) {
NodeListImpl children = (NodeListImpl)getChildNodes();
children.forEach(child -> {
Shape childShape = null;
if (child instanceof SVGGElementImpl) {
childShape = ((SVGGElementImpl) child).createShape(transform);
} else if (child instanceof SVGAElementImpl) {
childShape = ((SVGAElementImpl) child).createShape(transform);
} else if (child instanceof SVGImageElementImpl) {
SVGRect bbox = ((SVGImageElement) child).getBBox();
childShape = new Rectangle2D.Float(bbox.getX(), bbox.getY(), bbox.getWidth(), bbox.getHeight());
} else if (child instanceof SVGUseElementImpl) {
SVGRect bbox = ((SVGUseElement) child).getBBox();
childShape = new Rectangle2D.Float(bbox.getX(), bbox.getY(), bbox.getWidth(), bbox.getHeight());
} else if (child instanceof SVGSVGElementImpl) {
SVGSVGElement svg = (SVGSVGElement) child;
AffineTransform ctm = AffineTransform.getTranslateInstance(viewport.getX(), viewport.getY());
if (viewboxToViewportTransform != null) {
ctm.concatenate(viewboxToViewportTransform);
}
AffineTransform inverseTransform;
try {
inverseTransform = ctm.createInverse();
} catch (NoninvertibleTransformException e) {
inverseTransform = null;
}
float x = ((SVGLengthImpl) svg.getX()).getTransformedLength(inverseTransform);
float y = ((SVGLengthImpl) svg.getY()).getTransformedLength(inverseTransform);
float width = ((SVGLengthImpl) svg.getWidth()).getTransformedLength(inverseTransform);
float height = ((SVGLengthImpl) svg.getHeight()).getTransformedLength(inverseTransform);
childShape = new Rectangle2D.Float(x, y, width, height);
}
// transform the child shapae
if (child instanceof SVGTransformable) {
SVGAnimatedTransformList childTransformList = ((SVGTransformable) child).getTransform();
if (childTransformList != null) {
AffineTransform childTransform = ((SVGTransformListImpl) childTransformList.getAnimVal()).getAffineTransform();
childShape = childTransform.createTransformedShape(childShape);
}
}
if (childShape != null) {
path.append(childShape, false);
}
});
}
return path;
}
private void drawChildren(Graphics2D graphics) {
List<Node> drawableChildren = new ArrayList<>();
if (hasChildNodes()) {
NodeListImpl children = (NodeListImpl)getChildNodes();
children.forEach(child -> {
if (child instanceof Drawable) {
drawableChildren.add(child);
}
});
}
for (Node node : drawableChildren) {
SVGElement selem = (SVGElement)node;
selem.setOwnerSVGElement(this);
drawStyle(node);
Drawable child = (Drawable) node;
child.draw(graphics);
}
}
/** {@inheritDoc} */
@Override
public String toString() {
return "[object SVGSVGElement]";
}
}
| gpl-3.0 |
herpingdo/Hakkit | net/minecraft/src/EntityIronGolem.java | 8120 | package net.minecraft.src;
public class EntityIronGolem extends EntityGolem
{
/** deincrements, and a distance-to-home check is done at 0 */
private int homeCheckTimer;
Village villageObj;
private int attackTimer;
private int holdRoseTick;
public EntityIronGolem(World par1World)
{
super(par1World);
this.setSize(1.4F, 2.9F);
this.getNavigator().setAvoidsWater(true);
this.tasks.addTask(1, new EntityAIAttackOnCollide(this, 1.0D, true));
this.tasks.addTask(2, new EntityAIMoveTowardsTarget(this, 0.9D, 32.0F));
this.tasks.addTask(3, new EntityAIMoveThroughVillage(this, 0.6D, true));
this.tasks.addTask(4, new EntityAIMoveTowardsRestriction(this, 1.0D));
this.tasks.addTask(5, new EntityAILookAtVillager(this));
this.tasks.addTask(6, new EntityAIWander(this, 0.6D));
this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F));
this.tasks.addTask(8, new EntityAILookIdle(this));
this.targetTasks.addTask(1, new EntityAIDefendVillage(this));
this.targetTasks.addTask(2, new EntityAIHurtByTarget(this, false));
this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityLiving.class, 0, false, true, IMob.mobSelector));
}
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(16, Byte.valueOf((byte)0));
}
/**
* Returns true if the newer Entity AI code should be run
*/
public boolean isAIEnabled()
{
return true;
}
/**
* main AI tick function, replaces updateEntityActionState
*/
protected void updateAITick()
{
if (--this.homeCheckTimer <= 0)
{
this.homeCheckTimer = 70 + this.rand.nextInt(50);
this.villageObj = this.worldObj.villageCollectionObj.findNearestVillage(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ), 32);
if (this.villageObj == null)
{
this.func_110177_bN();
}
else
{
ChunkCoordinates var1 = this.villageObj.getCenter();
this.func_110171_b(var1.posX, var1.posY, var1.posZ, (int)((float)this.villageObj.getVillageRadius() * 0.6F));
}
}
super.updateAITick();
}
protected void func_110147_ax()
{
super.func_110147_ax();
this.func_110148_a(SharedMonsterAttributes.field_111267_a).func_111128_a(100.0D);
this.func_110148_a(SharedMonsterAttributes.field_111263_d).func_111128_a(0.25D);
}
/**
* Decrements the entity's air supply when underwater
*/
protected int decreaseAirSupply(int par1)
{
return par1;
}
protected void collideWithEntity(Entity par1Entity)
{
if (par1Entity instanceof IMob && this.getRNG().nextInt(20) == 0)
{
this.setAttackTarget((EntityLivingBase)par1Entity);
}
super.collideWithEntity(par1Entity);
}
/**
* Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons
* use this to react to sunlight and start to burn.
*/
public void onLivingUpdate()
{
super.onLivingUpdate();
if (this.attackTimer > 0)
{
--this.attackTimer;
}
if (this.holdRoseTick > 0)
{
--this.holdRoseTick;
}
if (this.motionX * this.motionX + this.motionZ * this.motionZ > 2.500000277905201E-7D && this.rand.nextInt(5) == 0)
{
int var1 = MathHelper.floor_double(this.posX);
int var2 = MathHelper.floor_double(this.posY - 0.20000000298023224D - (double)this.yOffset);
int var3 = MathHelper.floor_double(this.posZ);
int var4 = this.worldObj.getBlockId(var1, var2, var3);
if (var4 > 0)
{
this.worldObj.spawnParticle("tilecrack_" + var4 + "_" + this.worldObj.getBlockMetadata(var1, var2, var3), this.posX + ((double)this.rand.nextFloat() - 0.5D) * (double)this.width, this.boundingBox.minY + 0.1D, this.posZ + ((double)this.rand.nextFloat() - 0.5D) * (double)this.width, 4.0D * ((double)this.rand.nextFloat() - 0.5D), 0.5D, ((double)this.rand.nextFloat() - 0.5D) * 4.0D);
}
}
}
/**
* Returns true if this entity can attack entities of the specified class.
*/
public boolean canAttackClass(Class par1Class)
{
return this.isPlayerCreated() && EntityPlayer.class.isAssignableFrom(par1Class) ? false : super.canAttackClass(par1Class);
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
{
super.writeEntityToNBT(par1NBTTagCompound);
par1NBTTagCompound.setBoolean("PlayerCreated", this.isPlayerCreated());
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
{
super.readEntityFromNBT(par1NBTTagCompound);
this.setPlayerCreated(par1NBTTagCompound.getBoolean("PlayerCreated"));
}
public boolean attackEntityAsMob(Entity par1Entity)
{
this.attackTimer = 10;
this.worldObj.setEntityState(this, (byte)4);
boolean var2 = par1Entity.attackEntityFrom(DamageSource.causeMobDamage(this), (float)(7 + this.rand.nextInt(15)));
if (var2)
{
par1Entity.motionY += 0.4000000059604645D;
}
this.playSound("mob.irongolem.throw", 1.0F, 1.0F);
return var2;
}
public Village getVillage()
{
return this.villageObj;
}
public void setHoldingRose(boolean par1)
{
this.holdRoseTick = par1 ? 400 : 0;
this.worldObj.setEntityState(this, (byte)11);
}
/**
* Returns the sound this mob makes while it's alive.
*/
protected String getLivingSound()
{
return "none";
}
/**
* Returns the sound this mob makes when it is hurt.
*/
protected String getHurtSound()
{
return "mob.irongolem.hit";
}
/**
* Returns the sound this mob makes on death.
*/
protected String getDeathSound()
{
return "mob.irongolem.death";
}
/**
* Plays step sound at given x, y, z for the entity
*/
protected void playStepSound(int par1, int par2, int par3, int par4)
{
this.playSound("mob.irongolem.walk", 1.0F, 1.0F);
}
/**
* Drop 0-2 items of this living's type
*/
protected void dropFewItems(boolean par1, int par2)
{
int var3 = this.rand.nextInt(3);
int var4;
for (var4 = 0; var4 < var3; ++var4)
{
this.dropItem(Block.plantRed.blockID, 1);
}
var4 = 3 + this.rand.nextInt(3);
for (int var5 = 0; var5 < var4; ++var5)
{
this.dropItem(Item.ingotIron.itemID, 1);
}
}
public int getHoldRoseTick()
{
return this.holdRoseTick;
}
public boolean isPlayerCreated()
{
return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0;
}
public void setPlayerCreated(boolean par1)
{
byte var2 = this.dataWatcher.getWatchableObjectByte(16);
if (par1)
{
this.dataWatcher.updateObject(16, Byte.valueOf((byte)(var2 | 1)));
}
else
{
this.dataWatcher.updateObject(16, Byte.valueOf((byte)(var2 & -2)));
}
}
/**
* Called when the mob's health reaches 0.
*/
public void onDeath(DamageSource par1DamageSource)
{
if (!this.isPlayerCreated() && this.attackingPlayer != null && this.villageObj != null)
{
this.villageObj.setReputationForPlayer(this.attackingPlayer.getCommandSenderName(), -5);
}
super.onDeath(par1DamageSource);
}
}
| gpl-3.0 |
yihu5566/Camera | app/src/main/java/com/example/lxrent/camerademo/util/CompressVideoUtils.java | 1195 | package com.example.lxrent.camerademo.util;
import com.zero.smallvideorecord.LocalMediaCompress;
import com.zero.smallvideorecord.model.AutoVBRMode;
import com.zero.smallvideorecord.model.LocalMediaConfig;
import com.zero.smallvideorecord.model.OnlyCompressOverBean;
/**
* @Author : dongfang
* @Created Time : 2019-03-20 17:52
* @Description:
*/
public class CompressVideoUtils {
public CompressVideoUtils() {
}
/**
* 压缩文件哦
*
* @param filePath
* @return
*/
public static String startCompress(String filePath) {
//初始化压缩
LocalMediaConfig.Buidler buidler = new LocalMediaConfig.Buidler();
final LocalMediaConfig config = buidler
.setVideoPath(filePath)
.captureThumbnailsTime(1)
.doH264Compress(new AutoVBRMode())
.setFramerate(10)
.build();
OnlyCompressOverBean onlyCompressOverBean = new LocalMediaCompress(config).startCompress();
if (onlyCompressOverBean.isSucceed()) {
LogUtil.d(onlyCompressOverBean.getVideoPath());
}
return onlyCompressOverBean.getVideoPath();
}
}
| gpl-3.0 |
BetaCONCEPT/astroboa | astroboa-model/src/main/java/org/betaconceptframework/astroboa/serializer/ModelSerializer.java | 3645 | /*
* Copyright (C) 2005-2012 BetaCONCEPT Limited
*
* This file is part of Astroboa.
*
* Astroboa 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.
*
* Astroboa 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 Astroboa. If not, see <http://www.gnu.org/licenses/>.
*/
package org.betaconceptframework.astroboa.serializer;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.betaconceptframework.astroboa.api.model.io.ResourceRepresentationType;
import org.betaconceptframework.astroboa.api.service.DefinitionService;
import org.betaconceptframework.astroboa.configuration.RepositoryRegistry;
import org.betaconceptframework.astroboa.util.CmsConstants;
/**
*
* Class responsible to serialize the content model of a repository
* into one XML or JSON file
*
* @author Gregory Chomatas (gchomatas@betaconcept.com)
* @author Savvas Triantafyllou (striantafyllou@betaconcept.com)
*
*/
public class ModelSerializer extends AbstractSerializer{
private DefinitionService definitionService;
private String repository;
public ModelSerializer(boolean prettyPrint, boolean jsonOutput, DefinitionService definitionService, String repository) {
super(prettyPrint, jsonOutput);
this.repository = repository;
this.definitionService = definitionService;
}
public String serialize(){
if (! outputIsJSON()){
startElement("astroboa", true, true);
}
writeAttribute("server", RepositoryRegistry.INSTANCE.getDefaultServerURL());
writeAttribute("repository", repository);
if (! outputIsJSON()){
endElement("astroboa", true, false);
}
serializeModel();
if (! outputIsJSON()){
endElement("astroboa", false, true);
}
return super.serialize();
}
private void serializeModel() {
ResourceRepresentationType<String> output = outputIsJSON() ? ResourceRepresentationType.JSON : ResourceRepresentationType.XML;
boolean prettyPrintEnabled = prettyPrintEnabled();
boolean firstType = true;
startElement(CmsConstants.ARRAY_OF_OBJECT_TYPE_ELEMENT_NAME, false, true);
if (outputIsJSON()){
startArray(CmsConstants.OBJECT_TYPE_ELEMENT_NAME);
}
List<String> contentTypes = definitionService.getContentObjectTypes();
for (String contentType : contentTypes){
String contentTypeAsXmlorJson = definitionService.getCmsDefinition(contentType, output, prettyPrintEnabled);
if (!outputIsJSON()){
//Remove XML headers
contentTypeAsXmlorJson = StringUtils.remove(contentTypeAsXmlorJson, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
}
else{
//Remove root element
//contentTypeAsXmlorJson = contentTypeAsXmlorJson.replaceFirst("\\{","").replaceFirst("(.*?):", "");
//Remove end
//contentTypeAsXmlorJson = StringUtils.removeEnd(contentTypeAsXmlorJson, "}");
if (!firstType){
contentTypeAsXmlorJson = ","+contentTypeAsXmlorJson;
}
else{
firstType = false;
}
}
writeContent(contentTypeAsXmlorJson, false);
}
if (outputIsJSON()){
endArray(CmsConstants.OBJECT_TYPE_ELEMENT_NAME);
}
endElement(CmsConstants.ARRAY_OF_OBJECT_TYPE_ELEMENT_NAME, false, true);
}
}
| gpl-3.0 |
qt-haiku/LibreOffice | qadevOOo/tests/java/ifc/sheet/_XAreaLinks.java | 3118 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package ifc.sheet;
import com.sun.star.sheet.XAreaLinks;
import com.sun.star.table.CellAddress;
import lib.MultiMethodTest;
/**
* Testing <code>com.sun.star.sheet.XAreaLinks</code>
* interface methods :
* <ul>
* <li><code> insertAtPosition()</code></li>
* <li><code> removeByIndex()</code></li>
* </ul> <p>
* Test is <b> NOT </b> multithread compilant. <p>
* @see com.sun.star.sheet.XAreaLinks
*/
public class _XAreaLinks extends MultiMethodTest {
public XAreaLinks oObj = null;
/**
* Inserts a new link into collection. Checks number of links
* before and after method call. <p>
* Has <b>OK</b> status if after method call number of
* links increased by 1.
*/
public void _insertAtPosition(){
boolean bResult = true ;
int cnt = 0;
cnt = oObj.getCount() ;
CellAddress addr = new CellAddress ((short) 1,2,3) ;
String aSourceArea = util.utils.getFullTestURL("calcshapes.sxc");
oObj.insertAtPosition (addr, aSourceArea, "a2:b5", "", "") ;
if (bResult) {
int new_cnt = oObj.getCount() ;
if (cnt + 1 != new_cnt) {
bResult = false ;
log.println("Number of links before insertAtPosition() call was " + cnt +
", after call is " + new_cnt) ;
}
}
tRes.tested("insertAtPosition()", bResult) ;
}
/**
* Removes a link from collection. Checks number of links
* before and after method call. <p>
* Has <b>OK</b> status if after method call number of
* links decreases by 1. <p>
* The following method tests are to be completed successfully before :
* <ul>
* <li> <code> insertAtPosition </code> : to have at least one link. </li>
* </ul>
*/
public void _removeByIndex(){
requiredMethod("insertAtPosition()") ;
boolean bResult = true ;
int lcnt = 0;
lcnt = oObj.getCount() ;
oObj.removeByIndex(0) ;
int new_lcnt = oObj.getCount() ;
if (lcnt - 1 != new_lcnt) {
bResult = false ;
log.println(" # Number of links before removeByIndex() call was " +
lcnt + ", after call is " + new_lcnt) ;
}
tRes.tested("removeByIndex()", bResult) ;
}
} //EOC _XAreaLinks
| gpl-3.0 |
MinSikSon/niaas_sdnhub_odl_tutorial | learning-switch/implementation/src/main/java/org/sdnhub/odl/tutorial/learningswitch/impl/Niaas_Docker.java | 8368 | /*
* Name: SMS_Docker
*
* Ver: 1.0
*
* Data: 2016-0602
*/
package org.sdnhub.odl.tutorial.learningswitch.impl;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Niaas_Docker {
/**
* FOG_SERVER에서 docker container가 동작중인지 확인하고, 해당 ip를 ArrayList.
*
* @parameter: ArrayList<String> fogServerDockerList
* @return: void
*/
// private static ArrayList<String> fogServerDockerList = new ArrayList<String>();
public static void addFogServerIpToList(ArrayList<String> fogServer_Ip_List){
// final Logger LOG = LoggerFactory.getLogger(SMS_Docker.class);
// LOG.debug("addFogServerIpToList()++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
// int exist = 0;
try {
Process process = Runtime.getRuntime().exec("/home/sms/workspace/SDNHub_Opendaylight_Tutorial/admin/GET_DOCKER_STATUS.sh "
+ "/home/sms/workspace/SDNHub_Opendaylight_Tutorial/admin/DOCKER_SWITCH_IP.txt");
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
try {
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/home/sms/workspace/SDNHub_Opendaylight_Tutorial/admin/DOCKER_SWITCH_IP.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // no information
String value1 = "";
String value2 = "";
String value3 = "";
String ip = "";
int[] ipAddr = new int[4];
/*-
* $ docker -ps --format "table {{.Name}}@{{.Ports}}"
* 위의 docker 명령어를 사용하였을 때, 출력되는 데이터 중에 필요한 정보만 자르고 저장하는 과정.
*/
while (true) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line == null)
break;
StringTokenizer tokens1 = new StringTokenizer(line, "@");
// System.out.println("[token1 count] " + tokens1.countTokens());
while(true){
value1 = tokens1.nextToken();
// System.out.println("[tokens1 value] " + value1);
StringTokenizer tokens2 = new StringTokenizer(value1, ", ");
// if(tokens2.countTokens() > 2){
// System.out.println("<");
// System.out.println("[token2 count] " + tokens2.countTokens());
while(true){
value2 = tokens2.nextToken();
// System.out.println("[tokens2 value] " + value2);
StringTokenizer tokens3 = new StringTokenizer(value2, ".");
if(tokens3.countTokens() >= 4){
// System.out.println("<<");
// System.out.println("[token3 count] " + tokens3.countTokens());
int i = 0;
while(true){
value3 = tokens3.nextToken();
// System.out.println("[tokens3 value] " + value3);
if(i != 3){
ipAddr[i] = Integer.parseInt(value3);
}else if(i == 3){
StringTokenizer tokens4 = new StringTokenizer(value3, ":");
ipAddr[i] = Integer.parseInt(tokens4.nextToken());
}
i++;
if(tokens3.countTokens() == 0) break;
}
/*-
* ip주소가 FOG_SERVER ip list와 겹치는지 검사 후, 겹치지 않으면 삽입.
*/
ip = ipAddr[0] + "." + ipAddr[1] + "." + ipAddr[2] + "." + ipAddr[3];
boolean check = checkFogServerIpExistInArray(fogServer_Ip_List, ip);
if(check == false) fogServer_Ip_List.add(ip);
// System.out.println(ip);
// System.out.println(">>");
}
if(tokens2.countTokens() == 0) break;
}
// System.out.println(">");
// }
if(tokens1.countTokens() == 0) break;
}
// System.out.println("--------------------------");
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return exist;
// LOG.debug("addFogServerIpToList()------------------------------------------------------------");
}
/**
* addFogServerIpToList에서 사용. ArrayList에 fogServerIp에 해당하는 값이 존재하는지 확인.
*
* @parameter: ArrayList<String> fogServerDockerList,
* @parameter: String fogServerIp,
* @return: boolean
*/
public static boolean checkFogServerIpExistInArray(ArrayList<String> fogServer_Ip_List, String fogServerIp){
boolean check = fogServer_Ip_List.contains(fogServerIp);
return check;
}
/**
* CLOUD_SERVER ip를 확인해고, 해당 ip를 ArrayList에 저장.
*
* @parameter: ArrayList<String> cloudServer_Ip_List
* @return: void
*/
public static void addCloudServerIpToList(ArrayList<String> cloudServer_Ip_List){
// final Logger LOG = LoggerFactory.getLogger(SMS_Docker.class);
// LOG.debug("addFogServerOvsIdToList()++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/home/sms/workspace/SDNHub_Opendaylight_Tutorial/admin/CLOUD_SERVER_IP.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (line == null)
break;
boolean check = checkCloudServerIpExistInArray(cloudServer_Ip_List, line);
if(check == false) cloudServer_Ip_List.add(line);
}
// for(int i = 0 ; i < fogServerOvsIdList.size() ; i++){
// System.out.println(fogServerOvsIdList.get(i));
// }
// LOG.debug("addFogServerOvsIdToList()------------------------------------------------------------");
}
/**
* addCloudServerIpToList()에서 사용. ArrayList에 cloudServerIp에 해당하는 값이 존재하는지 확인.
*
* @parameter: ArrayList<String> cloudServer_Ip_List,
* @parameter: String cloudServerIp,
* @return: boolean
*/
public static boolean checkCloudServerIpExistInArray(ArrayList<String> cloudServer_Ip_List, String cloudServerIp) {
boolean check = cloudServer_Ip_List.contains(cloudServerIp);
return check;
}
///**
//* FOG_SERVER가 동작할 ovs의 id를 확인해고, 해당 id를 ArrayList에 저장.
//*
//* @parameter: ArrayList<String> fogServerOvsIdList
//* @return: void
//*/
//public static void addFogServerOvsIdToList(ArrayList<String> fogServerOvsIdList){
//// final Logger LOG = LoggerFactory.getLogger(SMS_Docker.class);
//// LOG.debug("addFogServerOvsIdToList()++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
// BufferedReader br = null;
// try {
// br = new BufferedReader(new FileReader("/home/sms/workspace/SDNHub_Opendaylight_Tutorial/admin/FOG_SERVER_OVS_ID.txt"));
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// while(true){
// String line = null;
// try {
// line = br.readLine();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// if (line == null)
// break;
// boolean check = checkFogServerIpExistInArray(fogServerOvsIdList, line);
//
// if(check == false) fogServerOvsIdList.add(line);
// }
//// for(int i = 0 ; i < fogServerOvsIdList.size() ; i++){
//// System.out.println(fogServerOvsIdList.get(i));
//// }
//// LOG.debug("addFogServerOvsIdToList()------------------------------------------------------------");
//}
//
///**
//* addFogServerOvsIdToList()에서 사용. ArrayList에 fogServerOvsId에 해당하는 값이 존재하는지 확인.
//*
//* @parameter: ArrayList<String> fogServerOvsIdList,
//* @parameter: String fogServerOvsId,
//* @return: boolean
//*/
//public static boolean checkFogServerOvsIdExistInArray(ArrayList<String> fogServerOvsIdList, String fogServerOvsId) {
// boolean check = fogServerOvsIdList.contains(fogServerOvsId);
// return check;
//}
}
| gpl-3.0 |
TexasLoki/Protocol | src/main/java/org/pistonmc/protocol/v47/login/client/PacketLoginInEncryptionResponse.java | 896 | package org.pistonmc.protocol.v47.login.client;
import org.pistonmc.exception.protocol.packet.PacketException;
import org.pistonmc.protocol.packet.ProtocolState;
import org.pistonmc.protocol.packet.UnreadPacket;
import org.pistonmc.protocol.packet.IncomingPacket;
import java.io.IOException;
public class PacketLoginInEncryptionResponse extends IncomingPacket {
private byte[] sharedSecret;
private byte[] verifyToken;
public PacketLoginInEncryptionResponse() {
super(ProtocolState.LOGIN, 0x01);
}
@Override
public void read(UnreadPacket packet) throws PacketException, IOException {
this.sharedSecret = packet.getStream().readBytes();
this.verifyToken = packet.getStream().readBytes();
}
public byte[] getSharedSecret() {
return sharedSecret;
}
public byte[] getVerifyToken() {
return verifyToken;
}
} | gpl-3.0 |
sprax/java | strings/BoyerMooreKMP.java | 4640 | package sprax.strings;
import java.util.ArrayList;
import sprax.sprout.Sx;
import sprax.test.Sz;
public class BoyerMooreKMP
{
protected final int mCharSetSize; // the radix
protected char[] mPatArr; // store the pattern as a character array
protected String mPatStr; // or as a string
protected int[] mRightmostArr; // the bad-character skip array
public BoyerMooreKMP(final String patStr, int charSetSize)
{
mPatStr = patStr;
mPatArr = patStr.toCharArray();
mCharSetSize = charSetSize;
initRightmost();
}
protected void initRightmost()
{
mRightmostArr = new int[mCharSetSize];
for (int c = 0; c < mCharSetSize; c++)
mRightmostArr[c] = -1;
for (int j = 0; j < mPatArr.length; j++)
mRightmostArr[mPatArr[j]] = j;
}
protected void intitGoodSuffix(char normal[])
{
/****************
char result[] = new char[mCharSetSize];
char left[] = (char *)normal;
char right[] = left + mCharSetSize;
char reversed[mCharSetSize + 1];
char *tmp = reversed + mCharSetSize;
int i;
// reverse string
*tmp = 0;
while (left < right)
*(--tmp) = *(left++);
int prefix_normal[mCharSetSize];
int prefix_reversed[mCharSetSize];
compute_prefix(normal, mCharSetSize, prefix_normal);
compute_prefix(reversed, mCharSetSize, prefix_reversed);
for (i = 0; i <= mCharSetSize; i++) {
result[i] = mCharSetSize - prefix_normal[mCharSetSize - 1];
}
for (i = 0; i < mCharSetSize; i++) {
int j = mCharSetSize - prefix_reversed[i];
int k = i - prefix_reversed[i] + 1;
if (result[j] > k)
result[j] = k;
}
*****************/
}
public int searchBadCharGoodSuffixHeuristics(String txt, int start)
{
int M = mPatArr.length;
int N = txt.length();
int skip;
for (int i = start; i < N - M; i += skip) {
skip = 0;
for (int j = M; --j >= 0; ) {
if (mPatArr[j] != txt.charAt(i+j)) {
skip = Math.max(1, j - mRightmostArr[txt.charAt(i+j)]);
break;
}
}
if (skip == 0)
return i; // found
}
return -N; // not found
}
//////////////////////////////////////////////////////////////////////
public int searchBadCharHeuristic(String txt, int start)
{
int M = mPatArr.length;
int N = txt.length();
return searchBadCharHeuristic(txt, start, N - M);
}
private int searchBadCharHeuristic(String txt, int start, int last)
{
int M = mPatArr.length;
int skip;
for (int i = start; i <= last; i += skip) {
skip = 0;
for (int j = M; --j >= 0; ) {
if (mPatArr[j] != txt.charAt(i+j)) {
int chrIdx = txt.charAt(i+j);
if (chrIdx < mCharSetSize) {
skip = j - mRightmostArr[chrIdx];
}
else
{
Sx.format("txt[%d] = %c\n", chrIdx, (char)chrIdx);
skip = 1;
}
break;
}
}
if (skip == 0)
return i; // found
}
return -last; // not found
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static int unit_test(int level)
{
String testName = BoyerMooreKMP.class.getName() + ".unit_test";
Sx.puts(testName + " BEGIN\n");
//String txt = "Our house is almost at the edge of the Seam.";
String txt = "Our house is almost at the edge of the Seam. I only have to pass a few gates to reach the scruffy field called the Meadow. Separating the Meadow from the woods, in fact enclosing all of District 12, is a high chain-link fence topped with barbed-wire loops. In theory, it's supposed to be electrified twenty-four hours a day as a deterrent to the predators that live in the wood -- packs of wild dogs, lone cougars, bears -- that used to threaten our streets. But since we're lucky to get two or three hours of electricity in the evenings, it's usually safe to touch. Even so, I always take a moment to listen carefully for the hum that means the fence is live. Right now, it's silent as a stone. Concealed by a clump of bushes, I flatten out on my belly and slide under a two-foot stretch that's been loose for years. There are several other weak spots in the fence, but this one is so close to home I almost always enter the woods here.";
String pat = "the";
BoyerMooreKMP bmk = new BoyerMooreKMP(pat, 256);
ArrayList<Integer> starts = new ArrayList<Integer>();
int ss = -1;
for (;;)
{
ss = bmk.searchBadCharHeuristic(txt, ss+1);
if (ss < 0)
break;
starts.add(ss);
}
Sx.format("Indexes of start of <%s>: ", pat);
Sx.putsList(starts);
Sz.end(testName, 0);
return 0;
}
public static void main(String args[]) { unit_test(1); }}
| gpl-3.0 |
shelllbw/workcraft | FsmPlugin/src/org/workcraft/plugins/fsm/tools/FsmUtils.java | 1419 | package org.workcraft.plugins.fsm.tools;
import java.util.HashMap;
import java.util.HashSet;
import org.workcraft.plugins.fsm.Event;
import org.workcraft.plugins.fsm.Fsm;
import org.workcraft.plugins.fsm.State;
public class FsmUtils {
public static HashMap<State, HashSet<Event>> calcStateOutgoingEventsMap(final Fsm fsm) {
HashMap<State, HashSet<Event>> stateOutgoingEvents = new HashMap<>();
for (State state: fsm.getStates()) {
HashSet<Event> events = new HashSet<>();
stateOutgoingEvents.put(state, events);
}
for (Event event: fsm.getEvents()) {
State fromState = (State) event.getFirst();
HashSet<Event> events = stateOutgoingEvents.get(fromState);
events.add(event);
}
return stateOutgoingEvents;
}
public static HashMap<State, HashSet<Event>> calcStateIncommingEventsMap(final Fsm fsm) {
HashMap<State, HashSet<Event>> stateIncommingEvents = new HashMap<>();
for (State state: fsm.getStates()) {
HashSet<Event> events = new HashSet<>();
stateIncommingEvents.put(state, events);
}
for (Event event: fsm.getEvents()) {
State toState = (State) event.getSecond();
HashSet<Event> events = stateIncommingEvents.get(toState);
events.add(event);
}
return stateIncommingEvents;
}
}
| gpl-3.0 |
Fivium/FOXopen | src/main/java/net/foxopen/fox/filetransfer/FiletransferProgressListener.java | 625 | package net.foxopen.fox.filetransfer;
import org.apache.commons.fileupload.ProgressListener;
public class FiletransferProgressListener
implements ProgressListener
{
public FiletransferProgressListener() {
}
private int mTransmissionProgress = 0;
private long mBytesRead = 0;
public int getTransmissionProgress () {
return mTransmissionProgress;
}
public long getBytesRead () {
return mBytesRead;
}
public void update (long pBytesRead, long pContentLength, int pItems) {
mBytesRead = pBytesRead;
mTransmissionProgress = (int)(((float)pBytesRead / (float)pContentLength) * 100);
}
}
| gpl-3.0 |
aria42/prototype-sequence-modeling | src/edu/berkeley/nlp/prototype/simmodel/SmallSparseVector.java | 2933 | package edu.berkeley.nlp.prototype.simmodel;
import java.io.Serializable;
import java.util.Arrays;
public class SmallSparseVector implements Serializable {
private static final long serialVersionUID = 42L;
float[] data = new float[0];
int[] indices = new int[0];
int length = 0;
private void grow() {
int curSize = data.length;
int newSize = curSize + 10;
float[] newData = new float[newSize];
System.arraycopy(data, 0, newData, 0, curSize);
data = newData;
int[] newIndices = new int[newSize];
System.arraycopy(indices, 0, newIndices, 0, curSize);
for (int i=curSize; i < newIndices.length; ++i) {
newIndices[i] = Integer.MAX_VALUE;
newData[i] = Float.POSITIVE_INFINITY;
}
indices = newIndices;
}
public double getCount(int index) {
int res = Arrays.binarySearch(indices, index);
if (res >= 0 && res < length) {
return data[res];
}
return 0.0;
}
public void incrementCount(int index0, double x0) {
double curCount = getCount(index0);
setCount(index0, curCount + x0);
}
public int size() {
return length;
}
public void setCount(int index0, double x0) {
float x = (float) x0;
// short index = (short) index0;
int res = Arrays.binarySearch(indices, index0);
// Greater than everything
if (res >= 0 && res < length) {
data[res] = x;
return;
}
if (length+1 >= data.length) {
grow();
}
// In the middle
int insertionPoint = -(res+1);
assert insertionPoint >= 0 && insertionPoint <= length : String.format("length: %d insertion: %d",length,insertionPoint);
// Shift The Stuff After
System.arraycopy(data, insertionPoint, data, insertionPoint+1, length-insertionPoint);
System.arraycopy(indices, insertionPoint, indices, insertionPoint+1, length-insertionPoint);
indices[insertionPoint] = index0;
data[insertionPoint] = x;
length++;
}
public int getActiveDimension(int i) {
assert i < indices.length;
return indices[i];
}
public double l2Norm() {
double sum = 0.0;
for (int i=0; i < length; ++i) {
sum += data[i] * data[i];
}
return Math.sqrt(sum);
}
public void scale(double c) {
for (int i=0; i < length; ++i) {
data[i] *= c;
}
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{ ");
for (int i=0; i < length; ++i) {
builder.append(String.format("%d : %.5f",indices[i],data[i]));
builder.append(" ");
}
builder.append(" }");
return builder.toString();
}
public double dotProduct(SmallSparseVector other) {
double sum = 0.0;
for (int i=0; i < this.size(); ++i) {
int dim = getActiveDimension(i);
sum += this.getCount(dim) * other.getCount(dim);
}
return sum;
}
public static void main(String[] args) {
SmallSparseVector sv = new SmallSparseVector();
sv.setCount(0, 1.0);
sv.setCount(1, 2.0);
sv.incrementCount(1, 1.0);
sv.incrementCount(-1, 10.0);
System.out.println(sv);
}
}
| gpl-3.0 |
diegoRodriguezAguila/Lecturas.Elfec.GD | betterPickers/src/main/java/com/codetroopers/betterpickers/calendardatepicker/MonthView.java | 25965 | /*
* Copyright (C) 2013 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.codetroopers.betterpickers.calendardatepicker;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.ExploreByTouchHelper;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import com.codetroopers.betterpickers.R;
import com.codetroopers.betterpickers.Utils;
import com.codetroopers.betterpickers.calendardatepicker.MonthAdapter.CalendarDay;
import java.security.InvalidParameterException;
import java.util.Calendar;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* A calendar-like view displaying a specified month and the appropriate selectable day numbers within the specified
* month.
*/
public abstract class MonthView extends View {
private static final String TAG = "MonthView";
/**
* These params can be passed into the view to control how it appears.
* {@link #VIEW_PARAMS_WEEK} is the only required field, though the default
* values are unlikely to fit most layouts correctly.
*/
/**
* This sets the height of this week in pixels
*/
public static final String VIEW_PARAMS_HEIGHT = "height";
/**
* This specifies the position (or weeks since the epoch) of this week, calculated using {@link
* Utils#getWeeksSinceEpochFromJulianDay}
*/
public static final String VIEW_PARAMS_MONTH = "month";
/**
* This specifies the position (or weeks since the epoch) of this week, calculated using {@link
* Utils#getWeeksSinceEpochFromJulianDay}
*/
public static final String VIEW_PARAMS_YEAR = "year";
/**
* This sets one of the days in this view as selected {@link android.text.format.Time#SUNDAY} through {@link
* android.text.format.Time#SATURDAY}.
*/
public static final String VIEW_PARAMS_SELECTED_DAY = "selected_day";
/**
* Which day the week should start on. {@link android.text.format.Time#SUNDAY} through {@link
* android.text.format.Time#SATURDAY}.
*/
public static final String VIEW_PARAMS_WEEK_START = "week_start";
/**
* How many days to display at a time. Days will be displayed starting with {@link #mWeekStart}.
*/
public static final String VIEW_PARAMS_NUM_DAYS = "num_days";
/**
* Which month is currently in focus, as defined by {@link android.text.format.Time#month} [0-11].
*/
public static final String VIEW_PARAMS_FOCUS_MONTH = "focus_month";
/**
* If this month should display week numbers. false if 0, true otherwise.
*/
public static final String VIEW_PARAMS_SHOW_WK_NUM = "show_wk_num";
protected static int DEFAULT_HEIGHT = 32;
protected static int MIN_HEIGHT = 10;
protected static final int DEFAULT_SELECTED_DAY = -1;
protected static final int DEFAULT_WEEK_START = Calendar.SUNDAY;
protected static final int DEFAULT_NUM_DAYS = 7;
protected static final int DEFAULT_SHOW_WK_NUM = 0;
protected static final int DEFAULT_FOCUS_MONTH = -1;
protected static final int DEFAULT_NUM_ROWS = 6;
protected static final int MAX_NUM_ROWS = 6;
private static final int SELECTED_CIRCLE_ALPHA = 60;
protected static int DAY_SEPARATOR_WIDTH = 1;
protected static int MINI_DAY_NUMBER_TEXT_SIZE;
protected static int MONTH_LABEL_TEXT_SIZE;
protected static int MONTH_DAY_LABEL_TEXT_SIZE;
protected static int MONTH_HEADER_SIZE;
protected static int DAY_SELECTED_CIRCLE_SIZE;
// used for scaling to the device density
protected static float mScale = 0;
// affects the padding on the sides of this view
protected int mPadding = 0;
private String mDayOfWeekTypeface;
private String mMonthTitleTypeface;
protected Paint mMonthNumPaint;
protected Paint mMonthTitlePaint;
protected Paint mMonthTitleBGPaint;
protected Paint mSelectedCirclePaint;
protected Paint mMonthDayLabelPaint;
private final Formatter mFormatter;
private final StringBuilder mStringBuilder;
// The Julian day of the first day displayed by this item
protected int mFirstJulianDay = -1;
// The month of the first day in this week
protected int mFirstMonth = -1;
// The month of the last day in this week
protected int mLastMonth = -1;
protected int mMonth;
protected int mYear;
// Quick reference to the width of this view, matches parent
protected int mWidth;
// The height this view should draw at in pixels, set by height param
protected int mRowHeight = DEFAULT_HEIGHT;
// If this view contains the today
protected boolean mHasToday = false;
// Which day is selected [0-6] or -1 if no day is selected
protected int mSelectedDay = -1;
// Which day is today [0-6] or -1 if no day is today
protected int mToday = DEFAULT_SELECTED_DAY;
// Which day of the week to start on [0-6]
protected int mWeekStart = DEFAULT_WEEK_START;
// How many days to display
protected int mNumDays = DEFAULT_NUM_DAYS;
// The number of days + a spot for week number if it is displayed
protected int mNumCells = mNumDays;
// The left edge of the selected day
protected int mSelectedLeft = -1;
// The right edge of the selected day
protected int mSelectedRight = -1;
private final Calendar mCalendar;
private final Calendar mDayLabelCalendar;
private final MonthViewTouchHelper mTouchHelper;
private int mNumRows = DEFAULT_NUM_ROWS;
// Optional listener for handling day click actions
private OnDayClickListener mOnDayClickListener;
// Whether to prevent setting the accessibility delegate
private boolean mLockAccessibilityDelegate;
protected int mDayTextColor;
protected int mTodayNumberColor;
protected int mMonthTitleColor;
protected int mMonthTitleBGColor;
public MonthView(Context context) {
super(context);
Resources res = context.getResources();
mDayLabelCalendar = Calendar.getInstance();
mCalendar = Calendar.getInstance();
mDayOfWeekTypeface = res.getString(R.string.day_of_week_label_typeface);
mMonthTitleTypeface = res.getString(R.string.sans_serif);
mDayTextColor = res.getColor(R.color.date_picker_text_normal);
mTodayNumberColor = res.getColor(R.color.bpBlue);
mMonthTitleColor = res.getColor(R.color.bpWhite);
mMonthTitleBGColor = res.getColor(R.color.circle_background);
mStringBuilder = new StringBuilder(50);
mFormatter = new Formatter(mStringBuilder, Locale.getDefault());
MINI_DAY_NUMBER_TEXT_SIZE = res.getDimensionPixelSize(R.dimen.day_number_size);
MONTH_LABEL_TEXT_SIZE = res.getDimensionPixelSize(R.dimen.month_label_size);
MONTH_DAY_LABEL_TEXT_SIZE = res.getDimensionPixelSize(R.dimen.month_day_label_text_size);
MONTH_HEADER_SIZE = res.getDimensionPixelOffset(R.dimen.month_list_item_header_height);
DAY_SELECTED_CIRCLE_SIZE = res
.getDimensionPixelSize(R.dimen.day_number_select_circle_radius);
mRowHeight = (res.getDimensionPixelOffset(R.dimen.date_picker_view_animator_height)
- MONTH_HEADER_SIZE) / MAX_NUM_ROWS;
// Set up accessibility components.
mTouchHelper = new MonthViewTouchHelper(this);
ViewCompat.setAccessibilityDelegate(this, mTouchHelper);
ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
mLockAccessibilityDelegate = true;
// Sets up any standard paints that will be used
initView();
}
@Override
public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
// Workaround for a JB MR1 issue where accessibility delegates on
// top-level ListView items are overwritten.
if (!mLockAccessibilityDelegate && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
super.setAccessibilityDelegate(delegate);
}
}
public void setOnDayClickListener(OnDayClickListener listener) {
mOnDayClickListener = listener;
}
/* Removed for backwards compatibility with Gingerbread
@Override
public boolean dispatchHoverEvent(MotionEvent event) {
// First right-of-refusal goes the touch exploration helper.
if (mTouchHelper.dispatchHoverEvent(event)) {
return true;
}
return super.dispatchHoverEvent(event);
}*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
final int day = getDayFromLocation(event.getX(), event.getY());
if (day >= 0) {
onDayClick(day);
}
break;
}
return true;
}
/**
* Sets up the text and style properties for painting. Override this if you want to use a different paint.
*/
protected void initView() {
mMonthTitlePaint = new Paint();
mMonthTitlePaint.setFakeBoldText(true);
mMonthTitlePaint.setAntiAlias(true);
mMonthTitlePaint.setTextSize(MONTH_LABEL_TEXT_SIZE);
mMonthTitlePaint.setTypeface(Typeface.create(mMonthTitleTypeface, Typeface.BOLD));
mMonthTitlePaint.setColor(mDayTextColor);
mMonthTitlePaint.setTextAlign(Align.CENTER);
mMonthTitlePaint.setStyle(Style.FILL);
mMonthTitleBGPaint = new Paint();
mMonthTitleBGPaint.setFakeBoldText(true);
mMonthTitleBGPaint.setAntiAlias(true);
mMonthTitleBGPaint.setColor(mMonthTitleBGColor);
mMonthTitleBGPaint.setTextAlign(Align.CENTER);
mMonthTitleBGPaint.setStyle(Style.FILL);
mSelectedCirclePaint = new Paint();
mSelectedCirclePaint.setFakeBoldText(true);
mSelectedCirclePaint.setAntiAlias(true);
mSelectedCirclePaint.setColor(mTodayNumberColor);
mSelectedCirclePaint.setTextAlign(Align.CENTER);
mSelectedCirclePaint.setStyle(Style.FILL);
mSelectedCirclePaint.setAlpha(SELECTED_CIRCLE_ALPHA);
mMonthDayLabelPaint = new Paint();
mMonthDayLabelPaint.setAntiAlias(true);
mMonthDayLabelPaint.setTextSize(MONTH_DAY_LABEL_TEXT_SIZE);
mMonthDayLabelPaint.setColor(mDayTextColor);
mMonthDayLabelPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL));
mMonthDayLabelPaint.setStyle(Style.FILL);
mMonthDayLabelPaint.setTextAlign(Align.CENTER);
mMonthDayLabelPaint.setFakeBoldText(true);
mMonthNumPaint = new Paint();
mMonthNumPaint.setAntiAlias(true);
mMonthNumPaint.setTextSize(MINI_DAY_NUMBER_TEXT_SIZE);
mMonthNumPaint.setStyle(Style.FILL);
mMonthNumPaint.setTextAlign(Align.CENTER);
mMonthNumPaint.setFakeBoldText(false);
}
@Override
protected void onDraw(Canvas canvas) {
drawMonthTitle(canvas);
drawMonthDayLabels(canvas);
drawMonthNums(canvas);
}
private int mDayOfWeekStart = 0;
/**
* Sets all the parameters for displaying this week. The only required parameter is the week number. Other
* parameters have a default value and will only update if a new value is included, except for focus month, which
* will always default to no focus month if no value is passed in. See {@link #VIEW_PARAMS_HEIGHT} for more info on
* parameters.
*
* @param params A map of the new parameters, see {@link #VIEW_PARAMS_HEIGHT}
*/
public void setMonthParams(HashMap<String, Integer> params) {
if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {
throw new InvalidParameterException("You must specify month and year for this view");
}
setTag(params);
// We keep the current value for any params not present
if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
mRowHeight = params.get(VIEW_PARAMS_HEIGHT);
if (mRowHeight < MIN_HEIGHT) {
mRowHeight = MIN_HEIGHT;
}
}
if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) {
mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY);
}
// Allocate space for caching the day numbers and focus values
mMonth = params.get(VIEW_PARAMS_MONTH);
mYear = params.get(VIEW_PARAMS_YEAR);
// Figure out what day today is
final Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
mHasToday = false;
mToday = -1;
mCalendar.set(Calendar.MONTH, mMonth);
mCalendar.set(Calendar.YEAR, mYear);
mCalendar.set(Calendar.DAY_OF_MONTH, 1);
mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);
if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
mWeekStart = params.get(VIEW_PARAMS_WEEK_START);
} else {
mWeekStart = mCalendar.getFirstDayOfWeek();
}
mNumCells = Utils.getDaysInMonth(mMonth, mYear);
for (int i = 0; i < mNumCells; i++) {
final int day = i + 1;
if (sameDay(day, today)) {
mHasToday = true;
mToday = day;
}
}
mNumRows = calculateNumRows();
// Invalidate cached accessibility information.
mTouchHelper.invalidateRoot();
}
public void reuse() {
mNumRows = DEFAULT_NUM_ROWS;
requestLayout();
}
private int calculateNumRows() {
int offset = findDayOffset();
int dividend = (offset + mNumCells) / mNumDays;
int remainder = (offset + mNumCells) % mNumDays;
return (dividend + (remainder > 0 ? 1 : 0));
}
private boolean sameDay(int day, Time today) {
return mYear == today.year &&
mMonth == today.month &&
day == today.monthDay;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mRowHeight * mNumRows
+ MONTH_HEADER_SIZE);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mWidth = w;
// Invalidate cached accessibility information.
mTouchHelper.invalidateRoot();
}
private String getMonthAndYearString() {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR
| DateUtils.FORMAT_NO_MONTH_DAY;
mStringBuilder.setLength(0);
long millis = mCalendar.getTimeInMillis();
return DateUtils.formatDateRange(getContext(), mFormatter, millis, millis, flags,
Time.getCurrentTimezone()).toString();
}
private void drawMonthTitle(Canvas canvas) {
int x = (mWidth + 2 * mPadding) / 2;
int y = (MONTH_HEADER_SIZE - MONTH_DAY_LABEL_TEXT_SIZE) / 2 + (MONTH_LABEL_TEXT_SIZE / 3);
canvas.drawText(getMonthAndYearString(), x, y, mMonthTitlePaint);
}
private void drawMonthDayLabels(Canvas canvas) {
int y = MONTH_HEADER_SIZE - (MONTH_DAY_LABEL_TEXT_SIZE / 2);
int dayWidthHalf = (mWidth - mPadding * 2) / (mNumDays * 2);
for (int i = 0; i < mNumDays; i++) {
int calendarDay = (i + mWeekStart) % mNumDays;
int x = (2 * i + 1) * dayWidthHalf + mPadding;
mDayLabelCalendar.set(Calendar.DAY_OF_WEEK, calendarDay);
canvas.drawText(mDayLabelCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT,
Locale.getDefault()).toUpperCase(Locale.getDefault()), x, y,
mMonthDayLabelPaint);
}
}
/**
* Draws the week and month day numbers for this week. Override this method if you need different placement.
*
* @param canvas The canvas to draw on
*/
protected void drawMonthNums(Canvas canvas) {
int y = (((mRowHeight + MINI_DAY_NUMBER_TEXT_SIZE) / 2) - DAY_SEPARATOR_WIDTH)
+ MONTH_HEADER_SIZE;
int dayWidthHalf = (mWidth - mPadding * 2) / (mNumDays * 2);
int j = findDayOffset();
for (int dayNumber = 1; dayNumber <= mNumCells; dayNumber++) {
int x = (2 * j + 1) * dayWidthHalf + mPadding;
int yRelativeToDay = (mRowHeight + MINI_DAY_NUMBER_TEXT_SIZE) / 2 - DAY_SEPARATOR_WIDTH;
int startX = x - dayWidthHalf;
int stopX = x + dayWidthHalf;
int startY = y - yRelativeToDay;
int stopY = startY + mRowHeight;
drawMonthDay(canvas, mYear, mMonth, dayNumber, x, y, startX, stopX, startY, stopY);
j++;
if (j == mNumDays) {
j = 0;
y += mRowHeight;
}
}
}
/**
* This method should draw the month day. Implemented by sub-classes to allow customization.
*
* @param canvas The canvas to draw on
* @param year The year of this month day
* @param month The month of this month day
* @param day The day number of this month day
* @param x The default x position to draw the day number
* @param y The default y position to draw the day number
* @param startX The left boundary of the day number rect
* @param stopX The right boundary of the day number rect
* @param startY The top boundary of the day number rect
* @param stopY The bottom boundary of the day number rect
*/
public abstract void drawMonthDay(Canvas canvas, int year, int month, int day,
int x, int y, int startX, int stopX, int startY, int stopY);
private int findDayOffset() {
return (mDayOfWeekStart < mWeekStart ? (mDayOfWeekStart + mNumDays) : mDayOfWeekStart)
- mWeekStart;
}
/**
* Calculates the day that the given x position is in, accounting for week number. Returns the day or -1 if the
* position wasn't in a day.
*
* @param x The x position of the touch event
* @return The day number, or -1 if the position wasn't in a day
*/
public int getDayFromLocation(float x, float y) {
int dayStart = mPadding;
if (x < dayStart || x > mWidth - mPadding) {
return -1;
}
// Selection is (x - start) / (pixels/day) == (x -s) * day / pixels
int row = (int) (y - MONTH_HEADER_SIZE) / mRowHeight;
int column = (int) ((x - dayStart) * mNumDays / (mWidth - dayStart - mPadding));
int day = column - findDayOffset() + 1;
day += row * mNumDays;
if (day < 1 || day > mNumCells) {
return -1;
}
return day;
}
/**
* Called when the user clicks on a day. Handles callbacks to the {@link OnDayClickListener} if one is set.
*
* @param day The day that was clicked
*/
private void onDayClick(int day) {
if (mOnDayClickListener != null) {
mOnDayClickListener.onDayClick(this, new CalendarDay(mYear, mMonth, day));
}
// This is a no-op if accessibility is turned off.
mTouchHelper.sendEventForVirtualView(day, AccessibilityEvent.TYPE_VIEW_CLICKED);
}
/**
* @return The date that has accessibility focus, or {@code null} if no date has focus
*/
public CalendarDay getAccessibilityFocus() {
final int day = mTouchHelper.getFocusedVirtualView();
if (day >= 0) {
return new CalendarDay(mYear, mMonth, day);
}
return null;
}
/**
* Clears accessibility focus within the view. No-op if the view does not contain accessibility focus.
*/
public void clearAccessibilityFocus() {
mTouchHelper.clearFocusedVirtualView();
}
/**
* Attempts to restore accessibility focus to the specified date.
*
* @param day The date which should receive focus
* @return {@code false} if the date is not valid for this month view, or {@code true} if the date received focus
*/
public boolean restoreAccessibilityFocus(CalendarDay day) {
if ((day.year != mYear) || (day.month != mMonth) || (day.day > mNumCells)) {
return false;
}
mTouchHelper.setFocusedVirtualView(day.day);
return true;
}
/**
* Provides a virtual view hierarchy for interfacing with an accessibility service.
*/
private class MonthViewTouchHelper extends ExploreByTouchHelper {
private static final String DATE_FORMAT = "dd MMMM yyyy";
private final Rect mTempRect = new Rect();
private final Calendar mTempCalendar = Calendar.getInstance();
public MonthViewTouchHelper(View host) {
super(host);
}
public void setFocusedVirtualView(int virtualViewId) {
getAccessibilityNodeProvider(MonthView.this).performAction(
virtualViewId, AccessibilityNodeInfoCompat.ACTION_ACCESSIBILITY_FOCUS, null);
}
public void clearFocusedVirtualView() {
final int focusedVirtualView = getFocusedVirtualView();
if (focusedVirtualView != ExploreByTouchHelper.INVALID_ID) {
getAccessibilityNodeProvider(MonthView.this).performAction(
focusedVirtualView,
AccessibilityNodeInfoCompat.ACTION_CLEAR_ACCESSIBILITY_FOCUS,
null);
}
}
@Override
protected int getVirtualViewAt(float x, float y) {
final int day = getDayFromLocation(x, y);
if (day >= 0) {
return day;
}
return ExploreByTouchHelper.INVALID_ID;
}
@Override
protected void getVisibleVirtualViews(List<Integer> virtualViewIds) {
for (int day = 1; day <= mNumCells; day++) {
virtualViewIds.add(day);
}
}
@Override
protected void onPopulateEventForVirtualView(int virtualViewId, AccessibilityEvent event) {
event.setContentDescription(getItemDescription(virtualViewId));
}
@Override
protected void onPopulateNodeForVirtualView(int virtualViewId,
AccessibilityNodeInfoCompat node) {
getItemBounds(virtualViewId, mTempRect);
node.setContentDescription(getItemDescription(virtualViewId));
node.setBoundsInParent(mTempRect);
node.addAction(AccessibilityNodeInfo.ACTION_CLICK);
if (virtualViewId == mSelectedDay) {
node.setSelected(true);
}
}
@Override
protected boolean onPerformActionForVirtualView(int virtualViewId, int action,
Bundle arguments) {
switch (action) {
case AccessibilityNodeInfo.ACTION_CLICK:
onDayClick(virtualViewId);
return true;
}
return false;
}
/**
* Calculates the bounding rectangle of a given time object.
*
* @param day The day to calculate bounds for
* @param rect The rectangle in which to store the bounds
*/
private void getItemBounds(int day, Rect rect) {
final int offsetX = mPadding;
final int offsetY = MONTH_HEADER_SIZE;
final int cellHeight = mRowHeight;
final int cellWidth = ((mWidth - (2 * mPadding)) / mNumDays);
final int index = ((day - 1) + findDayOffset());
final int row = (index / mNumDays);
final int column = (index % mNumDays);
final int x = (offsetX + (column * cellWidth));
final int y = (offsetY + (row * cellHeight));
rect.set(x, y, (x + cellWidth), (y + cellHeight));
}
/**
* Generates a description for a given time object. Since this description will be spoken, the components are
* ordered by descending specificity as DAY MONTH YEAR.
*
* @param day The day to generate a description for
* @return A description of the time object
*/
private CharSequence getItemDescription(int day) {
mTempCalendar.set(mYear, mMonth, day);
final CharSequence date = DateFormat.format(DATE_FORMAT,
mTempCalendar.getTimeInMillis());
if (day == mSelectedDay) {
return getContext().getString(R.string.item_is_selected, date);
}
return date;
}
}
/**
* Handles callbacks when the user clicks on a time object.
*/
public interface OnDayClickListener {
public void onDayClick(MonthView view, CalendarDay day);
}
}
| gpl-3.0 |
Mikescher/jClipCorn | src/test/de/jClipCorn/test/TestImageUtilities.java | 4420 | package de.jClipCorn.test;
import de.jClipCorn.properties.CCProperties;
import de.jClipCorn.properties.enumerations.CoverImageSize;
import de.jClipCorn.util.datatypes.Tuple;
import de.jClipCorn.util.helper.ImageUtilities;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TestImageUtilities extends ClipCornBaseTest {
@Test
public void testResizeToBounds_1() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(182, 254, ml.ccprops());
assertEquals((int)s0.Item1, 182);
assertEquals((int)s0.Item2, 254);
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(182.0 / 254.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_2() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(1820, 2540, ml.ccprops());
assertEquals((int)s0.Item1, 1820);
assertEquals((int)s0.Item2, 2540);
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(1820.0 / 2540.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_3() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(150, 254, ml.ccprops());
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(150.0 / 254.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_4() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(182, 200, ml.ccprops());
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(182.0 / 200.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_5() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(150, 200, ml.ccprops());
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(150.0 / 200.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_6() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(1950, 2540, ml.ccprops());
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(1950.0 / 2540.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_7() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(1820, 2950, ml.ccprops());
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(1820.0 / 2950.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_8() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(1950, 2950, ml.ccprops());
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
assertEquals(1950.0 / 2950.0, s0.Item1 * 1d / s0.Item2, 0.1d);
}
@Test
public void testResizeToBounds_9() {
var ml = createEmptyDB();
ml.ccprops().PROP_DATABASE_MAX_COVER_SIZE.setValue(CoverImageSize.DEC_SIZE); // 1820 x 2540
Tuple<Integer, Integer> s0 = ImageUtilities.calcImageSizeForStorage(300, 500, ml.ccprops());
assertEquals((int)s0.Item1, 300);
assertEquals((int)s0.Item2, 500);
assertTrue(isSizeOK(s0.Item1, s0.Item2, ml.ccprops()));
}
private boolean isSizeOK(int w, int h, CCProperties ccprops) {
if (w < ImageUtilities.BASE_COVER_WIDTH && h < ImageUtilities.BASE_COVER_HEIGHT) {
return false; // Cover too small
}
if (w > ImageUtilities.getCoverWidth(ccprops) && h < ImageUtilities.getCoverHeight(ccprops)) {
return false; // Cover too big
}
return true;
}
}
| gpl-3.0 |
mathisdt/trackworktime | app/src/main/java/org/zephyrsoft/trackworktime/location/TrackingMethod.java | 1066 | /*
* This file is part of TrackWorkTime (TWT).
*
* TWT is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License 3.0 as published by
* the Free Software Foundation.
*
* TWT 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 3.0 for more details.
*
* You should have received a copy of the GNU General Public License 3.0
* along with TWT. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zephyrsoft.trackworktime.location;
import org.zephyrsoft.trackworktime.R;
/**
* Available methods of automatically tracking work time.
*/
public enum TrackingMethod {
LOCATION(R.string.keyClockedInByLocation),
WIFI(R.string.keyClockedInByWifi);
private final int preferenceKeyId;
TrackingMethod(int preferenceKeyId) {
this.preferenceKeyId = preferenceKeyId;
}
public int getPreferenceKeyId() {
return preferenceKeyId;
}
}
| gpl-3.0 |
lyy289065406/expcodes | java/99-project/ali-math/src/main/java/exp/ali/math/question3/Qa.java | 54 | package exp.ali.math.question3;
public class Qa {
}
| gpl-3.0 |
andrey-gabchak/GoJavaOnlineLabs | src/main/java/ua/goit/Core/Hello_World/SortingAnArray.java | 1423 | package ua.goit.Core.Hello_World;
/**
* Created by coura on 30.03.2016.
*/
public class SortingAnArray {
//Сортировка бульбашкой (по возрастанию)
public static void bubbleSort(int[] array) {
for (int i = array.length-1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] > array[j+1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
//Сортировка бульбашкой (по убыванию)
public static void bubbleSortReverse(int[] array) {
for (int i = array.length-1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] < array[j+1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
//По возрастанию
public static class InsertionSortUtil {
public static void insertionSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i; j > 0 && array[j-1] > array[j]; j--) {
int temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
}
| gpl-3.0 |
jakobwenzel/rallye-server | Server/src/main/java/de/rallye/exceptions/NodeNotFoundException.java | 1039 | /*
* Copyright (c) 2014 Jakob Wenzel, Ramon Wirsch.
*
* This file is part of RallyeSoft.
*
* RallyeSoft 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.
*
* RallyeSoft 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 RallyeSoft. If not, see <http://www.gnu.org/licenses/>.
*/
package de.rallye.exceptions;
import javax.ws.rs.WebApplicationException;
public class NodeNotFoundException extends WebApplicationException{
public NodeNotFoundException() {
super("Node not found", 404);
}
/**
*
*/
private static final long serialVersionUID = 770278077138594737L;
}
| gpl-3.0 |
Hadron67/jphp | src/com/hadroncfy/jphp/jzend/ins/OptionalGotoIns.java | 1156 | package com.hadroncfy.jphp.jzend.ins;
import com.hadroncfy.jphp.jzend.VM;
import com.hadroncfy.jphp.jzend.types.Zbool;
import com.hadroncfy.jphp.jzend.types.typeInterfaces.Castable;
import com.hadroncfy.jphp.jzend.types.typeInterfaces.Zval;
/**
* Created by cfy on 16-9-2.
*/
@ExplicitTypeInstruction
public class OptionalGotoIns implements Instruction {
public int line1;
public int line2;
public OptionalGotoIns(int l1,int l2){
line1 = l1;
line2 = l2;
}
public OptionalGotoIns(){
}
@Override
public void exec(VM vm) {
Zval val = Tool.fullyDeRef(vm.pop());
boolean b;
if(val instanceof Zbool){
b = ((Zbool) val).value;
}
else if(val instanceof Castable){
b = ((Castable) val).boolCast().value;
}
else{
vm.makeError(val.getTypeName() + " is not a boolean");
return;
}
if(b){
vm.jump(line1);
}
else{
vm.jump(line2);
}
}
@Override
public String toString() {
return "OPTIONAL_GOTO " + line1 + "," + line2;
}
}
| gpl-3.0 |
leMaik/chunky | chunky/src/java/se/llbit/chunky/model/TurtleEggModel.java | 7639 | package se.llbit.chunky.model;
import se.llbit.chunky.resources.Texture;
import se.llbit.math.Quad;
import se.llbit.math.Vector3;
import se.llbit.math.Vector4;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class TurtleEggModel extends QuadModel {
//region EGG
private static final Quad[][] egg_models = {
{
// cube1
new Quad(
new Vector3(5 / 16.0, 7 / 16.0, 9 / 16.0),
new Vector3(10 / 16.0, 7 / 16.0, 9 / 16.0),
new Vector3(5 / 16.0, 7 / 16.0, 4 / 16.0),
new Vector4(0, 4 / 16.0, 12 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(5 / 16.0, 0, 4 / 16.0),
new Vector3(10 / 16.0, 0, 4 / 16.0),
new Vector3(5 / 16.0, 0, 9 / 16.0),
new Vector4(0, 4 / 16.0, 12 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(10 / 16.0, 0, 9 / 16.0),
new Vector3(10 / 16.0, 0, 4 / 16.0),
new Vector3(10 / 16.0, 7 / 16.0, 9 / 16.0),
new Vector4(1 / 16.0, 5 / 16.0, 5 / 16.0, 12 / 16.0)),
new Quad(
new Vector3(5 / 16.0, 0, 4 / 16.0),
new Vector3(5 / 16.0, 0, 9 / 16.0),
new Vector3(5 / 16.0, 7 / 16.0, 4 / 16.0),
new Vector4(1 / 16.0, 5 / 16.0, 5 / 16.0, 12 / 16.0)),
new Quad(
new Vector3(10 / 16.0, 0, 4 / 16.0),
new Vector3(5 / 16.0, 0, 4 / 16.0),
new Vector3(10 / 16.0, 7 / 16.0, 4 / 16.0),
new Vector4(1 / 16.0, 5 / 16.0, 5 / 16.0, 12 / 16.0)),
new Quad(
new Vector3(5 / 16.0, 0, 9 / 16.0),
new Vector3(10 / 16.0, 0, 9 / 16.0),
new Vector3(5 / 16.0, 7 / 16.0, 9 / 16.0),
new Vector4(1 / 16.0, 5 / 16.0, 5 / 16.0, 12 / 16.0)),
},
{
// cube2
new Quad(
new Vector3(1 / 16.0, 5 / 16.0, 11 / 16.0),
new Vector3(5 / 16.0, 5 / 16.0, 11 / 16.0),
new Vector3(1 / 16.0, 5 / 16.0, 7 / 16.0),
new Vector4(6 / 16.0, 10 / 16.0, 5 / 16.0, 9 / 16.0)),
new Quad(
new Vector3(1 / 16.0, 0, 7 / 16.0),
new Vector3(5 / 16.0, 0, 7 / 16.0),
new Vector3(1 / 16.0, 0, 11 / 16.0),
new Vector4(6 / 16.0, 10 / 16.0, 5 / 16.0, 9 / 16.0)),
new Quad(
new Vector3(5 / 16.0, 0, 11 / 16.0),
new Vector3(5 / 16.0, 0, 7 / 16.0),
new Vector3(5 / 16.0, 5 / 16.0, 11 / 16.0),
new Vector4(10 / 16.0, 14 / 16.0, 1 / 16.0, 6 / 16.0)),
new Quad(
new Vector3(1 / 16.0, 0, 7 / 16.0),
new Vector3(1 / 16.0, 0, 11 / 16.0),
new Vector3(1 / 16.0, 5 / 16.0, 7 / 16.0),
new Vector4(10 / 16.0, 14 / 16.0, 1 / 16.0, 6 / 16.0)),
new Quad(
new Vector3(5 / 16.0, 0, 7 / 16.0),
new Vector3(1 / 16.0, 0, 7 / 16.0),
new Vector3(5 / 16.0, 5 / 16.0, 7 / 16.0),
new Vector4(10 / 16.0, 14 / 16.0, 1 / 16.0, 6 / 16.0)),
new Quad(
new Vector3(1 / 16.0, 0, 11 / 16.0),
new Vector3(5 / 16.0, 0, 11 / 16.0),
new Vector3(1 / 16.0, 5 / 16.0, 11 / 16.0),
new Vector4(10 / 16.0, 14 / 16.0, 1 / 16.0, 6 / 16.0)),
},
{
// cube3
new Quad(
new Vector3(11 / 16.0, 4 / 16.0, 10 / 16.0),
new Vector3(14 / 16.0, 4 / 16.0, 10 / 16.0),
new Vector3(11 / 16.0, 4 / 16.0, 7 / 16.0),
new Vector4(5 / 16.0, 8 / 16.0, 13 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(11 / 16.0, 0, 7 / 16.0),
new Vector3(14 / 16.0, 0, 7 / 16.0),
new Vector3(11 / 16.0, 0, 10 / 16.0),
new Vector4(5 / 16.0, 8 / 16.0, 13 / 16.0, 16 / 16.0)),
new Quad(
new Vector3(14 / 16.0, 0, 10 / 16.0),
new Vector3(14 / 16.0, 0, 7 / 16.0),
new Vector3(14 / 16.0, 4 / 16.0, 10 / 16.0),
new Vector4(8 / 16.0, 11 / 16.0, 9 / 16.0, 13 / 16.0)),
new Quad(
new Vector3(11 / 16.0, 0, 7 / 16.0),
new Vector3(11 / 16.0, 0, 10 / 16.0),
new Vector3(11 / 16.0, 4 / 16.0, 7 / 16.0),
new Vector4(8 / 16.0, 11 / 16.0, 9 / 16.0, 13 / 16.0)),
new Quad(
new Vector3(14 / 16.0, 0, 7 / 16.0),
new Vector3(11 / 16.0, 0, 7 / 16.0),
new Vector3(14 / 16.0, 4 / 16.0, 7 / 16.0),
new Vector4(8 / 16.0, 11 / 16.0, 9 / 16.0, 13 / 16.0)),
new Quad(
new Vector3(11 / 16.0, 0, 10 / 16.0),
new Vector3(14 / 16.0, 0, 10 / 16.0),
new Vector3(11 / 16.0, 4 / 16.0, 10 / 16.0),
new Vector4(8 / 16.0, 11 / 16.0, 9 / 16.0, 13 / 16.0)),
},
{
// cube4
new Quad(
new Vector3(7 / 16.0, 3 / 16.0, 13 / 16.0),
new Vector3(10 / 16.0, 3 / 16.0, 13 / 16.0),
new Vector3(7 / 16.0, 3 / 16.0, 10 / 16.0),
new Vector4(0, 4 / 16.0, 1 / 16.0, 5 / 16.0)),
new Quad(
new Vector3(7 / 16.0, 0, 10 / 16.0),
new Vector3(10 / 16.0, 0, 10 / 16.0),
new Vector3(7 / 16.0, 0, 13 / 16.0),
new Vector4(0, 4 / 16.0, 1 / 16.0, 5 / 16.0)),
new Quad(
new Vector3(10 / 16.0, 0, 13 / 16.0),
new Vector3(10 / 16.0, 0, 10 / 16.0),
new Vector3(10 / 16.0, 3 / 16.0, 13 / 16.0),
new Vector4(4 / 16.0, 8 / 16.0, 1 / 16.0, 5 / 16.0)),
new Quad(
new Vector3(7 / 16.0, 0, 10 / 16.0),
new Vector3(7 / 16.0, 0, 13 / 16.0),
new Vector3(7 / 16.0, 3 / 16.0, 10 / 16.0),
new Vector4(4 / 16.0, 8 / 16.0, 1 / 16.0, 5 / 16.0)),
new Quad(
new Vector3(10 / 16.0, 0, 10 / 16.0),
new Vector3(7 / 16.0, 0, 10 / 16.0),
new Vector3(10 / 16.0, 3 / 16.0, 10 / 16.0),
new Vector4(4 / 16.0, 8 / 16.0, 1 / 16.0, 5 / 16.0)),
new Quad(
new Vector3(7 / 16.0, 0, 13 / 16.0),
new Vector3(10 / 16.0, 0, 13 / 16.0),
new Vector3(7 / 16.0, 3 / 16.0, 13 / 16.0),
new Vector4(4 / 16.0, 8 / 16.0, 1 / 16.0, 5 / 16.0)),
},
};
//endregion
private static final Texture[] eggTextures = {
Texture.turtleEgg,
Texture.turtleEggSlightlyCracked,
Texture.turtleEggVeryCracked
};
static final Quad[][][] rot;
static {
rot = new Quad[3][][];
rot[0] = egg_models;
rot[1] = new Quad[4][];
for (int i = 0; i < 4; ++i) {
rot[1][i] = Model.rotateNegY(egg_models[i]);
}
rot[2] = new Quad[4][];
for (int i = 0; i < 4; ++i) {
rot[2][i] = Model.rotateY(egg_models[i]);
}
}
private final Quad[] quads;
private final Texture[] textures;
public TurtleEggModel(int eggs, int hatch) {
eggs = Math.max(1, Math.min(egg_models.length, eggs));
hatch = Math.max(0, Math.min(rot.length, hatch));
ArrayList<Quad> quads = new ArrayList<>();
for (int i = 0; i < eggs; i++)
Collections.addAll(quads, rot[hatch][i]);
this.quads = quads.toArray(new Quad[0]);
this.textures = new Texture[this.quads.length];
Arrays.fill(this.textures, eggTextures[hatch]);
}
@Override
public Quad[] getQuads() {
return quads;
}
@Override
public Texture[] getTextures() {
return textures;
}
}
| gpl-3.0 |
gralog/gralog | gralog-computation-tree-logic/src/main/java/gralog/computationtreelogic/parser/ComputationTreeLogicSyntaxChecker.java | 541 | /* This file is part of Gralog, Copyright (c) 2016-2018 LaS group, TU Berlin.
* License: https://www.gnu.org/licenses/gpl.html GPL version 3 or later. */
package gralog.computationtreelogic.parser;
import gralog.parser.SyntaxChecker;
/**
*
*/
public class ComputationTreeLogicSyntaxChecker extends SyntaxChecker {
@Override
public SyntaxChecker.Result check(String formula) {
return checkWith(formula, ComputationTreeLogicParser::parseString);
}
public static String explanation() {
return "";
}
}
| gpl-3.0 |
samgau-repos/course_v2 | service/src/main/java/com/samgau/start/impl/DictionariesHolder.java | 1411 | package com.samgau.start.impl;
import com.samgau.start.model.Department;
import com.samgau.start.repository.api.DepartmentRepository;
import com.samgau.start.repository.api.DepartmentRepositoryLocal;
import com.samgau.start.to.DepartmentDTO;
import com.samgau.start.util.TransferUtil;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by Tolegen Izbassar on 12.05.2017.
*/
@Singleton
@Startup
public class DictionariesHolder {
@EJB(beanInterface = DepartmentRepositoryLocal.class)
private DepartmentRepository departmentRepository;
private List<DepartmentDTO> departmentDTOList;
private List<Department> departments;
@PostConstruct
public void init() {
departments = departmentRepository.findAll();
departmentDTOList = departments
.stream().map(TransferUtil::getDepartmentDTO)
.collect(Collectors.toList());
}
@Lock(LockType.READ)
public List<DepartmentDTO> getDepartmentDTOList() {
return departmentDTOList;
}
public Department getDepartmentById(Long departmentId) {
return departments.stream()
.filter(x -> x.getId().equals(departmentId))
.findFirst().get();
}
}
| gpl-3.0 |
mupen64plus-ae/mupen64plus-ae | app/src/main/java/paulscode/android/mupen64plusae/compat/AppCompatPreferenceFragment.java | 8306 | package paulscode.android.mupen64plusae.compat;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnChildAttachStateChangeListener;
import org.mupen64plusae.v3.alpha.R;
public class AppCompatPreferenceFragment extends PreferenceFragmentCompat
{
public interface OnDisplayDialogListener
{
/**
* Called when a preference dialog is being displayed. This must return
* the appropriate DialogFragment for the preference.
*
* @param preference
* The preference dialog
* @return The dialog fragment for the preference
*/
DialogFragment getPreferenceDialogFragment(Preference preference);
}
public interface OnFragmentCreationListener
{
/**
* Called when a preference dialog is being displayed. This must return
* the appropriate DialogFragment for the preference.
*
* @param currentFragment Current fragment
*/
void onFragmentCreation(AppCompatPreferenceFragment currentFragment);
/**
* Callback when the fragment views are created
* @param view Fragment main view
*/
void onViewCreation(View view);
}
private static final String STATE_SHATED_PREFS_NAME = "STATE_SHATED_PREFS_NAME";
private static final String STATE_RESOURCE_ID = "STATE_RESOURCE_ID";
private boolean mHasFocusBeenSet = false;
public static AppCompatPreferenceFragment newInstance(String sharedPrefsName, int resourceId, String rootKey)
{
AppCompatPreferenceFragment frag = new AppCompatPreferenceFragment();
Bundle args = new Bundle();
args.putString(STATE_SHATED_PREFS_NAME, sharedPrefsName);
args.putInt(STATE_RESOURCE_ID, resourceId);
args.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, rootKey);
frag.setArguments(args);
return frag;
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
{
Bundle arguments = getArguments();
if (arguments == null) {
return;
}
final String sharedPrefsName = arguments.getString(STATE_SHATED_PREFS_NAME);
final int resourceId = arguments.getInt(STATE_RESOURCE_ID);
// Load the preferences from an XML resource
if (sharedPrefsName != null)
{
getPreferenceManager().setSharedPreferencesName(sharedPrefsName);
}
if (rootKey == null)
{
addPreferencesFromResource(resourceId);
}
else
{
setPreferencesFromResource(resourceId, rootKey);
}
}
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (getActivity() instanceof OnFragmentCreationListener)
{
((OnFragmentCreationListener) getActivity()).onFragmentCreation(this);
}
mHasFocusBeenSet = false;
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onDisplayPreferenceDialog(@NonNull Preference preference)
{
DialogFragment fragment = null;
if (getActivity() instanceof OnDisplayDialogListener)
{
fragment = ((OnDisplayDialogListener) getActivity()).getPreferenceDialogFragment(preference);
if (fragment != null)
{
// TODO: Correct this deprecation once setTargetFragment is no longer required by
// PreferenceDialogFragmentCompat in Android preference library
fragment.setTargetFragment(this, 0);
try {
FragmentManager fragmentManager = getParentFragmentManager();
fragment.show(fragmentManager, "androidx.preference.PreferenceFragment.DIALOG");
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}
if (fragment == null)
{
super.onDisplayPreferenceDialog(preference);
}
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// Set the default white background in the view so as to avoid
// transparency
Context context = getContext();
if (context != null) {
view.setBackgroundColor(ContextCompat.getColor(context, R.color.mupen_black));
}
if (getActivity() instanceof OnFragmentCreationListener)
{
((OnFragmentCreationListener) getActivity()).onViewCreation(getListView());
}
// Detect when a view is added to the preference fragment and request focus if it's the first view
final RecyclerView recyclerView = getListView();
final RecyclerView.Adapter<?> adapter = recyclerView.getAdapter();
recyclerView.addOnChildAttachStateChangeListener(new OnChildAttachStateChangeListener()
{
@Override
public void onChildViewAttachedToWindow(@NonNull View childView)
{
final LinearLayoutManager layoutManager = (LinearLayoutManager)recyclerView.getLayoutManager();
//Prevent scrolling past the top
childView.setOnKeyListener((v, keyCode, event) -> {
View focusedChild;
if (layoutManager != null && adapter != null) {
focusedChild = layoutManager.getFocusedChild();
int selectedPos;
if (focusedChild != null) {
selectedPos = recyclerView.getChildAdapterPosition(focusedChild);
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
return !(selectedPos < adapter.getItemCount() - 1);
case KeyEvent.KEYCODE_DPAD_UP:
return selectedPos == 0;
case KeyEvent.KEYCODE_DPAD_RIGHT:
return true;
}
return false;
}
return false;
}
}
return false;
});
//Make sure all views are focusable
childView.setFocusable(true);
if(adapter != null && layoutManager != null && adapter.getItemCount() > 0)
{
int firstItem = layoutManager.findFirstCompletelyVisibleItemPosition();
//Get focus on the first visible item the first time it's displayed
if (firstItem != -1) {
RecyclerView.ViewHolder holder = recyclerView.findViewHolderForItemId(adapter.getItemId(firstItem));
if(holder != null)
{
if (!mHasFocusBeenSet)
{
mHasFocusBeenSet = true;
holder.itemView.requestFocus();
}
}
}
}
}
@Override
public void onChildViewDetachedFromWindow(@NonNull View arg0)
{
// Nothing to do here
}
});
}
} | gpl-3.0 |
aakash-sahai/XSV | src/main/java/com/ndroit/xsv/model/Line.java | 1116 | /**
*
*/
package com.ndroit.xsv.model;
import nu.xom.Element;
import nu.xom.Elements;
/**
* @author Aakash Sahai
*
*/
public class Line extends Geometry {
protected int x1, x2, y1, y2;
/**
*
*/
public Line() {
super();
this.x1 = this.x2 = this.y1 = this.y2 = 0;
}
/**
*
*/
public Line(int x1, int y1, int x2, int y2) {
super();
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
/* (non-Javadoc)
* @see com.ndroit.xsv.model.Geometry#draw(int, int)
*/
@Override
public void draw(int atX, int atY) {
this.draw(atX, atY, 1.0);
}
/* (non-Javadoc)
* @see com.ndroit.xsv.model.Geometry#draw(int, int, float)
*/
@Override
public void draw(int atX, int atY, double scale) {
// TODO Auto-generated method stub
}
public static Line parse(Element el) throws Exception {
Line line = new Line();
line.x1 = Integer.parseInt(el.getAttributeValue("x1"));
line.y1 = Integer.parseInt(el.getAttributeValue("y1"));
line.x2 = Integer.parseInt(el.getAttributeValue("x2"));
line.y2 = Integer.parseInt(el.getAttributeValue("y2"));
return line;
}
}
| gpl-3.0 |
elationfoundation/Reporta-Android | facebook/src/com/facebook/login/StartActivityDelegate.java | 1345 | /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
* <p/>
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
* <p/>
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright notice shall be
* included in all copies or substantial portions of the software.
* <p/>
* 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 com.facebook.login;
import android.app.Activity;
import android.content.Intent;
interface StartActivityDelegate {
void startActivityForResult(Intent intent, int requestCode);
Activity getActivityContext();
}
| gpl-3.0 |
isc-konstanz/OpenMUC | projects/driver/dlms/src/main/java/org/openmuc/framework/driver/dlms/settings/ChannelAddress.java | 4094 | /*
* Copyright 2011-2021 Fraunhofer ISE
*
* This file is part of OpenMUC.
* For more information visit http://www.openmuc.org
*
* OpenMUC 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.
*
* OpenMUC 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 OpenMUC. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openmuc.framework.driver.dlms.settings;
import static org.openmuc.framework.config.option.annotation.OptionType.ADDRESS;
import org.openmuc.framework.config.ArgumentSyntaxException;
import org.openmuc.framework.config.Configurable;
import org.openmuc.framework.config.option.annotation.Option;
import org.openmuc.framework.config.option.annotation.Syntax;
import org.openmuc.jdlms.AttributeAddress;
import org.openmuc.jdlms.ObisCode;
import org.openmuc.jdlms.datatypes.DataObject.Type;
@Syntax(separator = ";", assignment = "=", keyValuePairs = ADDRESS)
public class ChannelAddress extends Configurable {
private static final String LOGICAL_NAME_FORMAT = "<Interface_Class_ID>/<Instance_ID>/<Object_Attribute_ID>";
@Option(id = "a",
type = ADDRESS,
name = "Address",
description = "The Address in logical name format "+LOGICAL_NAME_FORMAT
)
private String address;
@Option(id = "t",
type = ADDRESS,
name = "Data Object Type",
valueSelection = "NULL_DATA:Null," +
"ARRAY:Array," +
"STRUCTURE:Structure," +
"BOOLEAN:Bool," +
"BIT_STRING:Bit String," +
"DOUBLE_LONG:Integer 32," +
"DOUBLE_LONG_UNSIGNED:Unsigned integer 32," +
"OCTET_STRING:Octet String," +
"UTF8_STRING:UTF-8 String," +
"VISIBLE_STRING:Visible String," +
"BCD:BCD," +
"INTEGER:Integer 8," +
"LONG_INTEGER:Integer 16," +
"UNSIGNED:Unsigned integer 8," +
"LONG_UNSIGNED:Unsigned integer 16," +
"COMPACT_ARRAY:Compact array," +
"LONG64:Integer 64," +
"LONG64_UNSIGNED:Unsigned integer 64," +
"ENUMERATE:Enum," +
"FLOAT32:Float 32," +
"FLOAT64:Float 64," +
"DATE_TIME:Date Time," +
"DATE:Date," +
"TIME:Time," +
"DONT_CARE:None"
)
private Type type;
private AttributeAddress attributeAddress;
public ChannelAddress(String address) throws ArgumentSyntaxException {
configure(ADDRESS, address);
String[] arguments = address.split("/");
if (arguments.length != 3) {
String msg = String.format("Wrong number of DLMS/COSEM address arguments. %s", LOGICAL_NAME_FORMAT);
throw new ArgumentSyntaxException(msg);
}
int classId = Integer.parseInt(arguments[0]);
ObisCode instanceId = new ObisCode(arguments[1]);
int attributeId = Integer.parseInt(arguments[2]);
attributeAddress = new AttributeAddress(classId, instanceId, attributeId);
}
public String getAddress() {
return address;
}
public Type getType() {
return type;
}
public AttributeAddress getAttributeAddress() {
return attributeAddress;
}
}
| gpl-3.0 |
cconard96/NovaCore | NovaCore/src/gui/controls/Label.java | 1477 | package gui.controls;
import render.FontRenderer;
import render.Renderer;
import util.Color;
public class Label extends Control {
public Label(float x, float y, float width, float height) {
this(x, y, width, height, "");
}
public Label(float x, float y, float width, float height, String text) {
this(x, y, width, height, text, 30, Color.BLACK, Color.GRAY, Color.BLACK);
}
public Label(float x, float y, float width, float height, String text, float textSize, Color textColor,
Color fillColor, Color borderColor) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.text = text;
this.textColor = textColor;
this.textSize = textSize;
this.fillColor = fillColor;
this.borderColor = borderColor;
}
@Override
public void update() {
}
@Override
public void drawLegacy() {
if (text != null) {
// GL11.glEnable(GL11.GL_SCISSOR_TEST);
// GL11.glScissor(x, -y + height, width, height);
Renderer.drawRectangle(x, y, width, height, borderColor);
Renderer.drawRectangle(x + 5, y + 5, width - 10, height - 10, fillColor);
int tw = (int) (text.length() * (textSize / 2));
int th = (int) textSize;
FontRenderer.instance.drawString((float) (x + ((0.5 * width) - (0.5 * tw))),
(float) (y + ((0.5 * height) - (0.5 * th))), text, textColor, textSize);
// GL11.glDisable(GL11.GL_SCISSOR_TEST);
}
}
@Override
public void onResize() {
}
}
| gpl-3.0 |
ReplayMod/ReplayMod | src/main/java/com/replaymod/render/rendering/Pipeline.java | 5453 | package com.replaymod.render.rendering;
import com.replaymod.core.mixin.MinecraftAccessor;
import com.replaymod.core.versions.MCVer;
import com.replaymod.render.capturer.WorldRenderer;
import com.replaymod.render.frame.BitmapFrame;
import com.replaymod.render.processor.GlToAbsoluteDepthProcessor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.crash.CrashException;
import net.minecraft.util.crash.CrashReport;
import org.lwjgl.glfw.GLFW;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static com.replaymod.core.versions.MCVer.getMinecraft;
public class Pipeline<R extends Frame, P extends Frame> implements Runnable {
private final WorldRenderer worldRenderer;
private final FrameCapturer<R> capturer;
private final FrameProcessor<R, P> processor;
private final GlToAbsoluteDepthProcessor depthProcessor;
private int consumerNextFrame;
private final Object consumerLock = new Object();
private final FrameConsumer<P> consumer;
private volatile boolean abort;
public Pipeline(WorldRenderer worldRenderer, FrameCapturer<R> capturer, FrameProcessor<R, P> processor, FrameConsumer<P> consumer) {
this.worldRenderer = worldRenderer;
this.capturer = capturer;
this.processor = processor;
this.consumer = consumer;
float near = 0.05f;
float far = getMinecraft().options.viewDistance * 16 * 4;
this.depthProcessor = new GlToAbsoluteDepthProcessor(near, far);
}
@Override
public synchronized void run() {
consumerNextFrame = 0;
int processors = Runtime.getRuntime().availableProcessors();
int processThreads = Math.max(1, processors - 2); // One processor for the main thread and one for ffmpeg, sorry OS :(
ExecutorService processService = new ThreadPoolExecutor(processThreads, processThreads,
0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(2) {
@Override
public boolean offer(Runnable runnable) {
try {
put(runnable);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
return true;
}
}, new ThreadPoolExecutor.DiscardPolicy());
MinecraftClient mc = MCVer.getMinecraft();
while (!capturer.isDone() && !abort) {
if (GLFW.glfwWindowShouldClose(mc.getWindow().getHandle()) || ((MinecraftAccessor) mc).getCrashReporter() != null) {
processService.shutdown();
return;
}
Map<Channel, R> rawFrame = capturer.process();
if (rawFrame != null) {
processService.submit(new ProcessTask(rawFrame));
}
}
processService.shutdown();
try {
processService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
try {
worldRenderer.close();
capturer.close();
processor.close();
consumer.close();
} catch (Throwable t) {
CrashReport crashReport = CrashReport.create(t, "Cleaning up rendering pipeline");
throw new CrashException(crashReport);
}
}
public void cancel() {
abort = true;
}
private class ProcessTask implements Runnable {
private final Map<Channel, R> rawChannels;
public ProcessTask(Map<Channel, R> rawChannels) {
this.rawChannels = rawChannels;
}
@Override
public void run() {
try {
Integer frameId = null;
Map<Channel, P> processedChannels = new HashMap<>();
for (Map.Entry<Channel, R> entry : rawChannels.entrySet()) {
P processedFrame = processor.process(entry.getValue());
if (entry.getKey() == Channel.DEPTH && processedFrame instanceof BitmapFrame) {
depthProcessor.process((BitmapFrame) processedFrame);
}
processedChannels.put(entry.getKey(), processedFrame);
frameId = processedFrame.getFrameId();
}
if (frameId == null) {
return;
}
synchronized (consumerLock) {
while (consumerNextFrame != frameId) {
try {
consumerLock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
consumer.consume(processedChannels);
consumerNextFrame++;
consumerLock.notifyAll();
}
} catch (Throwable t) {
CrashReport crashReport = CrashReport.create(t, "Processing frame");
MCVer.getMinecraft().setCrashReport(crashReport);
}
}
}
}
| gpl-3.0 |
bkopanja/opendatahakaton | ej_nabavke_android/app/src/test/java/com/hakaton/tim/ejnabavke/ExampleUnitTest.java | 318 | package com.hakaton.tim.ejnabavke;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | gpl-3.0 |
DmitryRendov/AuthMeReloaded | src/main/java/fr/xephi/authme/AuthMe.java | 14862 | package fr.xephi.authme;
import ch.jalu.injector.Injector;
import ch.jalu.injector.InjectorBuilder;
import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.api.API;
import fr.xephi.authme.api.NewAPI;
import fr.xephi.authme.command.CommandHandler;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.initialization.DataSourceProvider;
import fr.xephi.authme.initialization.OnShutdownPlayerSaver;
import fr.xephi.authme.initialization.OnStartupTasks;
import fr.xephi.authme.initialization.SettingsProvider;
import fr.xephi.authme.initialization.TaskCloser;
import fr.xephi.authme.listener.BlockListener;
import fr.xephi.authme.listener.EntityListener;
import fr.xephi.authme.listener.PlayerListener;
import fr.xephi.authme.listener.PlayerListener111;
import fr.xephi.authme.listener.PlayerListener16;
import fr.xephi.authme.listener.PlayerListener18;
import fr.xephi.authme.listener.PlayerListener19;
import fr.xephi.authme.listener.ServerListener;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PermissionsSystemType;
import fr.xephi.authme.security.crypts.SHA256;
import fr.xephi.authme.service.BackupService;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.GeoIpService;
import fr.xephi.authme.service.MigrationService;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.task.CleanupTask;
import fr.xephi.authme.task.purge.PurgeService;
import fr.xephi.authme.util.PlayerUtils;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitScheduler;
import java.io.File;
import static fr.xephi.authme.service.BukkitService.TICKS_PER_MINUTE;
import static fr.xephi.authme.util.Utils.isClassLoaded;
/**
* The AuthMe main class.
*/
public class AuthMe extends JavaPlugin {
// Constants
private static final String PLUGIN_NAME = "AuthMeReloaded";
private static final String LOG_FILENAME = "authme.log";
private static final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE;
// Default version and build number values
private static String pluginVersion = "N/D";
private static String pluginBuildNumber = "Unknown";
// Private instances
private CommandHandler commandHandler;
private PermissionsManager permsMan;
private Settings settings;
private DataSource database;
private BukkitService bukkitService;
private Injector injector;
private GeoIpService geoIpService;
private PlayerCache playerCache;
/**
* Constructor.
*/
public AuthMe() {
}
/*
* Constructor for unit testing.
*/
@VisibleForTesting
@SuppressWarnings("deprecation") // the super constructor is deprecated to mark it for unit testing only
protected AuthMe(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
}
/**
* Get the plugin's name.
*
* @return The plugin's name.
*/
public static String getPluginName() {
return PLUGIN_NAME;
}
/**
* Get the plugin's version.
*
* @return The plugin's version.
*/
public static String getPluginVersion() {
return pluginVersion;
}
/**
* Get the plugin's build number.
*
* @return The plugin's build number.
*/
public static String getPluginBuildNumber() {
return pluginBuildNumber;
}
/**
* Method used to obtain the plugin's api instance
*
* @return The plugin's api instance
*/
public static NewAPI getApi() {
return NewAPI.getInstance();
}
/**
* Method called when the server enables the plugin.
*/
@Override
public void onEnable() {
// Load the plugin version data from the plugin description file
loadPluginInfo(getDescription().getVersion());
// Initialize the plugin
try {
initialize();
} catch (Exception e) {
ConsoleLogger.logException("Aborting initialization of AuthMe:", e);
stopOrUnload();
return;
}
// Show settings warnings
showSettingsWarnings();
// If server is using PermissionsBukkit, print a warning that some features may not be supported
if (PermissionsSystemType.PERMISSIONS_BUKKIT.equals(permsMan.getPermissionSystem())) {
ConsoleLogger.warning("Warning! This server uses PermissionsBukkit for permissions. Some permissions features may not be supported!");
}
// Do a backup on start
new BackupService(this, settings).doBackup(BackupService.BackupCause.START);
// Set up Metrics
OnStartupTasks.sendMetrics(this, settings);
// Sponsor messages
ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt.");
ConsoleLogger.info("Do you want a good game server? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!");
// Successful message
ConsoleLogger.info("AuthMe " + getPluginVersion() + " build n." + getPluginBuildNumber() + " correctly enabled!");
// Purge on start if enabled
PurgeService purgeService = injector.getSingleton(PurgeService.class);
purgeService.runAutoPurge();
// Schedule clean up task
CleanupTask cleanupTask = injector.getSingleton(CleanupTask.class);
cleanupTask.runTaskTimerAsynchronously(this, CLEANUP_INTERVAL, CLEANUP_INTERVAL);
}
/**
* Load the version and build number of the plugin from the description file.
*
* @param versionRaw the version as given by the plugin description file
*/
private static void loadPluginInfo(String versionRaw) {
int index = versionRaw.lastIndexOf("-");
if (index != -1) {
pluginVersion = versionRaw.substring(0, index);
pluginBuildNumber = versionRaw.substring(index + 1);
if (pluginBuildNumber.startsWith("b")) {
pluginBuildNumber = pluginBuildNumber.substring(1);
}
}
}
/**
* Initialize the plugin and all the services.
*/
private void initialize() {
// Set the Logger instance and log file path
ConsoleLogger.setLogger(getLogger());
ConsoleLogger.setLogFile(new File(getDataFolder(), LOG_FILENAME));
// Create plugin folder
getDataFolder().mkdir();
// Create injector, provide elements from the Bukkit environment and register providers
injector = new InjectorBuilder().addDefaultHandlers("fr.xephi.authme").create();
injector.register(AuthMe.class, this);
injector.register(Server.class, getServer());
injector.register(PluginManager.class, getServer().getPluginManager());
injector.register(BukkitScheduler.class, getServer().getScheduler());
injector.provide(DataFolder.class, getDataFolder());
injector.registerProvider(Settings.class, SettingsProvider.class);
injector.registerProvider(DataSource.class, DataSourceProvider.class);
// Get settings and set up logger
settings = injector.getSingleton(Settings.class);
ConsoleLogger.setLoggingOptions(settings);
OnStartupTasks.setupConsoleFilter(settings, getLogger());
// Set all service fields on the AuthMe class
instantiateServices(injector);
// Convert deprecated PLAINTEXT hash entries
MigrationService.changePlainTextToSha256(settings, database, new SHA256());
// TODO: does this still make sense? -sgdc3
// If the server is empty (fresh start) just set all the players as unlogged
if (bukkitService.getOnlinePlayers().isEmpty()) {
database.purgeLogged();
}
// Register event listeners
registerEventListeners(injector);
// Start Email recall task if needed
OnStartupTasks onStartupTasks = injector.newInstance(OnStartupTasks.class);
onStartupTasks.scheduleRecallEmailTask();
}
/**
* Instantiates all services.
*
* @param injector the injector
*/
protected void instantiateServices(Injector injector) {
// PlayerCache is still injected statically sometimes
playerCache = PlayerCache.getInstance();
injector.register(PlayerCache.class, playerCache);
database = injector.getSingleton(DataSource.class);
permsMan = injector.getSingleton(PermissionsManager.class);
bukkitService = injector.getSingleton(BukkitService.class);
commandHandler = injector.getSingleton(CommandHandler.class);
geoIpService = injector.getSingleton(GeoIpService.class);
// Trigger construction of API classes; they will keep track of the singleton
injector.getSingleton(NewAPI.class);
injector.getSingleton(API.class);
}
/**
* Show the settings warnings, for various risky settings.
*/
private void showSettingsWarnings() {
// Force single session disabled
if (!settings.getProperty(RestrictionSettings.FORCE_SINGLE_SESSION)) {
ConsoleLogger.warning("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!");
}
// Session timeout disabled
if (settings.getProperty(PluginSettings.SESSIONS_TIMEOUT) == 0
&& settings.getProperty(PluginSettings.SESSIONS_ENABLED)) {
ConsoleLogger.warning("WARNING!!! You set session timeout to 0, this may cause security issues!");
}
}
/**
* Registers all event listeners.
*
* @param injector the injector
*/
protected void registerEventListeners(Injector injector) {
// Get the plugin manager instance
PluginManager pluginManager = getServer().getPluginManager();
// Register event listeners
pluginManager.registerEvents(injector.getSingleton(PlayerListener.class), this);
pluginManager.registerEvents(injector.getSingleton(BlockListener.class), this);
pluginManager.registerEvents(injector.getSingleton(EntityListener.class), this);
pluginManager.registerEvents(injector.getSingleton(ServerListener.class), this);
// Try to register 1.6 player listeners
if (isClassLoaded("org.bukkit.event.player.PlayerEditBookEvent")) {
pluginManager.registerEvents(injector.getSingleton(PlayerListener16.class), this);
}
// Try to register 1.8 player listeners
if (isClassLoaded("org.bukkit.event.player.PlayerInteractAtEntityEvent")) {
pluginManager.registerEvents(injector.getSingleton(PlayerListener18.class), this);
}
// Try to register 1.9 player listeners
if (isClassLoaded("org.bukkit.event.player.PlayerSwapHandItemsEvent")) {
pluginManager.registerEvents(injector.getSingleton(PlayerListener19.class), this);
}
// Register listener for 1.11 events if available
if (isClassLoaded("org.bukkit.event.entity.EntityAirChangeEvent")) {
pluginManager.registerEvents(injector.getSingleton(PlayerListener111.class), this);
}
}
/**
* Stops the server or disables the plugin, as defined in the configuration.
*/
public void stopOrUnload() {
if (settings == null || settings.getProperty(SecuritySettings.STOP_SERVER_ON_PROBLEM)) {
ConsoleLogger.warning("THE SERVER IS GOING TO SHUT DOWN AS DEFINED IN THE CONFIGURATION!");
setEnabled(false);
getServer().shutdown();
} else {
setEnabled(false);
}
}
@Override
public void onDisable() {
// onDisable is also called when we prematurely abort, so any field may be null
OnShutdownPlayerSaver onShutdownPlayerSaver = injector == null
? null
: injector.createIfHasDependencies(OnShutdownPlayerSaver.class);
if (onShutdownPlayerSaver != null) {
onShutdownPlayerSaver.saveAllPlayers();
}
// Do backup on stop if enabled
if (settings != null) {
new BackupService(this, settings).doBackup(BackupService.BackupCause.STOP);
}
// Wait for tasks and close data source
new TaskCloser(this, database).run();
// Disabled correctly
ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!");
ConsoleLogger.close();
}
public String replaceAllInfo(String message, Player player) {
String playersOnline = Integer.toString(bukkitService.getOnlinePlayers().size());
String ipAddress = PlayerUtils.getPlayerIp(player);
Server server = getServer();
return message
.replace("&", "\u00a7")
.replace("{PLAYER}", player.getName())
.replace("{ONLINE}", playersOnline)
.replace("{MAXPLAYERS}", Integer.toString(server.getMaxPlayers()))
.replace("{IP}", ipAddress)
.replace("{LOGINS}", Integer.toString(playerCache.getLogged()))
.replace("{WORLD}", player.getWorld().getName())
.replace("{SERVER}", server.getServerName())
.replace("{VERSION}", server.getBukkitVersion())
// TODO: We should cache info like this, maybe with a class that extends Player?
.replace("{COUNTRY}", geoIpService.getCountryName(ipAddress));
}
/**
* Handle Bukkit commands.
*
* @param sender The command sender (Bukkit).
* @param cmd The command (Bukkit).
* @param commandLabel The command label (Bukkit).
* @param args The command arguments (Bukkit).
*
* @return True if the command was executed, false otherwise.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
// Make sure the command handler has been initialized
if (commandHandler == null) {
getLogger().severe("AuthMe command handler is not available");
return false;
}
// Handle the command
return commandHandler.processCommand(sender, commandLabel, args);
}
}
| gpl-3.0 |
freaxmind/miage-l3 | langage-java/MachineTuring/src/turing/TableTransition.java | 1227 | package turing;
import java.util.ArrayList;
/**
* Stocke les transitions possibles pour une machine de Turing
*/
public class TableTransition {
// Structure interne
private ArrayList<Transition> liste;
/**
* Constructor
*/
public TableTransition() {
this.liste = new ArrayList<Transition>();
}
/**
* Ajoute une transition à la liste
*
* @param delta une transition
*/
public void ajout(Transition delta) {
this.liste.add(delta);
}
/**
* Recherche une transition dans la table pour un état et un symbole
*
* @note retourne la première transition trouvée
* @param q etat courant
* @param s symbole lu
*
* @return la transition trouvée ou null
*/
public Transition recherche(Etat q, String s) {
for (Transition delta : this.liste) {
if (delta.getEtatCourant().equals(q) && delta.getSymboleLu().equals(s)) {
return delta;
}
}
return null;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("Table de transition:\n");
for (Transition delta : this.liste) {
str.append(delta).append("\n");
}
return str.toString();
}
}
| gpl-3.0 |
jfinkels/jmona | jmona-examples/src/test/java/jmona/example/calc/nodes/SubtractionNodeTester.java | 2237 | /**
* SubtractionNodeTester.java
*
* Copyright 2009, 2010 Jeffrey Finkelstein
*
* This file is part of jmona.
*
* jmona 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.
*
* jmona 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
* jmona. If not, see <http://www.gnu.org/licenses/>.
*/
package jmona.example.calc.nodes;
import static org.junit.Assert.assertEquals;
import jfcommon.functional.MappingException;
import jfcommon.test.TestUtils;
import jmona.gp.EvaluationException;
import org.junit.Test;
/**
* Test class for the SubtractionNode class.
*
* @author Jeffrey Finkelstein
* @since 0.1
*/
public class SubtractionNodeTester {
/** The value by which to increment the input to the function. */
public static final double INCREMENT = 0.1;
/** The maximum value of the input to the function. */
public static final double MAX_VALUE = 100.0;
/** The minimum value of the input to the function. */
public static final double MIN_VALUE = 0.0;
/** Zero. */
public static final double ZERO_DELTA = 0.0;
/**
* Test method for
* {@link jmona.example.calc.nodes.SubtractionNode#SubtractionNode()}.
*/
@Test
public void testSubtractionNode() {
final SubtractionNode node = new SubtractionNode();
final double leftValue = 1.0;
final double rightValue = 2.0;
node.children().add(new NumberNode(leftValue));
node.children().add(new NumberNode(rightValue));
try {
for (double x = MIN_VALUE; x < MAX_VALUE; x += INCREMENT) {
assertEquals(leftValue - rightValue, node.evaluate().execute(x),
ZERO_DELTA);
}
} catch (final EvaluationException exception) {
TestUtils.fail(exception);
} catch (final MappingException exception) {
TestUtils.fail(exception);
}
}
}
| gpl-3.0 |
zeromancer/mangawatcher | src/gui/reading/GuiReadToolBar.java | 7239 | /*
MangaWatcher - a manga management program.
Copyright (C) 2013 David Siewert
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 gui.reading;
import gui.GuiFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.miginfocom.swing.MigLayout;
import data.Engine;
import data.Engine.Icons;
import data.Options;
public class GuiReadToolBar extends JToolBar {
private static final long serialVersionUID = 5673903268744027432L;
private final GuiFrame frame;
private final Options options;
private JSlider zoom;
private JSlider scroll;
private GuiRead gui;
private GuiReadView view;
private JToggleButton showZoom;
private JToggleButton showScroll;
private JButton resync;
private JButton previousChapter;
private JButton previousPage;
private JButton nextChapter;
private JButton nextPage;
public GuiReadToolBar(GuiFrame frame, GuiRead gui, GuiReadView view) {
this.frame = frame;
this.options = frame.getOptions();
this.gui = gui;
this.view = view;
constructGuiOptions();
}
public void constructGuiOptions() {
setLayout(new MigLayout("","0![grow]0!","0![]0![]0!"));
// LayoutManager layout = new GridLayout();
// setLayout(layout);
setBorder(new EmptyBorder(0, 0, 0, 0));
setBorder(BorderFactory.createEmptyBorder());
// resync = new JButton("Reload");
// showZoom = new JToggleButton("Show Zoom");
// showScroll = new JToggleButton("Show Scroll");
// previousChapter = new JButton("Chapter--");
// previousPage = new JButton("Page--");
// nextPage = new JButton("Page++");
// nextChapter = new JButton("Chapter++");
add(gui.getProgress(),"span 7, grow, shrink, h 30, wrap");
Engine engine = frame.getEngine();
resync = new JButton(new ImageIcon(engine.getIcon(Icons.REFRESH)));
// resync.setMargin(new Insets(0, 0, 0, 0));
showZoom = new JToggleButton(new ImageIcon(engine.getIcon(Icons.ZOOM)));
showScroll = new JToggleButton(new ImageIcon(engine.getIcon(Icons.SCROLL)));
previousChapter = new JButton(new ImageIcon(engine.getIcon(Icons.DOUBLELEFT)));
previousPage = new JButton(new ImageIcon(engine.getIcon(Icons.LEFT)));
nextPage = new JButton(new ImageIcon(engine.getIcon(Icons.RIGHT)));
nextChapter = new JButton(new ImageIcon(engine.getIcon(Icons.DOUBLERIGHT)));
resync.setFocusable(false);
showZoom.setFocusable(false);
showScroll.setFocusable(false);
previousChapter.setFocusable(false);
previousPage.setFocusable(false);
nextPage.setFocusable(false);
nextChapter.setFocusable(false);
zoom = new JSlider(10, 400, options.getReadingZoom());
zoom.setPaintTicks(true);
zoom.setMinorTickSpacing(10);
zoom.setSnapToTicks(true);
scroll = new JSlider(1, 500, options.getReadingScroll());
scroll.setPaintTicks(true);
scroll.setMinorTickSpacing(10);
scroll.setSnapToTicks(true);
Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
labelTable.put(new Integer(0), new JLabel("10%"));
labelTable.put(new Integer(100), new JLabel("100%"));
labelTable.put(new Integer(200), new JLabel("200%"));
labelTable.put(new Integer(300), new JLabel("300%"));
labelTable.put(new Integer(400), new JLabel("400%"));
zoom.setLabelTable(labelTable);
zoom.setPaintLabels(true);
labelTable = new Hashtable<Integer, JLabel>();
labelTable.put(new Integer(0), new JLabel("10 px"));
labelTable.put(new Integer(100), new JLabel("100 px"));
labelTable.put(new Integer(200), new JLabel("200 px"));
labelTable.put(new Integer(300), new JLabel("300 px"));
labelTable.put(new Integer(400), new JLabel("400 px"));
labelTable.put(new Integer(500), new JLabel("400 px"));
scroll.setLabelTable(labelTable);
scroll.setPaintLabels(true);
add(resync,"growx");
add(showZoom,"growx");
add(showScroll,"growx");
add(previousChapter,"growx");
add(previousPage,"growx");
add(nextPage,"growx");
add(nextChapter, "growx, wrap");
final String sliderOptions = "growx, span";
// add(zoom, zoomAdd);
resync.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(view.getManga()== null)
return;
view.getMapImages().clear();
view.getMapFiles().clear();
view.load();
}
});
showZoom.setSelected(false);
showZoom.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AbstractButton abstractButton = (AbstractButton) e.getSource();
boolean selected = abstractButton.getModel().isSelected();
if (selected)
add(zoom, sliderOptions);
else
remove(zoom);
revalidate();
repaint();
}
});
showScroll.setSelected(false);
showScroll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AbstractButton abstractButton = (AbstractButton) e.getSource();
boolean selected = abstractButton.getModel().isSelected();
if (selected)
add(scroll, sliderOptions);
else
remove(scroll);
revalidate();
repaint();
}
});
previousChapter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
view.previousChapter();
}
});
previousPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
view.previousPage();
}
});
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
view.nextPage();
}
});
nextChapter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
view.nextChapter();
}
});
zoom.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (zoom.getValueIsAdjusting())
return;
int value = zoom.getValue();
view.setZoom(value);
}
});
scroll.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (scroll.getValueIsAdjusting())
return;
int value = scroll.getValue();
options.setReadingScroll(value);
}
});
}
public void previousChapter(boolean enabled) {
previousChapter.setEnabled(enabled);
}
public void nextChapter(boolean enabled) {
nextChapter.setEnabled(enabled);
}
}
| gpl-3.0 |
virustotalop/ObsidianAuctions | src/main/java/com/gmail/virustotalop/obsidianauctions/event/AuctionEndEvent.java | 975 | package com.gmail.virustotalop.obsidianauctions.event;
import com.gmail.virustotalop.obsidianauctions.auction.Auction;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class AuctionEndEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
private final Auction auction;
public AuctionEndEvent(Auction auction, boolean cancelled) {
this.auction = auction;
this.cancelled = cancelled;
}
public Auction getAuction() {
return this.auction;
}
public boolean isCancelled() {
return this.cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return AuctionEndEvent.handlers;
}
}
| gpl-3.0 |
trashcutter/AnkiStats | app/src/main/java/com/wildplot/android/rendering/graphics/wrapper/Graphics2D.java | 305 | package com.wildplot.android.rendering.graphics.wrapper;
import android.graphics.Canvas;
import android.graphics.Paint;
public class Graphics2D extends Graphics {
public Graphics2D(Canvas canvas, Paint paint) {
super(canvas, paint);
// TODO Auto-generated constructor stub
}
}
| gpl-3.0 |
Konloch/bytecode-viewer | src/main/java/the/bytecode/club/bytecodeviewer/plugin/PluginTemplate.java | 2522 | package the.bytecode.club.bytecodeviewer.plugin;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
import the.bytecode.club.bytecodeviewer.BytecodeViewer;
import the.bytecode.club.bytecodeviewer.resources.IconResources;
/***************************************************************************
* Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite *
* Copyright (C) 2014 Kalen 'Konloch' Kinloch - http://bytecodeviewer.com *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
/**
* @author Konloch
* @since 7/1/2021
*/
public enum PluginTemplate
{
JAVA("/templates/Template_Plugin.java"),
JAVASCRIPT("/templates/Template_Plugin.js"),
;
private final String resourcePath;
private final String extension;
private String contents;
PluginTemplate(String resourcePath)
{
this.resourcePath = resourcePath;
this.extension = FilenameUtils.getExtension(resourcePath);
}
public String getContents() throws IOException
{
if(contents == null)
contents = IconResources.loadResourceAsString(resourcePath);
return contents;
}
public String getExtension()
{
return extension;
}
public PluginWriter openEditorExceptionHandled()
{
try
{
return openEditor();
}
catch (IOException e)
{
BytecodeViewer.handleException(e);
}
return null;
}
public PluginWriter openEditor() throws IOException
{
PluginWriter writer = new PluginWriter(this);
writer.setVisible(true);
return writer;
}
}
| gpl-3.0 |
kristotammeoja/ks | rstb/rstb-classification/src/main/java/org/csa/rstb/dat/wizards/PolarimetryWizard/PolSARWizardAction.java | 1421 | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.csa.rstb.dat.wizards.PolarimetryWizard;
import org.esa.beam.framework.ui.command.CommandEvent;
import org.esa.beam.visat.VisatApp;
import org.esa.beam.visat.actions.AbstractVisatAction;
import org.esa.nest.dat.wizards.WizardDialog;
import org.esa.snap.util.ImageUtils;
public class PolSARWizardAction extends AbstractVisatAction {
@Override
public void actionPerformed(final CommandEvent event) {
final WizardDialog dialog = new WizardDialog(VisatApp.getApp().getMainFrame(), false,
PolSARWizardInstructPanel.title, "PolSARWizard", new PolSARWizardInstructPanel());
dialog.setIcon(ImageUtils.rstbIcon);
dialog.setVisible(true);
}
} | gpl-3.0 |
gtri-iead/org.gtri.util.iteratee | api/src/main/java/org/gtri/util/iteratee/api/ImmutableBuffer.java | 2177 | /*
Copyright 2012 Georgia Tech Research Institute
Author: lance.gatlin@gtri.gatech.edu
This file is part of org.gtri.util.iteratee library.
org.gtri.util.iteratee library 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.
org.gtri.util.iteratee library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with org.gtri.util.iteratee library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gtri.util.iteratee.api;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An interface for an immutable buffer of items.
*
* @author lance.gatlin@gmail.com
*/
public interface ImmutableBuffer<A> extends Iterable<A> {
/**
* Get the length of the buffer.
* @return the length of the buffer.
*/
int length();
/**
* Get the item at the specified index
* @param idx zero-based index. must be less than length
* @return the item at the specified index
* @throws NoSuchElementException if index is greater than or equal to length
*/
A apply(int idx);
/**
* Get an iterator for the items in the buffer
* @return an iterator for the items in the buffer
*/
@Override Iterator<A> iterator();
/**
* Concatenate this buffer with another buffer.
* @return a new buffer containing the contents of both buffers
*/
ImmutableBuffer<A> append(ImmutableBuffer<A> rhs);
/**
* Select an interval of items.
* @param start the lowest index to include from this sequence
* @param end the highest index to EXCLUDE from this sequence
* @return a new buffer containing the selected items
*/
ImmutableBuffer<A> slice(int start, int end);
}
| gpl-3.0 |
fcristini/PPLite | interfaces/Java/parma_polyhedra_library/MIP_Problem.java | 11253 | /* MIP_Problem Java class declaration and implementation.
Copyright (C) 2001-2010 Roberto Bagnara <bagnara@cs.unipr.it>
Copyright (C) 2010-2016 BUGSENG srl (http://bugseng.com)
This file is part of the Parma Polyhedra Library (PPL).
The PPL 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.
The PPL 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 02111-1307, USA.
For the most up-to-date information see the Parma Polyhedra Library
site: http://bugseng.com/products/ppl/ . */
package parma_polyhedra_library;
//! A Mixed Integer (linear) Programming problem.
/*! \ingroup PPL_Java_interface
An object of this class encodes a mixed integer (linear) programming problem.
The MIP problem is specified by providing:
- the dimension of the vector space;
- the feasible region, by means of a finite set of linear equality
and non-strict inequality constraints;
- the subset of the unknown variables that range over the integers
(the other variables implicitly ranging over the reals);
- the objective function, described by a Linear_Expression;
- the optimization mode (either maximization or minimization).
The class provides support for the (incremental) solution of the
MIP problem based on variations of the revised simplex method and
on branch-and-bound techniques. The result of the resolution
process is expressed in terms of an enumeration, encoding the
feasibility and the unboundedness of the optimization problem.
The class supports simple feasibility tests (i.e., no optimization),
as well as the extraction of an optimal (resp., feasible) point,
provided the MIP_Problem is optimizable (resp., feasible).
By exploiting the incremental nature of the solver, it is possible
to reuse part of the computational work already done when solving
variants of a given MIP_Problem: currently, incremental resolution
supports the addition of space dimensions, the addition of constraints,
the change of objective function and the change of optimization mode.
*/
public class MIP_Problem extends PPL_Object {
//! \name Constructors and Destructor
/*@{*/
//! Builds a trivial MIP problem.
/*!
A trivial MIP problem requires to maximize the objective function
\f$0\f$ on a vector space under no constraints at all:
the origin of the vector space is an optimal solution.
\param dim
The dimension of the vector space enclosing \p this.
\exception Length_Error_Exception
Thrown if \p dim exceeds <CODE>max_space_dimension()</CODE>.
*/
public MIP_Problem(long dim) {
build_cpp_object(dim);
}
/*! \brief
Builds an MIP problem having space dimension \p dim from the constraint
system \p cs, the objective function \p obj and optimization mode
\p mode.
\param dim
The dimension of the vector space enclosing \p this.
\param cs
The constraint system defining the feasible region.
\param obj
The objective function.
\param mode
The optimization mode.
\exception Length_Error_Exception
Thrown if \p dim exceeds <CODE>max_space_dimension()</CODE>.
\exception Invalid_Argument_Exception
Thrown if the constraint system contains any strict inequality
or if the space dimension of the constraint system (resp., the
objective function) is strictly greater than \p dim.
*/
public MIP_Problem(long dim, Constraint_System cs, Linear_Expression obj,
Optimization_Mode mode) {
build_cpp_object(dim, cs, obj, mode);
}
//! Builds a copy of \p y.
public MIP_Problem(MIP_Problem y) {
build_cpp_object(y);
}
/*! \brief
Releases all resources managed by \p this,
also resetting it to a null reference.
*/
public native void free();
//! Releases all resources managed by \p this.
protected native void finalize();
/*@}*/ /* Constructors and Destructor */
//! \name Functions that Do Not Modify the MIP_Problem
/*@{*/
//! Returns the maximum space dimension an MIP_Problem can handle.
public native long max_space_dimension();
//! Returns the space dimension of the MIP problem.
public native long space_dimension();
/*! \brief
Returns a set containing all the variables' indexes constrained
to be integral.
*/
public native Variables_Set integer_space_dimensions();
//! Returns the constraints .
public native Constraint_System constraints();
//! Returns the objective function.
public native Linear_Expression objective_function();
//! Returns the optimization mode.
public native Optimization_Mode optimization_mode();
//! Returns an ascii formatted internal representation of \p this.
public native String ascii_dump();
//! Returns a string representation of \p this.
public native String toString();
/*! \brief
Returns the total size in bytes of the memory occupied by the
underlying C++ object.
*/
public native long total_memory_in_bytes();
//! Checks if all the invariants are satisfied.
public native boolean OK();
/*@}*/ /* Functions that Do Not Modify the MIP_Problem */
//! \name Functions that May Modify the MIP_Problem
/*@{*/
//! Resets \p this to be equal to the trivial MIP problem.
/*!
The space dimension is reset to \f$0\f$.
*/
public native void clear();
/*! \brief
Adds \p m new space dimensions and embeds the old MIP problem
in the new vector space.
\param m
The number of dimensions to add.
\exception Length_Error_Exception
Thrown if adding \p m new space dimensions would cause the
vector space to exceed dimension <CODE>max_space_dimension()</CODE>.
The new space dimensions will be those having the highest indexes
in the new MIP problem; they are initially unconstrained.
*/
public native void add_space_dimensions_and_embed(long m);
/*! \brief
Sets the variables whose indexes are in set \p i_vars to be
integer space dimensions.
\exception Invalid_Argument_Exception
Thrown if some index in \p i_vars does not correspond to
a space dimension in \p this.
*/
public native void add_to_integer_space_dimensions(Variables_Set i_vars);
/*! \brief
Adds a copy of constraint \p c to the MIP problem.
\exception Invalid_Argument_Exception
Thrown if the constraint \p c is a strict inequality or if its space
dimension is strictly greater than the space dimension of \p this.
*/
public native void add_constraint(Constraint c);
/*! \brief
Adds a copy of the constraints in \p cs to the MIP problem.
\exception Invalid_Argument_Exception
Thrown if the constraint system \p cs contains any strict inequality
or if its space dimension is strictly greater than the space dimension
of \p this.
*/
public native void add_constraints(Constraint_System cs);
//! Sets the objective function to \p obj.
/*!
\exception Invalid_Argument_Exception
Thrown if the space dimension of \p obj is strictly greater than
the space dimension of \p this.
*/
public native void set_objective_function(Linear_Expression obj);
//! Sets the optimization mode to \p mode.
public native void set_optimization_mode(Optimization_Mode mode);
/*@}*/ /* Functions that May Modify the MIP_Problem */
//! \name Computing the Solution of the MIP_Problem
/*@{*/
//! Checks satisfiability of \p this.
/*!
\return
<CODE>true</CODE> if and only if the MIP problem is satisfiable.
*/
public native boolean is_satisfiable();
//! Optimizes the MIP problem.
/*!
\return
An MIP_Problem_Status flag indicating the outcome of the optimization
attempt (unfeasible, unbounded or optimized problem).
*/
public native MIP_Problem_Status solve();
/*! \brief
Sets \p num and \p den so that \f$\frac{num}{den}\f$ is the result
of evaluating the objective function on \p evaluating_point.
\param evaluating_point
The point on which the objective function will be evaluated.
\param num
On exit will contain the numerator of the evaluated value.
\param den
On exit will contain the denominator of the evaluated value.
\exception Invalid_Argument_Exception
Thrown if \p this and \p evaluating_point are dimension-incompatible
or if the generator \p evaluating_point is not a point.
*/
public native void evaluate_objective_function(Generator evaluating_point,
Coefficient num,
Coefficient den);
//! Returns a feasible point for \p this, if it exists.
/*!
\exception Domain_Error_Exception
Thrown if the MIP problem is not satisfiable.
*/
public native Generator feasible_point();
//! Returns an optimal point for \p this, if it exists.
/*!
\exception Domain_Error_Exception
Thrown if \p this doesn't not have an optimizing point, i.e.,
if the MIP problem is unbounded or not satisfiable.
*/
public native Generator optimizing_point();
/*! \brief
Sets \p num and \p den so that \f$\frac{num}{den}\f$ is
the solution of the optimization problem.
\exception Domain_Error_Exception
Thrown if \p this doesn't not have an optimizing point, i.e.,
if the MIP problem is unbounded or not satisfiable.
*/
public native void optimal_value(Coefficient num, Coefficient den);
/*@}*/ /* Computing the Solution of the MIP_Problem */
//! \name Querying/Setting Control Parameters
/*@{*/
/*! \brief
Returns the value of control parameter \p name.
*/
public native Control_Parameter_Value
get_control_parameter(Control_Parameter_Name name);
/*! \brief
Sets control parameter \p value.
*/
public native void set_control_parameter(Control_Parameter_Value value);
/*@}*/ /* Querying/Setting Control Parameters */
//! Builds the underlying C++ object.
private native void build_cpp_object(long dim);
//! Builds the underlying C++ object.
private native void build_cpp_object(long dim,
Constraint_System cs,
Linear_Expression obj,
Optimization_Mode mode);
//! Builds the underlying C++ object.
private native void build_cpp_object(MIP_Problem y);
}
| gpl-3.0 |
irgsmirx/WebServer | src/main/java/com/ramforth/webserver/http/DispositionType.java | 2337 | /*
* Copyright (C) 2014 Tobias Ramforth
*
* 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.ramforth.webserver.http;
import java.nio.charset.Charset;
/**
*
* @author Tobias Ramforth <tobias.ramforth at tu-dortmund.de>
*/
public class DispositionType implements IDispositionType {
private static final String DEFAULT_MEDIA_TYPE = "application/octet-stream";
protected String type = DEFAULT_MEDIA_TYPE;
protected NameValueMap parameters = new NameValueMap();
@Override
public String getType() {
return type;
}
@Override
public void setType(String value) {
this.type = value;
}
@Override
public NameValueMap getParameters() {
return parameters;
}
@Override
public void addParameter(String name, String value) {
parameters.add(name, value);
}
@Override
public void removeParameter(String name) {
parameters.remove(name);
}
@Override
public void clearParameters() {
parameters.clear();
}
@Override
public int numberOfParameters() {
return parameters.numberOfEntries();
}
@Override
public String getValue(String name) {
return parameters.get(name);
}
@Override
public boolean containsParameter(String name) {
return parameters.containsName(name);
}
@Override
public Charset getCharset() {
try {
String charsetString = parameters.get("charset");
return Charset.forName(charsetString);
}
catch (Exception ex) {
return Charset.defaultCharset();
}
}
@Override
public String getName() {
return parameters.get("name");
}
}
| gpl-3.0 |
acgtun/leetcode | algorithms/java/Longest Substring Without Repeating Characters.java | 550 | public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int start = 0;
int res = 0;
for(int i = 0;i < s.length();++i) {
char c = s.charAt(i);
if(map.containsKey(c) && map.get(c) >= start) {
res = Math.max(res, i - start);
start = map.get(c) + 1;
}
map.put(c, i);
}
res = Math.max(res, s.length() - start);
return res;
}
} | gpl-3.0 |
MichSchli/DataApi | src/main/java/infrastructure/specifications/ISpecification.java | 172 | package infrastructure.specifications;
import java.util.List;
public interface ISpecification {
public List<Integer> getIds();
public boolean isIdentifierLookup();
}
| gpl-3.0 |
Captain-Chaos/WorldPainter | WorldPainter/WPGUI/src/main/java/org/pepsoft/worldpainter/selection/CopySelectionOperationOptions.java | 457 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.worldpainter.selection;
import org.pepsoft.worldpainter.operations.OperationOptions;
/**
*
* @author Pepijn
*/
public class CopySelectionOperationOptions extends SelectionOptions implements OperationOptions<CopySelectionOperation> {
// Empty
} | gpl-3.0 |
waikato-datamining/adams-base | adams-core/src/main/java/adams/flow/control/PlotProcessor.java | 11584 | /*
* 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/>.
*/
/**
* PlotProcessor.java
* Copyright (C) 2013-2015 University of Waikato, Hamilton, New Zealand
*/
package adams.flow.control;
import adams.core.QuickInfoHelper;
import adams.flow.container.SequencePlotterContainer;
import adams.flow.container.SequencePlotterContainer.ContentType;
import adams.flow.control.plotprocessor.AbstractPlotProcessor;
import adams.flow.control.plotprocessor.PassThrough;
import adams.flow.core.Token;
import adams.flow.transformer.AbstractTransformer;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
<!-- globalinfo-start -->
* Applies the specified processing algorithm to the stream of plot containers passing through. Injects any additionally created plot containers into the stream.
* <br><br>
<!-- globalinfo-end -->
*
<!-- flow-summary-start -->
* Input/output:<br>
* - accepts:<br>
* adams.flow.container.SequencePlotterContainer<br>
* - generates:<br>
* adams.flow.container.SequencePlotterContainer<br>
* <br><br>
* Container information:<br>
* - adams.flow.container.SequencePlotterContainer: PlotName, X, Y, Content type, Error X, Error Y, MetaData<br>
* - adams.flow.container.SequencePlotterContainer: PlotName, X, Y, Content type, Error X, Error Y, MetaData
* <br><br>
<!-- flow-summary-end -->
*
<!-- options-start -->
* <pre>-logging-level <OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST> (property: loggingLevel)
* The logging level for outputting errors and debugging output.
* default: WARNING
* </pre>
*
* <pre>-name <java.lang.String> (property: name)
* The name of the actor.
* default: PlotProcessor
* </pre>
*
* <pre>-annotation <adams.core.base.BaseAnnotation> (property: annotations)
* The annotations to attach to this actor.
* default:
* </pre>
*
* <pre>-skip <boolean> (property: skip)
* If set to true, transformation is skipped and the input token is just forwarded
* as it is.
* default: false
* </pre>
*
* <pre>-stop-flow-on-error <boolean> (property: stopFlowOnError)
* If set to true, the flow gets stopped in case this actor encounters an error;
* useful for critical actors.
* default: false
* </pre>
*
* <pre>-silent <boolean> (property: silent)
* If enabled, then no errors are output in the console.
* default: false
* </pre>
*
* <pre>-processor <adams.flow.control.plotprocessor.AbstractPlotProcessor> (property: processor)
* The plot processor to apply to the stream of plot containers passing through.
* default: adams.flow.control.plotprocessor.PassThrough
* </pre>
*
* <pre>-type <PLOT|MARKER|OVERLAY|UPDATE> (property: type)
* The type of plot container to create.
* default: OVERLAY
* </pre>
*
* <pre>-drop-input <boolean> (property: dropInput)
* If enabled, then the input plot container is dropped.
* default: false
* </pre>
*
<!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class PlotProcessor
extends AbstractTransformer {
/** for serialization. */
private static final long serialVersionUID = 7830411664107227699L;
/** the key for storing the additional output tokens in the backup. */
public final static String BACKUP_ADDITIONALOUTPUT = "additional output";
/** the processor to apply. */
protected AbstractPlotProcessor m_Processor;
/** the type to use. */
protected ContentType m_Type;
/** whether to drop the input. */
protected boolean m_DropInput;
/** the additional container tokens that were generated. */
protected List<Token> m_AdditionalOutputTokens;
/**
* Returns a string describing the object.
*
* @return a description suitable for displaying in the gui
*/
@Override
public String globalInfo() {
return
"Applies the specified processing algorithm to the stream of plot "
+ "containers passing through. Injects any additionally created "
+ "plot containers into the stream.";
}
/**
* Adds options to the internal list of options.
*/
@Override
public void defineOptions() {
super.defineOptions();
m_OptionManager.add(
"processor", "processor",
new PassThrough());
m_OptionManager.add(
"type", "type",
ContentType.OVERLAY);
m_OptionManager.add(
"drop-input", "dropInput",
false);
}
/**
* Resets the scheme.
*/
@Override
protected void reset() {
super.reset();
m_AdditionalOutputTokens = new ArrayList<Token>();
}
/**
* Returns a quick info about the actor, which will be displayed in the GUI.
*
* @return null if no info available, otherwise short string
*/
@Override
public String getQuickInfo() {
String result;
String value;
result = m_Processor.getQuickInfo();
if (result == null)
result = QuickInfoHelper.toString(this, "processor", m_Processor);
else
result = m_Processor.getClass().getSimpleName() + ": " + result;
result += QuickInfoHelper.toString(this, "type", m_Type, ", type: ");
value = QuickInfoHelper.toString(this, "dropInput", m_DropInput, ", drop");
if (value != null)
result += value;
return result;
}
/**
* Sets the processor to apply to the plot containers.
*
* @param value the processor
*/
public void setProcessor(AbstractPlotProcessor value) {
m_Processor = value;
reset();
}
/**
* Returns the processor to apply to the plot containers.
*
* @return the processor
*/
public AbstractPlotProcessor getProcessor() {
return m_Processor;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the GUI or for listing the options.
*/
public String processorTipText() {
return "The plot processor to apply to the stream of plot containers passing through.";
}
/**
* Sets the type of container to create.
*
* @param value the type
*/
public void setType(ContentType value) {
m_Type = value;
reset();
}
/**
* Returns the type of container to create.
*
* @return the type
*/
public ContentType getType() {
return m_Type;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the GUI or for listing the options.
*/
public String typeTipText() {
return "The type of plot container to create.";
}
/**
* Sets whether to drop the input plot container completely.
*
* @param value true if to drop input
*/
public void setDropInput(boolean value) {
m_DropInput = value;
reset();
}
/**
* Returns whether to drop the input plot container completely.
*
* @return true if input dropped
*/
public boolean getDropInput() {
return m_DropInput;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for
* displaying in the GUI or for listing the options.
*/
public String dropInputTipText() {
return "If enabled, then the input plot container is dropped.";
}
/**
* Removes entries from the backup.
*/
@Override
protected void pruneBackup() {
super.pruneBackup();
pruneBackup(BACKUP_ADDITIONALOUTPUT);
}
/**
* Backs up the current state of the actor before update the variables.
*
* @return the backup
*/
@Override
protected Hashtable<String,Object> backupState() {
Hashtable<String,Object> result;
result = super.backupState();
if (m_AdditionalOutputTokens != null)
result.put(BACKUP_ADDITIONALOUTPUT, m_AdditionalOutputTokens);
return result;
}
/**
* Restores the state of the actor before the variables got updated.
*
* @param state the backup of the state to restore from
*/
@Override
protected void restoreState(Hashtable<String,Object> state) {
if (state.containsKey(BACKUP_ADDITIONALOUTPUT)) {
m_AdditionalOutputTokens = (List<Token>) state.get(BACKUP_ADDITIONALOUTPUT);
state.remove(BACKUP_ADDITIONALOUTPUT);
}
super.restoreState(state);
}
/**
* Returns the class that the consumer accepts.
*
* @return the Class of objects that can be processed
*/
@Override
public Class[] accepts() {
return new Class[]{SequencePlotterContainer.class};
}
/**
* Returns the class of objects that it generates.
*
* @return the Class of the generated tokens
*/
@Override
public Class[] generates() {
return new Class[]{SequencePlotterContainer.class};
}
/**
* Executes the flow item.
*
* @return null if everything is fine, otherwise error message
*/
@Override
protected String doExecute() {
String result;
List<SequencePlotterContainer> cont;
m_AdditionalOutputTokens.clear();
if (isLoggingEnabled())
getLogger().fine("input: " + m_InputToken.getPayload());
cont = m_Processor.process((SequencePlotterContainer) m_InputToken.getPayload());
result = m_Processor.getLastError();
if ((result == null) && (cont != null)) {
for (SequencePlotterContainer c: cont) {
c.setValue(SequencePlotterContainer.VALUE_CONTENTTYPE, m_Type);
m_AdditionalOutputTokens.add(new Token(c));
if (isLoggingEnabled())
getLogger().fine("additional: " + c);
}
}
if (!m_DropInput)
m_OutputToken = m_InputToken;
return result;
}
/**
* Checks whether there is pending output to be collected after
* executing the flow item.
*
* @return true if there is pending output
*/
@Override
public boolean hasPendingOutput() {
return (m_AdditionalOutputTokens.size() > 0) || super.hasPendingOutput();
}
/**
* Returns the generated token.
*
* @return the generated token
*/
@Override
public Token output() {
Token result;
if (m_AdditionalOutputTokens.size() > 0) {
result = m_AdditionalOutputTokens.get(0);
m_AdditionalOutputTokens.remove(0);
}
else {
result = super.output();
}
return result;
}
/**
* Cleans up after the execution has finished.
*/
@Override
public void wrapUp() {
m_AdditionalOutputTokens.clear();
super.wrapUp();
}
/**
* Cleans up after the execution has finished. Also removes graphical
* components.
*/
@Override
public void cleanUp() {
m_Processor.cleanUp();
super.cleanUp();
}
}
| gpl-3.0 |
leonbornemann/stife | src/data_structures/Sequence.java | 18829 | package data_structures;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import algorithms.Algorithms;
import stife.distance.Event;
import stife.distance.EventType;
import stife.shapelet.evolution.NShapelet;
import stife.shapelet_size2.Shapelet_Size2;
import stife.shapelet_size2_new.ShapeletSize2;
import stife.shapelet_size2.ShapeletFeatureMatrix;
/***
*
* @author leon bornemann
*
*/
public class Sequence {
public static int getMaxDuration(List<Sequence> database) {
int maxDuration = -1;
for(Sequence seq : database){
maxDuration = Math.max(maxDuration,seq.duration());
}
return maxDuration;
}
/***
* Reads all sequences in a file and returns them as an unmodifiable list
* @param sequenceFilePath path to the input file.
* @return
* @throws IOException
*/
public static List<Sequence> readSequenceData(String sequenceFilePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File(sequenceFilePath)));
List<Sequence> sequences = new ArrayList<Sequence>();
List<Interval> eventsOfSameSequence = new LinkedList<>();
int curId = -1;
while(true){
String line = br.readLine();
if(line==null ||line.equals("")){
sequences.add(new Sequence(eventsOfSameSequence));
break;
}
String[] tokens = line.split(" ");
assert(tokens.length==4);
int curSeqId = Integer.parseInt(tokens[0]);
if(curSeqId == curId || curId==-1){
eventsOfSameSequence.add(new Interval(line));
} else{
sequences.add(new Sequence(eventsOfSameSequence));
eventsOfSameSequence.clear();
eventsOfSameSequence.add(new Interval(line));
}
curId = curSeqId;
}
br.close();
return Collections.unmodifiableList(sequences);
}
public static TreeSet<Integer> getDimensionSet(List<Sequence> sequences) {
TreeSet<Integer> dimensions = new TreeSet<>();
for(Sequence seq : sequences){
dimensions.addAll(seq.getAllDimensions());
}
//small consistency test of the data, if this does not hold, we have a problem with the algorithms:
//assert(dimensions.descendingIterator().next() == dimensions.size());
return dimensions;
}
/***
* uses a table and not a list of Event-objects to optimize performance, one line in this table is basically an event object
* first column: event dimension, second column: start-time, third column: end-time
*/
List<Interval> intervals = new ArrayList<>();
private boolean isSorted = false;
//number of temporal relationships between intervals is fixed.
public static final int NUM_RELATIONSHIPS = 7;
public Sequence(List<Interval> intervalList) {
assert(intervalList.size()>0);
fillIntervals(intervalList);
sortIntervals();
}
private void fillIntervals(List<Interval> intervalList) {
for(int i=0;i<intervalList.size();i++){
intervals.add( intervalList.get(i).deepCopy());
}
}
/***
* Creates a deep-copy of the specified sequence
* @param seq
*/
public Sequence(Sequence seq) {
fillIntervals(seq.getAllIntervals());
sortIntervals();
}
public Collection<Integer> getAllDimensions() {
return intervals.stream().map(i -> i.getDimension()).collect(Collectors.toSet());
}
/***
* Counts all shapelet occurences in this sequence and writes it to the shapeletFeatureMatrix
* @param seqId the id of this sequence, aka the row in the shapeletFeatureMatrix, to which the shapelet counts will be written
* @param shapeletFeatureMatrix
* @param epsilon maximum time span that points of time may differ from each other to still be considered equal
*/
public void countAllShapelets(Integer seqId, ShapeletFeatureMatrix shapeletFeatureMatrix, int epsilon) {
//epsilon:
int e = epsilon;
for(int i=0;i<intervals.size();i++){
int aId = intervals.get(i).getDimension();
int aStart = intervals.get(i).getStart();
int aEnd = intervals.get(i).getEnd();
//all events after A are always relevant
for(int j=i+1;j<intervals.size();j++){
int bId = intervals.get(j).getDimension();
int bStart = intervals.get(j).getStart();
int bEnd = intervals.get(j).getEnd();
int relationshipId = getRelationship(aStart,aEnd,bStart,bEnd,e);
shapeletFeatureMatrix.incAt(seqId, aId, bId, relationshipId);
}
//some events that start at the same time as A may be before A in the order, we need to consider those as well:
for(int j=i-1;j>=0;j--){
int bId = intervals.get(j).getDimension();
int bStart = intervals.get(j).getStart();
int bEnd = intervals.get(j).getEnd();
if(aStart - e > bStart){
break;
} else{
int relationshipId = getRelationship(aStart,aEnd,bStart,bEnd,e);
shapeletFeatureMatrix.incAt(seqId, aId, bId, relationshipId);
}
}
}
}
/***
* Method is only public, so unit-testing is possible
* @param aStart start of event A
* @param aStop end of event A
* @param bStart start of event B
* @param bStop end of event B
* @param e maximum tolerance two time values can be apart to still be considered equal
* @return An int ranging from 1 to 7 representing the temporal relationship between Interval A and B as follows:
* 1 - meet
* 2 - match
* 3 - overlap
* 4 - leftContains
* 5 - contains
* 6 - rightContains
* 7 - followedBy
*/
public int getRelationship(int aStart, int aStop, int bStart, int bStop, int e) {
assert(aStart-e <=bStart);
//Aliases to make returns more readable:
int meet = 1; int match = 2; int overlap = 3; int leftContains = 4; int contains = 5;int rightContains = 6; int followedBy = 7;
//results = list(meet=1,match=2,overlap=3,leftContains=4,contains=5,rightContains=6,followedBy=7)
boolean startsMatch = bStart >= aStart - e && bStart <= aStart + e;
boolean endsMatch = bStop >= aStop - e && bStop <= aStop + e;
if(startsMatch){
// can be either left-contain, match or overlap
if(endsMatch){
return match;
} else if(bStop < aStop-e){
return leftContains;
} else{
assert(bStop > aStop + e);
return overlap;
}
} else{
// can be either right-contain, overlap,contain, meet or follow
boolean endMatchesStart = bStart >= aStop -e && bStart <= aStop+e;
if(endsMatch){
return rightContains;
} else if(endMatchesStart){
return meet;
} else if(bStop < aStop -e){
return contains;
} else if(bStart < aStop-e){
assert(bStop > aStop + e);
return overlap;
} else{
assert(bStart > aStop + e);
return followedBy;
}
}
}
public int intervalCount() {
return intervals.size();
}
public int duration() {
return intervals.stream().mapToInt(i -> i.getEnd()).max().getAsInt();
}
public int earliestStart() {
return intervals.stream().mapToInt(i -> i.getStart()).min().getAsInt();
}
public Interval getInterval(int i) {
return intervals.get(i);
}
public List<Interval> getAllIntervals() {
return intervals;
}
public void rescaleTimeAxis(int newScaleMin, int newScaleMax){
int xmin = earliestStart();
int xmax = duration();
for(int i=0;i<intervals.size();i++){
int newStart = Algorithms.linearInterpolation(xmin,xmax,intervals.get(i).getStart(),newScaleMin,newScaleMax);
int newEnd = Algorithms.linearInterpolation(xmin,xmax,intervals.get(i).getEnd(),newScaleMin,newScaleMax);
intervals.set(i, new Interval(intervals.get(i).getDimension(),newStart,newEnd));
}
}
public short countShapeletOccurance(Shapelet_Size2 shapelet,int epsilon) {
//TODO: Test this oh man oh man :D
int e = epsilon;
short count = 0;
List<Interval> relevantIntervals = new ArrayList<>();
for(int i=0;i<intervals.size();i++){
int eventId = intervals.get(i).getDimension();
if(eventId == shapelet.getEventId1() || eventId==shapelet.getEventId2()){
relevantIntervals.add(new Interval(eventId,intervals.get(i).getStart(),intervals.get(i).getEnd()));
}
}
for(int i=0;i<relevantIntervals.size();i++){
int aId = relevantIntervals.get(i).getDimension();
if(aId != shapelet.getEventId1()){
continue;
}
//if we get here we know event A is of the right dimension
int aStart = relevantIntervals.get(i).getStart();
int aEnd = relevantIntervals.get(i).getEnd();
//all intervals after A are always relevant
for(int j=i+1;j<relevantIntervals.size();j++){
int bId = relevantIntervals.get(j).getDimension();
if(bId != shapelet.getEventId2()){
continue;
}
int bStart = relevantIntervals.get(j).getStart();
int bEnd = relevantIntervals.get(j).getEnd();
int relationshipId = getRelationship(aStart,aEnd,bStart,bEnd,e);
if(relationshipId == shapelet.getRelationshipId()){
count++;
}
}
//some intervals that start at the same time as A may be before A in the order, we need to consider those as well:
for(int j=i-1;j>=0;j--){
int bId = relevantIntervals.get(j).getDimension();
int bStart = relevantIntervals.get(j).getStart();
int bEnd = relevantIntervals.get(j).getEnd();
if(aStart - e > bStart){
break;
} else if(bId != shapelet.getEventId2()){
continue;
} else{
int relationshipId = getRelationship(aStart,aEnd,bStart,bEnd,e);
if(relationshipId == shapelet.getRelationshipId()){
count++;
}
}
}
}
return count;
}
/***
* Orders Intervals in this sequence according to the following scheme: startTime, (if startTime is equal: endTime), if both of these are equal, dimension
*/
public void sortIntervals() {
Collections.sort(intervals, new StandardIntervalComparator());
isSorted = true;
}
public Map<Integer, Integer> getDimensionOccurances() {
Map<Integer,Integer> occuranceMap = new HashMap<>();
for(int i=0;i<intervals.size();i++){
int curDim = intervals.get(i).getDimension();
if(occuranceMap.containsKey(curDim)){
occuranceMap.put(curDim, occuranceMap.get(curDim)+1);
} else{
occuranceMap.put(curDim, 1);
}
}
return occuranceMap;
}
public long getDensity() {
long density = 0;
for(int i=0;i<intervals.size();i++){
density += intervals.get(i).getEnd() - intervals.get(i).getStart();
}
return density;
}
public int getMaxConcurrentIntervalCount() {
//TODO: test this
PriorityQueue<Integer> endTimes = new PriorityQueue<>();
for(int i=0;i<intervals.size();i++){
endTimes.add(intervals.get(i).getEnd());
}
int searchStartRow = 0;
int maxCount = -1;
int ends = 0;
while(!endTimes.isEmpty()){
Integer curEnd = endTimes.remove();
int intervalCount = 0;
for(int i=searchStartRow;i<intervals.size();i++){
int curStart = intervals.get(i).getStart();
if(curStart > curEnd || i==intervals.size()-1){
if(i==intervals.size()-1){
intervalCount = i+1-ends;
} else{
intervalCount = i-ends;
searchStartRow = i;
}
break;
}
}
ends++;
assert(intervalCount>0 || endTimes.isEmpty());
if(intervalCount>maxCount){
maxCount = intervalCount;
}
}
return maxCount;
}
public int getConcurrentIntervalDuration(int numConcurrentIntervals) {
// TODO test this
List<Event> startAndStopEvents = getSortedEventList();
int curEventsActive = 0;
int maxDuration = 0;
for(int i=0;i<startAndStopEvents.size();i++){
Event curEvent = startAndStopEvents.get(i);
if(curEvent.getEventType()==EventType.Start){
curEventsActive++;
} else{
curEventsActive--;
}
assert(curEventsActive<=numConcurrentIntervals);
if(curEventsActive == numConcurrentIntervals){
Event nextEvent = startAndStopEvents.get(i+1);
assert(nextEvent.getEventType()==EventType.End);
int curDuration = nextEvent.getPointOfTime() - curEvent.getPointOfTime();
if(curDuration>maxDuration){
maxDuration = curDuration;
}
}
}
return maxDuration;
}
private List<Event> getSortedEventList() {
List<Event> startAndStopEvents = new ArrayList<>();
for(int i=0;i<intervals.size();i++){
startAndStopEvents.add(new Event(intervals.get(i).getStart(), intervals.get(i).getDimension(), EventType.Start));
startAndStopEvents.add(new Event(intervals.get(i).getEnd(), intervals.get(i).getDimension(), EventType.End));
}
Collections.sort(startAndStopEvents);
return startAndStopEvents;
}
public int getSummedPauseTime() {
List<Event> startAndStopEvents = getSortedEventList();
int curEventsActive = 0;
int duration = 0;
for(int i=0;i<startAndStopEvents.size();i++){
Event curEvent = startAndStopEvents.get(i);
if(curEvent.getEventType()==EventType.Start){
curEventsActive++;
} else{
curEventsActive--;
}
assert(curEventsActive>=0);
if(curEventsActive==0 && i!= startAndStopEvents.size()-1){
Event nextEvent = startAndStopEvents.get(i+1);
assert(nextEvent.getEventType()==EventType.Start);
duration += nextEvent.getPointOfTime() - curEvent.getPointOfTime();
}
}
return duration;
}
public void reassignDimensionIds(HashMap<Integer, Integer> newDimensionMapping) {
for(int i=0;i<intervals.size();i++){
intervals.set(i, new Interval(newDimensionMapping.get(intervals.get(i).getDimension()),intervals.get(i).getStart(),intervals.get(i).getEnd()));
}
}
public boolean containsNSHapelet(NShapelet shapelet,int epsilon) {
List<Pair<Integer, Integer>> occurrences = shapelet.get2Shapelet(0).getAllOccurrences(this, epsilon);
Set<Integer> relevantPreviousIds = occurrences.stream()
.map(p -> p.getSecond())
.distinct()
.collect(Collectors.toSet());
for(int i=1;i<shapelet.numTwoShapelets();i++){
if(relevantPreviousIds.isEmpty()){
return false;
}
ShapeletSize2 curShapelet = shapelet.get2Shapelet(i);
Set<Integer> newPreviousIds = new HashSet<>();
for(int intervalId : relevantPreviousIds){
assert(getInterval(intervalId).getDimension()==curShapelet.getEventId1());
List<Integer> occ = curShapelet.getOccurrences(this,intervalId, epsilon);
newPreviousIds.addAll(occ);
}
relevantPreviousIds = newPreviousIds;
}
return !relevantPreviousIds.isEmpty();
}
public List<List<Integer>> getAllOccurrences(NShapelet shapelet,int epsilon) {
List<Pair<Integer, Integer>> occurrences = shapelet.get2Shapelet(0).getAllOccurrences(this, epsilon);
List<List<Integer>> allOccurrences = occurrences.stream().map(p -> {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(p.getFirst());
list.add(p.getSecond());
return list;
}).collect(Collectors.toList());
for(int i=1;i<shapelet.numTwoShapelets();i++){
if(allOccurrences.isEmpty()){
return allOccurrences;
}
Map<Integer,List<List<Integer>>> occurrencesByLastIntervalId = allOccurrences.stream().collect(Collectors.groupingBy(l -> l.get(l.size()-1)));
ShapeletSize2 curShapelet = shapelet.get2Shapelet(i);
List<Integer> listOfPreviousIntervalIdSorted = occurrencesByLastIntervalId.keySet().stream().sorted().collect(Collectors.toList());
List<List<Integer>> newAllOccurrences = new ArrayList<>();
for(int intervalId : listOfPreviousIntervalIdSorted){
assert(getInterval(intervalId).getDimension()==curShapelet.getEventId1());
List<Integer> fittingIntervalIds = curShapelet.getOccurrences(this,intervalId, epsilon);
for(Integer toAppend : fittingIntervalIds){
List<List<Integer>> allOccurrencesToAppendTo = occurrencesByLastIntervalId.get(intervalId);
for(int j=0;j<allOccurrencesToAppendTo.size();j++){
//for each element in fitting intervalIds, add a new list
List<Integer> occurrence= allOccurrencesToAppendTo.get(j);
ArrayList<Integer> newOccurrence = new ArrayList<>(occurrence);
newOccurrence.add(toAppend);
if(new HashSet<>(newOccurrence).size()==newOccurrence.size()){
//only occurrences with each interval being used only once are allowed
newAllOccurrences.add(newOccurrence);
}
}
}
}
allOccurrences = newAllOccurrences;
}
//sort all Occurrences, so that we always get the same order in each execution:
Collections.sort(allOccurrences, (l1,l2) ->{
int i=0;
while(l1.get(i).compareTo(l2.get(i))==0 && i<l1.size()){
i++;
}
if(i==l1.size()){
return 0;
} else{
return l1.get(i).compareTo(l2.get(i));
}
});
return allOccurrences;
}
/***
* Returns all intervals that are within the bounds given to the function
* @param startTimeInclusive
* @param endTimeInclusive
* @param intervalId... forbidden
* @return
*/
public List<Pair<Integer,Interval>> getIntervalsInTimeRange(int startTimeInclusive, int endTimeInclusive, int forbidden) {
List<Pair<Integer,Interval>> results = new ArrayList<>();
for(int i=0;i<intervals.size();i++){
Interval interval = intervals.get(i);
if(interval.getStart()>= startTimeInclusive && interval.getEnd() <= endTimeInclusive && i != forbidden){
results.add(new Pair<>(i,interval));
}
}
return results;
//TODO: mit binärsuche machen (codeschnipsel unten)
// assert(isSorted);
// int startIndex = 0;
// int endIndex = intervals.size();
// int equalIndex = -1;
// while(startIndex <=endIndex){
// int toCheck = startIndex + ((endIndex - startIndex) / 2);
// int curStart = intervals.get(toCheck).getStart();
// if(curStart == startTimeInclusive){
// equalIndex = toCheck;
// break;
// } else if(curStart>startTimeInclusive){
// endIndex = toCheck-1;
// } else{
// startIndex = toCheck+1;
// }
// }
}
@Override
public String toString(){
return intervals.toString();
}
public int getRelationship(int intervalId1, int intervalId2, int epsilon) {
assert(intervalId2>intervalId1);
Interval a = getInterval(intervalId1);
Interval b = getInterval(intervalId2);
return getRelationship(a.getStart(),a.getEnd(),b.getStart(),b.getEnd(),epsilon)-1; //-1 due to getRelationship being a different interface that stupidly starts counting at 1 (relly should fix that)
}
}
| gpl-3.0 |
guardianproject/proofmode | app/src/main/java/org/witness/proofmode/SettingsActivity.java | 8299 | package org.witness.proofmode;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import org.witness.proofmode.crypto.PgpUtils;
import org.witness.proofmode.util.GPSTracker;
public class SettingsActivity extends AppCompatActivity {
private final static int REQUEST_CODE_LOCATION = 1;
private final static int REQUEST_CODE_NETWORK_STATE = 2;
private final static int REQUEST_CODE_READ_PHONE_STATE = 3;
private final static int REQUEST_CODE_LOCATION_BACKGROUND = 4;
private SharedPreferences mPrefs;
private PgpUtils mPgpUtils;
private CheckBox switchLocation;
private CheckBox switchMobile;
private CheckBox switchDevice;
private CheckBox switchNotarize;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
TextView title = toolbar.findViewById(R.id.toolbar_title);
title.setText(getTitle());
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
switchLocation = (CheckBox)findViewById(R.id.switchLocation);
switchMobile = (CheckBox)findViewById(R.id.switchCellInfo);
switchDevice = (CheckBox)findViewById(R.id.switchDevice);
switchNotarize = (CheckBox) findViewById(R.id.switchNotarize);
updateUI();
switchLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
if (!askForPermission(Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_CODE_LOCATION, R.layout.permission_location)) {
if (!askForPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION, REQUEST_CODE_LOCATION_BACKGROUND, 0)) {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_LOCATION,isChecked).commit();
refreshLocation();
}
}
} else {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_LOCATION,isChecked).commit();
}
updateUI();
}
});
switchMobile.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
if (!askForPermission(Manifest.permission.ACCESS_NETWORK_STATE, REQUEST_CODE_NETWORK_STATE, 0)) {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_NETWORK,isChecked).commit();
}
} else {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_NETWORK,isChecked).commit();
}
updateUI();
}
});
switchDevice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
if (!askForPermission(Manifest.permission.READ_PHONE_STATE, REQUEST_CODE_READ_PHONE_STATE, 0)) {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_PHONE,isChecked).commit();
}
} else {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_PHONE,isChecked).commit();
}
updateUI();
}
});
switchNotarize.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_NOTARY, switchNotarize.isChecked()).commit();
updateUI();
}
});
}
private void updateUI() {
switchLocation.setChecked(mPrefs.getBoolean(ProofMode.PREF_OPTION_LOCATION,ProofMode.PREF_OPTION_LOCATION_DEFAULT));
switchMobile.setChecked(mPrefs.getBoolean(ProofMode.PREF_OPTION_NETWORK,ProofMode.PREF_OPTION_NETWORK_DEFAULT));
switchDevice.setChecked(mPrefs.getBoolean(ProofMode.PREF_OPTION_PHONE,ProofMode.PREF_OPTION_PHONE_DEFAULT));
switchNotarize.setChecked(mPrefs.getBoolean(ProofMode.PREF_OPTION_NOTARY,ProofMode.PREF_OPTION_NOTARY_DEFAULT));
}
@Override
protected void onResume() {
super.onResume();
updateUI();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//Location
case REQUEST_CODE_LOCATION:
if (PermissionActivity.hasPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION })) {
askForPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION, REQUEST_CODE_LOCATION_BACKGROUND, 0);
}
updateUI();
break;
case REQUEST_CODE_LOCATION_BACKGROUND:
if (PermissionActivity.hasPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION })) {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_LOCATION, true).commit();
refreshLocation();
}
updateUI();
break;
case REQUEST_CODE_NETWORK_STATE:
if (PermissionActivity.hasPermissions(this, new String[] { Manifest.permission.ACCESS_NETWORK_STATE })) {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_NETWORK, true).commit();
}
updateUI();
break;
case REQUEST_CODE_READ_PHONE_STATE:
if (PermissionActivity.hasPermissions(this, new String[] { Manifest.permission.READ_PHONE_STATE })) {
mPrefs.edit().putBoolean(ProofMode.PREF_OPTION_PHONE, true).commit();
}
updateUI();
break;
}
}
@Override
public void onBackPressed() {
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean askForPermission(String permission, Integer requestCode, int layoutId) {
String[] permissions = new String[] { permission };
if (!PermissionActivity.hasPermissions(this, permissions)) {
Intent intent = new Intent(this, PermissionActivity.class);
intent.putExtra(PermissionActivity.ARG_PERMISSIONS, permissions);
if (layoutId != 0) {
intent.putExtra(PermissionActivity.ARG_LAYOUT_ID, R.layout.permission_location);
}
startActivityForResult(intent, requestCode);
return true;
}
return false;
}
private void refreshLocation ()
{
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
gpsTracker.getLocation();
}
}
}
| gpl-3.0 |
sethten/MoDesserts | mcp50/temp/src/minecraft_server/net/minecraft/src/SlotCrafting.java | 4131 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
// Referenced classes of package net.minecraft.src:
// Slot, ItemStack, EntityPlayer, Block,
// AchievementList, Item, IInventory, InventoryPlayer
public class SlotCrafting extends Slot
{
private final IInventory field_20103_a;
private EntityPlayer field_25004_e;
private int field_48418_g;
public SlotCrafting(EntityPlayer p_i615_1_, IInventory p_i615_2_, IInventory p_i615_3_, int p_i615_4_, int p_i615_5_, int p_i615_6_)
{
super(p_i615_3_, p_i615_4_, p_i615_5_, p_i615_6_);
field_25004_e = p_i615_1_;
field_20103_a = p_i615_2_;
}
public boolean func_20095_a(ItemStack p_20095_1_)
{
return false;
}
public ItemStack func_20088_a(int p_20088_1_)
{
if(func_27006_b())
{
field_48418_g += Math.min(p_20088_1_, func_20092_c().field_853_a);
}
return super.func_20088_a(p_20088_1_);
}
protected void func_48415_a(ItemStack p_48415_1_, int p_48415_2_)
{
field_48418_g += p_48415_2_;
func_48416_b(p_48415_1_);
}
protected void func_48416_b(ItemStack p_48416_1_)
{
p_48416_1_.func_48584_a(field_25004_e.field_9093_l, field_25004_e, field_48418_g);
field_48418_g = 0;
if(p_48416_1_.field_855_c == Block.field_9044_ay.field_573_bc)
{
field_25004_e.func_25046_a(AchievementList.field_25130_d, 1);
} else
if(p_48416_1_.field_855_c == Item.field_4143_r.field_234_aS)
{
field_25004_e.func_25046_a(AchievementList.field_27110_i, 1);
} else
if(p_48416_1_.field_855_c == Block.field_642_aC.field_573_bc)
{
field_25004_e.func_25046_a(AchievementList.field_27109_j, 1);
} else
if(p_48416_1_.field_855_c == Item.field_4166_L.field_234_aS)
{
field_25004_e.func_25046_a(AchievementList.field_27107_l, 1);
} else
if(p_48416_1_.field_855_c == Item.field_185_S.field_234_aS)
{
field_25004_e.func_25046_a(AchievementList.field_27106_m, 1);
} else
if(p_48416_1_.field_855_c == Item.field_21098_aX.field_234_aS)
{
field_25004_e.func_25046_a(AchievementList.field_27105_n, 1);
} else
if(p_48416_1_.field_855_c == Item.field_4139_v.field_234_aS)
{
field_25004_e.func_25046_a(AchievementList.field_27104_o, 1);
} else
if(p_48416_1_.field_855_c == Item.field_4145_p.field_234_aS)
{
field_25004_e.func_25046_a(AchievementList.field_27101_r, 1);
} else
if(p_48416_1_.field_855_c == Block.field_40175_bF.field_573_bc)
{
field_25004_e.func_25046_a(AchievementList.field_40472_D, 1);
} else
if(p_48416_1_.field_855_c == Block.field_604_ao.field_573_bc)
{
field_25004_e.func_25046_a(AchievementList.field_40474_F, 1);
}
}
public void func_20091_b(ItemStack p_20091_1_)
{
func_48416_b(p_20091_1_);
for(int i = 0; i < field_20103_a.func_83_a(); i++)
{
ItemStack itemstack = field_20103_a.func_82_a(i);
if(itemstack == null)
{
continue;
}
field_20103_a.func_20069_a(i, 1);
if(!itemstack.func_569_a().func_21088_g())
{
continue;
}
ItemStack itemstack1 = new ItemStack(itemstack.func_569_a().func_21087_f());
if(itemstack.func_569_a().func_46004_e(itemstack) && field_25004_e.field_416_aj.func_201_a(itemstack1))
{
continue;
}
if(field_20103_a.func_82_a(i) == null)
{
field_20103_a.func_206_a(i, itemstack1);
} else
{
field_25004_e.func_48348_b(itemstack1);
}
}
}
}
| gpl-3.0 |
PE-INTERNATIONAL/soda4lca | Registry/src/test/java/eu/europa/ec/jrc/lca/registry/service/DataSetDeregistrationServiceTest.java | 4534 | package eu.europa.ec.jrc.lca.registry.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.NoResultException;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import eu.europa.ec.jrc.lca.commons.rest.dto.DataSetDTO;
import eu.europa.ec.jrc.lca.commons.rest.dto.DataSetDeregistrationResult;
import eu.europa.ec.jrc.lca.commons.service.exceptions.DatasetIllegalStatusException;
import eu.europa.ec.jrc.lca.registry.dao.DataSetDao;
import eu.europa.ec.jrc.lca.registry.domain.DataSet;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/spring-context-test.xml" })
public class DataSetDeregistrationServiceTest {
@Autowired
private DataSetDeregistrationService dataSetDeregistrationService;
@Autowired
private NotificationService notificationService;
@Autowired
private DataSetDao dataSetDao;
@Before
public void setMockFields() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{
SendMailService sendMailService = Mockito.mock(SendMailService.class);
notificationService.setSendMailService(sendMailService);
BroadcastingService broadcastingService = Mockito.mock(BroadcastingService.class);
dataSetDeregistrationService.setBroadcastingService(broadcastingService);
}
@Test
public void testDeregisterDataSetsInternal() throws DatasetIllegalStatusException{
DataSet ds1 = dataSetDao.findByUUID("UUID_1").get(0);
DataSet ds2 = dataSetDao.findByUUID("UUID_3").get(0);
dataSetDeregistrationService.deregisterDataSets(Arrays.asList(new DataSet[]{ds1, ds2}));
Assert.assertEquals(0, dataSetDao.findByUUID("UUID_1").size());
Assert.assertEquals(0, dataSetDao.findByUUID("UUID_3").size());
}
@Test(expected=DatasetIllegalStatusException.class)
public void testDeregisterDataSetsInternalNotAccepted() throws DatasetIllegalStatusException{
DataSet ds1 = dataSetDao.findByUUID("UUID_2").get(0);
dataSetDeregistrationService.deregisterDataSets(Arrays.asList(new DataSet[]{ds1}));
}
@Test
public void testDeregisterDataSetsExternalWhenVersionDoesntExist(){
List<DataSetDTO> datasets = new ArrayList<DataSetDTO>();
datasets.add(new DataSetDTO("UUID_6", "2.00.00"));
List<DataSetDeregistrationResult> result = dataSetDeregistrationService.deregisterDataSets(datasets, "reason", "testNodeId1");
Assert.assertEquals(1, result.size());
Assert.assertEquals(DataSetDeregistrationResult.REJECTED_NOT_FOUND, result.get(0));
Assert.assertNotNull(dataSetDao.findByUUIDAndVersionAndNode("UUID_6", "1.00.00", "testNodeId1"));
}
@Test
public void testDeregisterDataSetsExternalWhenDSDoesntExist(){
List<DataSetDTO> datasets = new ArrayList<DataSetDTO>();
datasets.add(new DataSetDTO("UUID_7", "1.00.00"));
List<DataSetDeregistrationResult> result = dataSetDeregistrationService.deregisterDataSets(datasets, "reason", "testNodeId1");
Assert.assertEquals(1, result.size());
Assert.assertEquals(DataSetDeregistrationResult.REJECTED_NOT_FOUND, result.get(0));
Assert.assertNotNull(dataSetDao.findByUUIDAndVersionAndNode("UUID_7", "1.00.00", "testNodeId2"));
}
@Test
public void testDeregisterDataSetsExternalWhenNotAccepted(){
List<DataSetDTO> datasets = new ArrayList<DataSetDTO>();
datasets.add(new DataSetDTO("UUID_5", "1.00.00"));
List<DataSetDeregistrationResult> result = dataSetDeregistrationService.deregisterDataSets(datasets, "reason", "testNodeId1");
Assert.assertEquals(1, result.size());
Assert.assertEquals(DataSetDeregistrationResult.REJECTED_WRONG_STATUS, result.get(0));
Assert.assertNotNull(dataSetDao.findByUUIDAndVersionAndNode("UUID_5", "1.00.00", "testNodeId1"));
}
@Test(expected=NoResultException.class)
public void testDeregisterDataSetsExternal(){
List<DataSetDTO> datasets = new ArrayList<DataSetDTO>();
datasets.add(new DataSetDTO("UUID_4", "1.00.00"));
List<DataSetDeregistrationResult> result = dataSetDeregistrationService.deregisterDataSets(datasets, "reason", "testNodeId1");
Assert.assertEquals(1, result.size());
Assert.assertEquals(DataSetDeregistrationResult.DEREGISTERED, result.get(0));
dataSetDao.findByUUIDAndVersionAndNode("UUID_4", "1.00.00", "testNodeId1");
}
}
| gpl-3.0 |
AnyObject/OAT | src/OAT/trading/client/IbHistDataClient.java | 6473 | /*
Open Auto Trading : A fully automatic equities trading platform with machine learning capabilities
Copyright (C) 2015 AnyObject Ltd.
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 OAT.trading.client;
import com.google.common.collect.HashBiMap;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import OAT.data.Bar;
import OAT.data.BarDataset;
import OAT.trading.thread.BaseThread;
import OAT.trading.thread.DataThread;
import OAT.util.DateUtil;
/**
*
* @author Antonio Yip
*/
public class IbHistDataClient extends IbClient implements HistDataClient {
private Map<Integer, DataThread> dataThreadMap = new HashMap<Integer, DataThread>();
private HashBiMap<Integer, BarDataset> chartMap = HashBiMap.create();
public IbHistDataClient(BaseThread baseThread) {
super(baseThread);
}
@Override
public int getClientId() {
return 40;
}
/**
* Request historical data.
*
* @param dataThread
* @param chart
* @param end
* @param duration
*/
@Override
public void reqHistoricalData(final DataThread dataThread, final BarDataset chart, final long end, final long duration) {
connect();
// new Thread(new Runnable() {
//
// @Override
// public void run() {
if (chart == null) {
return;
}
int reqId = REQ_HISTORICAL_DATA_I + dataThread.getThreadId();
if (chartMap.containsValue(chart)) {
return;
}
while (chartMap.containsKey(reqId)) {
reqId++;
}
chartMap.put(reqId, chart);
dataThreadMap.put(reqId, dataThread);
dataThread.log(Level.FINE, "reqHistoricalData #{0}: {1} {2}",
new Object[]{
String.valueOf(reqId),
chart.getTitle(),
DateUtil.getHistDataDurationStr(duration)});
eClientSocket.reqHistoricalData(
reqId,
dataThread.getContract(),
DateUtil.getTimeStamp(end, "yyyyMMdd HH:mm:ss"),
DateUtil.getHistDataDurationStr(duration),
DateUtil.getHistDataBarSizeStr(chart.getBarSize()),
"TRADES", 1, 2);
// }
// }).start();
}
@Override
public void cancelHistoricalData(DataThread dataThread, BarDataset chart) {
if (!eClientSocket.isConnected()) {
return;
}
int reqId = chartMap.inverse().get(chart);
eClientSocket.cancelHistoricalData(reqId);
chartMap.remove(reqId);
}
//
//com.ib.client.Ewrapper
//
@Override
public void error(final int id, final int errorCode, final String errorMsg) {
// new Thread(new Runnable() {
//
// @Override
// public void run() {
DataThread dataThread = dataThreadMap.get(id);
int typeId = getReqTypeId(id);
if (errorCode == 322) { // Duplicate Id
logError(Level.WARNING, id, errorCode, errorMsg);
} else {
switch (typeId) {
case REQ_HISTORICAL_DATA_I:
logError(Level.WARNING, id, errorCode, errorMsg);
BarDataset reqChart = chartMap.get(id);
if (reqChart != null) {
dataThread.log(Level.WARNING,
"Error getting historical data: {0}",
reqChart.getTitle());
}
chartMap.remove(id);
return;
default:
unhandledError(id, errorCode, errorMsg);
}
}
// }
// }).start();
}
@Override
public void historicalData(final int reqId, final String date, final double open, final double high, final double low, final double close, final int volume, final int count, final double wap, final boolean hasGaps) {
// new Thread(new Runnable() {
//
// @Override
// public void run() {
try {
DataThread dataThread = dataThreadMap.get(reqId);
if (dataThread != null) {
BarDataset reqChart = chartMap.get(reqId);
if (reqChart != null) {
if (date.contains("finished")) {
reqChart.fireDatasetChanged();
dataThread.log(Level.FINE,
"histData #{0}: {1}",
new Object[]{
String.valueOf(reqId),
reqChart});
chartMap.remove(reqId);
} else {
Bar newBar = new Bar(
Long.parseLong(date) * 1000,
open, high, low, close,
volume, wap, count);
reqChart.add(newBar, false);
}
}
}
} catch (Exception e) {
log(Level.SEVERE, null, e);
}
// }
// }).start();
super.historicalData(reqId, date, open, high, low, close, volume, count, wap, hasGaps);
}
}
| gpl-3.0 |
CubeIsland/AntiGuest | src/main/java/de/cubeisland/antiguest/commands/PreventionManagementCommands.java | 8951 | package de.cubeisland.antiguest.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.cubeisland.antiguest.prevention.Prevention;
import de.cubeisland.antiguest.prevention.PreventionManager;
import de.cubeisland.libMinecraft.ChatColor;
import de.cubeisland.libMinecraft.command.Command;
import de.cubeisland.libMinecraft.command.CommandArgs;
import de.cubeisland.libMinecraft.command.RequiresPermission;
import static de.cubeisland.antiguest.AntiGuest.t;
/**
* @author CodeInfection
*/
public class PreventionManagementCommands
{
private final PreventionManager pm;
public PreventionManagementCommands()
{
this.pm = PreventionManager.getInstance();
}
@Command(usage = "<prevention|*> [-t]")
@RequiresPermission
public void enable(CommandSender sender, CommandArgs args)
{
if (args.size() > 0)
{
boolean temporary = args.hasFlag("t");
if ("*".equals(args.getString(0)))
{
for (Prevention prevention : this.pm.getPreventions())
{
this.pm.enablePrevention(prevention);
if (!temporary)
{
prevention.getConfig().set("enable", true);
prevention.saveConfig();
}
}
sender.sendMessage(t("preventionsEnabled"));
}
else
{
Prevention prevention = this.pm.getPrevention(args.getString(0));
if (prevention != null)
{
if (!prevention.isEnabled())
{
if (PreventionManager.getInstance().enablePrevention(prevention))
{
sender.sendMessage(t("preventionEnabled"));
if (!temporary)
{
prevention.getConfig().set("enable", true);
prevention.saveConfig();
}
}
else
{
sender.sendMessage(t("somethingFailed"));
}
}
else
{
sender.sendMessage(t("alreadyEnabled"));
}
}
else
{
sender.sendMessage(t("preventionNotFound"));
}
}
}
else
{
sender.sendMessage(t("noPrevention"));
}
}
@Command(usage = "<prevention> [-t]")
@RequiresPermission
public void disable(CommandSender sender, CommandArgs args)
{
if (args.size() > 0)
{
boolean temporary = args.hasFlag("t");
if ("*".equals(args.getString(0)))
{
for (Prevention prevention : this.pm.getPreventions())
{
this.pm.disablePrevention(prevention);
if (!temporary)
{
prevention.getConfig().set("enable", false);
prevention.saveConfig();
}
}
sender.sendMessage(t("preventionsDisabled"));
}
else
{
Prevention prevention = PreventionManager.getInstance().getPrevention(args.getString(0));
if (prevention != null)
{
if (prevention.isEnabled())
{
PreventionManager.getInstance().disablePrevention(prevention);
sender.sendMessage(t("preventionDisabled"));
if (!temporary)
{
prevention.getConfig().set("enable", false);
prevention.saveConfig();
}
}
else
{
sender.sendMessage(t("alreadyDisabled"));
}
}
else
{
sender.sendMessage(t("preventionNotFound"));
}
}
}
else
{
sender.sendMessage(t("noPrevention"));
}
}
@Command(usage = "<prevention>")
@RequiresPermission
public void enabled(CommandSender sender, CommandArgs args)
{
if (args.size() > 0)
{
Prevention prevention = PreventionManager.getInstance().getPrevention(args.getString(0));
if (prevention != null)
{
if (prevention.isEnabled())
{
sender.sendMessage(t("enabled"));
}
else
{
sender.sendMessage(t("disabled"));
}
}
else
{
sender.sendMessage(t("preventionNotFound"));
}
}
else
{
sender.sendMessage(t("noPrevention"));
}
}
@Command(usage = "[-a]")
@RequiresPermission
public void list(CommandSender sender, CommandArgs args)
{
if (args.hasFlag("a"))
{
sender.sendMessage(t("registeredPreventions"));
sender.sendMessage("");
for (Prevention prevention : PreventionManager.getInstance().getPreventions())
{
sender
.sendMessage(" - " + (prevention.isEnabled() ? ChatColor.BRIGHT_GREEN : ChatColor.RED) + prevention
.getName());
}
sender.sendMessage("");
}
else
{
sender.sendMessage(t("activePreventions"));
sender.sendMessage("");
for (Prevention prevention : PreventionManager.getInstance().getPreventions())
{
if (prevention.isEnabled())
{
sender.sendMessage(" - " + ChatColor.BRIGHT_GREEN + prevention.getName());
}
}
sender.sendMessage("");
}
}
@Command(usage = "[player] <prevention>")
@RequiresPermission
public void can(CommandSender sender, CommandArgs args)
{
Player player;
Prevention prevention;
if (args.size() > 1)
{
player = args.getBaseCommand().getPlugin().getServer().getPlayer(args.getString(0));
prevention = this.pm.getPrevention(args.getString(1));
}
else if (args.size() > 0 && sender instanceof Player)
{
player = (Player)sender;
prevention = this.pm.getPrevention(args.getString(0));
}
else
{
sender.sendMessage(t("tooFewArguments"));
sender.sendMessage(t("see", args.getBaseLabel() + " help"));
return;
}
if (player != null)
{
if (prevention != null)
{
if (prevention.can(player))
{
if (sender == player)
{
sender.sendMessage(t("you_ableToPass"));
}
else
{
sender.sendMessage(t("other_ableToPass"));
}
}
else
{
if (sender == player)
{
sender.sendMessage(t("you_unableToPass"));
}
else
{
sender.sendMessage(t("other_unableToPass"));
}
}
}
else
{
sender.sendMessage(t("preventionNotFound"));
}
}
else
{
sender.sendMessage(t("playerNotFound"));
}
}
@Command(usage = "<prevention> <message>")
@RequiresPermission
public void setMessage(CommandSender sender, CommandArgs args)
{
if (args.size() > 1)
{
Prevention prevention = PreventionManager.getInstance().getPrevention(args.getString(0));
if (prevention != null)
{
String message = args.getString(1);
prevention.setMessage(message);
prevention.getConfig().set("message", message);
prevention.saveConfig();
sender.sendMessage(t("messageSet"));
}
else
{
sender.sendMessage(t("preventionNotFound"));
}
}
else
{
sender.sendMessage(t("tooFewArguments"));
}
}
}
| gpl-3.0 |
shuqin/ALLIN | src/main/java/zzz/study/javatech/serialization/Point2.java | 652 | package zzz.study.javatech.serialization;
import java.io.Serializable;
public class Point2 implements Serializable {
// 添加了 serialVersionUID
private static final long serialVersionUID = 1L;
private int x;
private int y; // 在对象序列化后添加 字段 y , 模拟软件版本升级
public Point2() {
this.x = 0;
}
public Point2(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public String toString() {
// return "" + x;
return "(" + x + ", " + y + ")"; // 添加字段 y 后
}
}
| gpl-3.0 |
Relicum/Ipsum | src/main/java/com/relicum/ipsum/Commands/Group/IMessageFormat.java | 2201 | /*
* Ipsum is a rapid development API for Minecraft, developer by Relicum
* Copyright (C) 2014. Chris Lutte
*
* 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.relicum.ipsum.Commands.Group;
import org.bukkit.ChatColor;
/**
* The interface for creating a standard plugin message format.
*/
public interface IMessageFormat<T extends IMessageFormat> {
/**
* Sets standard message color.
*
* @param messageColor the standard message color
* @return the instance of itself so methods can be chained
*/
public T setStdMessageColor(ChatColor messageColor);
/**
* Sets error message color.
*
* @param errorMessageColor the error message color
* @return the instance of itself so methods can be chained
*/
public T setErrorMessageColor(ChatColor errorMessageColor);
/**
* Sets highlighter color, used to highlight parts of a message.
*
* @param highlighterColor the highlighter color
* @return the instance of itself so methods can be chained
*/
public T setHighlighterColor(ChatColor highlighterColor);
/**
* Sets admin color, used to display message when using admin commands.
*
* @param adminColor the admin color
* @return the instance of itself so methods can be chained
*/
public T setAdminColor(ChatColor adminColor);
/**
* Sets prefix that will be used at the start of all messages.
*
* @param prefix the prefix
* @return the instance of itself so methods can be chained
*/
public T setPrefix(Prefix prefix);
}
| gpl-3.0 |
MirakelX/davdroid | app/src/main/java/at/bitfire/davdroid/ui/settings/AccountFragment.java | 5486 | /*
* Copyright (c) 2013 – 2015 Ricki Hirner (bitfire web engineering).
* 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 at.bitfire.davdroid.ui.settings;
import android.accounts.Account;
import android.os.Build;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import at.bitfire.davdroid.mirakel.R;
import at.bitfire.davdroid.syncadapter.AccountSettings;
import ezvcard.VCardVersion;
import lombok.Setter;
public class AccountFragment extends PreferenceFragment {
final static String ARG_ACCOUNT = "account";
Account account;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_account_prefs);
account = getArguments().getParcelable(ARG_ACCOUNT);
readFromAccount();
}
public void readFromAccount() {
final AccountSettings settings = new AccountSettings(getActivity(), account);
// category: authentication
final EditTextPreference prefUserName = (EditTextPreference)findPreference("username");
prefUserName.setSummary(settings.getUserName());
prefUserName.setText(settings.getUserName());
prefUserName.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
settings.setUserName((String)newValue);
readFromAccount();
return true;
}
});
final EditTextPreference prefPassword = (EditTextPreference)findPreference("password");
prefPassword.setText(settings.getPassword());
prefPassword.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
settings.setPassword((String)newValue);
readFromAccount();
return true;
}
});
final SwitchPreference prefPreemptive = (SwitchPreference)findPreference("preemptive");
prefPreemptive.setChecked(settings.getPreemptiveAuth());
prefPreemptive.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
settings.setPreemptiveAuth((Boolean)newValue);
readFromAccount();
return true;
}
});
// category: synchronization
final ListPreference prefSyncContacts = (ListPreference)findPreference("sync_interval_contacts");
final Long syncIntervalContacts = settings.getContactsSyncInterval();
if (syncIntervalContacts != null) {
prefSyncContacts.setValue(syncIntervalContacts.toString());
if (syncIntervalContacts == AccountSettings.SYNC_INTERVAL_MANUALLY)
prefSyncContacts.setSummary(R.string.settings_sync_summary_manually);
else
prefSyncContacts.setSummary(getString(R.string.settings_sync_summary_periodically, syncIntervalContacts / 60));
prefSyncContacts.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
settings.setContactsSyncInterval(Long.parseLong((String)newValue));
readFromAccount();
return true;
}
});
} else {
prefSyncContacts.setEnabled(false);
prefSyncContacts.setSummary(R.string.settings_sync_summary_not_available);
}
final ListPreference prefSyncCalendars = (ListPreference)findPreference("sync_interval_calendars");
final Long syncIntervalCalendars = settings.getCalendarsSyncInterval();
if (syncIntervalCalendars != null) {
prefSyncCalendars.setValue(syncIntervalCalendars.toString());
if (syncIntervalCalendars == AccountSettings.SYNC_INTERVAL_MANUALLY)
prefSyncCalendars.setSummary(R.string.settings_sync_summary_manually);
else
prefSyncCalendars.setSummary(getString(R.string.settings_sync_summary_periodically, syncIntervalCalendars / 60));
prefSyncCalendars.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
settings.setCalendarsSyncInterval(Long.parseLong((String)newValue));
readFromAccount();
return true;
}
});
} else {
prefSyncCalendars.setEnabled(false);
prefSyncCalendars.setSummary(R.string.settings_sync_summary_not_available);
}
// category: address book
final CheckBoxPreference prefVCard4 = (CheckBoxPreference) findPreference("vcard4_support");
if (settings.getAddressBookURL() != null) { // does this account even have an address book?
final VCardVersion vCardVersion = settings.getAddressBookVCardVersion();
prefVCard4.setChecked(vCardVersion == VCardVersion.V4_0);
prefVCard4.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// don't change the value (it's not really a setting, only a display)
return false;
}
});
} else {
// account doesn't have an adress book, disable contact settings
prefVCard4.setEnabled(false);
}
}
}
| gpl-3.0 |
Gabrui/ces28_2017_gabriel-adriano | Labs/Lab4/test/Test/NotaFiscalTesteIVs.java | 1483 | package Test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import bancoDados.BDfake;
import notaFiscal.NotaFiscal;
import notaFiscal.NotaFiscalBuilder;
public class NotaFiscalTesteIVs {
BDfake bd;
NotaFiscalBuilder NFB;
NotaFiscalBuilder NFB2;
NotaFiscal NF;
@Before
public void setup() {
bd = new BDfake();
NFB = new NotaFiscalBuilder(bd);
NFB2 = new NotaFiscalBuilder(bd);
NFB2.adicionaItem("banana", 1);
NFB2.adicionaItem("pera", 2);
NFB2.adicionaItem("laranja", 5);
}
@Test
public void TestingAddingItemsOnBuilder() {
NFB.adicionaItem("banana", 1);
NFB.adicionaItem("pera", 3);
NF = NFB.buildEsboco();
assertEquals("banana\npera\n",NF.nomeItens());
}
@Test(expected = IllegalArgumentException.class)
public void ItemAddedOnBuilderDoesNotExistOnBD_ExpectIllegalArgumentException() {
NFB.adicionaItem("banana", 1);
NFB.adicionaItem("pera", 3);
NFB.adicionaItem("ps4", 1);
}
@Test(expected = IllegalArgumentException.class)
public void BuilderShouldNotGenerateEmptyNFAsEsboco_ExpectIllegalArgumentExceptio() {
NF = NFB.buildEsboco();
}
@Test(expected = IllegalArgumentException.class)
public void BuilderShouldNotValidateEmptyNF_ExpectIllegalArgumentExceptio() {
NF = NFB.valida();
}
@Test
public void TestingDeletingOnBuilderIfNUmberOfProductsAreHighterThanOne() {
NFB2.deletaItem("pera");
NF = NFB2.buildEsboco();
assertEquals("banana\nlaranja\n",NF.nomeItens());
}
}
| gpl-3.0 |
galenasphaug/Java | Unicoder/Unicoder.java | 1432 | import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class Unicoder {
public static void main(String[] args) {
//File containing unicode characters and values
File unicode = new File("/home/galenasphaug/data/unicode");
//Where we will store it (to keep file reading to a minimum)
HashMap<String, Integer> unicodeMap = new HashMap<>();
Scanner file = null; //Reads the file
Scanner stdin = new Scanner(System.in); //For user input
try {
file = new Scanner(unicode);
} catch (FileNotFoundException e) {
System.err.println("Can't find unicode file: " + unicode.getAbsolutePath());
System.exit(1);
}
while (file.hasNext()) {
int value = Integer.parseInt(file.next(), 16);
String key = file.next();
unicodeMap.put(key, value); //Add to map by value and decimal number
}
file.close(); //Close the file scanner
while (stdin.hasNext()) {
String input = stdin.next(); //User input
int output = 65; //Our unicode character in base-10
try {
output = unicodeMap.get(input); //See if we can find the user input in the HashMap
} catch (Exception e) {
main(null); //If we can't find it, try again.
}
System.out.print((char)output); //Print the character by casting it to char
}
stdin.close();
System.out.printf("\n");
}
}
| gpl-3.0 |
regueiro/easyRepair | src/StockUI/src/es/regueiro/easyrepair/ui/stock/PartTableCellRenderer.java | 980 | package es.regueiro.easyrepair.ui.stock;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
/**
*
* @author Santi
*/
public class PartTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component comp = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
int rowN = table.convertRowIndexToModel(row);
String s = table.getModel().getValueAt(rowN, 6).toString();
if (s.equalsIgnoreCase("yes")) {
comp.setForeground(Color.LIGHT_GRAY);
} else {
comp.setForeground(null);
}
return (comp);
}
}
| gpl-3.0 |
beldenge/Zenith | zenith-genetic-algorithm/src/main/java/com/ciphertool/zenith/genetic/population/Population.java | 4812 | /*
* Copyright 2017-2020 George Belden
*
* This file is part of Zenith.
*
* Zenith 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.
*
* Zenith 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
* Zenith. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ciphertool.zenith.genetic.population;
import com.ciphertool.zenith.genetic.GeneticAlgorithmStrategy;
import com.ciphertool.zenith.genetic.entities.Chromosome;
import com.ciphertool.zenith.genetic.entities.Gene;
import com.ciphertool.zenith.genetic.entities.Genome;
import com.ciphertool.zenith.genetic.entities.Parents;
import com.ciphertool.zenith.genetic.statistics.GenerationStatistics;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface Population {
Population getInstance();
void init(GeneticAlgorithmStrategy strategy);
Genome evaluateFitness(GenerationStatistics generationStatistics);
List<Genome> breed(int numberToBreed);
List<Parents> select();
void clearIndividuals();
int size();
List<Genome> getIndividuals();
boolean addIndividual(Genome individual);
void sortIndividuals();
@SuppressWarnings({"unchecked"})
default BigDecimal calculateEntropy() {
List<BigDecimal> entropies = new ArrayList<>(getIndividuals().get(0).getChromosomes().size());
for (int i = 0; i < getIndividuals().get(0).getChromosomes().size(); i ++) {
Map<Object, Map<Object, Integer>> symbolCounts = new HashMap<>();
Object geneKey;
Object geneValue;
Integer currentCount;
Map<Object, Integer> symbolCountMap;
// Count occurrences of each Gene value
for (Genome genome : getIndividuals()) {
Chromosome chromosome = genome.getChromosomes().get(i);
for (Map.Entry<Object, Gene> entry : ((Chromosome<Object>) chromosome).getGenes().entrySet()) {
geneKey = entry.getKey();
if (symbolCounts.containsKey(geneKey)) {
symbolCounts.put(geneKey, new HashMap<>());
}
symbolCountMap = symbolCounts.get(geneKey);
geneValue = entry.getValue();
currentCount = symbolCountMap.get(geneValue);
symbolCountMap.put(geneValue, (currentCount != null) ? (currentCount + 1) : 1);
}
}
Map<Object, Map<Object, Double>> symbolProbabilities = new HashMap<>();
double populationSize = this.size();
Map<Object, Double> probabilityMap;
// Calculate probability of each Gene value
for (Map.Entry<Object, Map<Object, Integer>> entry : symbolCounts.entrySet()) {
probabilityMap = new HashMap<>();
symbolProbabilities.put(entry.getKey(), probabilityMap);
for (Map.Entry<Object, Integer> entryInner : entry.getValue().entrySet()) {
probabilityMap.put(entryInner.getKey(), ((double) entryInner.getValue() / populationSize));
}
}
int base = symbolCounts.size();
double totalEntropy = 0.0;
// Calculate the Shannon entropy of each Gene independently, and add it to the total entropy value
for (Map.Entry<Object, Map<Object, Double>> entry : symbolProbabilities.entrySet()) {
for (Map.Entry<Object, Double> entryInner : entry.getValue().entrySet()) {
totalEntropy += (entryInner.getValue() * logBase(entryInner.getValue(), base));
}
}
totalEntropy *= -1.0;
// Use the average entropy among the symbols
entropies.add(BigDecimal.valueOf(totalEntropy / (double) symbolProbabilities.size()));
}
// Return the average entropy among all chromosomes
return BigDecimal.valueOf(entropies.stream().mapToDouble(BigDecimal::doubleValue).sum() / entropies.size());
}
// Use the change of base formula to calculate the logarithm with an arbitrary base
static double logBase(double num, int base) {
return (Math.log(num) / Math.log(base));
}
Double getTotalFitness();
Double getTotalProbability();
}
| gpl-3.0 |
mimi89999/librus-client | app/src/main/java/pl/librus/client/data/db/LocalDateConverter.java | 998 | package pl.librus.client.data.db;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import io.requery.Converter;
/**
* Created by robwys on 04/02/2017.
*/
public class LocalDateConverter implements Converter<LocalDate, Long> {
@Override
public Class<LocalDate> getMappedType() {
return LocalDate.class;
}
@Override
public Class<Long> getPersistedType() {
return Long.class;
}
@Override
public Integer getPersistedSize() {
return null;
}
@Override
public Long convertToPersisted(LocalDate value) {
if (value == null) {
return null;
}
return value.toDateTimeAtStartOfDay(DateTimeZone.UTC).getMillis();
}
@Override
public LocalDate convertToMapped(Class<? extends LocalDate> type, Long value) {
if (value == null) {
return null;
}
return new LocalDate(value, DateTimeZone.UTC);
}
} | gpl-3.0 |
nfloersch/wpgis | org/pepsoft/minecraft/ChunkImpl.java | 8700 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.pepsoft.minecraft;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.jnbt.CompoundTag;
import org.jnbt.Tag;
import static org.pepsoft.minecraft.Constants.*;
/**
* An "MCRegion" chunk.
*
* @author pepijn
*/
public final class ChunkImpl extends AbstractNBTItem implements Chunk {
public ChunkImpl(int xPos, int zPos, int maxHeight) {
super(new CompoundTag(TAG_LEVEL, new HashMap<String, Tag>()));
this.xPos = xPos;
this.zPos = zPos;
this.maxHeight = maxHeight;
blocks = new byte[256 * maxHeight];
data = new byte[128 * maxHeight];
skyLight = new byte[128 * maxHeight];
blockLight = new byte[128 * maxHeight];
heightMap = new byte[256];
entities = new ArrayList<Entity>();
tileEntities = new ArrayList<TileEntity>();
readOnly = false;
}
public ChunkImpl(CompoundTag tag, int maxHeight) {
this(tag, maxHeight, false);
}
public ChunkImpl(CompoundTag tag, int maxHeight, boolean readOnly) {
super((CompoundTag) tag.getTag(TAG_LEVEL));
this.maxHeight = maxHeight;
this.readOnly = readOnly;
blocks = getByteArray(TAG_BLOCKS);
data = getByteArray(TAG_DATA);
skyLight = getByteArray(TAG_SKY_LIGHT);
blockLight = getByteArray(TAG_BLOCK_LIGHT);
heightMap = getByteArray(TAG_HEIGHT_MAP);
List<Tag> entityTags = getList(TAG_ENTITIES);
entities = new ArrayList<Entity>(entityTags.size());
for (Tag entityTag: entityTags) {
entities.add(Entity.fromNBT(entityTag));
}
List<Tag> tileEntityTags = getList(TAG_TILE_ENTITIES);
tileEntities = new ArrayList<TileEntity>(tileEntityTags.size());
for (Tag tileEntityTag: tileEntityTags) {
tileEntities.add(TileEntity.fromNBT(tileEntityTag));
}
// TODO: last update is ignored, is that correct?
xPos = getInt(TAG_X_POS);
zPos = getInt(TAG_Z_POS);
terrainPopulated = getBoolean(TAG_TERRAIN_POPULATED);
}
@Override
public Tag toNBT() {
setByteArray(TAG_BLOCKS, blocks);
setByteArray(TAG_DATA, data);
setByteArray(TAG_SKY_LIGHT, skyLight);
setByteArray(TAG_BLOCK_LIGHT, blockLight);
setByteArray(TAG_HEIGHT_MAP, heightMap);
List<Tag> entityTags = new ArrayList<Tag>(entities.size());
for (Entity entity: entities) {
entityTags.add(entity.toNBT());
}
setList(TAG_ENTITIES, CompoundTag.class, entityTags);
List<Tag> tileEntityTags = new ArrayList<Tag>(entities.size());
for (TileEntity tileEntity: tileEntities) {
tileEntityTags.add(tileEntity.toNBT());
}
setList(TAG_TILE_ENTITIES, CompoundTag.class, tileEntityTags);
setLong(TAG_LAST_UPDATE, System.currentTimeMillis());
setInt(TAG_X_POS, xPos);
setInt(TAG_Z_POS, zPos);
setBoolean(TAG_TERRAIN_POPULATED, terrainPopulated);
return new CompoundTag("", Collections.singletonMap("", super.toNBT()));
}
@Override
public int getMaxHeight() {
return maxHeight;
}
@Override
public int getxPos() {
return xPos;
}
@Override
public int getzPos() {
return zPos;
}
@Override
public Point getCoords() {
return new Point(xPos, zPos);
}
@Override
public int getBlockType(int x, int y, int z) {
return blocks[blockOffset(x, y, z)] & 0xFF;
}
@Override
public void setBlockType(int x, int y, int z, int blockType) {
if (readOnly) {
return;
}
blocks[blockOffset(x, y, z)] = (byte) blockType;
}
@Override
public int getDataValue(int x, int y, int z) {
return getDataByte(data, x, y, z);
}
@Override
public void setDataValue(int x, int y, int z, int dataValue) {
if (readOnly) {
return;
}
setDataByte(data, x, y, z, dataValue);
}
@Override
public int getSkyLightLevel(int x, int y, int z) {
return getDataByte(skyLight, x, y, z);
}
@Override
public void setSkyLightLevel(int x, int y, int z, int skyLightLevel) {
if (readOnly) {
return;
}
setDataByte(skyLight, x, y, z, skyLightLevel);
}
@Override
public int getBlockLightLevel(int x, int y, int z) {
return getDataByte(blockLight, x, y, z);
}
@Override
public void setBlockLightLevel(int x, int y, int z, int blockLightLevel) {
if (readOnly) {
return;
}
setDataByte(blockLight, x, y, z, blockLightLevel);
}
@Override
public boolean isBiomesAvailable() {
throw new UnsupportedOperationException("Not supported");
}
@Override
public int getBiome(int x, int z) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void setBiome(int x, int z, int biome) {
throw new UnsupportedOperationException("Not supported");
}
@Override
public int getHeight(int x, int z) {
return heightMap[x + z * 16] & 0xFF;
}
@Override
public void setHeight(int x, int z, int height) {
if (readOnly) {
return;
}
heightMap[x + z * 16] = (byte) (Math.min(height, 255));
}
@Override
public boolean isTerrainPopulated() {
return terrainPopulated;
}
@Override
public void setTerrainPopulated(boolean terrainPopulated) {
if (readOnly) {
return;
}
this.terrainPopulated = terrainPopulated;
}
@Override
public List<Entity> getEntities() {
return entities;
}
@Override
public List<TileEntity> getTileEntities() {
return tileEntities;
}
@Override
public Material getMaterial(int x, int y, int z) {
return Material.get(getBlockType(x, y, z), getDataValue(x, y, z));
}
@Override
public void setMaterial(int x, int y, int z, Material material) {
setBlockType(x, y, z, material.getBlockType());
setDataValue(x, y, z, material.getData());
}
@Override
public boolean isReadOnly() {
return readOnly;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ChunkImpl other = (ChunkImpl) obj;
if (this.xPos != other.xPos) {
return false;
}
if (this.zPos != other.zPos) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + this.xPos;
hash = 67 * hash + this.zPos;
return hash;
}
/**
* @throws UnsupportedOperationException
*/
@Override
public ChunkImpl clone() {
throw new UnsupportedOperationException("ChunkImlp.clone() not supported");
}
private int getDataByte(byte[] array, int x, int y, int z) {
byte dataByte = array[blockOffset(x, y, z) / 2];
if (blockOffset(x, y, z) % 2 == 0) {
// Even byte -> least significant bits
return dataByte & 0x0F;
} else {
// Odd byte -> most significant bits
return (dataByte & 0xF0) >> 4;
}
}
private void setDataByte(byte[] array, int x, int y, int z, int dataValue) {
int blockOffset = blockOffset(x, y, z);
int offset = blockOffset / 2;
byte dataByte = array[offset];
if (blockOffset % 2 == 0) {
// Even byte -> least significant bits
dataByte &= 0xF0;
dataByte |= (dataValue & 0x0F);
} else {
// Odd byte -> most significant bits
dataByte &= 0x0F;
dataByte |= ((dataValue & 0x0F) << 4);
}
array[offset] = dataByte;
}
private int blockOffset(int x, int y, int z) {
return y + (z + x * 16) * maxHeight;
}
public final boolean readOnly;
final byte[] blocks;
final byte[] data;
final byte[] skyLight;
final byte[] blockLight;
final byte[] heightMap;
final int xPos, zPos;
boolean terrainPopulated;
final List<Entity> entities;
final List<TileEntity> tileEntities;
final int maxHeight;
private static final long serialVersionUID = 1L;
} | gpl-3.0 |
ratrecommends/dice-heroes | main/src/com/vlaaad/dice/pvp/messaging/messages/SpawnedToServer.java | 3281 | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* 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.vlaaad.dice.pvp.messaging.messages;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.ObjectMap;
import com.vlaaad.dice.Config;
import com.vlaaad.dice.game.config.abilities.Ability;
import com.vlaaad.dice.game.objects.Creature;
import com.vlaaad.dice.game.world.players.Player;
import com.vlaaad.dice.pvp.messaging.IPvpMessage;
import com.vlaaad.dice.pvp.messaging.objects.PlacedCreature;
/**
* Created 01.08.14 by vlaaad
*/
public class SpawnedToServer extends IPvpMessage {
public static void register() {
Config.json.addClassTag("sts", SpawnedToServer.class);
Config.json.setSerializer(SpawnedToServer.class, new Json.Serializer<SpawnedToServer>() {
@Override public void write(Json json, SpawnedToServer object, Class knownType) {
json.writeObjectStart();
if (knownType == null) json.writeType(SpawnedToServer.class);
json.writeValue("d", object.dice, Array.class);
json.writeValue("p", object.potions, ObjectMap.class, Integer.class);
json.writeValue("packetIdx", object.packetIdx);
json.writeObjectEnd();
}
@SuppressWarnings("unchecked")
@Override public SpawnedToServer read(Json json, JsonValue jsonData, Class type) {
Array<PlacedCreature> dice = json.readValue(Array.class, PlacedCreature.class, jsonData.get("d"));
ObjectMap potions = json.readValue(ObjectMap.class, Integer.class, jsonData.get("p"));
SpawnedToServer spawnedToServer = new SpawnedToServer(dice, potions);
spawnedToServer.packetIdx = jsonData.getInt("packetIdx");
return spawnedToServer;
}
});
}
public final Array<PlacedCreature> dice;
public final ObjectMap<String, Integer> potions;
public SpawnedToServer(Array<PlacedCreature> dice, ObjectMap<String, Integer> potions) {
this.dice = dice;
this.potions = potions;
}
public SpawnedToServer(Player player) {
dice = new Array<PlacedCreature>(player.creatures.size);
for (Creature creature : player.creatures) {
dice.add(new PlacedCreature(creature));
}
potions = new ObjectMap<String, Integer>();
for (Ability p : player.potions()) {
potions.put(p.id, player.getPotionCount(p));
}
}
}
| gpl-3.0 |
forgodsake/TowerPlus | Android/src/com/fuav/android/core/mission/commands/ChangeSpeedImpl.java | 1494 | package com.fuav.android.core.mission.commands;
import java.util.List;
import com.fuav.android.core.mission.Mission;
import com.fuav.android.core.mission.MissionItemImpl;
import com.fuav.android.core.mission.MissionItemType;
import com.MAVLink.common.msg_mission_item;
import com.MAVLink.enums.MAV_CMD;
import com.MAVLink.enums.MAV_FRAME;
public class ChangeSpeedImpl extends MissionCMD {
private double speed = 5; //meters per second
public ChangeSpeedImpl(MissionItemImpl item) {
super(item);
}
public ChangeSpeedImpl(msg_mission_item msg, Mission mission) {
super(mission);
unpackMAVMessage(msg);
}
public ChangeSpeedImpl(Mission mission, double speed) {
super(mission);
this.speed = speed;
}
@Override
public List<msg_mission_item> packMissionItem() {
List<msg_mission_item> list = super.packMissionItem();
msg_mission_item mavMsg = list.get(0);
mavMsg.command = MAV_CMD.MAV_CMD_DO_CHANGE_SPEED;
mavMsg.frame = MAV_FRAME.MAV_FRAME_GLOBAL_RELATIVE_ALT;
mavMsg.param2 = (float) speed;
return list;
}
@Override
public void unpackMAVMessage(msg_mission_item mavMsg) {
speed = mavMsg.param2;
}
@Override
public MissionItemType getType() {
return MissionItemType.CHANGE_SPEED;
}
/**
* @return the set speed in meters per second.
*/
public double getSpeed() {
return speed;
}
/**
* Set the speed
* @param speed speed in meters per second.
*/
public void setSpeed(double speed) {
this.speed = speed;
}
} | gpl-3.0 |
dotCMS/core | dotCMS/src/main/java/com/dotcms/rest/api/v1/workflow/CountWorkflowAction.java | 1905 | package com.dotcms.rest.api.v1.workflow;
import com.dotmarketing.portlets.contentlet.util.ActionletUtil;
import com.dotmarketing.portlets.workflows.model.WorkflowAction;
import com.dotmarketing.util.UtilMethods;
import java.util.Objects;
public class CountWorkflowAction {
private final long count;
private final WorkflowAction workflowAction;
private final boolean pushPublish;
private final boolean moveable;
private final boolean conditionPresent;
public CountWorkflowAction(final long count, final WorkflowAction workflowAction) {
this.count = count;
this.workflowAction = workflowAction;
this.pushPublish = ActionletUtil.hasPushPublishActionlet(workflowAction);
this.moveable = ActionletUtil.isMoveableActionlet(workflowAction);
this.conditionPresent = UtilMethods.isSet(workflowAction.getCondition());
}
public long getCount() {
return count;
}
public WorkflowAction getWorkflowAction() {
return workflowAction;
}
public boolean isPushPublish() {
return pushPublish;
}
public boolean isConditionPresent() {
return conditionPresent;
}
public boolean isMoveable() {
return moveable;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CountWorkflowAction that = (CountWorkflowAction) o;
return Objects.equals(workflowAction, that.workflowAction);
}
@Override
public int hashCode() {
return Objects.hash(workflowAction);
}
@Override
public String toString() {
return "CountWorkflowAction{" +
"count=" + count +
", workflowAction=" + workflowAction +
'}';
}
}
| gpl-3.0 |
blhps/lifeograph-android | app/src/main/java/net/sourceforge/lifeograph/ChartElem.java | 1498 | /* *********************************************************************************
Copyright (C) 2012-2021 Ahmet Öztürk (aoz_2@yahoo.com)
This file is part of Lifeograph.
Lifeograph 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.
Lifeograph 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 Lifeograph. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
package net.sourceforge.lifeograph;
public class ChartElem extends StringDefElem
{
public static final String DEFINITION_DEFAULT = "Gyc\nGo--MP";
public static final String DEFINITION_DEFAULT_Y = "Gyc\nGo--YP";
// DEFINITION_DEFAULT_Y is temporary: needed for diary upgrades
public ChartElem( Diary diary, String name, String definition ) {
super( diary, name, definition );
}
@Override
public Type
get_type(){
return Type.CHART;
}
@Override
public int
get_icon() {
return R.drawable.ic_chart;
}
}
| gpl-3.0 |
jeffreya12/Entrenador-de-Ajedrez | src/gui/EditarJugadaTactica.java | 14723 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import model.Jugada;
import model.JugadaTactica;
import model.Partida;
/**
*
* @author jeffrey-lmde
*/
public class EditarJugadaTactica extends javax.swing.JFrame {
private File fichero;
private int index;
private JugadaTactica jugada;
private Partida partida;
/**
* Creates new form CrearJugadaTeorica
*/
public EditarJugadaTactica(int pIndex) {
initComponents();
partida = application.EntrenadorDeAjedrez.getPartida();
index = pIndex;
jugada = (JugadaTactica) partida.getListaDeJugadas().get(index);
fichero = jugada.getImagen();
jugadorBlancoTXT.setText(jugada.getJugadorBlanco());
jugadorNegroTXT.setText(jugada.getJugadorNegro());
anioTXT.setText(jugada.getAnio());
setBoardPicture();
setIconImage(new ImageIcon(getClass().getResource("../resources/icon.png")).getImage());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
titulo = new javax.swing.JLabel();
jugadorBlanco = new javax.swing.JLabel();
guardar = new javax.swing.JToggleButton();
jugadorBlancoTXT = new javax.swing.JTextField();
jugadorNegroTXT = new javax.swing.JTextField();
jugadorNegro = new javax.swing.JLabel();
anioTXT = new javax.swing.JTextField();
anio = new javax.swing.JLabel();
cargarFoto = new javax.swing.JButton();
direccionImagen = new javax.swing.JLabel();
tablero = new javax.swing.JLabel();
cancelar1 = new javax.swing.JToggleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Entrenador de Ajedrez");
setMinimumSize(new java.awt.Dimension(500, 680));
setResizable(false);
titulo.setFont(new java.awt.Font("Roboto Light", 0, 24)); // NOI18N
titulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
titulo.setText("Jugada Tactica");
jugadorBlanco.setText("Jugador blanco:");
guardar.setText("Guardar");
guardar.setMaximumSize(new java.awt.Dimension(53, 27));
guardar.setMinimumSize(new java.awt.Dimension(53, 27));
guardar.setPreferredSize(new java.awt.Dimension(53, 27));
guardar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
guardarActionPerformed(evt);
}
});
jugadorBlancoTXT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jugadorBlancoTXTActionPerformed(evt);
}
});
jugadorNegroTXT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jugadorNegroTXTActionPerformed(evt);
}
});
jugadorNegro.setText("Jugador negro: ");
anioTXT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
anioTXTActionPerformed(evt);
}
});
anio.setText("Aňo / Identificador:");
cargarFoto.setText("Cargar foto");
cargarFoto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cargarFotoActionPerformed(evt);
}
});
direccionImagen.setMaximumSize(new java.awt.Dimension(75, 23));
direccionImagen.setMinimumSize(new java.awt.Dimension(75, 23));
direccionImagen.setPreferredSize(new java.awt.Dimension(75, 23));
tablero.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
tablero.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/board2.png"))); // NOI18N
tablero.setVerifyInputWhenFocusTarget(false);
cancelar1.setText("Cancelar");
cancelar1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelar1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(titulo, javax.swing.GroupLayout.PREFERRED_SIZE, 476, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jugadorBlanco, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jugadorBlancoTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jugadorNegro, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jugadorNegroTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(anio, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(anioTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(cargarFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(47, 47, 47)
.addComponent(direccionImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(tablero, javax.swing.GroupLayout.PREFERRED_SIZE, 476, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(cancelar1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(276, 276, 276)
.addComponent(guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(titulo)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jugadorBlanco))
.addComponent(jugadorBlancoTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jugadorNegro))
.addComponent(jugadorNegroTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(anio))
.addComponent(anioTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cargarFoto)
.addComponent(direccionImagen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(tablero)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cancelar1)
.addComponent(guardar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void setBoardPicture(){
try{
direccionImagen.setText(fichero.getPath());
ImageIcon icon = new ImageIcon(fichero.toString());
Icon icono = new ImageIcon(icon.getImage().getScaledInstance(
tablero.getWidth(), tablero.getHeight(), Image.SCALE_DEFAULT));
tablero.setIcon(icono);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "El archivo ha sido removido o cambiado", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void copyFile(File s, File t){
try{
FileChannel in = (new FileInputStream(s)).getChannel();
FileChannel out = (new FileOutputStream(t)).getChannel();
in.transferTo(0, s.length(), out);
in.close();
out.close();
}
catch(Exception e){}
}
private void jugadorBlancoTXTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jugadorBlancoTXTActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jugadorBlancoTXTActionPerformed
private void jugadorNegroTXTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jugadorNegroTXTActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jugadorNegroTXTActionPerformed
private void anioTXTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anioTXTActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_anioTXTActionPerformed
private void guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarActionPerformed
partida.getListaDeJugadas().remove(index);
String pJugadorBlanco, pJugadorNegro, pAnio;
pJugadorBlanco = jugadorBlancoTXT.getText();
pJugadorNegro = jugadorNegroTXT.getText();
pAnio = anioTXT.getText();
JugadaTactica nuevaJugadaTactica = new JugadaTactica (pJugadorBlanco, pJugadorNegro, pAnio, fichero);
partida.anadirJugada( (Jugada)nuevaJugadaTactica );
application.EntrenadorDeAjedrez.setPartida(partida);
application.EntrenadorDeAjedrez.write();
this.dispose();
}//GEN-LAST:event_guardarActionPerformed
private void cargarFotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cargarFotoActionPerformed
int resultado;
File copyFileAux;
SeleccionarArchivo ventana = new SeleccionarArchivo();
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
try{
ventana.fileChooser.setCurrentDirectory(new File (System.getProperty("user.home") + System.getProperty("file.separator")+ "Pictures"));
}
catch (Exception e){}
FileNameExtensionFilter filtro = new FileNameExtensionFilter("JPG y PNG"
,"jpg","png");
ventana.fileChooser.setFileFilter(filtro);
resultado = ventana.fileChooser.showOpenDialog(null);
if (JFileChooser.APPROVE_OPTION == resultado){
if (fichero != null){
fichero.delete();
}
copyFileAux = ventana.fileChooser.getSelectedFile();
copyFile(copyFileAux, new File("src/resources/images/" + dateFormat.format(date) + ".png"));
fichero = new File ("src/resources/images/" + dateFormat.format(date) + ".png");
}
setBoardPicture();
}//GEN-LAST:event_cargarFotoActionPerformed
private void cancelar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelar1ActionPerformed
this.dispose();
}//GEN-LAST:event_cancelar1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel anio;
private javax.swing.JTextField anioTXT;
private javax.swing.JToggleButton cancelar1;
private javax.swing.JButton cargarFoto;
private javax.swing.JLabel direccionImagen;
private javax.swing.JToggleButton guardar;
private javax.swing.JLabel jugadorBlanco;
private javax.swing.JTextField jugadorBlancoTXT;
private javax.swing.JLabel jugadorNegro;
private javax.swing.JTextField jugadorNegroTXT;
private javax.swing.JLabel tablero;
private javax.swing.JLabel titulo;
// End of variables declaration//GEN-END:variables
}
| gpl-3.0 |
dotCMS/core | dotCMS/src/main/java/org/apache/velocity/tools/view/tools/ImportTool.java | 3570 | /*
* Copyright 2003 The Apache Software Foundation.
*
* 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.apache.velocity.tools.view.tools;
import java.util.HashMap;
import java.util.Map;
import com.dotcms.http.CircuitBreakerUrl;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.tools.view.ImportSupport;
import org.apache.velocity.tools.view.context.ViewContext;
/**
* General-purpose text-importing view tool for templates.
* <p>Usage:<br />
* Just call $import.read("http://www.foo.com/bleh.jsp?sneh=bar") to insert the contents of the named
* resource into the template.
* </p>
* <p><pre>
* Toolbox configuration:
* <tool>
* <key>import</key>
* <scope>request</scope>
* <class>org.apache.velocity.tools.view.tools.ImportTool</class>
* </tool>
* </pre></p>
*
* @author <a href="mailto:marinoj@centrum.is">Marino A. Jonsson</a>
* @since VelocityTools 1.1
* @version $Revision: 72114 $ $Date: 2004-11-10 22:26:27 -0800 (Wed, 10 Nov 2004) $
*/
public class ImportTool extends ImportSupport implements ViewTool {
protected static final Log LOG = LogFactory.getLog(ImportTool.class);
/**
* Default constructor. Tool must be initialized before use.
*/
public ImportTool() {}
/**
* Initializes this tool.
*
* @param obj the current ViewContext
* @throws IllegalArgumentException if the param is not a ViewContext
*/
public void init(Object obj) {
if (! (obj instanceof ViewContext)) {
throw new IllegalArgumentException("Tool can only be initialized with a ViewContext");
}
ViewContext context = (ViewContext) obj;
this.request = context.getRequest();
this.response = context.getResponse();
this.application = context.getServletContext();
}
public String read(String url) {
return read(url, Config.getIntProperty("URL_CONNECTION_TIMEOUT", 15000), new HashMap<String, String>());
}
/**
* Returns the supplied URL rendered as a String.
*
* @param url the URL to import
* @return the URL as a string
*/
public String read(String url, int timeout) {
return read(url, timeout, new HashMap<String, String>());
}
/**
* Returns the supplied URL rendered as a String.
*
* @param url the URL to import
* @return the URL as a string
*/
public String read(String url, int timeout, Map<String, String> headers) {
try {
String x = CircuitBreakerUrl.builder().setHeaders(headers).setUrl(url).setTimeout(timeout).build().doString();
return x;
}
catch(Exception e) {
Logger.warn(this.getClass(), e.getMessage());
return null;
}
}
}
| gpl-3.0 |
ksmonkey123/WaDosUtil | waan/ch/waan/game/package-info.java | 802 | /**
* This API is designed for lightweight 2D game implementation.
* <p>
* It manages all aspects of the actively rendered UI and the basic tick clock
* stabilisation. The API supports single-window UIs both in window and in
* full-screen mode. The base logic is targeted at the usage of a finite state
* application model. Lightweight state transitions are internally handled. Even
* game termination is designed as a termination state.
* </p>
* <p>
* The API entry point is the {@link ch.waan.game.Game Game} class. Specifically
* the static {@link ch.waan.game.Game#initializeGame(SceneController)
* initializeGame(SceneController)} method. It manages the complete UI
* initialisation based off the single initial state.
* </p>
*
* @author Andreas Wälchli
*/
package ch.waan.game; | gpl-3.0 |
IntellectualCrafters/PlotSquared | Core/src/main/java/com/plotsquared/core/configuration/file/YamlConstructor.java | 3061 | /*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2021 IntellectualSites
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.configuration.file;
import com.plotsquared.core.configuration.serialization.ConfigurationSerialization;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.Tag;
import java.util.LinkedHashMap;
import java.util.Map;
public class YamlConstructor extends SafeConstructor {
YamlConstructor() {
yamlConstructors.put(Tag.MAP, new ConstructCustomObject());
}
private class ConstructCustomObject extends ConstructYamlMap {
@Override
public Object construct(final Node node) {
if (node.isTwoStepsConstruction()) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
final Map<?, ?> raw = (Map<?, ?>) super.construct(node);
if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
final Map<String, Object> typed = new LinkedHashMap<>(raw.size());
for (final Map.Entry<?, ?> entry : raw.entrySet()) {
typed.put(entry.getKey().toString(), entry.getValue());
}
try {
return ConfigurationSerialization.deserializeObject(typed);
} catch (final IllegalArgumentException ex) {
throw new YAMLException("Could not deserialize object", ex);
}
}
return raw;
}
@Override
public void construct2ndStep(final Node node, final Object object) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
}
}
| gpl-3.0 |
anu-doi/anudc | DataCommons/src/main/java/org/isotc211/_2005/gts/TMPrimitivePropertyType.java | 9386 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// 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: 2015.11.24 at 09:50:34 AM AEDT
//
package org.isotc211._2005.gts;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import net.opengis.gml.AbstractTimeGeometricPrimitiveType;
import net.opengis.gml.AbstractTimePrimitiveType;
import net.opengis.gml.AbstractTimeTopologyPrimitiveType;
import net.opengis.gml.TimeEdgeType;
import net.opengis.gml.TimeInstantType;
import net.opengis.gml.TimeNodeType;
import net.opengis.gml.TimePeriodType;
/**
* <p>Java class for TM_Primitive_PropertyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TM_Primitive_PropertyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element ref="{http://www.opengis.net/gml}AbstractTimePrimitive"/>
* </sequence>
* <attGroup ref="{http://www.isotc211.org/2005/gco}ObjectReference"/>
* <attribute ref="{http://www.isotc211.org/2005/gco}nilReason"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TM_Primitive_PropertyType", propOrder = {
"abstractTimePrimitive"
})
public class TMPrimitivePropertyType {
@XmlElementRef(name = "AbstractTimePrimitive", namespace = "http://www.opengis.net/gml", type = JAXBElement.class, required = false)
protected JAXBElement<? extends AbstractTimePrimitiveType> abstractTimePrimitive;
@XmlAttribute(name = "nilReason", namespace = "http://www.isotc211.org/2005/gco")
protected List<String> nilReason;
@XmlAttribute(name = "uuidref")
protected String uuidref;
@XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink")
protected String type;
@XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String href;
@XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String role;
@XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String arcrole;
@XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink")
protected String title;
@XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink")
protected String show;
@XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink")
protected String actuate;
/**
* Gets the value of the abstractTimePrimitive property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link AbstractTimeTopologyPrimitiveType }{@code >}
* {@link JAXBElement }{@code <}{@link TimePeriodType }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractTimePrimitiveType }{@code >}
* {@link JAXBElement }{@code <}{@link TimeNodeType }{@code >}
* {@link JAXBElement }{@code <}{@link TimeEdgeType }{@code >}
* {@link JAXBElement }{@code <}{@link TimeInstantType }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractTimeGeometricPrimitiveType }{@code >}
*
*/
public JAXBElement<? extends AbstractTimePrimitiveType> getAbstractTimePrimitive() {
return abstractTimePrimitive;
}
/**
* Sets the value of the abstractTimePrimitive property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link AbstractTimeTopologyPrimitiveType }{@code >}
* {@link JAXBElement }{@code <}{@link TimePeriodType }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractTimePrimitiveType }{@code >}
* {@link JAXBElement }{@code <}{@link TimeNodeType }{@code >}
* {@link JAXBElement }{@code <}{@link TimeEdgeType }{@code >}
* {@link JAXBElement }{@code <}{@link TimeInstantType }{@code >}
* {@link JAXBElement }{@code <}{@link AbstractTimeGeometricPrimitiveType }{@code >}
*
*/
public void setAbstractTimePrimitive(JAXBElement<? extends AbstractTimePrimitiveType> value) {
this.abstractTimePrimitive = value;
}
/**
* Gets the value of the nilReason property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nilReason property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNilReason().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNilReason() {
if (nilReason == null) {
nilReason = new ArrayList<String>();
}
return this.nilReason;
}
/**
* Gets the value of the uuidref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuidref() {
return uuidref;
}
/**
* Sets the value of the uuidref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuidref(String value) {
this.uuidref = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "simple";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the arcrole property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArcrole() {
return arcrole;
}
/**
* Sets the value of the arcrole property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArcrole(String value) {
this.arcrole = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the show property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShow() {
return show;
}
/**
* Sets the value of the show property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShow(String value) {
this.show = value;
}
/**
* Gets the value of the actuate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getActuate() {
return actuate;
}
/**
* Sets the value of the actuate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setActuate(String value) {
this.actuate = value;
}
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_xhtml/Content_var_Choice131.java | 828 | package tmp.generated_xhtml;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class Content_var_Choice131 extends Content_var_Choice1 {
public Content_var_Choice131(Element_button element_button, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<Element_button>("element_button", element_button)
}, firstToken, lastToken);
}
public Content_var_Choice131(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new Content_var_Choice131(cloneProperties(),firstToken,lastToken);
}
public Element_button getElement_button() {
return ((PropertyOne<Element_button>)getProperty("element_button")).getValue();
}
}
| gpl-3.0 |
Mazdallier/AncientWarfare2 | src/main/java/net/shadowmage/ancientwarfare/core/util/BlockPosition.java | 6045 | /**
Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513)
This software is distributed under the terms of the GNU General Public License.
Please see COPYING for precise license information.
This file is part of Ancient Warfare.
Ancient Warfare 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.
Ancient Warfare 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 Ancient Warfare. If not, see <http://www.gnu.org/licenses/>.
*/
package net.shadowmage.ancientwarfare.core.util;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.MathHelper;
public final class BlockPosition
{
public int x;
public int y;
public int z;
public BlockPosition()
{
}
public BlockPosition(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public BlockPosition(double x, double y, double z)
{
this.x = MathHelper.floor_double(x);
this.y = MathHelper.floor_double(y);
this.z = MathHelper.floor_double(z);
}
public BlockPosition(NBTTagCompound tag)
{
read(tag);
}
public BlockPosition(BlockPosition pos)
{
this.x = pos.x;
this.y = pos.y;
this.z = pos.z;
}
public final BlockPosition reassign(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
return this;
}
public final BlockPosition read(NBTTagCompound tag)
{
this.x = tag.getInteger("x");
this.y = tag.getInteger("y");
this.z = tag.getInteger("z");
return this;
}
/**
* return the distance of the CENTER of this block from the input position
* @param x
* @param y
* @param z
* @return
*/
public final float getCenterDistanceFrom(double x, double y, double z)
{
return Trig.getDistance(x, y, z, this.x+0.5d, this.y, this.z+0.5d);
}
public final NBTTagCompound writeToNBT(NBTTagCompound tag)
{
tag.setInteger("x", x);
tag.setInteger("y", y);
tag.setInteger("z", z);
return tag;
}
/**
* offsets THIS blockPosition by the passed in offset
* @param offsetVector
* @return
*/
public final BlockPosition offsetBy(BlockPosition offsetVector)
{
this.x += offsetVector.x;
this.y += offsetVector.y;
this.z += offsetVector.z;
return this;
}
public final BlockPosition offset(int x, int y, int z)
{
this.x += x;
this.y += y;
this.z += z;
return this;
}
/**
* moves the blocks position right by the input amount, relative to the input direction
* @param facing the direction that is 'forward'
* @param amt
*/
public final void moveRight(int facing, int amt)
{
this.offsetForHorizontalDirection(BlockTools.turnRight(facing), amt);
}
/**
* moves the blocks position backwards the input amount, relative to the input direction
* @param facing the direction that is 'forward'
* @param amt
*/
public final void moveBack(int facing, int amt)
{
this.offsetForHorizontalDirection(BlockTools.turnAround(facing), amt);
}
/**
* moves the blocks position left the input amount, relative to the input direction
* @param facing the direction that is 'forward'
* @param amt
*/
public final void moveLeft(int facing, int amt)
{
this.offsetForHorizontalDirection(BlockTools.turnLeft(facing), amt);
}
/**
* moves the blocks position forwards the input amount, relative to the input direction
* @param facing the direction that is 'forward'
* @param amt
*/
public final void moveForward(int facing, int amt)
{
this.offsetForHorizontalDirection(facing, amt);
}
/**
*
* @param direction MC direction (0=south, 1=west, 2=north, 3=east)
*/
public final void offsetForHorizontalDirection(int direction)
{
if(direction==0){this.z++;}
else if(direction==1){this.x--;}
else if(direction==2){this.z--;}
else if(direction==3){this.x++;}
}
/**
*
* @param direction MC direction (0=south, 1=west, 2=north, 3=east)
* @param amt how far to move in the given direction
*/
public final void offsetForHorizontalDirection(int direction, int amt)
{
if(direction==0){this.z+=amt;}
else if(direction==1){this.x-=amt;}
else if(direction==2){this.z-=amt;}
else if(direction==3){this.x+=amt;}
}
public final boolean equals(BlockPosition pos)
{
return pos!=null && this.x == pos.x && this.y == pos.y && this.z== pos.z ? true : false;
}
public final BlockPosition copy()
{
return new BlockPosition(this.x, this.y, this.z);
}
@Override
public final String toString()
{
return "X:"+this.x+" Y:"+this.y+" Z:"+this.z;
}
/**
* offset towards the side clicked on.<br>
* 0=down<br>
* 1=up<br>
* 2=north<br>
* 3=south<br>
* 4=east<br>
* 5=west<br>
* @param mcSide
*/
public final void offsetForMCSide(int mcSide)
{
switch (mcSide)
{
case 0:
--y;
break;
case 1:
++y;
break;
case 2:
--z;
break;
case 3:
++z;
break;
case 4:
--x;
break;
case 5:
++x;
}
}
@Override
public final int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
@Override
public final boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BlockPosition other = (BlockPosition) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
if (z != other.z)
return false;
return true;
}
}
| gpl-3.0 |
redsoftbiz/executequery | src/org/underworldlabs/swing/CollapsibleTitledPanel.java | 5939 | /*
* CollapsibleTitledPanel.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.underworldlabs.swing;
import org.underworldlabs.swing.table.ArrowIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Panel container with a titled border that may be 'collapsed'
* and 'expanded' to show/hide the panels contents.
*
* @author Takis Diakoumis
*/
public class CollapsibleTitledPanel extends JPanel
implements ActionListener {
/**
* the panel border title
*/
private String title;
/**
* selection button
*/
private JButton button;
/**
* indicates the collapsed state
*/
private boolean collapsed;
/**
* the collapsed border
*/
private CollapsedTitleBorder border;
/**
* the content panel
*/
private JPanel panel;
/**
* the normal expanded icon
*/
private Icon normalIcon;
/**
* collapsed icon
*/
private Icon collapsedIcon;
/**
* Creates a new instance of CollapsibleTitledPanel
*/
public CollapsibleTitledPanel(String title) {
super(new BorderLayout());
button = new BlankButton(title);
border = new CollapsedTitleBorder(button);
setBorder(border);
panel = new JPanel();
add(button);
add(panel);
this.title = title;
button.setIcon(getNormalIcon());
button.addActionListener(this);
}
public void setTitle(String title) {
this.title = title;
button.setText(title);
}
public String getTitle() {
return title;
}
public JPanel getContentPane() {
return panel;
}
public void doLayout() {
Insets insets = getInsets();
Rectangle rect = getBounds();
rect.x = 0;
rect.y = 0;
Rectangle compR = border.getComponentRect(rect, insets);
button.setBounds(compR);
rect.x += insets.left;
rect.y += insets.top;
rect.width -= insets.left + insets.right;
rect.height -= insets.top + insets.bottom;
panel.setBounds(rect);
}
public boolean isCollapsed() {
return collapsed;
}
public void setCollapsed(boolean collapsed) {
this.collapsed = collapsed;
stateChanged();
}
protected void stateChanged() {
if (isCollapsed()) {
button.setIcon(getCollapsedIcon());
getContentPane().setVisible(false);
} else {
button.setIcon(getNormalIcon());
getContentPane().setVisible(true);
}
}
public void actionPerformed(ActionEvent e) {
setCollapsed(!isCollapsed());
}
protected Icon getNormalIcon() {
if (normalIcon == null) {
normalIcon = new ArrowIcon(getForeground(), ArrowIcon.DOWN, 12);
}
return normalIcon;
}
protected Icon getCollapsedIcon() {
if (collapsedIcon == null) {
collapsedIcon = new ArrowIcon(getForeground(), ArrowIcon.RIGHT, 12);
}
return collapsedIcon;
}
// border drawing just the top line when collapsed
class CollapsedTitleBorder extends ComponentTitledBorder {
public CollapsedTitleBorder(JComponent component) {
super(component);
}
public void paintBorder(Component c, Graphics g,
int x, int y, int width, int height) {
if (!isCollapsed()) {
super.paintBorder(c, g, x, y, width, height);
return;
}
Rectangle borderR = new Rectangle(x + EDGE_SPACING,
y + EDGE_SPACING,
width - (EDGE_SPACING * 2),
height - (EDGE_SPACING * 2));
Insets borderInsets;
if (border != null) {
borderInsets = border.getBorderInsets(c);
} else {
borderInsets = new Insets(0, 0, 0, 0);
}
Rectangle rect = new Rectangle(x, y, width, height);
Insets insets = getBorderInsets(c);
Rectangle compR = getComponentRect(rect, insets);
int diff = insets.top / 2 - borderInsets.top - EDGE_SPACING;
borderR.y += diff;
borderR.height -= diff;
border.paintBorder(c, g, borderR.x, borderR.y,
borderR.width, 1);
Color col = g.getColor();
g.setColor(c.getBackground());
g.fillRect(compR.x - 2, compR.y, compR.width + 4, compR.height);
g.setColor(col);
if (component != null) {
component.repaint();
}
}
} // class CollapsedTitleBorder
// Simple borderless blank button
class BlankButton extends JButton {
public BlankButton(String text) {
super(text);
setMargin(new Insets(0, 0, 0, 0));
setFocusPainted(false);
setBorderPainted(false);
setOpaque(true);
try {
setUI(new javax.swing.plaf.basic.BasicButtonUI());
} catch (NullPointerException nullExc) {
}
}
} // class BlankButton
}
| gpl-3.0 |
carlgreen/Lexicon-MPX-G2-Editor | mpxg2-model/src/main/java/info/carlwithak/mpxg2/model/effects/algorithms/ThreeBandMono.java | 3496 | /*
* Copyright (C) 2011 Carl Green
*
* 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 info.carlwithak.mpxg2.model.effects.algorithms;
import info.carlwithak.mpxg2.model.effects.Eq;
import info.carlwithak.mpxg2.model.parameters.EqModeValue;
import info.carlwithak.mpxg2.model.parameters.GenericValue;
import info.carlwithak.mpxg2.model.parameters.Parameter;
/**
* Class for 3-Band (M) parameters.
*
* @author Carl Green
*/
public class ThreeBandMono extends Eq {
private static final String NAME = "3-Band (M)";
public final GenericValue<Integer> gain1 = new GenericValue<>("Gain1", "dB", -72, 24);
public final GenericValue<Integer> gain2 = new GenericValue<>("Gain2", "dB", -72, 24);
public final GenericValue<Integer> gain3 = new GenericValue<>("Gain3", "dB", -72, 24);
public final GenericValue<Integer> fc1 = new GenericValue<>("Fc 1", "Hz", 20, 20000);
public final GenericValue<Integer> fc2 = new GenericValue<>("Fc 2", "Hz", 20, 20000);
public final GenericValue<Integer> fc3 = new GenericValue<>("Fc 3", "Hz", 20, 20000);
public final GenericValue<Double> q1 = new GenericValue<>("Q 1", "", 0.1, 10.0);
public final GenericValue<Double> q2 = new GenericValue<>("Q 2", "", 0.1, 10.0);
public final GenericValue<Double> q3 = new GenericValue<>("Q 3", "", 0.1, 10.0);
public final EqModeValue mode1 = new EqModeValue("Mode1");
public final EqModeValue mode2 = new EqModeValue("Mode2");
public final EqModeValue mode3 = new EqModeValue("Mode3");
@Override
public String getName() {
return NAME;
}
@Override
public Parameter getParameter(final int parameterIndex) {
Parameter parameter;
switch (parameterIndex) {
case 0:
case 1:
parameter = super.getParameter(parameterIndex);
break;
case 2:
parameter = gain1;
break;
case 3:
parameter = gain2;
break;
case 4:
parameter = gain3;
break;
case 5:
parameter = fc1;
break;
case 6:
parameter = fc2;
break;
case 7:
parameter = fc3;
break;
case 8:
parameter = q1;
break;
case 9:
parameter = q2;
break;
case 10:
parameter = q3;
break;
case 11:
parameter = mode1;
break;
case 12:
parameter = mode2;
break;
case 13:
parameter = mode3;
break;
default:
parameter = null;
}
return parameter;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | external/proguard/src/proguard/classfile/util/InstructionSequenceMatcher.java | 26408 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2013 Eric Lafortune (eric@graphics.cornell.edu)
*
* 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.classfile.util;
import proguard.classfile.*;
import proguard.classfile.attribute.CodeAttribute;
import proguard.classfile.constant.*;
import proguard.classfile.constant.visitor.ConstantVisitor;
import proguard.classfile.instruction.*;
import proguard.classfile.instruction.visitor.InstructionVisitor;
import java.util.Arrays;
/**
* This InstructionVisitor checks whether a given pattern instruction sequence
* occurs in the instructions that are visited. The arguments of the
* instruction sequence can be wildcards that are matched.
*
* @author Eric Lafortune
*/
public class InstructionSequenceMatcher
extends SimplifiedVisitor
implements InstructionVisitor,
ConstantVisitor
{
/*
public static boolean DEBUG = true;
public static boolean DEBUG_MORE = true;
/*/
private static final boolean DEBUG = false;
private static final boolean DEBUG_MORE = false;
//*/
public static final int X = 0x40000000;
public static final int Y = 0x40000001;
public static final int Z = 0x40000002;
public static final int A = 0x40000003;
public static final int B = 0x40000004;
public static final int C = 0x40000005;
public static final int D = 0x40000006;
private final Constant[] patternConstants;
private final Instruction[] patternInstructions;
private boolean matching;
private int patternInstructionIndex;
private final int[] matchedInstructionOffsets;
private int matchedArgumentFlags;
private final int[] matchedArguments = new int[7];
private final long[] matchedConstantFlags;
private final int[] matchedConstantIndices;
private int constantFlags;
private int previousConstantFlags;
// Fields acting as a parameter and a return value for visitor methods.
private Constant patternConstant;
private boolean matchingConstant;
/**
* Creates a new InstructionSequenceMatcher.
* @param patternConstants any constants referenced by the pattern
* instruction.
* @param patternInstructions the pattern instruction sequence.
*/
public InstructionSequenceMatcher(Constant[] patternConstants,
Instruction[] patternInstructions)
{
this.patternConstants = patternConstants;
this.patternInstructions = patternInstructions;
matchedInstructionOffsets = new int[patternInstructions.length];
matchedConstantFlags = new long[(patternConstants.length + 63) / 64];
matchedConstantIndices = new int[patternConstants.length];
}
/**
* Starts matching from the first instruction again next time.
*/
public void reset()
{
patternInstructionIndex = 0;
matchedArgumentFlags = 0;
Arrays.fill(matchedConstantFlags, 0L);
previousConstantFlags = constantFlags;
constantFlags = 0;
}
/**
* Returns whether the complete pattern sequence has been matched.
*/
public boolean isMatching()
{
return matching;
}
/**
* Returns the number of instructions in the pattern sequence.
*/
public int instructionCount()
{
return patternInstructions.length;
}
/**
* Returns the matched instruction offset of the specified pattern
* instruction.
*/
public int matchedInstructionOffset(int index)
{
return matchedInstructionOffsets[index];
}
/**
* Returns whether the specified wildcard argument was a constant from
* the constant pool in the most recent match.
*/
public boolean wasConstant(int argument)
{
return (previousConstantFlags & (1 << (argument - X))) != 0;
}
/**
* Returns the value of the specified matched argument (wildcard or not).
*/
public int matchedArgument(int argument)
{
int argumentIndex = argument - X;
return argumentIndex < 0 ?
argument :
matchedArguments[argumentIndex];
}
/**
* Returns the values of the specified matched arguments (wildcard or not).
*/
public int[] matchedArguments(int[] arguments)
{
int[] matchedArguments = new int[arguments.length];
for (int index = 0; index < arguments.length; index++)
{
matchedArguments[index] = matchedArgument(arguments[index]);
}
return matchedArguments;
}
/**
* Returns the index of the specified matched constant (wildcard or not).
*/
public int matchedConstantIndex(int constantIndex)
{
int argumentIndex = constantIndex - X;
return argumentIndex < 0 ?
matchedConstantIndices[constantIndex] :
matchedArguments[argumentIndex];
}
/**
* Returns the value of the specified matched branch offset (wildcard or
* not).
*/
public int matchedBranchOffset(int offset, int branchOffset)
{
int argumentIndex = branchOffset - X;
return argumentIndex < 0 ?
branchOffset :
matchedArguments[argumentIndex] - offset;
}
/**
* Returns the values of the specified matched jump offsets (wildcard or
* not).
*/
public int[] matchedJumpOffsets(int offset, int[] jumpOffsets)
{
int[] matchedJumpOffsets = new int[jumpOffsets.length];
for (int index = 0; index < jumpOffsets.length; index++)
{
matchedJumpOffsets[index] = matchedBranchOffset(offset,
jumpOffsets[index]);
}
return matchedJumpOffsets;
}
// Implementations for InstructionVisitor.
public void visitSimpleInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, SimpleInstruction simpleInstruction)
{
Instruction patternInstruction = patternInstructions[patternInstructionIndex];
// Check if the instruction matches the next instruction in the sequence.
boolean condition =
matchingOpcodes(simpleInstruction, patternInstruction) &&
matchingArguments(simpleInstruction.constant,
((SimpleInstruction)patternInstruction).constant);
// Check if the instruction sequence is matching now.
checkMatch(condition,
clazz,
method,
codeAttribute,
offset,
simpleInstruction);
}
public void visitVariableInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VariableInstruction variableInstruction)
{
Instruction patternInstruction = patternInstructions[patternInstructionIndex];
// Check if the instruction matches the next instruction in the sequence.
boolean condition =
matchingOpcodes(variableInstruction, patternInstruction) &&
matchingArguments(variableInstruction.variableIndex,
((VariableInstruction)patternInstruction).variableIndex) &&
matchingArguments(variableInstruction.constant,
((VariableInstruction)patternInstruction).constant);
// Check if the instruction sequence is matching now.
checkMatch(condition,
clazz,
method,
codeAttribute,
offset,
variableInstruction);
}
public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction)
{
Instruction patternInstruction = patternInstructions[patternInstructionIndex];
// Check if the instruction matches the next instruction in the sequence.
boolean condition =
matchingOpcodes(constantInstruction, patternInstruction) &&
matchingConstantIndices(clazz,
constantInstruction.constantIndex,
((ConstantInstruction)patternInstruction).constantIndex) &&
matchingArguments(constantInstruction.constant,
((ConstantInstruction)patternInstruction).constant);
// Check if the instruction sequence is matching now.
checkMatch(condition,
clazz,
method,
codeAttribute,
offset,
constantInstruction);
}
public void visitBranchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, BranchInstruction branchInstruction)
{
Instruction patternInstruction = patternInstructions[patternInstructionIndex];
// Check if the instruction matches the next instruction in the from
// sequence.
boolean condition =
matchingOpcodes(branchInstruction, patternInstruction) &&
matchingBranchOffsets(offset,
branchInstruction.branchOffset,
((BranchInstruction)patternInstruction).branchOffset);
// Check if the instruction sequence is matching now.
checkMatch(condition,
clazz,
method,
codeAttribute,
offset,
branchInstruction);
}
public void visitTableSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, TableSwitchInstruction tableSwitchInstruction)
{
Instruction patternInstruction = patternInstructions[patternInstructionIndex];
// Check if the instruction matches the next instruction in the sequence.
boolean condition =
matchingOpcodes(tableSwitchInstruction, patternInstruction) &&
matchingBranchOffsets(offset,
tableSwitchInstruction.defaultOffset,
((TableSwitchInstruction)patternInstruction).defaultOffset) &&
matchingArguments(tableSwitchInstruction.lowCase,
((TableSwitchInstruction)patternInstruction).lowCase) &&
matchingArguments(tableSwitchInstruction.highCase,
((TableSwitchInstruction)patternInstruction).highCase) &&
matchingJumpOffsets(offset,
tableSwitchInstruction.jumpOffsets,
((TableSwitchInstruction)patternInstruction).jumpOffsets);
// Check if the instruction sequence is matching now.
checkMatch(condition,
clazz,
method,
codeAttribute,
offset,
tableSwitchInstruction);
}
public void visitLookUpSwitchInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, LookUpSwitchInstruction lookUpSwitchInstruction)
{
Instruction patternInstruction = patternInstructions[patternInstructionIndex];
// Check if the instruction matches the next instruction in the sequence.
boolean condition =
matchingOpcodes(lookUpSwitchInstruction, patternInstruction) &&
matchingBranchOffsets(offset,
lookUpSwitchInstruction.defaultOffset,
((LookUpSwitchInstruction)patternInstruction).defaultOffset) &&
matchingArguments(lookUpSwitchInstruction.cases,
((LookUpSwitchInstruction)patternInstruction).cases) &&
matchingJumpOffsets(offset,
lookUpSwitchInstruction.jumpOffsets,
((LookUpSwitchInstruction)patternInstruction).jumpOffsets);
// Check if the instruction sequence is matching now.
checkMatch(condition,
clazz,
method,
codeAttribute,
offset,
lookUpSwitchInstruction);
}
// Implementations for ConstantVisitor.
public void visitIntegerConstant(Clazz clazz, IntegerConstant integerConstant)
{
IntegerConstant integerPatternConstant = (IntegerConstant)patternConstant;
// Compare the integer values.
matchingConstant = integerConstant.getValue() ==
integerPatternConstant.getValue();
}
public void visitLongConstant(Clazz clazz, LongConstant longConstant)
{
LongConstant longPatternConstant = (LongConstant)patternConstant;
// Compare the long values.
matchingConstant = longConstant.getValue() ==
longPatternConstant.getValue();
}
public void visitFloatConstant(Clazz clazz, FloatConstant floatConstant)
{
FloatConstant floatPatternConstant = (FloatConstant)patternConstant;
// Compare the float values.
matchingConstant = floatConstant.getValue() ==
floatPatternConstant.getValue();
}
public void visitDoubleConstant(Clazz clazz, DoubleConstant doubleConstant)
{
DoubleConstant doublePatternConstant = (DoubleConstant)patternConstant;
// Compare the double values.
matchingConstant = doubleConstant.getValue() ==
doublePatternConstant.getValue();
}
public void visitStringConstant(Clazz clazz, StringConstant stringConstant)
{
StringConstant stringPatternConstant = (StringConstant)patternConstant;
// Check the UTF-8 constant.
matchingConstant =
matchingConstantIndices(clazz,
stringConstant.u2stringIndex,
stringPatternConstant.u2stringIndex);
}
public void visitUtf8Constant(Clazz clazz, Utf8Constant utf8Constant)
{
Utf8Constant utf8PatternConstant = (Utf8Constant)patternConstant;
// Compare the actual strings.
matchingConstant = utf8Constant.getString().equals(
utf8PatternConstant.getString());
}
public void visitInvokeDynamicConstant(Clazz clazz, InvokeDynamicConstant invokeDynamicConstant)
{
InvokeDynamicConstant invokeDynamicPatternConstant = (InvokeDynamicConstant)patternConstant;
// Check the bootstrap method and the name and type.
matchingConstant =
matchingConstantIndices(clazz,
invokeDynamicConstant.getBootstrapMethodAttributeIndex(),
invokeDynamicPatternConstant.getBootstrapMethodAttributeIndex()) &&
matchingConstantIndices(clazz,
invokeDynamicConstant.getNameAndTypeIndex(),
invokeDynamicPatternConstant.getNameAndTypeIndex());
}
public void visitMethodHandleConstant(Clazz clazz, MethodHandleConstant methodHandleConstant)
{
MethodHandleConstant methodHandlePatternConstant = (MethodHandleConstant)patternConstant;
// Check the handle type and the name and type.
matchingConstant =
matchingArguments(methodHandleConstant.getReferenceKind(),
methodHandlePatternConstant.getReferenceKind()) &&
matchingConstantIndices(clazz,
methodHandleConstant.getReferenceIndex(),
methodHandlePatternConstant.getReferenceIndex());
}
public void visitAnyRefConstant(Clazz clazz, RefConstant refConstant)
{
RefConstant refPatternConstant = (RefConstant)patternConstant;
// Check the class and the name and type.
matchingConstant =
matchingConstantIndices(clazz,
refConstant.getClassIndex(),
refPatternConstant.getClassIndex()) &&
matchingConstantIndices(clazz,
refConstant.getNameAndTypeIndex(),
refPatternConstant.getNameAndTypeIndex());
}
public void visitClassConstant(Clazz clazz, ClassConstant classConstant)
{
ClassConstant classPatternConstant = (ClassConstant)patternConstant;
// Check the class name.
matchingConstant =
matchingConstantIndices(clazz,
classConstant.u2nameIndex,
classPatternConstant.u2nameIndex);
}
public void visitMethodTypeConstant(Clazz clazz, MethodTypeConstant methodTypeConstant)
{
MethodTypeConstant typePatternConstant = (MethodTypeConstant)patternConstant;
// Check the descriptor.
matchingConstant =
matchingConstantIndices(clazz,
methodTypeConstant.u2descriptorIndex,
typePatternConstant.u2descriptorIndex);
}
public void visitNameAndTypeConstant(Clazz clazz, NameAndTypeConstant nameAndTypeConstant)
{
NameAndTypeConstant typePatternConstant = (NameAndTypeConstant)patternConstant;
// Check the name and the descriptor.
matchingConstant =
matchingConstantIndices(clazz,
nameAndTypeConstant.u2nameIndex,
typePatternConstant.u2nameIndex) &&
matchingConstantIndices(clazz,
nameAndTypeConstant.u2descriptorIndex,
typePatternConstant.u2descriptorIndex);
}
// Small utility methods.
private boolean matchingOpcodes(Instruction instruction1,
Instruction instruction2)
{
// Check the opcode.
return instruction1.opcode == instruction2.opcode ||
instruction1.canonicalOpcode() == instruction2.opcode;
}
private boolean matchingArguments(int argument1,
int argument2)
{
int argumentIndex = argument2 - X;
if (argumentIndex < 0)
{
// Check the literal argument.
return argument1 == argument2;
}
else if (!isMatchingArgumentIndex(argumentIndex))
{
// Store the wildcard argument.
setMatchingArgument(argumentIndex, argument1);
return true;
}
else
{
// Check the previously stored wildcard argument.
return matchedArguments[argumentIndex] == argument1;
}
}
/**
* Marks the specified argument (by index) as matching the specified
* argument value.
*/
private void setMatchingArgument(int argumentIndex,
int argument)
{
matchedArguments[argumentIndex] = argument;
matchedArgumentFlags |= 1 << argumentIndex;
}
/**
* Returns whether the specified wildcard argument (by index) has been
* matched.
*/
private boolean isMatchingArgumentIndex(int argumentIndex)
{
return (matchedArgumentFlags & (1 << argumentIndex)) != 0;
}
private boolean matchingArguments(int[] arguments1,
int[] arguments2)
{
if (arguments1.length != arguments2.length)
{
return false;
}
for (int index = 0; index < arguments1.length; index++)
{
if (!matchingArguments(arguments1[index], arguments2[index]))
{
return false;
}
}
return true;
}
private boolean matchingConstantIndices(Clazz clazz,
int constantIndex1,
int constantIndex2)
{
if (constantIndex2 >= X)
{
// Remember that we are trying to match a constant.
constantFlags |= 1 << (constantIndex2 - X);
// Check the constant index.
return matchingArguments(constantIndex1, constantIndex2);
}
else if (!isMatchingConstantIndex(constantIndex2))
{
// Check the actual constant.
matchingConstant = false;
patternConstant = patternConstants[constantIndex2];
if (clazz.getTag(constantIndex1) == patternConstant.getTag())
{
clazz.constantPoolEntryAccept(constantIndex1, this);
if (matchingConstant)
{
// Store the constant index.
setMatchingConstant(constantIndex2, constantIndex1);
}
}
return matchingConstant;
}
else
{
// Check a previously stored constant index.
return matchedConstantIndices[constantIndex2] == constantIndex1;
}
}
/**
* Marks the specified constant (by index) as matching the specified
* constant index value.
*/
private void setMatchingConstant(int constantIndex,
int constantIndex1)
{
matchedConstantIndices[constantIndex] = constantIndex1;
matchedConstantFlags[constantIndex / 64] |= 1L << constantIndex;
}
/**
* Returns whether the specified wildcard constant has been matched.
*/
private boolean isMatchingConstantIndex(int constantIndex)
{
return (matchedConstantFlags[constantIndex / 64] & (1L << constantIndex)) != 0;
}
private boolean matchingBranchOffsets(int offset,
int branchOffset1,
int branchOffset2)
{
int argumentIndex = branchOffset2 - X;
if (argumentIndex < 0)
{
// Check the literal argument.
return branchOffset1 == branchOffset2;
}
else if (!isMatchingArgumentIndex(argumentIndex))
{
// Store a wildcard argument.
setMatchingArgument(argumentIndex, offset + branchOffset1);
return true;
}
else
{
// Check the previously stored wildcard argument.
return matchedArguments[argumentIndex] == offset + branchOffset1;
}
}
private boolean matchingJumpOffsets(int offset,
int[] jumpOffsets1,
int[] jumpOffsets2)
{
if (jumpOffsets1.length != jumpOffsets2.length)
{
return false;
}
for (int index = 0; index < jumpOffsets1.length; index++)
{
if (!matchingBranchOffsets(offset,
jumpOffsets1[index],
jumpOffsets2[index]))
{
return false;
}
}
return true;
}
private void checkMatch(boolean condition,
Clazz clazz,
Method method,
CodeAttribute codeAttribute,
int offset,
Instruction instruction)
{
if (DEBUG_MORE)
{
System.out.println("InstructionSequenceMatcher: ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"]: "+patternInstructions[patternInstructionIndex].toString(patternInstructionIndex)+(condition?"\t== ":"\t ")+instruction.toString(offset));
}
// Did the instruction match?
if (condition)
{
// Remember the offset of the matching instruction.
matchedInstructionOffsets[patternInstructionIndex] = offset;
// Try to match the next instruction next time.
patternInstructionIndex++;
// Did we match all instructions in the sequence?
matching = patternInstructionIndex == patternInstructions.length;
if (matching)
{
if (DEBUG)
{
System.out.println("InstructionSequenceMatcher: ["+clazz.getName()+"."+method.getName(clazz)+method.getDescriptor(clazz)+"]");
for (int index = 0; index < patternInstructionIndex; index++)
{
System.out.println(" "+InstructionFactory.create(codeAttribute.code, matchedInstructionOffsets[index]).toString(matchedInstructionOffsets[index]));
}
}
// Start matching from the first instruction again next time.
reset();
}
}
else
{
// The instruction didn't match.
matching = false;
// Is this a failed second instruction?
boolean retry = patternInstructionIndex == 1;
// Start matching from the first instruction next time.
reset();
// Retry a failed second instruction as a first instruction.
if (retry)
{
instruction.accept(clazz, method, codeAttribute, offset, this);
}
}
}
}
| gpl-3.0 |
Kyrremann/TagStory | tagstory/src/main/java/no/tagstory/story/activity/option/ArrowNavigationActivity.java | 7621 | package no.tagstory.story.activity.option;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.*;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import no.tagstory.R;
import no.tagstory.story.Story;
import no.tagstory.story.StoryTagOption;
import no.tagstory.story.activity.StoryActivity;
import no.tagstory.story.activity.StoryTravelActivity;
public class ArrowNavigationActivity extends StoryTravelActivity {
private final float DIST_ACCEPT = 10;
private final float COMPASS_PUSH = 40;
private String PLACE;
private SensorManager mSensorManager;
private Sensor mSensor;
private CompassView mView;
private float dir = 0.0f;
private float[] compassValues = {0};
private MediaPlayer player;
private long dist = 100;
private LocationManager locationManager;
private LocationListener locationlistener;
private Location loc;
private Location lastKnownLocation;
private String locationProvider;
private SensorEventListener magnetListener;
private TextView distance;
private Bitmap compassCircle;
private Bitmap compassHand;
Runnable onEverySecond = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_arrow);
// getActionBar().setDisplayHomeAsUpEnabled(true);
Bundle bundle = getIntent().getExtras();
option = (StoryTagOption) bundle
.getSerializable(StoryTravelActivity.OPTION);
story = (Story) bundle.getSerializable(StoryActivity.EXTRA_STORY);
tagId = bundle.getString(StoryActivity.EXTRA_TAG);
((TextView) findViewById(R.id.story_arrow_hint)).setText(option
.getHintText());
// TODO: Screen orientation
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Graphic
Resources res = this.getResources();
compassCircle = BitmapFactory.decodeResource(res, R.drawable.compass);
compassHand = BitmapFactory.decodeResource(res, R.drawable.hand);
mView = new CompassView(this);
FrameLayout fl = (FrameLayout) findViewById(R.id.story_arrow_layout);
fl.addView(mView, 0);
distance = (TextView) findViewById(R.id.story_arrow_distance);
// TODO: Should we play a sound when you are near enough?
// player = MediaPlayer.create(this, R.raw.ding);
// player.setLooping(false);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
magnetListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
compassValues = event.values;
if (mView != null)
mView.invalidate();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
// mSensorManager.registerListener(magnetListener, mSensor,
// SensorManager.SENSOR_DELAY_NORMAL);
// Last known user location
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
locationlistener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationlistener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationlistener);
if (!locationManager
.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("GPS");
builder.setMessage(R.string.story_arrow_gps_is_off);
builder.setPositiveButton(R.string.story_arrow_turn_on,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
});
builder.setNegativeButton(R.string.story_arrow_no,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
public void playFoundSound() {
player.start();
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(magnetListener, mSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
mSensorManager.unregisterListener(magnetListener);
super.onStop();
}
/*@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
Intent intent = new Intent(this, StoryActivity.class);
intent.putExtra(StoryActivity.EXTRA_STORY, story);
intent.putExtra(StoryActivity.EXTRA_TAG, tagId);
intent.putExtra(StoryActivity.PREVIOUSTAG, previousTag);
NavUtils.navigateUpTo(this, intent);
return true;
}
return super.onOptionsItemSelected(item);
}*/
private class CompassView extends View {
private Paint mPaint;
private Path arrowPath;
public CompassView(Context context) {
super(context);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
arrowPath = new Path();
// Construct a wedge-shaped path
arrowPath.moveTo(0, -100);
arrowPath.lineTo(-70, 100);
arrowPath.lineTo(0, 80);
arrowPath.lineTo(70, 100);
arrowPath.close();
}
@Override
protected void onDraw(Canvas canvas) {
int w = canvas.getWidth();
int h = canvas.getHeight();
int cx = w / 2;
int cy = h / 2;
if (loc == null) {
distance.setText(R.string.story_arrow_gps_wait);
} else {
distance.setText(String.format("%d m",
Math.max((int) dist - 10, 0)));
// Draw that compass
canvas.translate(cx, cy + COMPASS_PUSH);
canvas.translate(-compassCircle.getWidth() / 2,
-compassCircle.getHeight() / 2);
canvas.drawBitmap(compassCircle, 0, 0, mPaint);
// Back to center!
canvas.translate(compassCircle.getWidth() / 2,
compassCircle.getHeight() / 2);
canvas.rotate(dir - compassValues[0]);
canvas.translate(-compassHand.getWidth() / 2,
-compassHand.getHeight() / 2);
canvas.translate(0, -65);
canvas.drawBitmap(compassHand, 0, 0, mPaint);
}
}
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
loc = location;
Location target = new Location("TEST"); // TODO: Set the
// location here
target.setLatitude(option.getLatitude());
target.setLongitude(option.getLongitude());
dist = (long) loc.distanceTo(target);
dir = loc.bearingTo(target);
mView.invalidate();
// if (dist < DIST_ACCEPT) {
// playFoundSound();
// // TODO: Inform the user that they are close enough to find
// // it
// }
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
| gpl-3.0 |
kivimango/weather-widget | java/kivimango/weatherwidget/model/WeatherTest.java | 1006 | package kivimango.weatherwidget.model;
import org.junit.Assert;
import org.junit.Test;
public class WeatherTest {
@Test
public void weatherCreationTest() {
// Given
String testCountryCode = "HU";
String testCityName = "Budapest";
String testWeatherType = "Clouds";
String testWeatherDescription = "Scattered clouds";
String testIcon = "01d";
double testTemperature = 18.0;
// When
Weather weather = new Weather(testCountryCode, testCityName, testWeatherType, testWeatherDescription, testIcon, testTemperature);
// Then
Assert.assertEquals(testCountryCode, weather.getCountryCode());
Assert.assertEquals(testCityName, weather.getCityName());
Assert.assertEquals(testWeatherType, weather.getWeatherType());
Assert.assertEquals(testWeatherDescription, weather.getWeatherDescription());
Assert.assertEquals(testIcon, weather.getWeatherIcon());
Assert.assertEquals(testTemperature, weather.getTemperature(), 0.0);
Assert.assertTrue(weather instanceof Weather);
}
}
| gpl-3.0 |
talek69/curso | stimulsoft/src/com/stimulsoft/base/serializing/StiDeserializingProcessingRef.java | 1817 | /*
* Decompiled with CFR 0_114.
*/
package com.stimulsoft.base.serializing;
import com.stimulsoft.base.serializing.interfaceobject.IStiSerializableRef;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
public class StiDeserializingProcessingRef {
private final HashMap<String, Object> classes = new HashMap();
private final ArrayList<RefMetod> methods = new ArrayList();
public void addRef(Object object, String string) {
this.classes.put(string, object);
}
public void addRef(IStiSerializableRef iStiSerializableRef, int n) {
this.addRef((Object)iStiSerializableRef, String.valueOf(n));
}
public void addClass(Object object, Method method, String string) {
this.methods.add(new RefMetod(object, method, string));
}
public void finish() {
for (RefMetod refMetod : this.methods) {
Method method = refMetod.method;
Object object = refMetod.obj;
String string = refMetod.ref;
try {
method.invoke(object, this.classes.get(string));
continue;
}
catch (Exception var6_6) {
throw new RuntimeException("\u043d\u0435\u0443\u0434\u0430\u043b\u043e\u0441\u044c \u0441\u043a\u043e\u0440\u0440\u0435\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0441\u0441\u044b\u043b\u043a\u0443\n\u043c\u0435\u0442\u043e\u0434 " + method, var6_6);
}
}
}
private class RefMetod {
private final Object obj;
private final Method method;
private final String ref;
public RefMetod(Object object, Method method, String string) {
this.obj = object;
this.method = method;
this.ref = string;
}
}
}
| gpl-3.0 |
dotpanic/urlbooster | URLBooster/src/com/u8t/urlbooster/Main.java | 2400 | /*
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.u8t.urlbooster;
import com.u8t.urlbooster.app.Application;
import com.u8t.urlbooster.app.Console;
import com.u8t.urlbooster.app.Gui;
import com.u8t.urlbooster.components.LogManager;
public class Main {
private enum execMode {
CONSOLE, GUI;
}
private static Application app;
public static void logInfo(String msg) {
app.logInfo(msg);
}
public static void main(String[] args) {
LogManager.initLogManager();
// Paramètres par défaut du programme
execMode mode = execMode.GUI;
String configFile = "";
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-console"))
mode = execMode.CONSOLE;
if (args[i].equals("-configFile"))
configFile = args[++i];
}
}
if (mode == execMode.CONSOLE) {
app = new Console();
if (!configFile.equals(""))
configFile = "urlbooster.ini";
} else {
app = new Gui();
if (!configFile.equals(""))
configFile = "urlbooster.xml";
}
app.getConfig().setPropertiesFile(configFile);
app.init();
app.setPriority(Thread.MIN_PRIORITY);
app.start();
while (!app.isTerminate()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LogManager.traceException(e);
}
}
}
public static final Application getApp() {
return app;
}
}
| gpl-3.0 |
pietrobraione/jbse | src/main/java/jbse/tree/DecisionAlternative_XLOAD_GETX_Expands.java | 2373 | package jbse.tree;
import jbse.bc.ClassFile;
import jbse.val.ReferenceSymbolic;
/**
* {@link DecisionAlternative_XLOAD_GETX} for the case a read access to a field/variable
* returned a {@link ReferenceSymbolic} to an object in the heap that has
* not been yet discovered during execution.
*
* @author Pietro Braione
*/
public final class DecisionAlternative_XLOAD_GETX_Expands extends DecisionAlternative_XLOAD_GETX_Unresolved implements DecisionAlternative_XYLOAD_GETX_Expands {
private final ClassFile classFileOfTargetObject;
private final int hashCode;
/**
* Constructor.
*
* @param referenceToResolve the {@link ReferenceSymbolic} loaded from the field/variable.
* @param classFileOfTargetObject the {@link ClassFile} for the class of the
* object {@code referenceToResolve} expands to.
* @param branchNumber an {@code int}, the branch number.
*/
public DecisionAlternative_XLOAD_GETX_Expands(ReferenceSymbolic referenceToResolve, ClassFile classFileOfTargetObject, int branchNumber) {
super(ALT_CODE + "_Expands:" + classFileOfTargetObject.getClassName(), referenceToResolve, branchNumber);
this.classFileOfTargetObject = classFileOfTargetObject;
final int prime = 2819;
int result = 1;
result = prime * result +
((this.classFileOfTargetObject == null) ? 0 : this.classFileOfTargetObject.hashCode());
this.hashCode = result;
}
@Override
public void accept(VisitorDecisionAlternative_XLOAD_GETX v) throws Exception {
v.visitDecisionAlternative_XLOAD_GETX_Expands(this);
}
@Override
public ClassFile getClassFileOfTargetObject() {
return this.classFileOfTargetObject;
}
@Override
public int hashCode() {
return this.hashCode;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
final DecisionAlternative_XLOAD_GETX_Expands other = (DecisionAlternative_XLOAD_GETX_Expands) obj;
if (this.classFileOfTargetObject == null) {
if (other.classFileOfTargetObject != null) {
return false;
}
} else if (!this.classFileOfTargetObject.equals(other.classFileOfTargetObject)) {
return false;
}
return true;
}
}
| gpl-3.0 |
senbox-org/snap-desktop | snap-sta-ui/src/main/java/org/esa/snap/modules/ManifestBuilder.java | 1375 | package org.esa.snap.modules;
import java.util.HashMap;
import java.util.Map;
/**
* Created by kraftek on 11/4/2016.
*/
public class ManifestBuilder extends AbstractBuilder {
private String version;
private String javaVersion;
private Map<String, String> properties;
public ManifestBuilder() {
version = "1.0";
javaVersion = System.getProperty("java.version");
javaVersion = javaVersion.substring(0, javaVersion.indexOf("_"));
properties = new HashMap<>();
}
public ManifestBuilder version(String value) {
version = value;
return this;
}
public ManifestBuilder javaVersion(String value) {
javaVersion = value;
return this;
}
public ManifestBuilder property(String name, String value) {
properties.putIfAbsent(name, value);
return this;
}
@Override
public String build(boolean standalone) {
StringBuilder builder = new StringBuilder();
builder.append("Manifest-Version: ").append(safeValue(version)).append("\n")
.append("Created-By: ").append(safeValue(javaVersion)).append("\n");
for (Map.Entry<String, String> entry : properties.entrySet()) {
builder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return builder.toString();
}
}
| gpl-3.0 |
lveci/nest | beam/ceres-0.x/ceres-glayer/src/main/java/com/bc/ceres/glayer/LayerContext.java | 2006 | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package com.bc.ceres.glayer;
/**
* The context in which layers are managed, created and/or rendered, e.g. the view used to
* display multiple layers.
* <p/>
* By default, the context is composed of the root layer and a common coordinate reference system (CRS)
* shared by all layers, this is the root layer and all of its child layers and so forth.
* <p/>
* Instances of this interface are passed to the several methods of {@link LayerType}
* in order to provide special layer type implementations with access to application specific services.
* Therefore this interface is intended to be implemented by clients.
* Since implementations of this interface are application-specific, there is no default implementation.
*
* @author Norman Fomferra
*/
public interface LayerContext {
/**
* The coordinate reference system (CRS) used by all the layers in this context.
* The CRS defines the model coordinate system and may be used by a
* {@link com.bc.ceres.glayer.LayerType} in order to decide whether
* it is can create new layer instance for this context.
*
* @return The CRS. May be {@code null}, if not used.
*/
Object getCoordinateReferenceSystem();
/**
* @return The root layer.
*/
Layer getRootLayer();
}
| gpl-3.0 |
Inspiredsoft/processor | src/main/java/it/inspired/wf/impl/ConcurrentProcessor.java | 3416 | /*******************************************************************************
* Inspired Processor is a framework to implement a processor manager.
* Copyright (C) 2017 Inspired Soft
*
* 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 it.inspired.wf.impl;
import it.inspired.wf.Activity;
import it.inspired.wf.ExceptionHandler;
import it.inspired.wf.WorkflowContext;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Executes actovities in parrallel
*
* @author Massimo Romano
*
*/
public class ConcurrentProcessor extends AbstractProcessor {
private static final CompletionService<Boolean> compService = new ExecutorCompletionService<Boolean>( Executors.newFixedThreadPool( 10 ) );
/*
* (non-Javadoc)
* @see it.inspired.wf.Processor#execute(it.inspired.wf.WorkflowContext)
*/
public WorkflowContext execute(WorkflowContext context) {
Set<Future<Boolean>> futures = new HashSet<Future<Boolean>>();
for ( Activity activity : activities ) {
futures.add( compService.submit( new ActivityExecutor(context, activity) ) );
}
Boolean stop = null;
Future<Boolean> completedFuture = null;
try {
while (futures.size() > 0) {
// block until a callable completes
completedFuture = compService.take();
futures.remove(completedFuture);
stop = completedFuture.get();
if ( stop ) {
for (Future<Boolean> future: futures) {
future.cancel(true);
}
}
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException( e );
}
return context;
}
/**
* Utility class to execute parallel activities
* @author Massimo Romano
*
*/
private class ActivityExecutor implements Callable<Boolean> {
private WorkflowContext context;
private Activity activity;
public ActivityExecutor( WorkflowContext context, Activity activity ) {
this.context = context;
this.activity = activity;
}
public Boolean call() throws Exception {
Boolean result = false;
try {
context = activity.execute( context );
} catch (Throwable th) {
ExceptionHandler errorHandler = activity.getExceptionHandler();
if ( errorHandler != null ) {
result = errorHandler.handleException(context, th);
} else if ( defaultExceptionHandler != null ) {
result = defaultExceptionHandler.handleException(context, th);
} else {
throw new RuntimeException( th );
}
}
return result;
}
}
}
| gpl-3.0 |
ahmaabdo/ReadifyRSS | app/src/main/java/ahmaabdo/readify/rss/receiver/ConnectionChangeReceiver.java | 2915 | /**
* spaRSS
* <p/>
* Copyright (c) 2015-2016 Arnaud Renaud-Goud
* Copyright (c) 2012-2015 Frederic Julian
* <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 3 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, see <http://www.gnu.org/licenses/>.
*/
package ahmaabdo.readify.rss.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.SystemClock;
import android.util.Log;
import ahmaabdo.readify.rss.Constants;
import ahmaabdo.readify.rss.service.FetcherService;
import ahmaabdo.readify.rss.service.RefreshService;
import ahmaabdo.readify.rss.utils.PrefUtils;
public class ConnectionChangeReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectionChangeReceive";
private boolean mConnection = false;
@Override
public void onReceive(Context context, Intent intent) {
if (mConnection && intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
mConnection = false;
} else if (!mConnection && !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
mConnection = true;
if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false) && PrefUtils.getBoolean(PrefUtils.REFRESH_ENABLED, true)) {
int time = 3600000;
try {
time = Math.max(60000, Integer.parseInt(PrefUtils.getString(PrefUtils.REFRESH_INTERVAL, RefreshService.SIXTY_MINUTES)));
} catch (Exception ignored) {
Log.e(TAG, "Exception", ignored);
}
long lastRefresh = PrefUtils.getLong(PrefUtils.LAST_SCHEDULED_REFRESH, 0);
long elapsedRealTime = SystemClock.elapsedRealtime();
// If the system rebooted, we need to reset the last value
if (elapsedRealTime < lastRefresh) {
lastRefresh = 0;
PrefUtils.putLong(PrefUtils.LAST_SCHEDULED_REFRESH, 0);
}
if (lastRefresh == 0 || elapsedRealTime - lastRefresh > time) {
context.startService(new Intent(context, FetcherService.class).setAction(FetcherService.ACTION_REFRESH_FEEDS).putExtra(Constants.FROM_AUTO_REFRESH, true));
}
}
}
}
} | gpl-3.0 |
ftninformatika/bisis-v5 | bisis-swing-client/src/main/java/com/ftninformatika/utils/gson/GsonUTCDateAdapter.java | 1549 | package com.ftninformatika.utils.gson;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Created by Petar on 8/2/2017.
*/
public class GsonUTCDateAdapter implements JsonSerializer<Date>,JsonDeserializer<Date> {
private final DateFormat dateFormat;
public GsonUTCDateAdapter() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'", Locale.US); //This is the format I need
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); //This is the key line which converts the date to UTC which cannot be accessed with the default serializer
//System.out.println("Kreirao GsonUTCDateAdapter !!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
@Override public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
//System.out.println(" serialize !!!!!!!!!!!!!!!!!!!!!!!!!!!");
return new JsonPrimitive(dateFormat.format(date));
}
@Override public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
try {
//System.out.println(" deserialize !!!!!!!!!!!!!!!!!!!!!!!!!!!");
return dateFormat.parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
} | gpl-3.0 |
BGI-flexlab/SOAPgaeaDevelopment4.0 | src/main/java/org/bgi/flexlab/gaea/tools/annotator/SampleAnnotationContext.java | 9606 | /*******************************************************************************
* Copyright (c) 2017, BGI-Shenzhen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*******************************************************************************/
package org.bgi.flexlab.gaea.tools.annotator;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.GenotypeLikelihoods;
import htsjdk.variant.variantcontext.VariantContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The special annotation context for each sample
*/
public class SampleAnnotationContext{
public enum FilterTag {
FAIL, PASS, DUBIOUS
}
private String sampleName;
private List<String> alts; // variants at chr:pos
private int depth;
private int alleleDepthSum;
private Map<String, Integer> alleleDepths = null;
private Map<String, String> alleleRatios = null;
private Map<String, String> zygosity = null;
private Map<String, String> filter = null;
private boolean hasNearVar = false;
private boolean isCalled;
private String singleAlt;
private String qual;
public SampleAnnotationContext() {}
public SampleAnnotationContext(String sampleName) {
this.sampleName = sampleName;
}
public SampleAnnotationContext(String sampleName, VariantContext variantContext) {
this.sampleName = sampleName;
init(variantContext);
}
void init(VariantContext variantContext){
DecimalFormat df = new DecimalFormat("0.000");
df.setRoundingMode(RoundingMode.HALF_UP);
Genotype gt = variantContext.getGenotype(sampleName);
Map<String, Integer> alleleDepths = new HashMap<>();
Map<String, String> zygosity = new HashMap<>();
int i = 0;
List<String> alts = new ArrayList<>();
for(Allele allele: variantContext.getAlleles()){
if(gt.hasAD()){
alleleDepths.put(allele.getBaseString(), gt.getAD()[i]);
}
zygosity.put(allele.getBaseString(), getZygosityType(gt));
if(i > 0)
alts.add(allele.getBaseString());
i++;
}
setQual(df.format(variantContext.getPhredScaledQual()));
setCalled(gt.isCalled());
setAlleleDepths(alleleDepths);
setDepth(gt.getDP());
setAlts(alts);
setAlleleDepthSum(gt);
setZygosity(zygosity);
setFilter(variantContext, gt);
}
void add(VariantContext variantContext){
Genotype gt = variantContext.getGenotype(sampleName);
int[] AD = gt.getAD();
int i = 0;
for(Allele allele: variantContext.getAlternateAlleles()){
i++;
if(alts.contains(allele.getBaseString()))
continue;
alts.add(allele.getBaseString());
alleleDepths.put(allele.getBaseString(), AD[i]);
zygosity.put(allele.getBaseString(), getZygosityType(gt));
filter.put(allele.getBaseString(), calculateAlleleFilterTag(variantContext, gt, AD[i]).toString());
}
}
private String getZygosityType(Genotype gt){
if(gt.isNoCall())
return "noCall";
if(gt.isHetNonRef())
return "het-alt";
if(gt.isHet())
return "het-ref";
if(gt.isHomVar())
return "hom-alt";
return ".";
}
public String getFieldByName(String fieldName, String allele) {
switch (fieldName) {
case "SAMPLE":
return getSampleName();
case "NbGID":
if(hasNearVar) return "1";
else return "0";
case "A.Depth":
return Integer.toString(getAlleleDepth(allele));
case "A.Ratio":
return getAlleleRatio(allele);
case "Zygosity":
return getAlleleZygosity(allele);
case "Filter":
return getAlleleFilter(allele);
case "QUAL":
return getQual();
case "DP":
return Integer.toString(getDepth());
default:
return null;
}
}
public String getSampleName() {
return sampleName;
}
public void setSampleName(String sampleName) {
this.sampleName = sampleName;
}
public boolean isHasNearVar() {
return hasNearVar;
}
public void setHasNearVar() {
this.hasNearVar = true;
updateFilterTag();
}
private void updateFilterTag() {
for (String key: filter.keySet()){
if(filter.get(key).equals(FilterTag.PASS.toString()))
filter.put(key, FilterTag.DUBIOUS.toString());
}
}
private void setAlleleRatios(){
if(alleleDepths.isEmpty() || getDepth() == -1) return;
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
alleleRatios = new HashMap<>();
for(String alt: getAlts()){
double ratio = getDepth() == 0 ? 0 : getAlleleDepth(alt)*1.0 / getAlleleDepthSum();
alleleRatios.put(alt, df.format(ratio));
}
}
public String getAlleleZygosity(String allele) {
return zygosity.get(allele);
}
public Map<String, String> getZygosity() {
return zygosity;
}
public void setZygosity(Map<String, String> zygosity) {
this.zygosity = zygosity;
}
public void setAlleleDepthSum(Genotype gt) {
alleleDepthSum = 0;
for(int altDP: gt.getAD()){
alleleDepthSum += altDP;
}
}
public int getDepth() {
return depth;
}
public int getAlleleDepthSum() {
return alleleDepthSum;
}
public void setDepth(int depth) {
this.depth = depth;
}
public Map<String, Integer> getAlleleDepths() {
return alleleDepths;
}
public void setAlleleDepths(Map<String, Integer> alleleDepths) {
this.alleleDepths = alleleDepths;
}
public List<String> getAlts() {
return alts;
}
public void setAlts(List<String> alts) {
this.alts = alts;
}
public String getSingleAlt() {
return singleAlt;
}
public boolean hasAlt(String alt){
return alts.contains(alt);
}
public String getAlleleRatio(String allele){
if(alleleRatios == null || alleleRatios.isEmpty())
return ".";
return alleleRatios.get(allele);
}
public int getAlleleDepth(String allele){
if(alleleDepths == null || alleleDepths.isEmpty())
return -1;
return alleleDepths.get(allele);
}
public String toAlleleString(String allele){
if(null == alleleRatios)
setAlleleRatios();
StringBuilder sb = new StringBuilder();
sb.append(getSampleName());
sb.append("|");
sb.append(allele);
sb.append("|");
sb.append(getAlleleRatio(allele));
sb.append("|");
sb.append(getAlleleDepth(allele) == -1 ? "." : getAlleleDepth(allele));
sb.append("|");
sb.append(isHasNearVar() ? 1 : 0);
sb.append("|");
sb.append(getAlleleZygosity(allele));
sb.append("|");
sb.append(getAlleleFilter(allele));
sb.append("|");
sb.append(getQual());
sb.append("|");
sb.append(getDepth());
return sb.toString();
}
public void parseAlleleString(String alleleString){
String[] fields = alleleString.split("\\|");
setSampleName(fields[0]);
singleAlt = fields[1];
alleleRatios = new HashMap<>();
alleleDepths = new HashMap<>();
zygosity = new HashMap<>();
filter = new HashMap<>();
if(!fields[2].equals("."))
alleleRatios.put(singleAlt, fields[2]);
if(!fields[3].equals("."))
alleleDepths.put(singleAlt, Integer.parseInt(fields[3]));
if(fields[4].equals("1"))
setHasNearVar();
zygosity.put(singleAlt, fields[5]);
filter.put(singleAlt, fields[6]);
setQual(fields[7]);
setDepth(Integer.parseInt(fields[8]));
}
public boolean isCalled() {
return isCalled;
}
public void setCalled(boolean called) {
isCalled = called;
}
public String getAlleleFilter(String allele) {
return filter.get(allele);
}
public void setFilter(VariantContext vc, Genotype gt) {
Map<String, String> filter = new HashMap<>();
for(Allele allele : gt.getAlleles()){
if(allele.isNonReference()){
int alleleDepth = getAlleleDepth(allele.getBaseString());
FilterTag ft = calculateAlleleFilterTag(vc, gt, alleleDepth);
filter.put(allele.getBaseString(), ft.toString());
}
}
this.filter = filter;
}
private FilterTag calculateAlleleFilterTag(VariantContext vc, Genotype gt, int alleleDepth) {
int plIndicator = getAllelePLindicator(vc, gt);
if(alleleDepth <= 2 || plIndicator < 0)
return FilterTag.FAIL;
if(alleleDepth >= 8 && plIndicator > 0 && vc.isNotFiltered())
return FilterTag.PASS;
return FilterTag.DUBIOUS;
}
public static int getAllelePLindicator(VariantContext vc, Genotype gt){
if(!gt.hasPL())
return 1;
List<Integer> index = vc.getAlleleIndices(gt.getAlleles());
int plIndex = GenotypeLikelihoods.calculatePLindex(index.get(0), index.get(1));
int[] pls = gt.getPL();
int plValue = pls[plIndex];
if(plValue > 3 || hasOtherZeroPL(pls, plIndex)){
return -1;
}else if(plValue > 0 || hasOtherLessTenPL(pls, plIndex)) {
return 0;
}
return 1;
}
public static boolean hasOtherZeroPL(int[] pls, int skipIndex){
for (int i = 0; i < pls.length; i++) {
if(skipIndex == i)
continue;
if(pls[i] == 0)
return true;
}
return false;
}
public static boolean hasOtherLessTenPL(int[] pls, int skipIndex){
for (int i = 0; i < pls.length; i++) {
if(skipIndex == i)
continue;
if(pls[i] < 10)
return true;
}
return false;
}
public String getQual() {
return qual;
}
public void setQual(String qual) {
this.qual = qual;
}
}
| gpl-3.0 |
guardianproject/proofmode | app/src/main/java/org/witness/proofmode/ProofModeApp.java | 1896 | package org.witness.proofmode;
import static org.witness.proofmode.ProofMode.PREFS_DOPROOF;
import static org.witness.proofmode.ProofService.ACTION_START;
import android.content.Context;
import androidx.multidex.MultiDexApplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.util.Log;
import org.witness.proofmode.util.SafetyNetCheck;
import timber.log.Timber;
/**
* Created by n8fr8 on 10/10/16.
*/
public class ProofModeApp extends MultiDexApplication {
public final static String TAG = "ProofMode";
@Override
public void onCreate() {
super.onCreate();
init(this);
}
public void init (Context context)
{
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (prefs.getBoolean(PREFS_DOPROOF,false)) {
Intent intentService = new Intent(context, ProofService.class);
intentService.setAction(ACTION_START);
if (Build.VERSION.SDK_INT >= 26) {
context.startForegroundService(intentService);
} else {
context.startService(intentService);
}
}
}
public void cancel (Context context)
{
Intent intentService = new Intent(context, ProofService.class);
context.stopService(intentService);
}
/** A tree which logs important information for crash reporting. */
private static class CrashReportingTree extends Timber.Tree {
@Override protected void log(int priority, String tag, String message, Throwable t) {
if (priority == Log.VERBOSE || priority == Log.DEBUG) {
return;
}
}
}
}
| gpl-3.0 |