repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
swift/stroke | src/com/isode/stroke/avatars/OfflineAvatarManager.java | 955 | /*
* Copyright (c) 2010-2015 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
/*
* Copyright (c) 2015 Tarun Gupta.
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
package com.isode.stroke.avatars;
import com.isode.stroke.avatars.AvatarProvider;
import com.isode.stroke.avatars.AvatarStorage;
import com.isode.stroke.jid.JID;
public class OfflineAvatarManager extends AvatarProvider {
private AvatarStorage avatarStorage;
public OfflineAvatarManager(AvatarStorage avatarStorage) {
this.avatarStorage = avatarStorage;
}
@Override
public void delete() {
}
@Override
public String getAvatarHash(JID jid) {
return avatarStorage.getAvatarForJID(jid);
}
public void setAvatar(JID jid, String hash) {
if (!hash.equals(getAvatarHash(jid))) {
avatarStorage.setAvatarForJID(jid, hash);
onAvatarChanged.emit(jid);
}
}
} | gpl-3.0 |
Avalara/avataxbr-clients | java-client/src/main/java/io/swagger/client/model/TaxByTypeSummaryForGoods.java | 4101 | /*
* AvaTax Brazil
* The Avatax-Brazil API exposes the most commonly services available for interacting with the AvaTax-Brazil services, allowing calculation of taxes, issuing electronic invoice documents and modifying existing transactions when allowed by tax authorities. This API is exclusively for use by business with a physical presence in Brazil.
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* summary of all taxes
*/
@ApiModel(description = "summary of all taxes")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2017-04-06T17:54:07.550Z")
public class TaxByTypeSummaryForGoods {
@SerializedName("calcbase")
private Double calcbase = null;
@SerializedName("tax")
private Double tax = null;
@SerializedName("jurisdictions")
private List<TaxByTypeSummaryJurisdictionForGoods> jurisdictions = new ArrayList<TaxByTypeSummaryJurisdictionForGoods>();
public TaxByTypeSummaryForGoods calcbase(Double calcbase) {
this.calcbase = calcbase;
return this;
}
/**
* sum of all lines calcbase
* @return calcbase
**/
@ApiModelProperty(example = "null", value = "sum of all lines calcbase")
public Double getCalcbase() {
return calcbase;
}
public void setCalcbase(Double calcbase) {
this.calcbase = calcbase;
}
public TaxByTypeSummaryForGoods tax(Double tax) {
this.tax = tax;
return this;
}
/**
* sum of referenced tax value
* @return tax
**/
@ApiModelProperty(example = "null", value = "sum of referenced tax value")
public Double getTax() {
return tax;
}
public void setTax(Double tax) {
this.tax = tax;
}
public TaxByTypeSummaryForGoods jurisdictions(List<TaxByTypeSummaryJurisdictionForGoods> jurisdictions) {
this.jurisdictions = jurisdictions;
return this;
}
public TaxByTypeSummaryForGoods addJurisdictionsItem(TaxByTypeSummaryJurisdictionForGoods jurisdictionsItem) {
this.jurisdictions.add(jurisdictionsItem);
return this;
}
/**
* Get jurisdictions
* @return jurisdictions
**/
@ApiModelProperty(example = "null", value = "")
public List<TaxByTypeSummaryJurisdictionForGoods> getJurisdictions() {
return jurisdictions;
}
public void setJurisdictions(List<TaxByTypeSummaryJurisdictionForGoods> jurisdictions) {
this.jurisdictions = jurisdictions;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TaxByTypeSummaryForGoods taxByTypeSummaryForGoods = (TaxByTypeSummaryForGoods) o;
return Objects.equals(this.calcbase, taxByTypeSummaryForGoods.calcbase) &&
Objects.equals(this.tax, taxByTypeSummaryForGoods.tax) &&
Objects.equals(this.jurisdictions, taxByTypeSummaryForGoods.jurisdictions);
}
@Override
public int hashCode() {
return Objects.hash(calcbase, tax, jurisdictions);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TaxByTypeSummaryForGoods {\n");
sb.append(" calcbase: ").append(toIndentedString(calcbase)).append("\n");
sb.append(" tax: ").append(toIndentedString(tax)).append("\n");
sb.append(" jurisdictions: ").append(toIndentedString(jurisdictions)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| gpl-3.0 |
TheDragonTeam/TheDragonLib | src/main/java/net/thedragonteam/thedragonlib/network/internet/POSTResponse.java | 1302 | package net.thedragonteam.thedragonlib.network.internet;
public class POSTResponse {
public int statuscode;
public String result;
public String target;
public String params;
public String useragent;
public POSTResponse(int code) {
statuscode = code;
result = "";
target = "";
params = "";
useragent = "";
}
public POSTResponse(String res) {
statuscode = 200;
result = res;
target = "";
params = "";
useragent = "";
}
public POSTResponse(int code, String res) {
statuscode = code;
result = res;
target = "";
params = "";
useragent = "";
}
public POSTResponse(int code, String res, String tar) {
statuscode = code;
result = res;
target = tar;
params = "";
useragent = "";
}
public POSTResponse(int code, String res, String tar, String par) {
statuscode = code;
result = res;
target = tar;
params = par;
useragent = "";
}
public POSTResponse(int code, String res, String tar, String par, String agent) {
statuscode = code;
result = res;
target = tar;
params = par;
useragent = agent;
}
}
| gpl-3.0 |
WanDoJoe/MaxQ | MaxQ/src/com/utils/widget/MyGridView.java | 26583 | package com.utils.widget;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.DataSetObservable;
import android.database.DataSetObserver;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
/**
* 可以嵌套的GridView 所有absListView 只要复写onMeasure 即可实现正常嵌套
* 添加可以添加headerview和foodview功能
*
* @author sinosoft_wan
*
*/
public class MyGridView extends GridView {
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
initHeaderGridView();
}
/**
* 设置不滚动
*/
public static boolean DEBUG = false;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
/**
* A class that represents a fixed view in a list, for example a header at
* the top or a footer at the bottom.
*/
private static class FixedViewInfo {
/**
* The view to add to the grid
*/
public View view;
public ViewGroup viewContainer;
/**
* The data backing the view. This is returned from
* {@link ListAdapter#getItem(int)}.
*/
public Object data;
/**
* <code>true</code> if the fixed view should be selectable in the grid
*/
public boolean isSelectable;
}
private int mNumColumns = AUTO_FIT;
private View mViewForMeasureRowHeight = null;
private int mRowHeight = -1;
// log tag can be at most 23 characters
private static final String LOG_TAG = "GridViewHeaderAndFooter";
private ArrayList<FixedViewInfo> mHeaderViewInfos = new ArrayList<FixedViewInfo>();
private ArrayList<FixedViewInfo> mFooterViewInfos = new ArrayList<FixedViewInfo>();
private ListAdapter mOriginalAdapter;
private ItemClickHandler mItemClickHandler;
private void initHeaderGridView() {
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpecHeight = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpecHeight);
ListAdapter adapter = getAdapter();
if (adapter != null && adapter instanceof HeaderViewGridAdapter) {
((HeaderViewGridAdapter) adapter)
.setNumColumns(getNumColumnsCompatible());
((HeaderViewGridAdapter) adapter).setRowHeight(getRowHeight());
}
}
@Override
public void setClipChildren(boolean clipChildren) {
// Ignore, since the header rows depend on not being clipped
}
/**
* Do not call this method unless you know how it works.
*
* @param clipChildren
*/
public void setClipChildrenSupper(boolean clipChildren) {
super.setClipChildren(false);
}
/**
* Add a fixed view to appear at the top of the grid. If addHeaderView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p/>
* NOTE: Call this before calling setAdapter. This is so HeaderGridView can
* wrap the supplied cursor with one that will also account for header
* views.
*
* @param v
* The view to add.
*/
public void addHeaderView(View v) {
addHeaderView(v, null, true);
}
/**
* Add a fixed view to appear at the top of the grid. If addHeaderView is
* called more than once, the views will appear in the order they were
* added. Views added using this call can take focus if they want.
* <p/>
* NOTE: Call this before calling setAdapter. This is so HeaderGridView can
* wrap the supplied cursor with one that will also account for header
* views.
*
* @param v
* The view to add.
* @param data
* Data to associate with this view
* @param isSelectable
* whether the item is selectable
*/
public void addHeaderView(View v, Object data, boolean isSelectable) {
ListAdapter adapter = getAdapter();
if (adapter != null && !(adapter instanceof HeaderViewGridAdapter)) {
throw new IllegalStateException(
"Cannot add header view to grid -- setAdapter has already been called.");
}
ViewGroup.LayoutParams lyp = v.getLayoutParams();
FixedViewInfo info = new FixedViewInfo();
FrameLayout fl = new FullWidthFixedViewLayout(getContext());
if (lyp != null) {
v.setLayoutParams(new FrameLayout.LayoutParams(lyp.width,
lyp.height));
fl.setLayoutParams(new AbsListView.LayoutParams(lyp.width,
lyp.height));
}
fl.addView(v);
info.view = v;
info.viewContainer = fl;
info.data = data;
info.isSelectable = isSelectable;
mHeaderViewInfos.add(info);
// in the case of re-adding a header view, or adding one later on,
// we need to notify the observer
if (adapter != null) {
((HeaderViewGridAdapter) adapter).notifyDataSetChanged();
}
}
public void addFooterView(View v) {
addFooterView(v, null, true);
}
public void addFooterView(View v, Object data, boolean isSelectable) {
ListAdapter mAdapter = getAdapter();
if (mAdapter != null && !(mAdapter instanceof HeaderViewGridAdapter)) {
throw new IllegalStateException(
"Cannot add header view to grid -- setAdapter has already been called.");
}
ViewGroup.LayoutParams lyp = v.getLayoutParams();
FixedViewInfo info = new FixedViewInfo();
FrameLayout fl = new FullWidthFixedViewLayout(getContext());
if (lyp != null) {
v.setLayoutParams(new FrameLayout.LayoutParams(lyp.width,
lyp.height));
fl.setLayoutParams(new AbsListView.LayoutParams(lyp.width,
lyp.height));
}
fl.addView(v);
info.view = v;
info.viewContainer = fl;
info.data = data;
info.isSelectable = isSelectable;
mFooterViewInfos.add(info);
if (mAdapter != null) {
((HeaderViewGridAdapter) mAdapter).notifyDataSetChanged();
}
}
public int getHeaderViewCount() {
return mHeaderViewInfos.size();
}
public int getFooterViewCount() {
return mFooterViewInfos.size();
}
/**
* Removes a previously-added header view.
*
* @param v
* The view to remove
* @return true if the view was removed, false if the view was not a header
* view
*/
public boolean removeHeaderView(View v) {
if (mHeaderViewInfos.size() > 0) {
boolean result = false;
ListAdapter adapter = getAdapter();
if (adapter != null
&& ((HeaderViewGridAdapter) adapter).removeHeader(v)) {
result = true;
}
removeFixedViewInfo(v, mHeaderViewInfos);
return result;
}
return false;
}
/**
* Removes a previously-added footer view.
*
* @param v
* The view to remove
* @return true if the view was removed, false if the view was not a header
* view
*/
public boolean removeFooterView(View v) {
if (mFooterViewInfos.size() > 0) {
boolean result = false;
ListAdapter adapter = getAdapter();
if (adapter != null
&& ((HeaderViewGridAdapter) adapter).removeFooter(v)) {
result = true;
}
removeFixedViewInfo(v, mFooterViewInfos);
return result;
}
return false;
}
private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where) {
int len = where.size();
for (int i = 0; i < len; ++i) {
FixedViewInfo info = where.get(i);
if (info.view == v) {
where.remove(i);
break;
}
}
}
@TargetApi(11)
private int getNumColumnsCompatible() {
if (Build.VERSION.SDK_INT >= 11) {
return super.getNumColumns();
} else {
try {
Field numColumns = GridView.class
.getDeclaredField("mNumColumns");
numColumns.setAccessible(true);
return numColumns.getInt(this);
} catch (Exception e) {
if (mNumColumns != -1) {
return mNumColumns;
}
throw new RuntimeException(
"Can not determine the mNumColumns for this API platform, please call setNumColumns to set it.");
}
}
}
@TargetApi(16)
private int getColumnWidthCompatible() {
if (Build.VERSION.SDK_INT >= 16) {
return super.getColumnWidth();
} else {
try {
Field numColumns = GridView.class
.getDeclaredField("mColumnWidth");
numColumns.setAccessible(true);
return numColumns.getInt(this);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mViewForMeasureRowHeight = null;
}
public void invalidateRowHeight() {
mRowHeight = -1;
}
public int getHeaderHeight(int row) {
if (row >= 0) {
return mHeaderViewInfos.get(row).view.getMeasuredHeight();
}
return 0;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public int getVerticalSpacing() {
int value = 0;
try {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < Build.VERSION_CODES.JELLY_BEAN) {
Field field = GridView.class
.getDeclaredField("mVerticalSpacing");
field.setAccessible(true);
value = field.getInt(this);
} else {
value = super.getVerticalSpacing();
}
} catch (Exception ignore) {
}
return value;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public int getHorizontalSpacing() {
int value = 0;
try {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < Build.VERSION_CODES.JELLY_BEAN) {
Field field = GridView.class
.getDeclaredField("mHorizontalSpacing");
field.setAccessible(true);
value = field.getInt(this);
} else {
value = super.getHorizontalSpacing();
}
} catch (Exception ignore) {
}
return value;
}
public int getRowHeight() {
if (mRowHeight > 0) {
return mRowHeight;
}
ListAdapter adapter = getAdapter();
int numColumns = getNumColumnsCompatible();
// adapter has not been set or has no views in it;
if (adapter == null
|| adapter.getCount() <= numColumns
* (mHeaderViewInfos.size() + mFooterViewInfos.size())) {
return -1;
}
int mColumnWidth = getColumnWidthCompatible();
View view = getAdapter().getView(numColumns * mHeaderViewInfos.size(),
mViewForMeasureRowHeight, this);
AbsListView.LayoutParams p = (AbsListView.LayoutParams) view
.getLayoutParams();
if (p == null) {
p = new AbsListView.LayoutParams(-1, -2, 0);
view.setLayoutParams(p);
}
int childHeightSpec = getChildMeasureSpec(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 0,
p.height);
int childWidthSpec = getChildMeasureSpec(
MeasureSpec.makeMeasureSpec(mColumnWidth, MeasureSpec.EXACTLY),
0, p.width);
view.measure(childWidthSpec, childHeightSpec);
mViewForMeasureRowHeight = view;
mRowHeight = view.getMeasuredHeight();
return mRowHeight;
}
@TargetApi(11)
public void tryToScrollToBottomSmoothly() {
int lastPos = getAdapter().getCount() - 1;
if (Build.VERSION.SDK_INT >= 11) {
smoothScrollToPositionFromTop(lastPos, 0);
} else {
setSelection(lastPos);
}
}
@TargetApi(11)
public void tryToScrollToBottomSmoothly(int duration) {
int lastPos = getAdapter().getCount() - 1;
if (Build.VERSION.SDK_INT >= 11) {
smoothScrollToPositionFromTop(lastPos, 0, duration);
} else {
setSelection(lastPos);
}
}
@Override
public void setAdapter(ListAdapter adapter) {
mOriginalAdapter = adapter;
if (mHeaderViewInfos.size() > 0 || mFooterViewInfos.size() > 0) {
HeaderViewGridAdapter headerViewGridAdapter = new HeaderViewGridAdapter(
mHeaderViewInfos, mFooterViewInfos, adapter);
int numColumns = getNumColumnsCompatible();
if (numColumns > 1) {
headerViewGridAdapter.setNumColumns(numColumns);
}
headerViewGridAdapter.setRowHeight(getRowHeight());
super.setAdapter(headerViewGridAdapter);
} else {
super.setAdapter(adapter);
}
}
/**
* Return original adapter for convenience.
*
* @return
*/
public ListAdapter getOriginalAdapter() {
return mOriginalAdapter;
}
/**
* full width
*/
private class FullWidthFixedViewLayout extends FrameLayout {
public FullWidthFixedViewLayout(Context context) {
super(context);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
int realLeft = MyGridView.this.getPaddingLeft() + getPaddingLeft();
// Try to make where it should be, from left, full width
if (realLeft != left) {
offsetLeftAndRight(realLeft - left);
}
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int targetWidth = MyGridView.this.getMeasuredWidth()
- MyGridView.this.getPaddingLeft()
- MyGridView.this.getPaddingRight();
widthMeasureSpec = MeasureSpec.makeMeasureSpec(targetWidth,
MeasureSpec.getMode(widthMeasureSpec));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
public void setNumColumns(int numColumns) {
super.setNumColumns(numColumns);
mNumColumns = numColumns;
ListAdapter adapter = getAdapter();
if (adapter != null && adapter instanceof HeaderViewGridAdapter) {
((HeaderViewGridAdapter) adapter).setNumColumns(numColumns);
}
}
/**
* ListAdapter used when a HeaderGridView has header views. This ListAdapter
* wraps another one and also keeps track of the header views and their
* associated data objects.
* <p>
* This is intended as a base class; you will probably not need to use this
* class directly in your own code.
*/
private static class HeaderViewGridAdapter implements WrapperListAdapter,
Filterable {
// This is used to notify the container of updates relating to number of
// columns
// or headers changing, which changes the number of placeholders needed
private final DataSetObservable mDataSetObservable = new DataSetObservable();
private final ListAdapter mAdapter;
static final ArrayList<FixedViewInfo> EMPTY_INFO_LIST = new ArrayList<FixedViewInfo>();
// This ArrayList is assumed to NOT be null.
ArrayList<FixedViewInfo> mHeaderViewInfos;
ArrayList<FixedViewInfo> mFooterViewInfos;
private int mNumColumns = 1;
private int mRowHeight = -1;
boolean mAreAllFixedViewsSelectable;
private final boolean mIsFilterable;
private boolean mCachePlaceHoldView = true;
// From Recycle Bin or calling getView, this a question...
private boolean mCacheFirstHeaderView = false;
public HeaderViewGridAdapter(ArrayList<FixedViewInfo> headerViewInfos,
ArrayList<FixedViewInfo> footViewInfos, ListAdapter adapter) {
mAdapter = adapter;
mIsFilterable = adapter instanceof Filterable;
if (headerViewInfos == null) {
mHeaderViewInfos = EMPTY_INFO_LIST;
} else {
mHeaderViewInfos = headerViewInfos;
}
if (footViewInfos == null) {
mFooterViewInfos = EMPTY_INFO_LIST;
} else {
mFooterViewInfos = footViewInfos;
}
mAreAllFixedViewsSelectable = areAllListInfosSelectable(mHeaderViewInfos)
&& areAllListInfosSelectable(mFooterViewInfos);
}
public void setNumColumns(int numColumns) {
if (numColumns < 1) {
return;
}
if (mNumColumns != numColumns) {
mNumColumns = numColumns;
notifyDataSetChanged();
}
}
public void setRowHeight(int height) {
mRowHeight = height;
}
public int getHeadersCount() {
return mHeaderViewInfos.size();
}
public int getFootersCount() {
return mFooterViewInfos.size();
}
/**
* @return true if this adapter doesn't contain any data. This is used
* to determine whether the empty view should be displayed. A
* typical implementation will return getCount() == 0 but since
* getCount() includes the headers and footers, specialized
* adapters might want a different behavior.
*/
@Override
public boolean isEmpty() {
return (mAdapter == null || mAdapter.isEmpty());
}
private boolean areAllListInfosSelectable(ArrayList<FixedViewInfo> infos) {
if (infos != null) {
for (FixedViewInfo info : infos) {
if (!info.isSelectable) {
return false;
}
}
}
return true;
}
public boolean removeHeader(View v) {
for (int i = 0; i < mHeaderViewInfos.size(); i++) {
FixedViewInfo info = mHeaderViewInfos.get(i);
if (info.view == v) {
mHeaderViewInfos.remove(i);
mAreAllFixedViewsSelectable = areAllListInfosSelectable(mHeaderViewInfos)
&& areAllListInfosSelectable(mFooterViewInfos);
mDataSetObservable.notifyChanged();
return true;
}
}
return false;
}
public boolean removeFooter(View v) {
for (int i = 0; i < mFooterViewInfos.size(); i++) {
FixedViewInfo info = mFooterViewInfos.get(i);
if (info.view == v) {
mFooterViewInfos.remove(i);
mAreAllFixedViewsSelectable = areAllListInfosSelectable(mHeaderViewInfos)
&& areAllListInfosSelectable(mFooterViewInfos);
mDataSetObservable.notifyChanged();
return true;
}
}
return false;
}
@Override
public int getCount() {
if (mAdapter != null) {
return (getFootersCount() + getHeadersCount()) * mNumColumns
+ getAdapterAndPlaceHolderCount();
} else {
return (getFootersCount() + getHeadersCount()) * mNumColumns;
}
}
@Override
public boolean areAllItemsEnabled() {
return mAdapter == null || mAreAllFixedViewsSelectable
&& mAdapter.areAllItemsEnabled();
}
private int getAdapterAndPlaceHolderCount() {
return (int) (Math.ceil(1f * mAdapter.getCount() / mNumColumns) * mNumColumns);
}
@Override
public boolean isEnabled(int position) {
// Header (negative positions will throw an
// IndexOutOfBoundsException)
int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
if (position < numHeadersAndPlaceholders) {
return position % mNumColumns == 0
&& mHeaderViewInfos.get(position / mNumColumns).isSelectable;
}
// Adapter
final int adjPosition = position - numHeadersAndPlaceholders;
int adapterCount = 0;
if (mAdapter != null) {
adapterCount = getAdapterAndPlaceHolderCount();
if (adjPosition < adapterCount) {
return adjPosition < mAdapter.getCount()
&& mAdapter.isEnabled(adjPosition);
}
}
// Footer (off-limits positions will throw an
// IndexOutOfBoundsException)
final int footerPosition = adjPosition - adapterCount;
return footerPosition % mNumColumns == 0
&& mFooterViewInfos.get(footerPosition / mNumColumns).isSelectable;
}
@Override
public Object getItem(int position) {
// Header (negative positions will throw an
// ArrayIndexOutOfBoundsException)
int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
if (position < numHeadersAndPlaceholders) {
if (position % mNumColumns == 0) {
return mHeaderViewInfos.get(position / mNumColumns).data;
}
return null;
}
// Adapter
final int adjPosition = position - numHeadersAndPlaceholders;
int adapterCount = 0;
if (mAdapter != null) {
adapterCount = getAdapterAndPlaceHolderCount();
if (adjPosition < adapterCount) {
if (adjPosition < mAdapter.getCount()) {
return mAdapter.getItem(adjPosition);
} else {
return null;
}
}
}
// Footer (off-limits positions will throw an
// IndexOutOfBoundsException)
final int footerPosition = adjPosition - adapterCount;
if (footerPosition % mNumColumns == 0) {
return mFooterViewInfos.get(footerPosition).data;
} else {
return null;
}
}
@Override
public long getItemId(int position) {
int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
if (mAdapter != null && position >= numHeadersAndPlaceholders) {
int adjPosition = position - numHeadersAndPlaceholders;
int adapterCount = mAdapter.getCount();
if (adjPosition < adapterCount) {
return mAdapter.getItemId(adjPosition);
}
}
return -1;
}
@Override
public boolean hasStableIds() {
return mAdapter != null && mAdapter.hasStableIds();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (DEBUG) {
Log.d(LOG_TAG, String.format("getView: %s, reused: %s",
position, convertView == null));
}
// Header (negative positions will throw an
// ArrayIndexOutOfBoundsException)
int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
if (position < numHeadersAndPlaceholders) {
View headerViewContainer = mHeaderViewInfos.get(position
/ mNumColumns).viewContainer;
if (position % mNumColumns == 0) {
return headerViewContainer;
} else {
if (convertView == null) {
convertView = new View(parent.getContext());
}
// We need to do this because GridView uses the height of
// the last item
// in a row to determine the height for the entire row.
convertView.setVisibility(View.INVISIBLE);
convertView.setMinimumHeight(headerViewContainer
.getHeight());
return convertView;
}
}
// Adapter
final int adjPosition = position - numHeadersAndPlaceholders;
int adapterCount = 0;
if (mAdapter != null) {
adapterCount = getAdapterAndPlaceHolderCount();
if (adjPosition < adapterCount) {
if (adjPosition < mAdapter.getCount()) {
return mAdapter.getView(adjPosition, convertView,
parent);
} else {
if (convertView == null) {
convertView = new View(parent.getContext());
}
convertView.setVisibility(View.INVISIBLE);
convertView.setMinimumHeight(mRowHeight);
return convertView;
}
}
}
// Footer
final int footerPosition = adjPosition - adapterCount;
if (footerPosition < getCount()) {
View footViewContainer = mFooterViewInfos.get(footerPosition
/ mNumColumns).viewContainer;
if (position % mNumColumns == 0) {
return footViewContainer;
} else {
if (convertView == null) {
convertView = new View(parent.getContext());
}
// We need to do this because GridView uses the height of
// the last item
// in a row to determine the height for the entire row.
convertView.setVisibility(View.INVISIBLE);
convertView.setMinimumHeight(footViewContainer.getHeight());
return convertView;
}
}
throw new ArrayIndexOutOfBoundsException(position);
}
@Override
public int getItemViewType(int position) {
final int numHeadersAndPlaceholders = getHeadersCount()
* mNumColumns;
final int adapterViewTypeStart = mAdapter == null ? 0 : mAdapter
.getViewTypeCount() - 1;
int type = AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER;
if (mCachePlaceHoldView) {
// Header
if (position < numHeadersAndPlaceholders) {
if (position == 0) {
if (mCacheFirstHeaderView) {
type = adapterViewTypeStart
+ mHeaderViewInfos.size()
+ mFooterViewInfos.size() + 1 + 1;
}
}
if (position % mNumColumns != 0) {
type = adapterViewTypeStart
+ (position / mNumColumns + 1);
}
}
}
// Adapter
final int adjPosition = position - numHeadersAndPlaceholders;
int adapterCount = 0;
if (mAdapter != null) {
adapterCount = getAdapterAndPlaceHolderCount();
if (adjPosition >= 0 && adjPosition < adapterCount) {
if (adjPosition < mAdapter.getCount()) {
type = mAdapter.getItemViewType(adjPosition);
} else {
if (mCachePlaceHoldView) {
type = adapterViewTypeStart
+ mHeaderViewInfos.size() + 1;
}
}
}
}
if (mCachePlaceHoldView) {
// Footer
final int footerPosition = adjPosition - adapterCount;
if (footerPosition >= 0 && footerPosition < getCount()
&& (footerPosition % mNumColumns) != 0) {
type = adapterViewTypeStart + mHeaderViewInfos.size() + 1
+ (footerPosition / mNumColumns + 1);
}
}
if (DEBUG) {
Log.d(LOG_TAG, String.format(
"getItemViewType: pos: %s, result: %s", position, type,
mCachePlaceHoldView, mCacheFirstHeaderView));
}
return type;
}
/**
* content view, content view holder, header[0], header and footer
* placeholder(s)
*
* @return
*/
@Override
public int getViewTypeCount() {
int count = mAdapter == null ? 1 : mAdapter.getViewTypeCount();
if (mCachePlaceHoldView) {
int offset = mHeaderViewInfos.size() + 1
+ mFooterViewInfos.size();
if (mCacheFirstHeaderView) {
offset += 1;
}
count += offset;
}
if (DEBUG) {
Log.d(LOG_TAG, String.format("getViewTypeCount: %s", count));
}
return count;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
mDataSetObservable.registerObserver(observer);
if (mAdapter != null) {
mAdapter.registerDataSetObserver(observer);
}
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
mDataSetObservable.unregisterObserver(observer);
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(observer);
}
}
@Override
public Filter getFilter() {
if (mIsFilterable) {
return ((Filterable) mAdapter).getFilter();
}
return null;
}
@Override
public ListAdapter getWrappedAdapter() {
return mAdapter;
}
public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}
}
@Override
public void setOnItemClickListener(OnItemClickListener l) {
mOnItemClickListener = l;
super.setOnItemClickListener(getItemClickHandler());
}
@Override
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
mOnItemLongClickListener = listener;
super.setOnItemLongClickListener(getItemClickHandler());
}
private ItemClickHandler getItemClickHandler() {
if (mItemClickHandler == null) {
mItemClickHandler = new ItemClickHandler();
}
return mItemClickHandler;
}
private class ItemClickHandler implements
android.widget.AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (mOnItemClickListener != null) {
int resPos = position - getHeaderViewCount()
* getNumColumnsCompatible();
if (resPos >= 0) {
mOnItemClickListener.onItemClick(parent, view, resPos, id);
}
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
if (mOnItemLongClickListener != null) {
int resPos = position - getHeaderViewCount()
* getNumColumnsCompatible();
if (resPos >= 0) {
mOnItemLongClickListener.onItemLongClick(parent, view,
resPos, id);
}
}
return true;
}
}
}
| gpl-3.0 |
wbhicks/annotated-configs | GroovyTest1_2008-12-nn/our/SimpleTileJ.java | 1427 | /**
* The purpose of this file is to hold the class of the same name.
* Created Dec 18, 2008.
*/
package our;
/**
* Will be hex tiles, for now.
*/
public class SimpleTileJ implements Tile {
/**
* nice column for the next tile to be constructed
*/
static int candidateXPosition = 0;
/**
* nice row for the next tile to be constructed
*/
static int candidateYPosition = 0;
/**
* 0 indicates the leftmost column
*/
int xPosition;
/**
* 0 indicates the bottom row
*/
int yPosition;
/**
* TODO clear (i.e. transparent) should be the default
*/
java.awt.Color color = java.awt.Color.MAGENTA;
/**
* @param theXPosition Which column?
* @param theYPosition Which row?
*/
public SimpleTileJ(int theXPosition, int theYPosition) {
xPosition = theXPosition;
yPosition = theYPosition;
if ( xPosition == candidateXPosition
&& yPosition == candidateYPosition )
{
updateCandidatePositions();
}
}
/**
* the no-arg constructor
*/
public SimpleTileJ() {
xPosition = candidateXPosition;
yPosition = candidateYPosition;
updateCandidatePositions();
}
/**
* Called IFF the candidate location has
* just been filled, and we need a new one.
*/
private void updateCandidatePositions() {
/*
* Foolishly assumes (x+1,y+1) is free. This is
* dangerous if the no-arg constructor is called.
* Also, tiles will race toward the northeast.
*/
candidateXPosition++;
candidateYPosition++;
}
}
| gpl-3.0 |
getgauge/Gauge-Eclipse | io.getgauge/src-gen/io/getgauge/spec/impl/SpecPackageImpl.java | 18423 | /**
*/
package io.getgauge.spec.impl;
import io.getgauge.spec.Comment;
import io.getgauge.spec.DynamicParam;
import io.getgauge.spec.Element;
import io.getgauge.spec.Model;
import io.getgauge.spec.Scenario;
import io.getgauge.spec.Spec;
import io.getgauge.spec.SpecFactory;
import io.getgauge.spec.SpecPackage;
import io.getgauge.spec.StaticParam;
import io.getgauge.spec.Step;
import io.getgauge.spec.StepDefinition;
import io.getgauge.spec.Table;
import io.getgauge.spec.TableCell;
import io.getgauge.spec.TableRow;
import io.getgauge.spec.Tags;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class SpecPackageImpl extends EPackageImpl implements SpecPackage
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass modelEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass elementEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass specEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass scenarioEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass stepEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass stepDefinitionEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass staticParamEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass dynamicParamEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass tagsEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass commentEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass tableEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass tableRowEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass tableCellEClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see io.getgauge.spec.SpecPackage#eNS_URI
* @see #init()
* @generated
*/
private SpecPackageImpl()
{
super(eNS_URI, SpecFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link SpecPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static SpecPackage init()
{
if (isInited) return (SpecPackage)EPackage.Registry.INSTANCE.getEPackage(SpecPackage.eNS_URI);
// Obtain or create and register package
SpecPackageImpl theSpecPackage = (SpecPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof SpecPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new SpecPackageImpl());
isInited = true;
// Create package meta-data objects
theSpecPackage.createPackageContents();
// Initialize created meta-data
theSpecPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theSpecPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(SpecPackage.eNS_URI, theSpecPackage);
return theSpecPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getModel()
{
return modelEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getModel_Definitions()
{
return (EReference)modelEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getElement()
{
return elementEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getSpec()
{
return specEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getSpec_Name()
{
return (EAttribute)specEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getScenario()
{
return scenarioEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getScenario_Name()
{
return (EAttribute)scenarioEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getStep()
{
return stepEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getStep_Definition()
{
return (EReference)stepEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getStep_Table()
{
return (EReference)stepEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getStepDefinition()
{
return stepDefinitionEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getStepDefinition_StaticParams()
{
return (EReference)stepDefinitionEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getStepDefinition_DynamicParams()
{
return (EReference)stepDefinitionEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getStepDefinition_Text()
{
return (EAttribute)stepDefinitionEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getStepDefinition_Separators()
{
return (EAttribute)stepDefinitionEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getStaticParam()
{
return staticParamEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getStaticParam_Name()
{
return (EAttribute)staticParamEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getDynamicParam()
{
return dynamicParamEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getDynamicParam_Name()
{
return (EAttribute)dynamicParamEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getTags()
{
return tagsEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getComment()
{
return commentEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getComment_Name()
{
return (EAttribute)commentEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getTable()
{
return tableEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getTable_Heading()
{
return (EReference)tableEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getTable_Rows()
{
return (EReference)tableEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getTableRow()
{
return tableRowEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getTableRow_Cells()
{
return (EReference)tableRowEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getTableCell()
{
return tableCellEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getTableCell_Name()
{
return (EAttribute)tableCellEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SpecFactory getSpecFactory()
{
return (SpecFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents()
{
if (isCreated) return;
isCreated = true;
// Create classes and their features
modelEClass = createEClass(MODEL);
createEReference(modelEClass, MODEL__DEFINITIONS);
elementEClass = createEClass(ELEMENT);
specEClass = createEClass(SPEC);
createEAttribute(specEClass, SPEC__NAME);
scenarioEClass = createEClass(SCENARIO);
createEAttribute(scenarioEClass, SCENARIO__NAME);
stepEClass = createEClass(STEP);
createEReference(stepEClass, STEP__DEFINITION);
createEReference(stepEClass, STEP__TABLE);
stepDefinitionEClass = createEClass(STEP_DEFINITION);
createEReference(stepDefinitionEClass, STEP_DEFINITION__STATIC_PARAMS);
createEReference(stepDefinitionEClass, STEP_DEFINITION__DYNAMIC_PARAMS);
createEAttribute(stepDefinitionEClass, STEP_DEFINITION__TEXT);
createEAttribute(stepDefinitionEClass, STEP_DEFINITION__SEPARATORS);
staticParamEClass = createEClass(STATIC_PARAM);
createEAttribute(staticParamEClass, STATIC_PARAM__NAME);
dynamicParamEClass = createEClass(DYNAMIC_PARAM);
createEAttribute(dynamicParamEClass, DYNAMIC_PARAM__NAME);
tagsEClass = createEClass(TAGS);
commentEClass = createEClass(COMMENT);
createEAttribute(commentEClass, COMMENT__NAME);
tableEClass = createEClass(TABLE);
createEReference(tableEClass, TABLE__HEADING);
createEReference(tableEClass, TABLE__ROWS);
tableRowEClass = createEClass(TABLE_ROW);
createEReference(tableRowEClass, TABLE_ROW__CELLS);
tableCellEClass = createEClass(TABLE_CELL);
createEAttribute(tableCellEClass, TABLE_CELL__NAME);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents()
{
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
specEClass.getESuperTypes().add(this.getElement());
scenarioEClass.getESuperTypes().add(this.getElement());
stepEClass.getESuperTypes().add(this.getElement());
tagsEClass.getESuperTypes().add(this.getElement());
commentEClass.getESuperTypes().add(this.getElement());
// Initialize classes and features; add operations and parameters
initEClass(modelEClass, Model.class, "Model", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getModel_Definitions(), this.getElement(), null, "definitions", null, 0, -1, Model.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(elementEClass, Element.class, "Element", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEClass(specEClass, Spec.class, "Spec", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getSpec_Name(), ecorePackage.getEString(), "name", null, 0, -1, Spec.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(scenarioEClass, Scenario.class, "Scenario", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getScenario_Name(), ecorePackage.getEString(), "name", null, 0, -1, Scenario.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(stepEClass, Step.class, "Step", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getStep_Definition(), this.getStepDefinition(), null, "definition", null, 0, 1, Step.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getStep_Table(), this.getTable(), null, "table", null, 0, 1, Step.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(stepDefinitionEClass, StepDefinition.class, "StepDefinition", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getStepDefinition_StaticParams(), this.getStaticParam(), null, "staticParams", null, 0, -1, StepDefinition.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getStepDefinition_DynamicParams(), this.getDynamicParam(), null, "dynamicParams", null, 0, -1, StepDefinition.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getStepDefinition_Text(), ecorePackage.getEString(), "text", null, 0, -1, StepDefinition.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getStepDefinition_Separators(), ecorePackage.getEString(), "separators", null, 0, -1, StepDefinition.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(staticParamEClass, StaticParam.class, "StaticParam", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getStaticParam_Name(), ecorePackage.getEString(), "name", null, 0, 1, StaticParam.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(dynamicParamEClass, DynamicParam.class, "DynamicParam", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getDynamicParam_Name(), ecorePackage.getEString(), "name", null, 0, 1, DynamicParam.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(tagsEClass, Tags.class, "Tags", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEClass(commentEClass, Comment.class, "Comment", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getComment_Name(), ecorePackage.getEString(), "name", null, 0, -1, Comment.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(tableEClass, Table.class, "Table", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getTable_Heading(), this.getTableRow(), null, "heading", null, 0, 1, Table.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getTable_Rows(), this.getTableRow(), null, "rows", null, 0, -1, Table.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(tableRowEClass, TableRow.class, "TableRow", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getTableRow_Cells(), this.getTableCell(), null, "cells", null, 0, -1, TableRow.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(tableCellEClass, TableCell.class, "TableCell", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getTableCell_Name(), ecorePackage.getEString(), "name", null, 0, -1, TableCell.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, !IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Create resource
createResource(eNS_URI);
}
} //SpecPackageImpl
| gpl-3.0 |
hu-team/coproco-deelteam1 | src/main/java/nl/hu/coproco/domain/ScopeStorage.java | 690 | package nl.hu.coproco.domain;
import java.util.ArrayList;
public class ScopeStorage {
private static ScopeStorage instance;
private ArrayList<Scope> scopeStorage;
public static ScopeStorage getInstance() {
if (instance == null) {
instance = new ScopeStorage();
}
return instance;
}
public ScopeStorage() {
this.scopeStorage = new ArrayList<>();
this.initDefaultScopes();
}
private void initDefaultScopes() {
this.scopeStorage.add(new Scope("Class"));
this.scopeStorage.add(new Scope("Object"));
}
public ArrayList<Scope> getScopes() {
return this.scopeStorage;
}
}
| gpl-3.0 |
mcai/Pickapack | src/main/java/net/pickapack/model/WithCreateTime.java | 1180 | /*******************************************************************************
* Copyright (c) 2010-2012 by Min Cai (min.cai.china@gmail.com).
*
* This file is part of the PickaPack library.
*
* PickaPack 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.
*
* PickaPack 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 PickaPack. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package net.pickapack.model;
/**
* With create time.
*
* @author Min Cai
*/
public interface WithCreateTime extends WithId {
/**
* Get the time when it is created.
*
* @return the time when it is created
*/
long getCreateTime();
}
| gpl-3.0 |
cltorrento/mvcTest | src/main/java/com/torrento/Prueba/mvcTest/service/UserService.java | 950 | package main.java.com.torrento.Prueba.mvcTest.service;
import java.util.List;
import org.springframework.stereotype.Service;
import main.java.com.torrento.Prueba.mvcTest.dao.UserDAOImpl;
import main.java.com.torrento.Prueba.mvcTest.entity.User;
@Service
public class UserService implements UserServiceInterface {
//@Autowired
private UserDAOImpl UserDAO;
@Override
public List<User> getAllUsers() {
return UserDAO.getAllUsers();
}
@Override
public User getUserById(int userId) {
User usr = UserDAO.getUserById(userId);
return usr;
}
@Override
public boolean addUser(User user) {
if (UserDAO.userExists(user.getName(), user.getSurname())) {
return false;
} else {
UserDAO.addUser(user);
return true;
}
}
@Override
public void updateUser(User user) {
UserDAO.updateUser(user);
}
@Override
public void deleteUser(int userId) {
UserDAO.deleteUser(userId);
}
}
| gpl-3.0 |
jhelom/Nukkit | src/main/java/cn/nukkit/block/BlockNetherPortal.java | 1584 | package cn.nukkit.block;
import cn.nukkit.item.Item;
import cn.nukkit.math.BlockFace;
import cn.nukkit.utils.BlockColor;
/**
* Created on 2016/1/5 by xtypr.
* Package cn.nukkit.block in project nukkit .
* The name NetherPortalBlock comes from minecraft wiki.
*/
public class BlockNetherPortal extends BlockFlowable {
public BlockNetherPortal() {
this(0);
}
public BlockNetherPortal(int meta) {
super(0);
}
@Override
public String getName() {
return "Nether Portal Block";
}
@Override
public int getId() {
return NETHER_PORTAL;
}
@Override
public boolean canPassThrough() {
return true;
}
@Override
public boolean isBreakable(Item item) {
return false;
}
@Override
public double getHardness() {
return -1;
}
@Override
public int getLightLevel() {
return 11;
}
@Override
public boolean onBreak(Item item) {
boolean result = super.onBreak(item);
for (BlockFace face : BlockFace.values()) {
Block b = this.getSide(face);
if (b != null) {
if (b instanceof BlockNetherPortal) {
result &= b.onBreak(item);
}
}
}
return result;
}
@Override
public boolean hasEntityCollision() {
return true;
}
@Override
public BlockColor getColor() {
return BlockColor.AIR_BLOCK_COLOR;
}
@Override
public boolean canBePushed() {
return false;
}
}
| gpl-3.0 |
AuScope/C3DMM | src/main/java/org/auscope/portal/server/web/controllers/VocabController.java | 10397 | package org.auscope.portal.server.web.controllers;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import net.sf.json.JSONArray;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.auscope.portal.csw.CSWOnlineResource;
import org.auscope.portal.csw.CSWRecord;
import org.auscope.portal.csw.ICSWMethodMaker;
import org.auscope.portal.server.util.PortalPropertyPlaceholderConfigurer;
import org.auscope.portal.server.web.service.CSWService;
import org.auscope.portal.server.web.service.HttpServiceCaller;
import org.auscope.portal.server.web.view.CSWRecordResponse;
import org.auscope.portal.server.web.view.JSONModelAndView;
import org.auscope.portal.server.web.view.ViewCSWRecordFactory;
import org.auscope.portal.vocabs.Concept;
import org.auscope.portal.vocabs.VocabularyServiceResponseHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* Controller that enables access to vocabulary services.
*/
@Controller
public class VocabController extends CSWRecordResponse {
protected final Log log = LogFactory.getLog(getClass());
private GetMethod method;
private HttpServiceCaller httpServiceCaller;
private VocabularyServiceResponseHandler vocabularyServiceResponseHandler;
private PortalPropertyPlaceholderConfigurer portalPropertyPlaceholderConfigurer;
private CSWService cswService;
private ViewCSWRecordFactory viewCSWRecordFactory;
/**
* Construct
* @param
*/
@Autowired
public VocabController(HttpServiceCaller httpServiceCaller,
VocabularyServiceResponseHandler vocabularyServiceResponseHandler,
PortalPropertyPlaceholderConfigurer portalPropertyPlaceholderConfigurer,
CSWService cswService, ViewCSWRecordFactory viewCSWRecordFactory) {
this.httpServiceCaller = httpServiceCaller;
this.vocabularyServiceResponseHandler = vocabularyServiceResponseHandler;
this.portalPropertyPlaceholderConfigurer = portalPropertyPlaceholderConfigurer;
this.cswService = cswService;
this.viewCSWRecordFactory = viewCSWRecordFactory;
String vocabServiceUrl = portalPropertyPlaceholderConfigurer.resolvePlaceholder("HOST.vocabService.url");
log.debug("vocab service URL: " + vocabServiceUrl);
this.method = new GetMethod(vocabServiceUrl + "/rdf/getConceptByLabel?C3DMM/*");
}
//TODO: optimise this function, loops in loops can't be optimal
@RequestMapping("/getProducts.do")
public ModelAndView getProducts() throws Exception {
//update the records if need be
//cswService.updateRecordsInBackground();
//query the vocab service
String vocabResponse = httpServiceCaller.getMethodResponseAsString(method, httpServiceCaller.getHttpClient());
//extract the concepts from the response9
List<Concept> concepts = new VocabularyServiceResponseHandler().getConcepts(vocabResponse);
log.debug("Number of data products retrieved: " + concepts.size());
//get WMS layers from the CSW service
CSWRecord[] cswRecords = cswService.getWMSRecordsOfOrg("C3DMM");
log.debug("Number of WMS layers retrieved: " + cswRecords.length);
List<CSWRecord> filteredRecords = new ArrayList<CSWRecord>();
for (CSWRecord cswRecord : cswRecords) {
for (Concept concept : concepts) {
if (cswRecord.containsKeyword(concept.getConceptUrn())) {
cswRecord.setServiceName(concept.getPreferredLabel());
cswRecord.setDataIdentificationAbstract(concept.getScopeNotes());
filteredRecords.add(cswRecord);
}
}
}
return generateJSONResponse(this.viewCSWRecordFactory, filteredRecords.toArray(new CSWRecord[filteredRecords.size()]));
}
/**
* Performs a query to the vocabulary service on behalf of the client and returns a JSON Map
* success: Set to either true or false
* data: The raw XML response
* scopeNote: The scope note element from the response
* label: The label element from the response
* @param repository
* @param label
* @return
*/
@RequestMapping("/getScalar.do")
public ModelAndView getScalarQuery( @RequestParam("repository") final String repository,
@RequestParam("label") final String label) throws Exception {
String response = "";
//Attempt to request and parse our response
try {
//Do the request
response = httpServiceCaller.getMethodResponseAsString(new ICSWMethodMaker() {
public HttpMethodBase makeMethod() {
// GetMethod method = new GetMethod(portalPropertyPlaceholderConfigurer.resolvePlaceholder("HOST.vocabService.url.nvclScalars"));
GetMethod method = new GetMethod(portalPropertyPlaceholderConfigurer.resolvePlaceholder("HOST.vocabService.url")+"/getConceptByLabel");
method.setQueryString(repository+"/"+label);
return method;
}
}.makeMethod(), httpServiceCaller.getHttpClient());
//Parse the response
XPath xPath = XPathFactory.newInstance().newXPath();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(response));
Document doc = builder.parse(inputSource);
String extractLabelExpression = "/RDF/Concept/prefLabel";
Node tempNode = (Node)xPath.evaluate(extractLabelExpression, doc, XPathConstants.NODE);
final String labelString = tempNode != null ? tempNode.getTextContent() : "";
String extractScopeExpression = "/RDF/Concept/scopeNote";
tempNode = (Node)xPath.evaluate(extractScopeExpression, doc, XPathConstants.NODE);
final String scopeNoteString = tempNode != null ? tempNode.getTextContent() : "";
String extractDefinitionExpression = "/RDF/Concept/definition";
tempNode = (Node)xPath.evaluate(extractDefinitionExpression, doc, XPathConstants.NODE);
final String definitionString = tempNode != null ? tempNode.getTextContent() : "";
return CreateScalarQueryModel(true,response, scopeNoteString, labelString, definitionString);
} catch (Exception ex) {
//On error, just return failure JSON (and the response string if any)
log.error("getVocabQuery ERROR: " + ex.getMessage());
return CreateScalarQueryModel(false,response, "", "", "");
}
}
private JSONModelAndView CreateScalarQueryModel
(final boolean success, final String data, final String scopeNote, final String label, final String definition) {
ModelMap map = new ModelMap();
map.put("success", success);
map.put("data", data);
map.put("scopeNote", scopeNote);
map.put("definition", definition);
map.put("label", label);
return new JSONModelAndView(map);
}
/**
* Get all GA commodity URNs with prefLabels
*
* @param
*/
@RequestMapping("getAllCommodities.do")
public ModelAndView getAllCommodities() throws Exception {
String response = "";
JSONArray dataItems = new JSONArray();
//Attempt to request and parse our response
try {
//Do the request
response = httpServiceCaller.getMethodResponseAsString(new ICSWMethodMaker() {
public HttpMethodBase makeMethod() {
GetMethod method = new GetMethod(portalPropertyPlaceholderConfigurer.resolvePlaceholder("HOST.vocabService.url")+"/getCommodity");
method.setQueryString("commodity_vocab/urn:cgi:classifierScheme:GA:commodity");
return method;
}
}.makeMethod(), httpServiceCaller.getHttpClient());
// Parse the response
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(response));
Document doc = builder.parse(inputSource);
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList exprResult = (NodeList)xPath.evaluate("/sparql/results/result", doc, XPathConstants.NODESET);
JSONArray tableRow;
for (int i=0; i < exprResult.getLength(); i++) {
Element result = (Element)exprResult.item(i);
tableRow = new JSONArray();
tableRow.add(result.getElementsByTagName("uri").item(0).getTextContent());
tableRow.add(result.getElementsByTagName("literal").item(0).getTextContent());
//add to the list
dataItems.add(tableRow);
}
return new JSONModelAndView(dataItems);
} catch (Exception ex) {
//On error, just return failure JSON (and the response string if any)
log.error("getAllCommodities Exception: " + ex.getMessage());
return new JSONModelAndView(dataItems);
}
}
}
| gpl-3.0 |
fracpete/tclass-weka-package | src/main/java/tclass/DataTypeMgr.java | 3430 | /*
* 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/>.
*/
/**
* A prototype manager for DataTypes
*
*
* @author Waleed Kadous
* @version $Id: DataTypeMgr.java,v 1.1.1.1 2002/06/28 07:36:16 waleed Exp $
*/
package tclass;
import java.util.Enumeration;
import java.util.Hashtable;
import tclass.datatype.Continuous;
import tclass.datatype.Discrete;
public class DataTypeMgr {
Hashtable registry = new Hashtable();
static DataTypeMgr instance;
/**
* The constructor. A good place to register the various
* datatypes.
*
*
*/
public DataTypeMgr(){
register((DataTypeI) new Continuous());
register((DataTypeI) new Discrete());
}
public static DataTypeMgr getInstance(){
if(instance == null){
instance = new DataTypeMgr();
return instance;
}
else {
return instance;
}
}
public void register(DataTypeI prototype){
registry.put(prototype.getName(), prototype);
}
/**
* Gets a datatype by name. WARNING: This does
* clone it. This is necessary for safety reasons. Otherwise,
* other people's code could modify the things stored in the
* prototype. This is BAD.
*
* This is the default version of the object.
*
* @param name name of the prototype to retrieve
* @return A clone of the prototype. null
* if there is no such prototype known.
*/
public DataTypeI getClone(String name){
DataTypeI dt = (DataTypeI) registry.get(name);
if(dt == null)
return null;
else
return (DataTypeI) dt.clone();
}
/**
* Gets a list of all the PEPs available by name
*
*/
public String[] getNames(){
String[] retval = new String[registry.size()];
int i = 0;
for(Enumeration e = registry.keys(); e.hasMoreElements(); i++){
retval[i] = (String) e.nextElement();
}
return retval;
}
public static void main(String[] args) throws Exception {
DataTypeMgr dtm = DataTypeMgr.getInstance();
DataTypeI dt = dtm.getClone("continuous");
DataTypeI dt2 = dtm.getClone("continuous");
DataTypeI dt3 = dtm.getClone("discrete");
dt.setParam("distance", "linear");
dt2.setParam("distance", "square");
dt3.setParam("costmetric", "complex");
dt3.setParam("cost", "true false 5");
dt3.setParam("cost", "false true 0.1");
System.out.println("Distance linear = " + dt.distance((float) 7.0, (float) 5.0));
System.out.println("Distance square = " + dt2.distance((float) 7.0, (float) 5.0));
System.out.println("Distance disc = "
+ dt3.distance(dt3.read("true"), dt3.read("false")));
System.out.println("Distance disc = "
+ dt3.distance(dt3.read("false"),
dt3.read("true")));
System.out.println(dt3.print((float) 0.0) + " " + dt3.print((float) 1.0));
}
}
| gpl-3.0 |
Diveboard/diveboard-web | test/Integration/src/AfterFailures/AfterFailure.java | 374 | package AfterFailures;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to mark a method to be called when a test fails.
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AfterFailure {
}
| gpl-3.0 |
sdp0et/barsuift-simlife | simLifeCore/src/test/java/barsuift/simLife/environment/WindStateFactoryTest.java | 1384 | /**
* barsuift-simlife is a life simulator program
*
* Copyright (C) 2010 Cyrille GACHOT
*
* This file is part of barsuift-simlife.
*
* barsuift-simlife 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.
*
* barsuift-simlife 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 barsuift-simlife. If not, see
* <http://www.gnu.org/licenses/>.
*/
package barsuift.simLife.environment;
import org.testng.annotations.Test;
import barsuift.simLife.j3d.environment.Wind3DState;
import static org.fest.assertions.Assertions.assertThat;
public class WindStateFactoryTest {
@Test
public void testCreateWindState() {
WindStateFactory factory = new WindStateFactory();
WindState windState = factory.createWindState();
assertThat(windState).isNotNull();
Wind3DState wind3DState = windState.getWind3D();
assertThat(wind3DState).isNotNull();
}
}
| gpl-3.0 |
raymondbh/TFCraft | src/Common/com/bioxx/tfc/WorldGen/MapGen/MapGenCavesTFC.java | 9132 | package com.bioxx.tfc.WorldGen.MapGen;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import com.bioxx.tfc.Core.TFC_Climate;
import com.bioxx.tfc.Core.TFC_Core;
import com.bioxx.tfc.WorldGen.DataLayer;
import com.bioxx.tfc.api.TFCBlocks;
public class MapGenCavesTFC extends MapGenBaseTFC
{
private byte[] metaArray;
public void generate(IChunkProvider par1IChunkProvider, World par2World, int par3, int par4, Block[] idsBig, byte[] metaBig)
{
metaArray = metaBig;
super.generate(par1IChunkProvider, par2World, par3, par4, idsBig);
}
/**
* Generates a larger initial cave node than usual. Called 25% of the time.
*/
protected void generateLargeCaveNode(long par1, int par3, int par4, Block[] par5, double par6, double par8, double par10)
{
this.generateCaveNode(par1, par3, par4, par5, par6, par8, par10, 1.0F + this.rand.nextFloat() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D, 2.5D);
}
/**
* Generates a node in the current cave system recursion tree.
*/
protected void generateCaveNode(long seed, int chunkX, int chunkZ, Block[] idArray, double i, double j, double k, float par12, float par13, float par14, int par15, int par16, double par17, double width)
{
double worldX = chunkX * 16 + 8;
double worldZ = chunkZ * 16 + 8;
float var23 = 0.0F;
float var24 = 0.0F;
Random var25 = new Random(seed);
if (par16 <= 0)
{
int var26 = this.range * 16 - 16;
par16 = var26 - var25.nextInt(var26 / 4);
}
boolean var54 = false;
if (par15 == -1)
{
par15 = par16 / 2;
var54 = true;
}
int var27 = var25.nextInt(par16 / 2) + par16 / 4;
for (boolean var28 = var25.nextInt(6) == 0; par15 < par16; ++par15)
{
double var29 = width + MathHelper.sin(par15 * (float)Math.PI / par16) * par12 * 1.0F;
double var31 = var29 * par17;
float var33 = MathHelper.cos(par14);
float var34 = MathHelper.sin(par14);
i += MathHelper.cos(par13) * var33;
j += var34;
k += MathHelper.sin(par13) * var33;
if (var28)
par14 *= 0.92F;
else
par14 *= 0.7F;
par14 += var24 * 0.1F;
par13 += var23 * 0.1F;
var24 *= 0.9F;
var23 *= 0.75F;
var24 += (var25.nextFloat() - var25.nextFloat()) * var25.nextFloat() * 2.0F;
var23 += (var25.nextFloat() - var25.nextFloat()) * var25.nextFloat() * 4.0F;
if (!var54 && par15 == var27 && par12 > 1.0F && par16 > 0)
{
this.generateCaveNode(var25.nextLong(), chunkX, chunkZ, idArray, i, j, k, var25.nextFloat() * 0.5F + 0.5F, par13 - ((float)Math.PI / 2F), par14 / 3.0F, par15, par16, 1.0D, width);
this.generateCaveNode(var25.nextLong(), chunkX, chunkZ, idArray, i, j, k, var25.nextFloat() * 0.5F + 0.5F, par13 + ((float)Math.PI / 2F), par14 / 3.0F, par15, par16, 1.0D, width);
return;
}
if (var54 || var25.nextInt(4) != 0)
{
double var35 = i - worldX;
double var37 = k - worldZ;
double var39 = par16 - par15;
double var41 = par12 + 2.0F + 16.0F;
if (var35 * var35 + var37 * var37 - var39 * var39 > var41 * var41)
return;
if (i >= worldX - 16.0D - var29 * 2.0D && k >= worldZ - 16.0D - var29 * 2.0D && i <= worldX + 16.0D + var29 * 2.0D && k <= worldZ + 16.0D + var29 * 2.0D)
{
int var55 = MathHelper.floor_double(i - var29) - chunkX * 16 - 1;
int var36 = MathHelper.floor_double(i + var29) - chunkX * 16 + 1;
int var57 = MathHelper.floor_double(j - var31) - 1;
int yCoord = MathHelper.floor_double(j + var31) + 1;
int var56 = MathHelper.floor_double(k - var29) - chunkZ * 16 - 1;
int var40 = MathHelper.floor_double(k + var29) - chunkZ * 16 + 1;
if (var55 < 0)
var55 = 0;
if (var36 > 16)
var36 = 16;
if (var57 < 1)
var57 = 1;
if (yCoord > 250)
yCoord = 250;
if (var56 < 0)
var56 = 0;
if (var40 > 16)
var40 = 16;
boolean var58 = false;
int xCoord;
int zCoord;
for (xCoord = var55; !var58 && xCoord < var36; ++xCoord)
{
for (zCoord = var56; !var58 && zCoord < var40; ++zCoord)
{
for (int y = yCoord + 1; !var58 && y >= var57 - 1; --y)
{
int index = (xCoord * 16 + zCoord) * 256 + y;
if (y >= 0 && y < 256)
{
if (idArray[index] == TFCBlocks.SaltWaterStationary || idArray[index] == TFCBlocks.FreshWaterStationary)
var58 = true;
if (y != var57 - 1 && xCoord != var55 && xCoord != var36 - 1 && zCoord != var56 && zCoord != var40 - 1)
y = var57;
}
}
}
}
if (!var58)
{
for (xCoord = var55; xCoord < var36; ++xCoord)
{
double var59 = (xCoord + chunkX * 16 + 0.5D - i) / var29;
for (zCoord = var56; zCoord < var40; ++zCoord)
{
double var46 = (zCoord + chunkZ * 16 + 0.5D - k) / var29;
int index = (xCoord * 16 + zCoord) * 256 + yCoord;
boolean isGrass = false;
Block grassBlock = Blocks.air;
if (var59 * var59 + var46 * var46 < 1.0D)
{
for (int var50 = yCoord - 1; var50 >= var57; --var50)
{
double var51 = (var50 + 0.5D - j) / var31;
if (var51 > -0.7D && var59 * var59 + var51 * var51 + var46 * var46 < 1.0D)
{
if (TFC_Core.isGrass(idArray[index]))
{
grassBlock = idArray[index];
isGrass = true;
}
if (TFC_Core.isSoil(idArray[index]) || TFC_Core.isRawStone(idArray[index]))
{
if(TFC_Core.isSoilOrGravel(idArray[index+1]))
{
for(int upCount = 1; TFC_Core.isSoilOrGravel(idArray[index+upCount]); upCount++)
{idArray[index+upCount] = Blocks.air;}
}
if (var50 < 10 && TFC_Climate.getStability(this.worldObj, (int)worldX, (int)worldZ) == 1)
{
idArray[index] = TFCBlocks.Lava;
metaArray[index] = 0;
}
else
{
idArray[index] = Blocks.air;
metaArray[index] = 0;
if (isGrass && TFC_Core.isDirt(idArray[index - 1]))
{
//int meta = metaArray[index - 1];
idArray[index - 1] = grassBlock;
}
}
}
}
--index;
}
}
}
}
if (var54)
break;
}
}
}
}
}
/**
* Recursively called by generate() (generate) and optionally by itself.
*/
@Override
protected void recursiveGenerate(World world, int par2, int par3, int par4, int par5, Block[] ids)
{
int var7 = this.rand.nextInt(this.rand.nextInt(this.rand.nextInt(40) + 1) + 1);
double xCoord = par2 * 16 + this.rand.nextInt(16);
double yCoord = this.rand.nextInt(1+this.rand.nextInt(140))+60;
double zCoord = par3 * 16 + this.rand.nextInt(16);
DataLayer rockLayer1 = TFC_Climate.getCacheManager(world).getRockLayerAt((int)xCoord, (int)zCoord, 0);
float rain = TFC_Climate.getRainfall(world, (int)xCoord, 144, (int)zCoord);
double width = 2;
int caveChance = 35;
if(rain > 1000)
{
width += 0.5;
caveChance -= 5;
}
else if(rain > 2000)
{
width += 1;
caveChance -= 10;
}
else if(rain < 1000)
{
width -= 0.5;
caveChance += 5;
}
else if(rain < 500)
{
width -= 1;
caveChance += 10;
}
else if(rain < 250)
{
width -= 1.25;
caveChance += 15;
}
Block layerID = rockLayer1.block;
if(layerID == TFCBlocks.StoneIgEx)
{
width -= 0.4;
}
else if(layerID == TFCBlocks.StoneIgIn)
{
width -= 0.5;
}
else if(layerID == TFCBlocks.StoneSed)
{
width += 0.2;
var7 += 5;
}
else if(layerID == TFCBlocks.StoneMM)
{
width += 0.3;
}
if(yCoord < 32)
width *= 0.5;
else if (yCoord < 64)
width *= 0.65;
else if (yCoord < 96)
width *= 0.80;
else if (yCoord < 120)
width *= 0.90;
else
width *= 0.5;
if(this.rand.nextInt(8) == 0)
width += 1;
if (this.rand.nextInt(caveChance) != 0)
var7 = 0;
for (int var8 = 0; var8 < var7; ++var8)
{
int var15 = 1;
if (this.rand.nextInt(4) == 0)
{
this.generateLargeCaveNode(this.rand.nextLong(), par4, par5, ids, xCoord, yCoord, zCoord);
var15 += this.rand.nextInt(4);
}
for (int var16 = 0; var16 < var15; ++var16)
{
float var17 = this.rand.nextFloat() * (float)Math.PI * 2.0F;
float var18 = (this.rand.nextFloat() - 0.5F) * 2.0F / 8.0F;
float var19 = this.rand.nextFloat() * 2.0F + this.rand.nextFloat();
if (this.rand.nextInt(10) == 0)
var19 *= this.rand.nextFloat() * this.rand.nextFloat() * 3.0F + 1.0F;
this.generateCaveNode(this.rand.nextLong(), par4, par5, ids, xCoord, yCoord, zCoord, var19, var17, var18, 0, 0, 1.0D, width);
}
}
}
}
| gpl-3.0 |
rhilker/ReadXplorer | readxplorer-rnatrimming/src/main/java/de/cebitec/readxplorer/rnatrimming/RegularExpressionTrimMethod.java | 4847 | /*
* Copyright (C) 2014 Institute for Bioinformatics and Systems Biology, University Giessen, Germany
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cebitec.readxplorer.rnatrimming;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* RegularExpressionTrimMethod trims a sequence based on the given
* regular expression.
* <p>
* @author Evgeny Anisiforov
*/
public class RegularExpressionTrimMethod extends TrimMethod {
private Pattern regularexpression;
private final String regularexpressionTemplate;
private final int groupnumberMain;
private final int groupnumberTrimLeft;
private final int groupnumberTrimRight;
private final String name;
public RegularExpressionTrimMethod( String regularexpression, int groupnumberMain, int groupnumberTrimLeft, int groupnumberTrimRight, String name, String shortName ) {
this.regularexpressionTemplate = regularexpression;
this.groupnumberMain = groupnumberMain;
this.groupnumberTrimLeft = groupnumberTrimLeft;
this.groupnumberTrimRight = groupnumberTrimRight;
this.name = name;
this.setMaximumTrimLength( 10 );
this.setShortName( shortName );
}
public void replacePlaceholder( String placeholder, String value ) {
this.regularexpression = Pattern.compile( regularexpressionTemplate.replace( placeholder, value ) );
}
@Override
public void setMaximumTrimLength( int maximumTrimLength ) {
super.setMaximumTrimLength( maximumTrimLength );
this.replacePlaceholder( "%X%", maximumTrimLength + "" );
}
@Override
public TrimMethodResult trim( String sequence ) {
Matcher matcher = regularexpression.matcher( sequence );
TrimMethodResult result = new TrimMethodResult( sequence, sequence, 0, 0 );
if( matcher.find() ) {
result.setSequence( matcher.group( this.groupnumberMain ) );
if( this.groupnumberTrimLeft > 0 ) {
result.setTrimmedCharsFromLeft( matcher.group( this.groupnumberTrimLeft ).length() );
}
if( this.groupnumberTrimRight > 0 ) {
result.setTrimmedCharsFromRight( matcher.group( this.groupnumberTrimRight ).length() );
}
}
//if the pattern does not match, just return the full string
return result;
}
@Override
public String toString() {
return this.name;
}
public enum Type {
VARIABLE_RIGHT, VARIABLE_LEFT, VARIABLE_BOTH,
FIXED_LEFT, FIXED_RIGHT, FIXED_BOTH
};
public static final int GROUPNUMBER_UNUSED = -1;
/*
* a list of default instances is provided here
*/
public static RegularExpressionTrimMethod createNewInstance( Type t ) {
if( t.equals( Type.VARIABLE_RIGHT ) ) {
return new RegularExpressionTrimMethod( "^(.*?)(A{0,%X%})$", 1, GROUPNUMBER_UNUSED, 2, "trim poly-A from 3' end (right to left) by variable length", "v_r" );
} else if( t.equals( Type.VARIABLE_LEFT ) ) {
return new RegularExpressionTrimMethod( "^(A{0,%X%})(.*?)$", 2, 1, GROUPNUMBER_UNUSED, "trim poly-A from 5' end (left to right) by variable length", "v_l" );
} else if( t.equals( Type.VARIABLE_BOTH ) ) {
return new HalfedLengthTrimMethod( "^(A{0,%X%})(.*?)(A{0,%X%})$", 2, 1, 3, "trim poly-A from 3' and from 5' end by variable length", "v_lr" );
} else if( t.equals( Type.FIXED_RIGHT ) ) {
return new RegularExpressionTrimMethod( "^(.*?)(.{%X%})$", 1, GROUPNUMBER_UNUSED, 2, "trim all nucleotides from 3' end (right to left) by fixed length", "f_r" );
} else if( t.equals( Type.FIXED_LEFT ) ) {
return new RegularExpressionTrimMethod( "^(.{%X%})(.*?)$", 2, 1, GROUPNUMBER_UNUSED, "trim all nucleotides from 5' end (left to right) by fixed length", "f_l" );
} else if( t.equals( Type.FIXED_BOTH ) ) {
return new HalfedLengthTrimMethod( "^(.{%X%})(.*?)(.{%X%})$", 2, 1, 3, "trim all nucleotides from 3' and from 5' end by fixed length", "f_lr" );
} else {
return new HalfedLengthTrimMethod( "^(.{%X%})(.*?)(.{%X%})$", 2, 1, 3, "UNKNOWN", "unkn" );
}
}
}
| gpl-3.0 |
AnomalyXII/bot | bot-manager-core/src/main/java/net/anomalyxii/botmanager/impl/GenericBotEventListenerManager.java | 1345 | package net.anomalyxii.botmanager.impl;
import net.anomalyxii.bot.api.Bot;
import net.anomalyxii.bot.api.BotEventListener;
import net.anomalyxii.botmanager.api.BotEventListenerManager;
/**
* A generic {@link BotEventListenerManager}.
*
* Created by Anomaly on 21/05/2017.
*/
public class GenericBotEventListenerManager implements BotEventListenerManager {
// ******************************
// Members
// ******************************
private final Bot bot;
private final BotEventListener listener;
// ******************************
// Constructors
// ******************************
public GenericBotEventListenerManager(Bot bot, BotEventListener listener) {
this.bot = bot;
this.listener = listener;
}
// ******************************
// BotEventListenerManager Methods
// ******************************
@Override
public BotEventListener getBotEventListener() {
return listener;
}
@Override
public boolean isAttached() {
return bot.asEventSubscriber().hasBotEventListener(listener);
}
@Override
public void attach() {
bot.asEventSubscriber().registerBotEventListener(listener);
}
@Override
public void detach() {
bot.asEventSubscriber().unregisterBotEventListener(listener);
}
}
| gpl-3.0 |
ProgDan/maratona | URI/URI_1929 Triângulo.java | 1101 | /*
+------------------+
|Daniel Arndt Alves|
| URI 1929 |
| Triângulo |
+------------------+
*/
import java.util.Scanner;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Locale.setDefault(new Locale("en", "US"));
Scanner sc = new Scanner(System.in);
int A, B, C, D;
A = sc.nextInt();
B = sc.nextInt();
C = sc.nextInt();
D = sc.nextInt();
if ((A < (B+C)) && (A > Math.abs(B-C)) ||
(A < (B+D)) && (A > Math.abs(B-D)) ||
(A < (C+D)) && (A > Math.abs(C-D)) ||
(B < (A+C)) && (B > Math.abs(A-C)) ||
(B < (A+D)) && (B > Math.abs(A-D)) ||
(B < (C+D)) && (B > Math.abs(C-D)) ||
(C < (A+B)) && (C > Math.abs(A-B)) ||
(C < (A+D)) && (C > Math.abs(A-D)) ||
(C < (B+D)) && (C > Math.abs(B-D)) ||
(D < (A+B)) && (D > Math.abs(A-B)) ||
(D < (A+C)) && (D > Math.abs(A-C)) ||
(D < (B+C)) && (D > Math.abs(B-C)))
System.out.println("S");
else
System.out.println("N");
sc.close();
}
} | gpl-3.0 |
ricecakesoftware/CommunityMedicalLink | ricecakesoftware.communitymedicallink.ebrs/src/ricecakesoftware/communitymedicallink/ebrs/common/ExternalIdentifier.java | 2206 | package ricecakesoftware.communitymedicallink.ebrs.common;
import java.io.Serializable;
/**
* ExternalIdentifier
* @author RCSW)Y.Omoya
*/
public class ExternalIdentifier implements Serializable {
/** registryObject */
private String registryObject;
/** identificationScheme */
private String identificationScheme;
/** 値 */
private String value;
/** オブジェクトタイプ */
private String objectType;
/** 名称 */
private String name;
/**
* コンストラクター
*/
public ExternalIdentifier() {
this.registryObject = null;
this.identificationScheme = null;
this.value = null;
this.objectType = null;
this.name = null;
}
/**
* registryObject取得
* @return registryObject
*/
public String getRegistryObject() {
return this.registryObject;
}
/**
* registryObject設定
* @param registryObject registryObject
*/
public void setRegistryObject(String registryObject) {
this.registryObject = registryObject;
}
/**
* identificationScheme取得
* @return identificationScheme
*/
public String getIdentificationScheme() {
return this.identificationScheme;
}
/**
* identificationScheme設定
* @param identificationScheme identificationScheme
*/
public void setIdentificationScheme(String identificationScheme) {
this.identificationScheme = identificationScheme;
}
/**
* 値取得
* @return 値
*/
public String getValue() {
return this.value;
}
/**
* 値設定
* @param value 値
*/
public void setValue(String value) {
this.value = value;
}
/**
* オブジェクトタイプ取得
* @return オブジェクトタイプ
*/
public String getObjectType() {
return this.objectType;
}
/**
* オブジェクトタイプ設定
* @param objectType オブジェクトタイプ
*/
public void setObjectType(String objectType) {
this.objectType = objectType;
}
/**
* 名称取得
* @return 名称
*/
public String getName() {
return this.name;
}
/**
* 名称設定
* @param name 名称
*/
public void setName(String name) {
this.name = name;
}
}
| gpl-3.0 |
smap-consulting/smapserver | sdDAL/src/org/smap/sdal/model/ActionLink.java | 79 | package org.smap.sdal.model;
public class ActionLink {
public String link;
}
| gpl-3.0 |
PapenfussLab/PathOS | Tools/Hl7Tools/src/main/java/org/petermac/hl7/model/v251/message/ADT_A18.java | 7483 | /*
* This class is an auto-generated source file for a HAPI
* HL7 v2.x standard structure class.
*
* For more information, visit: http://hl7api.sourceforge.net/
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
* specific language governing rights and limitations under the License.
*
* The Original Code is "[file_name]". Description:
* "[one_line_description]"
*
* The Initial Developer of the Original Code is University Health Network. Copyright (C)
* 2012. All Rights Reserved.
*
* Contributor(s): ______________________________________.
*
* Alternatively, the contents of this file may be used under the terms of the
* GNU General Public License (the "GPL"), in which case the provisions of the GPL are
* applicable instead of those above. If you wish to allow use of your version of this
* file only under the terms of the GPL and not to allow others to use your version
* of this file under the MPL, indicate your decision by deleting the provisions above
* and replace them with the notice and other provisions required by the GPL License.
* If you do not delete the provisions above, a recipient may use your version of
* this file under either the MPL or the GPL.
*
*/
package org.petermac.hl7.model.v251.message;
import org.petermac.hl7.model.v251.group.*;
import org.petermac.hl7.model.v251.segment.*;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.parser.ModelClassFactory;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import ca.uhn.hl7v2.model.*;
/**
* <p>Represents a ADT_A18 message structure (see chapter 3.3.18). This structure contains the
* following elements: </p>
* <ul>
* <li>1: MSH (Message Header) <b> </b> </li>
* <li>2: SFT (Software Segment) <b>optional repeating</b> </li>
* <li>3: EVN (Event Type) <b> </b> </li>
* <li>4: PID (Patient Identification) <b> </b> </li>
* <li>5: PD1 (Patient Additional Demographic) <b>optional </b> </li>
* <li>6: MRG (Merge Patient Information) <b> </b> </li>
* <li>7: PV1 (Patient Visit) <b> </b> </li>
* </ul>
*/
//@SuppressWarnings("unused")
public class ADT_A18 extends AbstractMessage {
/**
* Creates a new ADT_A18 message with DefaultModelClassFactory.
*/
public ADT_A18() {
this(new DefaultModelClassFactory());
}
/**
* Creates a new ADT_A18 message with custom ModelClassFactory.
*/
public ADT_A18(ModelClassFactory factory) {
super(factory);
init(factory);
}
private void init(ModelClassFactory factory) {
try {
this.add(MSH.class, true, false);
this.add(SFT.class, false, true);
this.add(EVN.class, true, false);
this.add(PID.class, true, false);
this.add(PD1.class, false, false);
this.add(MRG.class, true, false);
this.add(PV1.class, true, false);
} catch(HL7Exception e) {
log.error("Unexpected error creating ADT_A18 - this is probably a bug in the source code generator.", e);
}
}
/**
* Returns "2.5.1"
*/
public String getVersion() {
return "2.5.1";
}
/**
* <p>
* Returns
* MSH (Message Header) - creates it if necessary
* </p>
*
*
*/
public MSH getMSH() {
return getTyped("MSH", MSH.class);
}
/**
* <p>
* Returns
* the first repetition of
* SFT (Software Segment) - creates it if necessary
* </p>
*
*
*/
public SFT getSFT() {
return getTyped("SFT", SFT.class);
}
/**
* <p>
* Returns a specific repetition of
* SFT (Software Segment) - creates it if necessary
* </p>
*
*
* @param rep The repetition index (0-indexed, i.e. the first repetition is at index 0)
* @throws HL7Exception if the repetition requested is more than one
* greater than the number of existing repetitions.
*/
public SFT getSFT(int rep) {
return getTyped("SFT", rep, SFT.class);
}
/**
* <p>
* Returns the number of existing repetitions of SFT
* </p>
*
*/
public int getSFTReps() {
return getReps("SFT");
}
/**
* <p>
* Returns a non-modifiable List containing all current existing repetitions of SFT.
* <p>
* <p>
* Note that unlike {@link #getSFT()}, this method will not create any reps
* if none are already present, so an empty list may be returned.
* </p>
*
*/
public java.util.List<SFT> getSFTAll() throws HL7Exception {
return getAllAsList("SFT", SFT.class);
}
/**
* <p>
* Inserts a specific repetition of SFT (Software Segment)
* </p>
*
*
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public void insertSFT(SFT structure, int rep) throws HL7Exception {
super.insertRepetition( "SFT", structure, rep);
}
/**
* <p>
* Inserts a specific repetition of SFT (Software Segment)
* </p>
*
*
* @see AbstractGroup#insertRepetition(Structure, int)
*/
public SFT insertSFT(int rep) throws HL7Exception {
return (SFT)super.insertRepetition("SFT", rep);
}
/**
* <p>
* Removes a specific repetition of SFT (Software Segment)
* </p>
*
*
* @see AbstractGroup#removeRepetition(String, int)
*/
public SFT removeSFT(int rep) throws HL7Exception {
return (SFT)super.removeRepetition("SFT", rep);
}
/**
* <p>
* Returns
* EVN (Event Type) - creates it if necessary
* </p>
*
*
*/
public EVN getEVN() {
return getTyped("EVN", EVN.class);
}
/**
* <p>
* Returns
* PID (Patient Identification) - creates it if necessary
* </p>
*
*
*/
public PID getPID() {
return getTyped("PID", PID.class);
}
/**
* <p>
* Returns
* PD1 (Patient Additional Demographic) - creates it if necessary
* </p>
*
*
*/
public PD1 getPD1() {
return getTyped("PD1", PD1.class);
}
/**
* <p>
* Returns
* MRG (Merge Patient Information) - creates it if necessary
* </p>
*
*
*/
public MRG getMRG() {
return getTyped("MRG", MRG.class);
}
/**
* <p>
* Returns
* PV1 (Patient Visit) - creates it if necessary
* </p>
*
*
*/
public PV1 getPV1() {
return getTyped("PV1", PV1.class);
}
}
| gpl-3.0 |
sistemi-territoriali/StatPortalOpenData | DataModel/src/main/java/it/sister/statportal/odata/domain/MdRelHierNodePK.java | 176 | package it.sister.statportal.odata.domain;
import org.springframework.roo.addon.entity.RooIdentifier;
@RooIdentifier(dbManaged = true)
public final class MdRelHierNodePK {
}
| gpl-3.0 |
Malow/GladiatorManager | GladiatorManagerServer/src/com/gladiatormanager/game/GameHandler.java | 3015 | package com.gladiatormanager.game;
import java.util.ArrayList;
import java.util.List;
import com.gladiatormanager.Globals;
import com.gladiatormanager.account.Account;
import com.gladiatormanager.comstructs.AuthorizedRequest;
import com.gladiatormanager.comstructs.ErrorResponse;
import com.gladiatormanager.comstructs.Response;
import com.gladiatormanager.comstructs.game.ChooseInitialMercenariesRequest;
import com.gladiatormanager.comstructs.game.GetMercenariesResponse;
import com.gladiatormanager.database.AccountAccessor;
import com.gladiatormanager.database.MercenaryAccessor;
public class GameHandler
{
public static Response getMercenaries(AuthorizedRequest req)
{
try
{
int accId = AccountAccessor.read(req.email).id;
List<Mercenary> mercenaries = MercenaryAccessor.getMercenariesForAccount(accId);
return new GetMercenariesResponse(true, mercenaries);
}
catch (Exception e)
{
System.out.println("Unexpected error when trying to get mercenaries: " + e.toString());
e.printStackTrace();
return new ErrorResponse(false, "Unexpected error");
}
}
public static Response chooseInitialMercenaries(ChooseInitialMercenariesRequest req)
{
try
{
if (req.mercenariesIds.size() != Globals.Config.STARTER_MERCENARIES_TO_BE_CHOSEN)
throw new Exception("Amount of mercenariesIds does not match the correct amount.");
Account acc = AccountAccessor.read(req.email);
if (acc.state == Account.State.HAS_TEAMNAME)
{
List<Mercenary> mercenaries = MercenaryAccessor.getMercenariesForAccount(acc.id);
List<Mercenary> mercenariesToBeKept = new ArrayList<Mercenary>();
for (Integer mercenaryId : req.mercenariesIds)
{
boolean found = false;
for (Mercenary mercenary : mercenaries)
{
if (mercenary.id == mercenaryId)
{
if (found) throw new Exception("Found multiple mercenaries for an id.");
mercenariesToBeKept.add(mercenary);
found = true;
}
}
if (!found) throw new Exception("Didn't find any mercenaries for an id.");
}
List<Mercenary> mercenariesToBeDeleted = new ArrayList<Mercenary>(mercenaries);
for (Mercenary mercenary : mercenariesToBeKept)
{
mercenariesToBeDeleted.remove(mercenary);
}
for (Mercenary mercenary : mercenariesToBeDeleted)
{
MercenaryAccessor.delete(mercenary);
}
acc.state = Account.State.IS_ACTIVE;
AccountAccessor.update(acc);
return new Response(true);
}
else
{
throw new Exception("Account state is incorrect for this action: " + acc.state);
}
}
catch (Exception e)
{
System.out.println("Unexpected error when trying to pick initial mercenaries: " + e.toString());
e.printStackTrace();
return new ErrorResponse(false, "Unexpected error");
}
}
}
| gpl-3.0 |
rhilker/ReadXplorer | readxplorer-tools-snpdetection/src/main/java/de/cebitec/readxplorer/tools/snpdetection/ParameterSetSNPs.java | 5302 | /*
* Copyright (C) 2014 Institute for Bioinformatics and Systems Biology, University Giessen, Germany
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cebitec.readxplorer.tools.snpdetection;
import de.cebitec.readxplorer.api.enums.FeatureType;
import de.cebitec.readxplorer.databackend.ParameterSetI;
import de.cebitec.readxplorer.databackend.ParametersFeatureTypesAndReadClasses;
import de.cebitec.readxplorer.databackend.ParametersReadClasses;
import java.util.Set;
/**
* Data storage for all parameters associated with a SNP and DIP detection.
*
* @author Rolf Hilker <rhilker at cebitec.uni-bielefeld.de>
*/
public class ParameterSetSNPs extends ParametersFeatureTypesAndReadClasses implements
ParameterSetI<ParameterSetSNPs> {
private int minMismatchBases;
private double minPercentage;
private final boolean useMainBase;
private final byte minBaseQuality;
private final byte minAverageBaseQual;
private final int minAverageMappingQual;
/**
* Data storage for all parameters associated with a SNP and DIP detection.
* <p>
* @param minMismatchBases the minimum number of mismatches at a SNP
* position
* @param minPercentage the minimum percentage of mismatches at a
* SNP
* position
* @param useMainBase <code>true</code>, if the minVaryingBases
* count
* corresponds to the count of the most frequent base at the current
* position. <code>false</code>, if the minVaryingBases count corresponds to
* the overall mismatch count at the current position.
* @param selFeatureTypes list of seletect feature types to use for
* the snp
* translation.
* @param readClassParams only include mappings in the analysis, which
* belong to the selected mapping classes.
* @param minBaseQuality Minimum phred scaled base quality or -1 if
* unknown.
* @param minAverageBaseQual Minimum average phred scaled base quality or
* -1
* if unknown.
* @param minAverageMappingQual Minimum average phred scaled mapping quality
* or -1 if unknown.
*/
public ParameterSetSNPs( int minMismatchBases, double minPercentage, boolean useMainBase, Set<FeatureType> selFeatureTypes, ParametersReadClasses readClassParams,
byte minBaseQuality, byte minAverageBaseQual, int minAverageMappingQual ) {
super( selFeatureTypes, readClassParams );
this.minMismatchBases = minMismatchBases;
this.minPercentage = minPercentage;
this.useMainBase = useMainBase;
this.minBaseQuality = minBaseQuality;
this.minAverageBaseQual = minAverageBaseQual;
this.minAverageMappingQual = minAverageMappingQual;
}
/**
* @return the minimum number of mismatches at a SNP position
*/
public int getMinMismatchingBases() {
return minMismatchBases;
}
/**
* @param minVaryingBases The minimum number of varying bases at a SNP
* position.
*/
public void setMinVaryingBases( int minVaryingBases ) {
this.minMismatchBases = minVaryingBases;
}
/**
* @return the minimum percentage of mismatches at a SNP position
*/
public double getMinPercentage() {
return minPercentage;
}
/**
* @return <code>true</code>, if the minVaryingBases count corresponds to
* the count of
* the most frequent base at the current position. <code>false</code>, if
* the
* minVaryingBases count corresponds to the overall mismatch count at the
* current position.
*/
public boolean isUseMainBase() {
return this.useMainBase;
}
/**
* @return Minimum phred scaled base quality or -1 if unknown.
*/
public byte getMinBaseQuality() {
return this.minBaseQuality;
}
/**
* @return Minimum average phred scaled base quality or -1 if unknown.
*/
public int getMinAverageBaseQual() {
return this.minAverageBaseQual;
}
/**
* @return Minimum average phred scaled mapping quality or 255 if unknown.
*/
public int getMinAverageMappingQual() {
return this.minAverageMappingQual;
}
}
| gpl-3.0 |
IcmVis/VisNow-Pro | src/pl/edu/icm/visnow/lib/basic/viewers/FieldViewer3D/GeometryTools/RadiusTool.java | 5511 | /* VisNow
Copyright (C) 2006-2013 University of Warsaw, ICM
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
University of Warsaw, Interdisciplinary Centre for Mathematical and
Computational Modelling, Pawinskiego 5a, 02-106 Warsaw, Poland.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package pl.edu.icm.visnow.lib.basic.viewers.FieldViewer3D.GeometryTools;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import pl.edu.icm.visnow.lib.basic.viewers.FieldViewer3D.Geometry.CalculableParameter;
/**
* @author Bartosz Borucki (babor@icm.edu.pl)
* University of Warsaw, Interdisciplinary Centre
* for Mathematical and Computational Modelling
*/
public class RadiusTool extends GeometryTool {
private final int pointRadius = 3;
private Point startPoint = null;
private Point currentPoint = null;
private Point endPoint = null;
@Override
public void paint(Graphics g) {
if(holding && startPoint != null && currentPoint != null) {
int[][] pp = new int[2][2];
pp[0][0] = startPoint.x;
pp[0][1] = startPoint.y;
pp[1][0] = currentPoint.x;
pp[1][1] = currentPoint.y;
int[] c = new int[2];
c[0] = (startPoint.x+currentPoint.x)/2;
c[1] = (startPoint.y+currentPoint.y)/2;
float d = (float)(Math.sqrt( (pp[1][0]-pp[0][0])*(pp[1][0]-pp[0][0]) + (pp[1][1]-pp[0][1])*(pp[1][1]-pp[0][1]) ));
int cx = (int)Math.round((float)c[0]-d/2.0f);
int cy = (int)Math.round((float)c[1]-d/2.0f);
int cd = (int)Math.round(d);
g.setColor(Color.YELLOW);
g.drawLine(pp[0][0], pp[0][1], c[0], c[1]);
g.setColor(Color.RED);
g.drawLine(c[0], c[1], pp[1][0], pp[1][1]);
g.drawOval(cx, cy, cd, cd);
g.fillRect(c[0]-pointRadius, c[1]-pointRadius, 2*pointRadius+1, 2*pointRadius+1);
g.fillRect(pp[0][0]-pointRadius, pp[0][1]-pointRadius, 2*pointRadius+1, 2*pointRadius+1);
}
}
public void mouseDragged(MouseEvent e) {
if(holding) {
currentPoint = e.getPoint();
fireGeometryToolRepaintNeeded();
}
}
public void mouseMoved(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
holding = true;
this.startPoint = e.getPoint();
this.currentPoint = e.getPoint();
fireGeometryToolRepaintNeeded();
}
public void mouseReleased(MouseEvent e) {
holding = false;
this.endPoint = e.getPoint();
fireGeometryToolRepaintNeeded();
metadata = null;
fireGeometryToolStateChanged();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
@Override
public Cursor getCursor() {
return Cursor.getDefaultCursor();
}
@Override
public boolean isMouseWheelBlocking() {
return holding;
}
@Override
public int[][] getPoints() {
if(startPoint == null || endPoint == null)
return null;
int[][] out = new int[2][2];
out[0][0] = startPoint.x;
out[0][1] = startPoint.y;
out[1][0] = (endPoint.x+startPoint.x)/2;
out[1][1] = (endPoint.y+startPoint.y)/2;
return out;
}
@Override
public Metadata[] getPointMetadata() {
return null;
}
@Override
public int[][] getConnections() {
if(startPoint == null || endPoint == null)
return null;
int[][] out = new int[1][2];
out[0][0] = 0;
out[0][1] = 1;
return out;
}
@Override
public CalculableParameter getCalculable() {
return null;
}
@Override
public Metadata getCalculableMetadata() {
return null;
}
@Override
public int getMinimumNPoints() {
return 2;
}
}
| gpl-3.0 |
hack1nt0/AC | src/main/java/template/egork/generated/collections/CharStream.java | 24396 | package template.egork.generated.collections;
import template.egork.generated.collections.iterator.DoubleIterator;
import template.egork.generated.collections.list.CharArrayList;
import template.egork.generated.collections.comparator.CharComparator;
import template.egork.generated.collections.function.CharCharToCharFunction;
import template.egork.generated.collections.function.CharCharToDoubleFunction;
import template.egork.generated.collections.function.CharCharToIntFunction;
import template.egork.generated.collections.function.CharCharToLongFunction;
import template.egork.generated.collections.function.CharDoubleToCharFunction;
import template.egork.generated.collections.function.CharDoubleToDoubleFunction;
import template.egork.generated.collections.function.CharDoubleToIntFunction;
import template.egork.generated.collections.function.CharDoubleToLongFunction;
import template.egork.generated.collections.function.CharFilter;
import template.egork.generated.collections.function.CharIntToCharFunction;
import template.egork.generated.collections.function.CharIntToDoubleFunction;
import template.egork.generated.collections.function.CharIntToIntFunction;
import template.egork.generated.collections.function.CharIntToLongFunction;
import template.egork.generated.collections.function.CharLongToCharFunction;
import template.egork.generated.collections.function.CharLongToDoubleFunction;
import template.egork.generated.collections.function.CharLongToIntFunction;
import template.egork.generated.collections.function.CharLongToLongFunction;
import template.egork.generated.collections.function.CharTask;
import template.egork.generated.collections.function.CharToCharFunction;
import template.egork.generated.collections.function.CharToDoubleFunction;
import template.egork.generated.collections.function.CharToIntFunction;
import template.egork.generated.collections.function.CharToLongFunction;
import template.egork.generated.collections.function.DoubleCharToDoubleFunction;
import template.egork.generated.collections.function.IntCharToIntFunction;
import template.egork.generated.collections.function.LongCharToLongFunction;
import template.egork.generated.collections.iterator.CharIterator;
import template.egork.generated.collections.iterator.IntIterator;
import template.egork.generated.collections.iterator.LongIterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
public interface CharStream extends Iterable<Character>, Comparable<CharStream> {
//abstract
public CharIterator charIterator();
//base
default public Iterator<Character> iterator() {
return new Iterator<Character>() {
private CharIterator it = charIterator();
public boolean hasNext() {
return it.isValid();
}
public Character next() {
char result = it.value();
it.advance();
return result;
}
};
}
default public char first() {
return charIterator().value();
}
default public CharCollection compute() {
return new CharArrayList(this);
}
default public int compareTo(CharStream c) {
CharIterator it = charIterator();
CharIterator jt = c.charIterator();
while (it.isValid() && jt.isValid()) {
char i = it.value();
char j = jt.value();
if (i < j) {
return -1;
} else if (i > j) {
return 1;
}
it.advance();
jt.advance();
}
if (it.isValid()) {
return 1;
}
if (jt.isValid()) {
return -1;
}
return 0;
}
//algorithms
default public void forEach(CharTask task) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
task.process(it.value());
}
}
default public boolean contains(char value) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
if (it.value() == value) {
return true;
}
}
return false;
}
default public boolean contains(CharFilter filter) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
if (filter.accept(it.value())) {
return true;
}
}
return false;
}
default public int count(char value) {
int result = 0;
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
if (it.value() == value) {
result++;
}
}
return result;
}
default public int count(CharFilter filter) {
int result = 0;
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
if (filter.accept(it.value())) {
result++;
}
}
return result;
}
default public char min() {
char result = Character.MAX_VALUE;
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
char current = it.value();
if (current < result) {
result = current;
}
}
return result;
}
default public char min(CharComparator comparator) {
char result = Character.MAX_VALUE;
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
char current = it.value();
if (result == Character.MAX_VALUE || comparator.compare(result, current) > 0) {
result = current;
}
}
return result;
}
default public char max() {
char result = Character.MIN_VALUE;
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
char current = it.value();
if (current > result) {
result = current;
}
}
return result;
}
default public char max(CharComparator comparator) {
char result = Character.MAX_VALUE;
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
char current = it.value();
if (result == Character.MAX_VALUE || comparator.compare(result, current) < 0) {
result = current;
}
}
return result;
}
default public int sum() {
int result = 0;
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
result += it.value();
}
return result;
}
default public int[] qty(int bound) {
int[] result = new int[bound];
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
result[(int) it.value()]++;
}
return result;
}
default public int[] qty() {
return qty((int) (max() + 1));
}
default public boolean allOf(CharFilter f) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
if (!f.accept(it.value())) {
return false;
}
}
return true;
}
default public boolean anyOf(CharFilter f) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
if (f.accept(it.value())) {
return true;
}
}
return false;
}
default public boolean noneOf(CharFilter f) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
if (f.accept(it.value())) {
return false;
}
}
return true;
}
default public char reduce(CharCharToCharFunction f) {
CharIterator it = charIterator();
if (!it.isValid()) {
return Character.MAX_VALUE;
}
char result = it.value();
while (it.advance()) {
result = f.value(result, it.value());
}
return result;
}
default public double reduce(double initial, DoubleCharToDoubleFunction f) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
initial = f.value(initial, it.value());
}
return initial;
}
default public int reduce(int initial, IntCharToIntFunction f) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
initial = f.value(initial, it.value());
}
return initial;
}
default public long reduce(long initial, LongCharToLongFunction f) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
initial = f.value(initial, it.value());
}
return initial;
}
default public char reduce(char initial, CharCharToCharFunction f) {
for (CharIterator it = charIterator(); it.isValid(); it.advance()) {
initial = f.value(initial, it.value());
}
return initial;
}
//views
default public CharStream union(CharStream other) {
return () -> new CharIterator() {
private CharIterator first = CharStream.this.charIterator();
private CharIterator second;
public char value() throws NoSuchElementException {
if (first.isValid()) {
return first.value();
}
return second.value();
}
public boolean advance() throws NoSuchElementException {
if (first.isValid()) {
first.advance();
if (!first.isValid()) {
second = other.charIterator();
}
return second.isValid();
} else {
return second.advance();
}
}
public boolean isValid() {
return first.isValid() || second.isValid();
}
public void remove() {
if (first.isValid()) {
first.remove();
} else {
second.remove();
}
}
};
}
default public CharStream filter(CharFilter f) {
return () -> new CharIterator() {
private CharIterator it = CharStream.this.charIterator();
{
next();
}
private void next() {
while (it.isValid() && !f.accept(it.value())) {
it.advance();
}
}
public char value() {
return it.value();
}
public boolean advance() {
it.advance();
next();
return isValid();
}
public boolean isValid() {
return it.isValid();
}
public void remove() {
it.remove();
}
};
}
default public DoubleStream map(CharToDoubleFunction function) {
return () -> new DoubleIterator() {
private CharIterator it = CharStream.this.charIterator();
public double value() {
return function.value(it.value());
}
public boolean advance() {
return it.advance();
}
public boolean isValid() {
return it.isValid();
}
public void remove() {
it.remove();
}
};
}
default public IntStream map(CharToIntFunction function) {
return () -> new IntIterator() {
private CharIterator it = CharStream.this.charIterator();
public int value() {
return function.value(it.value());
}
public boolean advance() {
return it.advance();
}
public boolean isValid() {
return it.isValid();
}
public void remove() {
it.remove();
}
};
}
default public LongStream map(CharToLongFunction function) {
return () -> new LongIterator() {
private CharIterator it = CharStream.this.charIterator();
public long value() {
return function.value(it.value());
}
public boolean advance() {
return it.advance();
}
public boolean isValid() {
return it.isValid();
}
public void remove() {
it.remove();
}
};
}
default public CharStream map(CharToCharFunction function) {
return () -> new CharIterator() {
private CharIterator it = CharStream.this.charIterator();
public char value() {
return function.value(it.value());
}
public boolean advance() {
return it.advance();
}
public boolean isValid() {
return it.isValid();
}
public void remove() {
it.remove();
}
};
}
default public DoubleStream join(DoubleStream other, CharDoubleToDoubleFunction f) {
return () -> new DoubleIterator() {
private CharIterator it = CharStream.this.charIterator();
private DoubleIterator jt = other.doubleIterator();
public double value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public IntStream join(DoubleStream other, CharDoubleToIntFunction f) {
return () -> new IntIterator() {
private CharIterator it = CharStream.this.charIterator();
private DoubleIterator jt = other.doubleIterator();
public int value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public LongStream join(DoubleStream other, CharDoubleToLongFunction f) {
return () -> new LongIterator() {
private CharIterator it = CharStream.this.charIterator();
private DoubleIterator jt = other.doubleIterator();
public long value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public CharStream join(DoubleStream other, CharDoubleToCharFunction f) {
return () -> new CharIterator() {
private CharIterator it = CharStream.this.charIterator();
private DoubleIterator jt = other.doubleIterator();
public char value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public DoubleStream join(IntStream other, CharIntToDoubleFunction f) {
return () -> new DoubleIterator() {
private CharIterator it = CharStream.this.charIterator();
private IntIterator jt = other.intIterator();
public double value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public IntStream join(IntStream other, CharIntToIntFunction f) {
return () -> new IntIterator() {
private CharIterator it = CharStream.this.charIterator();
private IntIterator jt = other.intIterator();
public int value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public LongStream join(IntStream other, CharIntToLongFunction f) {
return () -> new LongIterator() {
private CharIterator it = CharStream.this.charIterator();
private IntIterator jt = other.intIterator();
public long value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public CharStream join(IntStream other, CharIntToCharFunction f) {
return () -> new CharIterator() {
private CharIterator it = CharStream.this.charIterator();
private IntIterator jt = other.intIterator();
public char value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public DoubleStream join(LongStream other, CharLongToDoubleFunction f) {
return () -> new DoubleIterator() {
private CharIterator it = CharStream.this.charIterator();
private LongIterator jt = other.longIterator();
public double value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public IntStream join(LongStream other, CharLongToIntFunction f) {
return () -> new IntIterator() {
private CharIterator it = CharStream.this.charIterator();
private LongIterator jt = other.longIterator();
public int value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public LongStream join(LongStream other, CharLongToLongFunction f) {
return () -> new LongIterator() {
private CharIterator it = CharStream.this.charIterator();
private LongIterator jt = other.longIterator();
public long value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public CharStream join(LongStream other, CharLongToCharFunction f) {
return () -> new CharIterator() {
private CharIterator it = CharStream.this.charIterator();
private LongIterator jt = other.longIterator();
public char value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public DoubleStream join(CharStream other, CharCharToDoubleFunction f) {
return () -> new DoubleIterator() {
private CharIterator it = CharStream.this.charIterator();
private CharIterator jt = other.charIterator();
public double value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public IntStream join(CharStream other, CharCharToIntFunction f) {
return () -> new IntIterator() {
private CharIterator it = CharStream.this.charIterator();
private CharIterator jt = other.charIterator();
public int value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public LongStream join(CharStream other, CharCharToLongFunction f) {
return () -> new LongIterator() {
private CharIterator it = CharStream.this.charIterator();
private CharIterator jt = other.charIterator();
public long value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
default public CharStream join(CharStream other, CharCharToCharFunction f) {
return () -> new CharIterator() {
private CharIterator it = CharStream.this.charIterator();
private CharIterator jt = other.charIterator();
public char value() {
return f.value(it.value(), jt.value());
}
public boolean advance() {
return it.advance() && jt.advance();
}
public boolean isValid() {
return it.isValid() && jt.isValid();
}
public void remove() {
it.remove();
jt.remove();
}
};
}
} | gpl-3.0 |
alexholehouse/SBMLIntegrator | libsbml-5.0.0/src/bindings/java/test/org/sbml/libsbml/test/sbml/TestConsistencyChecks.java | 6370 | /*
* @file TestConsistencyChecks.java
* @brief Reads test-data/inconsistent.xml into memory and tests it.
*
* @author Akiya Jouraku (Java conversion)
* @author Sarah Keating
*
* $Id$
* $HeadURL$
*
* ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ======
*
* DO NOT EDIT THIS FILE.
*
* This file was generated automatically by converting the file located at
* src/sbml/test/TestConsistencyChecks.cpp
* using the conversion program dev/utilities/translateTests/translateTests.pl.
* Any changes made here will be lost the next time the file is regenerated.
*
* -----------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright 2005-2010 California Institute of Technology.
* Copyright 2002-2005 California Institute of Technology and
* Japan Science and Technology Corporation.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* -----------------------------------------------------------------------------
*/
package org.sbml.libsbml.test.sbml;
import org.sbml.libsbml.*;
import java.io.File;
import java.lang.AssertionError;
public class TestConsistencyChecks {
static void assertTrue(boolean condition) throws AssertionError
{
if (condition == true)
{
return;
}
throw new AssertionError();
}
static void assertEquals(Object a, Object b) throws AssertionError
{
if ( (a == null) && (b == null) )
{
return;
}
else if ( (a == null) || (b == null) )
{
throw new AssertionError();
}
else if (a.equals(b))
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(Object a, Object b) throws AssertionError
{
if ( (a == null) && (b == null) )
{
throw new AssertionError();
}
else if ( (a == null) || (b == null) )
{
return;
}
else if (a.equals(b))
{
throw new AssertionError();
}
}
static void assertEquals(boolean a, boolean b) throws AssertionError
{
if ( a == b )
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(boolean a, boolean b) throws AssertionError
{
if ( a != b )
{
return;
}
throw new AssertionError();
}
static void assertEquals(int a, int b) throws AssertionError
{
if ( a == b )
{
return;
}
throw new AssertionError();
}
static void assertNotEquals(int a, int b) throws AssertionError
{
if ( a != b )
{
return;
}
throw new AssertionError();
}
public void test_consistency_checks()
{
SBMLReader reader = new SBMLReader();
SBMLDocument d;
long errors;
String filename = new String( "../../sbml/test/test-data/" );
filename += "inconsistent.xml";
d = reader.readSBML(filename);
if (d == null);
{
}
errors = d.checkConsistency();
assertTrue( errors == 1 );
assertTrue( d.getError(0).getErrorId() == 10301 );
d.getErrorLog().clearLog();
d.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY,false);
errors = d.checkConsistency();
assertTrue( errors == 1 );
assertTrue( d.getError(0).getErrorId() == 20612 );
d.getErrorLog().clearLog();
d.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY,false);
errors = d.checkConsistency();
assertTrue( errors == 1 );
assertTrue( d.getError(0).getErrorId() == 10701 );
d.getErrorLog().clearLog();
d.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY,false);
errors = d.checkConsistency();
assertTrue( errors == 1 );
assertTrue( d.getError(0).getErrorId() == 10214 );
d.getErrorLog().clearLog();
d.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY,false);
errors = d.checkConsistency();
assertTrue( errors == 3 );
assertTrue( d.getError(0).getErrorId() == 99505 );
assertTrue( d.getError(1).getErrorId() == 99505 );
assertTrue( d.getError(2).getErrorId() == 80701 );
d.getErrorLog().clearLog();
d.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY,false);
errors = d.checkConsistency();
assertTrue( errors == 0 );
d = null;
}
/**
* Loads the SWIG-generated libSBML Java module when this class is
* loaded, or reports a sensible diagnostic message about why it failed.
*/
static
{
String varname;
String shlibname;
if (System.getProperty("mrj.version") != null)
{
varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
shlibname = "libsbmlj.jnilib and/or libsbml.dylib";
}
else
{
varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
shlibname = "libsbmlj.so and/or libsbml.so";
}
try
{
System.loadLibrary("sbmlj");
// For extra safety, check that the jar file is in the classpath.
Class.forName("org.sbml.libsbml.libsbml");
}
catch (SecurityException e)
{
e.printStackTrace();
System.err.println("Could not load the libSBML library files due to a"+
" security exception.\n");
System.exit(1);
}
catch (UnsatisfiedLinkError e)
{
e.printStackTrace();
System.err.println("Error: could not link with the libSBML library files."+
" It is likely\nyour " + varname +
" environment variable does not include the directories\n"+
"containing the " + shlibname + " library files.\n");
System.exit(1);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.err.println("Error: unable to load the file libsbmlj.jar."+
" It is likely\nyour -classpath option and CLASSPATH" +
" environment variable\n"+
"do not include the path to libsbmlj.jar.\n");
System.exit(1);
}
}
}
| gpl-3.0 |
danielhuson/dendroscope3 | src/dendroscope/hybrid/EasySiblingMemory.java | 5767 | /*
* EasySiblingMemory.java Copyright (C) 2020 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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/>.
*/
/*
* Copyright (C) This is third party code.
*/
package dendroscope.hybrid;
import java.util.*;
/**
* @author Beckson
*/
public class EasySiblingMemory {
private final Vector<String> taxaOrdering;
private final Vector<String> taxonLabels;
private final Hashtable<BitSet, HashSet<BitSet>> treeSetToForestSet = new Hashtable<>();
private final Hashtable<String, Vector<String>> taxontToTaxa = new Hashtable<>();
// private BitSet treeSet;
// private BitSet forestSet;
@SuppressWarnings("unchecked")
public EasySiblingMemory(Vector<String> taxaOrdering) {
this.taxaOrdering = taxaOrdering;
this.taxonLabels = (Vector<String>) taxaOrdering.clone();
}
public EasySiblingMemory(EasyTree t, Vector<HybridTree> forest, Vector<String> taxaOrdering) {
this.taxaOrdering = taxaOrdering;
taxonLabels = new Vector<>();
for (EasyNode v : t.getLeaves())
taxonLabels.add(v.getLabel());
}
public BitSet getForestSet(Vector<EasyTree> forest) {
Vector<BitSet> forestSets = new Vector<>();
for (EasyTree t : forest) {
BitSet b = new BitSet(taxaOrdering.size());
for (EasyNode v : t.getLeaves()) {
if (taxontToTaxa.containsKey(v.getLabel())) {
for (String s : taxontToTaxa.get(v.getLabel()))
b.set(taxaOrdering.indexOf(s));
} else
b.set(taxaOrdering.indexOf(v.getLabel()));
}
forestSets.add(b);
}
Collections.sort(forestSets, new FirstBitComparator());
BitSet b = new BitSet(forestSets.size() * taxaOrdering.size());
for (BitSet f : forestSets) {
int bitIndex = f.nextSetBit(0);
while (bitIndex != -1) {
b.set(bitIndex + forestSets.indexOf(f) * taxaOrdering.size());
bitIndex = f.nextSetBit(bitIndex + 1);
}
}
return b;
}
public BitSet getTreeSet(EasyTree t) {
BitSet b = new BitSet(taxonLabels.size());
for (EasyNode v : t.getLeaves()) {
String label = v.getLabel();
b.set(taxonLabels.indexOf(label));
}
return b;
}
public boolean contains(EasyTree t, Vector<EasyTree> forest) {
BitSet treeSet = getTreeSet(t);
BitSet forestSet = getForestSet(forest);
if (treeSetToForestSet.containsKey(treeSet)) {
for (BitSet b : treeSetToForestSet.get(treeSet)) {
if (b.size() > forestSet.size()) {
if (b.equals(forestSet))
return true;
} else if (forestSet.equals(b))
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
public void addEntry(EasyTree t, Vector<EasyTree> forest) {
BitSet treeSet = getTreeSet(t);
BitSet forestSet = getForestSet(forest);
if (treeSetToForestSet.containsKey(treeSet)) {
HashSet<BitSet> set = (HashSet<BitSet>) treeSetToForestSet.get(
treeSet).clone();
set.add(forestSet);
treeSetToForestSet.remove(treeSet);
treeSetToForestSet.put(treeSet, set);
} else {
HashSet<BitSet> set = new HashSet<>();
set.add(forestSet);
treeSetToForestSet.put(treeSet, set);
}
}
public void addTreeLabel(String label) {
if (!taxonLabels.contains(label))
taxonLabels.add(label);
}
public void addTaxon(String taxon, Vector<String> taxa) {
Vector<String> v = new Vector<>();
if (taxontToTaxa.containsKey(taxa.get(0))) {
for (String s : taxontToTaxa.get(taxa.get(0)))
v.add(s);
} else
v.add(taxa.get(0));
if (taxontToTaxa.containsKey(taxa.get(1))) {
for (String s : taxontToTaxa.get(taxa.get(1)))
v.add(s);
} else
v.add(taxa.get(1));
taxontToTaxa.put(taxon, v);
}
public boolean hasSameLeafSet(EasyTree t1, EasyTree t2) {
if (t1.getLeaves().size() == t2.getLeaves().size()) {
BitSet b1 = getTreeSet(t1);
BitSet b2 = getTreeSet(t2);
if (b1.equals(b2))
return true;
}
return false;
}
public Hashtable<String, Vector<String>> getTaxontToTaxa() {
return taxontToTaxa;
}
public boolean compareTaxa(String s1, String s2) {
if (taxonLabels.contains(s1) && taxonLabels.contains(s2)) {
BitSet b1 = new BitSet(taxonLabels.size());
b1.set(taxonLabels.indexOf(s1));
BitSet b2 = new BitSet(taxonLabels.size());
b2.set(taxonLabels.indexOf(s2));
if (b1.equals(b2))
return true;
}
return false;
}
}
| gpl-3.0 |
PGMacDesign/PGMacDesign-Android_RSR_Toolbox | src/com/pgmacdesign/rsrtoolbox/SplashScreen.java | 2824 | /*
Copyright (C) <2014> <Patrick Gray MacDowell>
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.pgmacdesign.rsrtoolbox;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
//This is the splash screen that pops up when the app opens up
public class SplashScreen extends Activity {
MediaPlayer ourIntroSong, doorClose; //Doorclose not used at this point, will setup for transitional sound at some point
@Override
protected void onCreate(Bundle inputVariableToSendToSuperClass) {
super.onCreate(inputVariableToSendToSuperClass);
setContentView(R.layout.splash);
//Remember: Sound pool used for small clips (gun, explosion, etc.) and Media player used for larger clips (background music)
ourIntroSong = MediaPlayer.create(SplashScreen.this, R.raw.cinematic_impact);
MediaPlayer doorClose = MediaPlayer.create(SplashScreen.this, R.raw.door_close_1);
//getPrefs variable to determine if they have turned off the music preference in the introduction
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean music = getPrefs.getBoolean("checkBox", true);
if (music == true){
ourIntroSong.start();
}
//Determines length of time splash screen is open
Thread timer = new Thread()
{
public void run()
{
try
{
//In Milliseconds, set to 3 seconds at this point
sleep(3000);
} catch (InterruptedException e01) {
String error_in_splash = e01.toString(); //For Debugging purposes
e01.printStackTrace();
} finally {
//After thread has run, transition to main class for menu options
Intent openMain = new Intent("com.pgmacdesign.rsrtoolbox.MAIN");
startActivity(openMain);
}
}
};
timer.start();
}
@Override
protected void onPause() {
super.onPause();
//This kills the music so it isn't carried over between splash screens
ourIntroSong.release();
//Destroys the class when it goes on pause. Not ideal for most programs, but, for a splash screen, this works fine as we don't want it to show up again.
finish();
}
} | gpl-3.0 |
disconnectme/disconnect-mobile-android | engineinterface/src/me/disconnect/securefi/engine/LoggingConfig.java | 342 | package me.disconnect.securefi.engine;
/** WARNING
*
* This file is automatically updated using ANT to config either
* the logging on or off Any changes should be made to
* the version in /config rather than in /src/me/disconnect/securefi/engine
*/
public class LoggingConfig {
public final static boolean LOGGING = true;
}
| gpl-3.0 |
Social-projects-Rivne/rv-018.java | src/main/java/ua/softserve/rv_018/greentourism/service/SecurityUserService.java | 154 | package ua.softserve.rv_018.greentourism.service;
public interface SecurityUserService {
String validatePasswordResetToken(long id, String token);
}
| gpl-3.0 |
luiswolff/arden2bytecode | src/arden/runtime/jdbc/JDBCQuery.java | 4652 | // arden2bytecode
// Copyright (c) 2010, Daniel Grunwald
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// - Neither the name of the owner nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package arden.runtime.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import arden.runtime.ArdenList;
import arden.runtime.ArdenNumber;
import arden.runtime.ArdenString;
import arden.runtime.ArdenValue;
import arden.runtime.DatabaseQuery;
public class JDBCQuery extends DatabaseQuery {
private Connection connection;
private String mapping;
public JDBCQuery(String mapping, Connection connection) {
this.mapping = mapping;
this.connection = connection;
}
public static ArdenValue objectToArdenValue(Object o) {
if (o instanceof String) {
return new ArdenString((String)o);
} else if (o instanceof Double) {
return new ArdenNumber(((Double)o).doubleValue());
} else if (o instanceof Integer) {
return new ArdenNumber(((Integer)o).doubleValue());
} else {
return new ArdenString(o.toString());
}
}
public static ArdenValue[] resultSetToArdenValues(ResultSet results) throws SQLException {
if (results == null) {
return ArdenList.EMPTY.values;
}
int columnCount = results.getMetaData().getColumnCount();
List<List<ArdenValue>> resultTable =
new ArrayList<List<ArdenValue>>(columnCount);
for (int column = 0; column < columnCount; column++) {
resultTable.add(new LinkedList<ArdenValue>());
}
int rowCount = 0;
while (results.next()) {
rowCount++;
for (int column = 0; column < columnCount; column++) {
Object o = results.getObject(column + 1);
resultTable.get(column).add(objectToArdenValue(o));
}
}
if (rowCount == 0) {
throw new RuntimeException("no results");
} else if (rowCount == 1) {
// one row
List<ArdenValue> ardenResult = new LinkedList<ArdenValue>();
for (int column = 0; column < columnCount; column++) {
ardenResult.add(resultTable.get(column).get(0));
}
return ardenResult.toArray(new ArdenValue[0]);
} else if (rowCount > 1) {
List<ArdenList> ardenResult = new LinkedList<ArdenList>();
for (int column = 0; column < columnCount; column++) {
// convert every column to ArdenList
ardenResult.add(
new ArdenList(
resultTable.get(column).toArray(
new ArdenValue[0])));
}
return ardenResult.toArray(new ArdenList[0]);
} else {
throw new RuntimeException("not implemented");
}
}
@Override
public ArdenValue[] execute() {
try {
Statement stmt = connection.createStatement();
boolean resultSetAvailable = stmt.execute(mapping);
ResultSet results = null;
if (resultSetAvailable) {
results = stmt.getResultSet();
}
return resultSetToArdenValues(results);
} catch (SQLException e) {
System.out.println("SQL Exception");
while (e != null) {
System.out.println(" State: " + e.getSQLState());
System.out.println(" Message: " + e.getMessage());
System.out.println(" Error: " + e.getErrorCode());
e = e.getNextException();
}
return ArdenList.EMPTY.values;
}
}
}
| gpl-3.0 |
manhcuongkd/blynk-server | server/core/src/main/java/cc/blynk/server/core/dao/ReportingDao.java | 7262 | package cc.blynk.server.core.dao;
import cc.blynk.server.core.model.auth.User;
import cc.blynk.server.core.model.enums.GraphType;
import cc.blynk.server.core.model.enums.PinType;
import cc.blynk.server.core.protocol.exceptions.NoDataException;
import cc.blynk.server.core.reporting.GraphPinRequest;
import cc.blynk.server.core.reporting.average.AverageAggregatorProcessor;
import cc.blynk.server.core.reporting.raw.RawDataProcessor;
import cc.blynk.utils.FileUtils;
import cc.blynk.utils.NumberUtil;
import cc.blynk.utils.ServerProperties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static cc.blynk.utils.ArrayUtil.EMPTY_BYTES;
import static cc.blynk.utils.StringUtils.DEVICE_SEPARATOR;
/**
* The Blynk Project.
* Created by Dmitriy Dumanskiy.
* Created on 2/18/2015.
*/
public class ReportingDao implements Closeable {
private static final Logger log = LogManager.getLogger(ReportingDao.class);
public final AverageAggregatorProcessor averageAggregator;
public final RawDataProcessor rawDataProcessor;
public final CSVGenerator csvGenerator;
public final String dataFolder;
private final boolean ENABLE_RAW_DB_DATA_STORE;
//for test only
public ReportingDao(String reportingFolder, AverageAggregatorProcessor averageAggregator, ServerProperties serverProperties) {
this.averageAggregator = averageAggregator;
this.dataFolder = reportingFolder;
this.ENABLE_RAW_DB_DATA_STORE = serverProperties.getBoolProperty("enable.raw.db.data.store");
this.rawDataProcessor = new RawDataProcessor(ENABLE_RAW_DB_DATA_STORE);
this.csvGenerator = new CSVGenerator(this);
}
public ReportingDao(String reportingFolder , ServerProperties serverProperties) {
this.averageAggregator = new AverageAggregatorProcessor(reportingFolder);
this.dataFolder = reportingFolder;
this.ENABLE_RAW_DB_DATA_STORE = serverProperties.getBoolProperty("enable.raw.db.data.store");
this.rawDataProcessor = new RawDataProcessor(ENABLE_RAW_DB_DATA_STORE);
this.csvGenerator = new CSVGenerator(this);
}
public static String generateFilename(int dashId, int deviceId, char pinType, byte pin, GraphType type) {
switch (type) {
case MINUTE :
return formatMinute(dashId, deviceId, pinType, pin);
case HOURLY :
return formatHour(dashId, deviceId, pinType, pin);
default :
return formatDaily(dashId, deviceId, pinType, pin);
}
}
public static ByteBuffer getByteBufferFromDisk(String dataFolder, User user, int dashId, int deviceId, PinType pinType, byte pin, int count, GraphType type) {
Path userDataFile = Paths.get(dataFolder, FileUtils.getUserReportingDir(user), generateFilename(dashId, deviceId, pinType.pintTypeChar, pin, type));
if (Files.notExists(userDataFile)) {
return null;
}
try {
return FileUtils.read(userDataFile, count);
} catch (IOException ioe) {
log.error(ioe);
}
return null;
}
private static boolean checkNoData(byte[][] data) {
boolean noData = true;
for (byte[] pinData : data) {
noData = noData && pinData.length == 0;
}
return noData;
}
public ByteBuffer getByteBufferFromDisk(User user, int dashId, int deviceId, PinType pinType, byte pin, int count, GraphType type) {
return getByteBufferFromDisk(dataFolder, user, dashId, deviceId, pinType, pin, count, type);
}
public void delete(User user, int dashId, int deviceId, PinType pinType, byte pin) {
log.debug("Removing {}{} pin data for dashId {}, deviceId {}.", pinType.pintTypeChar, pin, dashId, deviceId);
Path userDataMinuteFile = Paths.get(dataFolder, FileUtils.getUserReportingDir(user), formatMinute(dashId, deviceId, pinType.pintTypeChar, pin));
Path userDataHourlyFile = Paths.get(dataFolder, FileUtils.getUserReportingDir(user), formatHour(dashId, deviceId, pinType.pintTypeChar, pin));
Path userDataDailyFile = Paths.get(dataFolder, FileUtils.getUserReportingDir(user), formatDaily(dashId, deviceId, pinType.pintTypeChar, pin));
FileUtils.deleteQuietly(userDataMinuteFile);
FileUtils.deleteQuietly(userDataHourlyFile);
FileUtils.deleteQuietly(userDataDailyFile);
}
protected static String formatMinute(int dashId, int deviceId, char pinType, byte pin) {
return format("minute", dashId, deviceId, pinType, pin);
}
protected static String formatHour(int dashId, int deviceId, char pinType, byte pin) {
return format("hourly", dashId, deviceId, pinType, pin);
}
protected static String formatDaily(int dashId, int deviceId, char pinType, byte pin) {
return format("daily", dashId, deviceId, pinType, pin);
}
private static String format(String type, int dashId, int deviceId, char pinType, byte pin) {
//todo this is back compatibility code. should be removed in future versions.
if (deviceId == 0) {
return "history_" + dashId + "_" + pinType + pin + "_" + type + ".bin";
}
return "history_" + dashId + DEVICE_SEPARATOR + deviceId + "_" + pinType + pin + "_" + type + ".bin";
}
public void process(User user, int dashId, int deviceId, byte pin, PinType pinType, String value, long ts) {
try {
double doubleVal = NumberUtil.parseDouble(value);
process(user, dashId, deviceId, pin, pinType, value, ts, doubleVal);
} catch (Exception e) {
//just in case
log.trace("Error collecting reporting entry.");
}
}
private void process(User user, int dashId, int deviceId, byte pin, PinType pinType, String value, long ts, double doubleVal) {
if (ENABLE_RAW_DB_DATA_STORE) {
rawDataProcessor.collect(user, dashId, deviceId, pinType.pintTypeChar, pin, ts, value, doubleVal);
}
//not a number, nothing to aggregate
if (doubleVal == NumberUtil.NO_RESULT) {
return;
}
averageAggregator.collect(user, dashId, deviceId, pinType.pintTypeChar, pin, ts, doubleVal);
}
public byte[][] getAllFromDisk(User user, GraphPinRequest[] requestedPins) {
byte[][] values = new byte[requestedPins.length][];
for (int i = 0; i < requestedPins.length; i++) {
final ByteBuffer byteBuffer = getByteBufferFromDisk(user,
requestedPins[i].dashId, requestedPins[i].deviceId, requestedPins[i].pinType,
requestedPins[i].pin, requestedPins[i].count, requestedPins[i].type);
values[i] = byteBuffer == null ? EMPTY_BYTES : byteBuffer.array();
}
if (checkNoData(values)) {
throw new NoDataException();
}
return values;
}
@Override
public void close() {
System.out.println("Stopping aggregator...");
this.averageAggregator.close();
}
}
| gpl-3.0 |
dSquadAdmin/grpc-chat | src/main/java/np/com/keshavbist/chat/messages/MessageType.java | 254 | package np.com.keshavbist.chat.messages;
/**
* @author Dominic
* @since 03-Sep-16
* Website: www.dominicheal.com
* Github: www.github.com/DomHeal
*/
public enum MessageType {
DISCONNECTED, CONNECTED, STATUS, USER, SERVER, NOTIFICATION, VOICE
}
| gpl-3.0 |
SZitzelsberger/Spreadsheet-Inspection-Framework | src/sif/model/elements/custom/IntermediateCell.java | 1182 | package sif.model.elements.custom;
import sif.model.elements.BasicAbstractElement;
import sif.model.elements.CustomAbstractElement;
import sif.model.elements.basic.cell.Cell;
import sif.model.elements.basic.cell.ICellElement;
import sif.model.elements.basic.reference.IReferencedElement;
import sif.model.elements.basic.reference.IReferencingElement;
/**
* An intermediate cell has at least one outgoing and at least one incoming
* reference.
*
* @see {@link IReferencingElement} @see {@link IReferencedElement};
*
* @author Sebastian Zitzelsberger
*
*/
public class IntermediateCell extends CustomAbstractElement implements
ICellElement {
private Cell cell;
@Override
public BasicAbstractElement getBaseElement() {
return cell;
}
@Override
public Cell getCell() {
return cell;
}
@Override
public String getLocation() {
return cell.getLocation();
}
@Override
public String getStringRepresentation() {
return cell.getStringRepresentation();
}
@Override
public String getValueAsString() {
return cell.getValueAsString();
}
public void setCell(Cell cell) {
this.cell = cell;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | external/proguard/src/proguard/gui/splash/LinearDouble.java | 1786 | /*
* 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.gui.splash;
/**
* This VariableDouble varies linearly with respect to its Timing.
*
* @author Eric Lafortune
*/
public class LinearDouble implements VariableDouble
{
private final double fromValue;
private final double toValue;
private final Timing timing;
/**
* Creates a new LinearDouble.
* @param fromValue the value that corresponds to a timing of 0.
* @param toValue the value that corresponds to a timing of 1.
* @param timing the applied timing.
*/
public LinearDouble(double fromValue, double toValue, Timing timing)
{
this.fromValue = fromValue;
this.toValue = toValue;
this.timing = timing;
}
// Implementation for VariableDouble.
public double getDouble(long time)
{
return fromValue + timing.getTiming(time) * (toValue - fromValue);
}
}
| gpl-3.0 |
innovad/4mila | backend/src/main/java/com/_4mila/backend/service/course/iof2/xml/CourseData.java | 5535 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// 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: 2011.07.09 at 05:12:48 PM MESZ
//
package com._4mila.backend.service.course.iof2.xml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"iofVersion",
"map",
"startPoint",
"control",
"finishPoint",
"course"
})
@XmlRootElement(name = "CourseData")
public class CourseData {
@XmlElement(name = "IOFVersion")
protected IOFVersion iofVersion;
@XmlElement(name = "Map")
protected Map map;
@XmlElement(name = "StartPoint")
protected List<StartPoint> startPoint;
@XmlElement(name = "Control")
protected List<XmlControl> control;
@XmlElement(name = "FinishPoint")
protected List<FinishPoint> finishPoint;
@XmlElement(name = "Course")
protected List<XmlCourse> course;
/**
* Gets the value of the iofVersion property.
*
* @return
* possible object is
* {@link IOFVersion }
*
*/
public IOFVersion getIOFVersion() {
return iofVersion;
}
/**
* Sets the value of the iofVersion property.
*
* @param value
* allowed object is
* {@link IOFVersion }
*
*/
public void setIOFVersion(IOFVersion value) {
this.iofVersion = value;
}
/**
* Gets the value of the map property.
*
* @return
* possible object is
* {@link Map }
*
*/
public Map getMap() {
return map;
}
/**
* Sets the value of the map property.
*
* @param value
* allowed object is
* {@link Map }
*
*/
public void setMap(Map value) {
this.map = value;
}
/**
* Gets the value of the startPoint 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 startPoint property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStartPoint().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StartPoint }
*
*
*/
public List<StartPoint> getStartPoint() {
if (startPoint == null) {
startPoint = new ArrayList<StartPoint>();
}
return this.startPoint;
}
/**
* Gets the value of the control 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 control property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getControl().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link XmlControl }
*
*
*/
public List<XmlControl> getControl() {
if (control == null) {
control = new ArrayList<XmlControl>();
}
return this.control;
}
/**
* Gets the value of the finishPoint 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 finishPoint property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFinishPoint().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FinishPoint }
*
*
*/
public List<FinishPoint> getFinishPoint() {
if (finishPoint == null) {
finishPoint = new ArrayList<FinishPoint>();
}
return this.finishPoint;
}
/**
* Gets the value of the course 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 course property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCourse().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link XmlCourse }
*
*
*/
public List<XmlCourse> getCourse() {
if (course == null) {
course = new ArrayList<XmlCourse>();
}
return this.course;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | frameworks/base/core/java/android/widget/DatePickerCalendarDelegate.java | 28492 | /*
* Copyright (C) 2014 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 android.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import com.android.internal.R;
import com.android.internal.widget.AccessibleDateAnimator;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Locale;
/**
* A delegate for picking up a date (day / month / year).
*/
class DatePickerCalendarDelegate extends DatePicker.AbstractDatePickerDelegate implements
View.OnClickListener, DatePickerController {
private static final int USE_LOCALE = 0;
private static final int UNINITIALIZED = -1;
private static final int MONTH_AND_DAY_VIEW = 0;
private static final int YEAR_VIEW = 1;
private static final int DEFAULT_START_YEAR = 1900;
private static final int DEFAULT_END_YEAR = 2100;
private static final int ANIMATION_DURATION = 300;
private static final int MONTH_INDEX = 0;
private static final int DAY_INDEX = 1;
private static final int YEAR_INDEX = 2;
private SimpleDateFormat mYearFormat = new SimpleDateFormat("y", Locale.getDefault());
private SimpleDateFormat mDayFormat = new SimpleDateFormat("d", Locale.getDefault());
private TextView mDayOfWeekView;
/** Layout that contains the current month, day, and year. */
private LinearLayout mMonthDayYearLayout;
/** Clickable layout that contains the current day and year. */
private LinearLayout mMonthAndDayLayout;
private TextView mHeaderMonthTextView;
private TextView mHeaderDayOfMonthTextView;
private TextView mHeaderYearTextView;
private DayPickerView mDayPickerView;
private YearPickerView mYearPickerView;
private boolean mIsEnabled = true;
// Accessibility strings.
private String mDayPickerDescription;
private String mSelectDay;
private String mYearPickerDescription;
private String mSelectYear;
private AccessibleDateAnimator mAnimator;
private DatePicker.OnDateChangedListener mDateChangedListener;
private int mCurrentView = UNINITIALIZED;
private Calendar mCurrentDate;
private Calendar mTempDate;
private Calendar mMinDate;
private Calendar mMaxDate;
private int mFirstDayOfWeek = USE_LOCALE;
private HashSet<OnDateChangedListener> mListeners = new HashSet<OnDateChangedListener>();
public DatePickerCalendarDelegate(DatePicker delegator, Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(delegator, context);
final Locale locale = Locale.getDefault();
mMinDate = getCalendarForLocale(mMinDate, locale);
mMaxDate = getCalendarForLocale(mMaxDate, locale);
mTempDate = getCalendarForLocale(mMaxDate, locale);
mCurrentDate = getCalendarForLocale(mCurrentDate, locale);
mMinDate.set(DEFAULT_START_YEAR, 1, 1);
mMaxDate.set(DEFAULT_END_YEAR, 12, 31);
final Resources res = mDelegator.getResources();
final TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.DatePicker, defStyleAttr, defStyleRes);
final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
final int layoutResourceId = a.getResourceId(
R.styleable.DatePicker_internalLayout, R.layout.date_picker_holo);
final View mainView = inflater.inflate(layoutResourceId, null);
mDelegator.addView(mainView);
mDayOfWeekView = (TextView) mainView.findViewById(R.id.date_picker_header);
// Layout that contains the current date and day name header.
final LinearLayout dateLayout = (LinearLayout) mainView.findViewById(
R.id.day_picker_selector_layout);
mMonthDayYearLayout = (LinearLayout) mainView.findViewById(
R.id.date_picker_month_day_year_layout);
mMonthAndDayLayout = (LinearLayout) mainView.findViewById(
R.id.date_picker_month_and_day_layout);
mMonthAndDayLayout.setOnClickListener(this);
mHeaderMonthTextView = (TextView) mainView.findViewById(R.id.date_picker_month);
mHeaderDayOfMonthTextView = (TextView) mainView.findViewById(R.id.date_picker_day);
mHeaderYearTextView = (TextView) mainView.findViewById(R.id.date_picker_year);
mHeaderYearTextView.setOnClickListener(this);
// Obtain default highlight color from the theme.
final int defaultHighlightColor = mHeaderYearTextView.getHighlightColor();
// Use Theme attributes if possible
final int dayOfWeekTextAppearanceResId = a.getResourceId(
R.styleable.DatePicker_dayOfWeekTextAppearance, -1);
if (dayOfWeekTextAppearanceResId != -1) {
mDayOfWeekView.setTextAppearance(context, dayOfWeekTextAppearanceResId);
}
mDayOfWeekView.setBackground(a.getDrawable(R.styleable.DatePicker_dayOfWeekBackground));
dateLayout.setBackground(a.getDrawable(R.styleable.DatePicker_headerBackground));
final int headerSelectedTextColor = a.getColor(
R.styleable.DatePicker_headerSelectedTextColor, defaultHighlightColor);
final int monthTextAppearanceResId = a.getResourceId(
R.styleable.DatePicker_headerMonthTextAppearance, -1);
if (monthTextAppearanceResId != -1) {
mHeaderMonthTextView.setTextAppearance(context, monthTextAppearanceResId);
}
mHeaderMonthTextView.setTextColor(ColorStateList.addFirstIfMissing(
mHeaderMonthTextView.getTextColors(), R.attr.state_selected,
headerSelectedTextColor));
final int dayOfMonthTextAppearanceResId = a.getResourceId(
R.styleable.DatePicker_headerDayOfMonthTextAppearance, -1);
if (dayOfMonthTextAppearanceResId != -1) {
mHeaderDayOfMonthTextView.setTextAppearance(context, dayOfMonthTextAppearanceResId);
}
mHeaderDayOfMonthTextView.setTextColor(ColorStateList.addFirstIfMissing(
mHeaderDayOfMonthTextView.getTextColors(), R.attr.state_selected,
headerSelectedTextColor));
final int yearTextAppearanceResId = a.getResourceId(
R.styleable.DatePicker_headerYearTextAppearance, -1);
if (yearTextAppearanceResId != -1) {
mHeaderYearTextView.setTextAppearance(context, yearTextAppearanceResId);
}
mHeaderYearTextView.setTextColor(ColorStateList.addFirstIfMissing(
mHeaderYearTextView.getTextColors(), R.attr.state_selected,
headerSelectedTextColor));
mDayPickerView = new DayPickerView(mContext);
mDayPickerView.setFirstDayOfWeek(mFirstDayOfWeek);
mDayPickerView.setMinDate(mMinDate.getTimeInMillis());
mDayPickerView.setMaxDate(mMaxDate.getTimeInMillis());
mDayPickerView.setDate(mCurrentDate.getTimeInMillis());
mDayPickerView.setOnDaySelectedListener(mOnDaySelectedListener);
mYearPickerView = new YearPickerView(mContext);
mYearPickerView.init(this);
mYearPickerView.setRange(mMinDate, mMaxDate);
final int yearSelectedCircleColor = a.getColor(R.styleable.DatePicker_yearListSelectorColor,
defaultHighlightColor);
mYearPickerView.setYearSelectedCircleColor(yearSelectedCircleColor);
final ColorStateList calendarTextColor = a.getColorStateList(
R.styleable.DatePicker_calendarTextColor);
final int calendarSelectedTextColor = a.getColor(
R.styleable.DatePicker_calendarSelectedTextColor, defaultHighlightColor);
mDayPickerView.setCalendarTextColor(ColorStateList.addFirstIfMissing(
calendarTextColor, R.attr.state_selected, calendarSelectedTextColor));
mDayPickerDescription = res.getString(R.string.day_picker_description);
mSelectDay = res.getString(R.string.select_day);
mYearPickerDescription = res.getString(R.string.year_picker_description);
mSelectYear = res.getString(R.string.select_year);
mAnimator = (AccessibleDateAnimator) mainView.findViewById(R.id.animator);
mAnimator.addView(mDayPickerView);
mAnimator.addView(mYearPickerView);
mAnimator.setDateMillis(mCurrentDate.getTimeInMillis());
final Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(ANIMATION_DURATION);
mAnimator.setInAnimation(animation);
final Animation animation2 = new AlphaAnimation(1.0f, 0.0f);
animation2.setDuration(ANIMATION_DURATION);
mAnimator.setOutAnimation(animation2);
updateDisplay(false);
setCurrentView(MONTH_AND_DAY_VIEW);
}
/**
* Gets a calendar for locale bootstrapped with the value of a given calendar.
*
* @param oldCalendar The old calendar.
* @param locale The locale.
*/
private Calendar getCalendarForLocale(Calendar oldCalendar, Locale locale) {
if (oldCalendar == null) {
return Calendar.getInstance(locale);
} else {
final long currentTimeMillis = oldCalendar.getTimeInMillis();
Calendar newCalendar = Calendar.getInstance(locale);
newCalendar.setTimeInMillis(currentTimeMillis);
return newCalendar;
}
}
/**
* Compute the array representing the order of Month / Day / Year views in their layout.
* Will be used for I18N purpose as the order of them depends on the Locale.
*/
private int[] getMonthDayYearIndexes(String pattern) {
int[] result = new int[3];
final String filteredPattern = pattern.replaceAll("'.*?'", "");
final int dayIndex = filteredPattern.indexOf('d');
final int monthMIndex = filteredPattern.indexOf("M");
final int monthIndex = (monthMIndex != -1) ? monthMIndex : filteredPattern.indexOf("L");
final int yearIndex = filteredPattern.indexOf("y");
if (yearIndex < monthIndex) {
result[YEAR_INDEX] = 0;
if (monthIndex < dayIndex) {
result[MONTH_INDEX] = 1;
result[DAY_INDEX] = 2;
} else {
result[MONTH_INDEX] = 2;
result[DAY_INDEX] = 1;
}
} else {
result[YEAR_INDEX] = 2;
if (monthIndex < dayIndex) {
result[MONTH_INDEX] = 0;
result[DAY_INDEX] = 1;
} else {
result[MONTH_INDEX] = 1;
result[DAY_INDEX] = 0;
}
}
return result;
}
private void updateDisplay(boolean announce) {
if (mDayOfWeekView != null) {
mDayOfWeekView.setText(mCurrentDate.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
Locale.getDefault()));
}
// Compute indices of Month, Day and Year views
final String bestDateTimePattern =
DateFormat.getBestDateTimePattern(mCurrentLocale, "yMMMd");
final int[] viewIndices = getMonthDayYearIndexes(bestDateTimePattern);
// Position the Year and MonthAndDay views within the header.
mMonthDayYearLayout.removeAllViews();
if (viewIndices[YEAR_INDEX] == 0) {
mMonthDayYearLayout.addView(mHeaderYearTextView);
mMonthDayYearLayout.addView(mMonthAndDayLayout);
} else {
mMonthDayYearLayout.addView(mMonthAndDayLayout);
mMonthDayYearLayout.addView(mHeaderYearTextView);
}
// Position Day and Month views within the MonthAndDay view.
mMonthAndDayLayout.removeAllViews();
if (viewIndices[MONTH_INDEX] > viewIndices[DAY_INDEX]) {
mMonthAndDayLayout.addView(mHeaderDayOfMonthTextView);
mMonthAndDayLayout.addView(mHeaderMonthTextView);
} else {
mMonthAndDayLayout.addView(mHeaderMonthTextView);
mMonthAndDayLayout.addView(mHeaderDayOfMonthTextView);
}
mHeaderMonthTextView.setText(mCurrentDate.getDisplayName(Calendar.MONTH, Calendar.SHORT,
Locale.getDefault()).toUpperCase(Locale.getDefault()));
mHeaderDayOfMonthTextView.setText(mDayFormat.format(mCurrentDate.getTime()));
mHeaderYearTextView.setText(mYearFormat.format(mCurrentDate.getTime()));
// Accessibility.
long millis = mCurrentDate.getTimeInMillis();
mAnimator.setDateMillis(millis);
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
String monthAndDayText = DateUtils.formatDateTime(mContext, millis, flags);
mMonthAndDayLayout.setContentDescription(monthAndDayText);
if (announce) {
flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
String fullDateText = DateUtils.formatDateTime(mContext, millis, flags);
mAnimator.announceForAccessibility(fullDateText);
}
}
private void setCurrentView(final int viewIndex) {
long millis = mCurrentDate.getTimeInMillis();
switch (viewIndex) {
case MONTH_AND_DAY_VIEW:
mDayPickerView.setDate(getSelectedDay().getTimeInMillis());
if (mCurrentView != viewIndex) {
mMonthAndDayLayout.setSelected(true);
mHeaderYearTextView.setSelected(false);
mAnimator.setDisplayedChild(MONTH_AND_DAY_VIEW);
mCurrentView = viewIndex;
}
final int flags = DateUtils.FORMAT_SHOW_DATE;
final String dayString = DateUtils.formatDateTime(mContext, millis, flags);
mAnimator.setContentDescription(mDayPickerDescription + ": " + dayString);
mAnimator.announceForAccessibility(mSelectDay);
break;
case YEAR_VIEW:
mYearPickerView.onDateChanged();
if (mCurrentView != viewIndex) {
mMonthAndDayLayout.setSelected(false);
mHeaderYearTextView.setSelected(true);
mAnimator.setDisplayedChild(YEAR_VIEW);
mCurrentView = viewIndex;
}
final CharSequence yearString = mYearFormat.format(millis);
mAnimator.setContentDescription(mYearPickerDescription + ": " + yearString);
mAnimator.announceForAccessibility(mSelectYear);
break;
}
}
@Override
public void init(int year, int monthOfYear, int dayOfMonth,
DatePicker.OnDateChangedListener callBack) {
mCurrentDate.set(Calendar.YEAR, year);
mCurrentDate.set(Calendar.MONTH, monthOfYear);
mCurrentDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDateChangedListener = callBack;
onDateChanged(false, false);
}
@Override
public void updateDate(int year, int month, int dayOfMonth) {
mCurrentDate.set(Calendar.YEAR, year);
mCurrentDate.set(Calendar.MONTH, month);
mCurrentDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
onDateChanged(false, true);
}
private void onDateChanged(boolean fromUser, boolean callbackToClient) {
if (callbackToClient && mDateChangedListener != null) {
final int year = mCurrentDate.get(Calendar.YEAR);
final int monthOfYear = mCurrentDate.get(Calendar.MONTH);
final int dayOfMonth = mCurrentDate.get(Calendar.DAY_OF_MONTH);
mDateChangedListener.onDateChanged(mDelegator, year, monthOfYear, dayOfMonth);
}
for (OnDateChangedListener listener : mListeners) {
listener.onDateChanged();
}
mDayPickerView.setDate(getSelectedDay().getTimeInMillis());
updateDisplay(fromUser);
if (fromUser) {
tryVibrate();
}
}
@Override
public int getYear() {
return mCurrentDate.get(Calendar.YEAR);
}
@Override
public int getMonth() {
return mCurrentDate.get(Calendar.MONTH);
}
@Override
public int getDayOfMonth() {
return mCurrentDate.get(Calendar.DAY_OF_MONTH);
}
@Override
public void setMinDate(long minDate) {
mTempDate.setTimeInMillis(minDate);
if (mTempDate.get(Calendar.YEAR) == mMinDate.get(Calendar.YEAR)
&& mTempDate.get(Calendar.DAY_OF_YEAR) != mMinDate.get(Calendar.DAY_OF_YEAR)) {
return;
}
if (mCurrentDate.before(mTempDate)) {
mCurrentDate.setTimeInMillis(minDate);
onDateChanged(false, true);
}
mMinDate.setTimeInMillis(minDate);
mDayPickerView.setMinDate(minDate);
mYearPickerView.setRange(mMinDate, mMaxDate);
}
@Override
public Calendar getMinDate() {
return mMinDate;
}
@Override
public void setMaxDate(long maxDate) {
mTempDate.setTimeInMillis(maxDate);
if (mTempDate.get(Calendar.YEAR) == mMaxDate.get(Calendar.YEAR)
&& mTempDate.get(Calendar.DAY_OF_YEAR) != mMaxDate.get(Calendar.DAY_OF_YEAR)) {
return;
}
if (mCurrentDate.after(mTempDate)) {
mCurrentDate.setTimeInMillis(maxDate);
onDateChanged(false, true);
}
mMaxDate.setTimeInMillis(maxDate);
mDayPickerView.setMaxDate(maxDate);
mYearPickerView.setRange(mMinDate, mMaxDate);
}
@Override
public Calendar getMaxDate() {
return mMaxDate;
}
@Override
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
mDayPickerView.setFirstDayOfWeek(firstDayOfWeek);
}
@Override
public int getFirstDayOfWeek() {
if (mFirstDayOfWeek != USE_LOCALE) {
return mFirstDayOfWeek;
}
return mCurrentDate.getFirstDayOfWeek();
}
@Override
public void setEnabled(boolean enabled) {
mMonthAndDayLayout.setEnabled(enabled);
mHeaderYearTextView.setEnabled(enabled);
mAnimator.setEnabled(enabled);
mIsEnabled = enabled;
}
@Override
public boolean isEnabled() {
return mIsEnabled;
}
@Override
public CalendarView getCalendarView() {
throw new UnsupportedOperationException(
"CalendarView does not exists for the new DatePicker");
}
@Override
public void setCalendarViewShown(boolean shown) {
// No-op for compatibility with the old DatePicker.
}
@Override
public boolean getCalendarViewShown() {
return false;
}
@Override
public void setSpinnersShown(boolean shown) {
// No-op for compatibility with the old DatePicker.
}
@Override
public boolean getSpinnersShown() {
return false;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
mYearFormat = new SimpleDateFormat("y", newConfig.locale);
mDayFormat = new SimpleDateFormat("d", newConfig.locale);
}
@Override
public Parcelable onSaveInstanceState(Parcelable superState) {
final int year = mCurrentDate.get(Calendar.YEAR);
final int month = mCurrentDate.get(Calendar.MONTH);
final int day = mCurrentDate.get(Calendar.DAY_OF_MONTH);
int listPosition = -1;
int listPositionOffset = -1;
if (mCurrentView == MONTH_AND_DAY_VIEW) {
listPosition = mDayPickerView.getMostVisiblePosition();
} else if (mCurrentView == YEAR_VIEW) {
listPosition = mYearPickerView.getFirstVisiblePosition();
listPositionOffset = mYearPickerView.getFirstPositionOffset();
}
return new SavedState(superState, year, month, day, mMinDate.getTimeInMillis(),
mMaxDate.getTimeInMillis(), mCurrentView, listPosition, listPositionOffset);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
mCurrentDate.set(ss.getSelectedYear(), ss.getSelectedMonth(), ss.getSelectedDay());
mCurrentView = ss.getCurrentView();
mMinDate.setTimeInMillis(ss.getMinDate());
mMaxDate.setTimeInMillis(ss.getMaxDate());
updateDisplay(false);
setCurrentView(mCurrentView);
final int listPosition = ss.getListPosition();
if (listPosition != -1) {
if (mCurrentView == MONTH_AND_DAY_VIEW) {
mDayPickerView.postSetSelection(listPosition);
} else if (mCurrentView == YEAR_VIEW) {
mYearPickerView.postSetSelectionFromTop(listPosition, ss.getListPositionOffset());
}
}
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
onPopulateAccessibilityEvent(event);
return true;
}
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
event.getText().add(mCurrentDate.getTime().toString());
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
event.setClassName(DatePicker.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
info.setClassName(DatePicker.class.getName());
}
@Override
public void onYearSelected(int year) {
adjustDayInMonthIfNeeded(mCurrentDate.get(Calendar.MONTH), year);
mCurrentDate.set(Calendar.YEAR, year);
onDateChanged(true, true);
// Auto-advance to month and day view.
setCurrentView(MONTH_AND_DAY_VIEW);
}
// If the newly selected month / year does not contain the currently selected day number,
// change the selected day number to the last day of the selected month or year.
// e.g. Switching from Mar to Apr when Mar 31 is selected -> Apr 30
// e.g. Switching from 2012 to 2013 when Feb 29, 2012 is selected -> Feb 28, 2013
private void adjustDayInMonthIfNeeded(int month, int year) {
int day = mCurrentDate.get(Calendar.DAY_OF_MONTH);
int daysInMonth = getDaysInMonth(month, year);
if (day > daysInMonth) {
mCurrentDate.set(Calendar.DAY_OF_MONTH, daysInMonth);
}
}
public static int getDaysInMonth(int month, int year) {
switch (month) {
case Calendar.JANUARY:
case Calendar.MARCH:
case Calendar.MAY:
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.OCTOBER:
case Calendar.DECEMBER:
return 31;
case Calendar.APRIL:
case Calendar.JUNE:
case Calendar.SEPTEMBER:
case Calendar.NOVEMBER:
return 30;
case Calendar.FEBRUARY:
return (year % 4 == 0) ? 29 : 28;
default:
throw new IllegalArgumentException("Invalid Month");
}
}
@Override
public void registerOnDateChangedListener(OnDateChangedListener listener) {
mListeners.add(listener);
}
@Override
public Calendar getSelectedDay() {
return mCurrentDate;
}
@Override
public void tryVibrate() {
mDelegator.performHapticFeedback(HapticFeedbackConstants.CALENDAR_DATE);
}
@Override
public void onClick(View v) {
tryVibrate();
if (v.getId() == R.id.date_picker_year) {
setCurrentView(YEAR_VIEW);
} else if (v.getId() == R.id.date_picker_month_and_day_layout) {
setCurrentView(MONTH_AND_DAY_VIEW);
}
}
/**
* Listener called when the user selects a day in the day picker view.
*/
private final DayPickerView.OnDaySelectedListener
mOnDaySelectedListener = new DayPickerView.OnDaySelectedListener() {
@Override
public void onDaySelected(DayPickerView view, Calendar day) {
mCurrentDate.setTimeInMillis(day.getTimeInMillis());
onDateChanged(true, true);
}
};
/**
* Class for managing state storing/restoring.
*/
private static class SavedState extends View.BaseSavedState {
private final int mSelectedYear;
private final int mSelectedMonth;
private final int mSelectedDay;
private final long mMinDate;
private final long mMaxDate;
private final int mCurrentView;
private final int mListPosition;
private final int mListPositionOffset;
/**
* Constructor called from {@link DatePicker#onSaveInstanceState()}
*/
private SavedState(Parcelable superState, int year, int month, int day,
long minDate, long maxDate, int currentView, int listPosition,
int listPositionOffset) {
super(superState);
mSelectedYear = year;
mSelectedMonth = month;
mSelectedDay = day;
mMinDate = minDate;
mMaxDate = maxDate;
mCurrentView = currentView;
mListPosition = listPosition;
mListPositionOffset = listPositionOffset;
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
mSelectedYear = in.readInt();
mSelectedMonth = in.readInt();
mSelectedDay = in.readInt();
mMinDate = in.readLong();
mMaxDate = in.readLong();
mCurrentView = in.readInt();
mListPosition = in.readInt();
mListPositionOffset = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(mSelectedYear);
dest.writeInt(mSelectedMonth);
dest.writeInt(mSelectedDay);
dest.writeLong(mMinDate);
dest.writeLong(mMaxDate);
dest.writeInt(mCurrentView);
dest.writeInt(mListPosition);
dest.writeInt(mListPositionOffset);
}
public int getSelectedDay() {
return mSelectedDay;
}
public int getSelectedMonth() {
return mSelectedMonth;
}
public int getSelectedYear() {
return mSelectedYear;
}
public long getMinDate() {
return mMinDate;
}
public long getMaxDate() {
return mMaxDate;
}
public int getCurrentView() {
return mCurrentView;
}
public int getListPosition() {
return mListPosition;
}
public int getListPositionOffset() {
return mListPositionOffset;
}
@SuppressWarnings("all")
// suppress unused and hiding
public static final Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| gpl-3.0 |
MestreLion/boinc-debian | android/BOINC/src/edu/berkeley/boinc/rpc/GlobalPreferencesParser.java | 9652 | /*******************************************************************************
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2012 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package edu.berkeley.boinc.rpc;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import edu.berkeley.boinc.debug.Logging;
import android.util.Log;
import android.util.Xml;
public class GlobalPreferencesParser extends BaseParser {
private static final String TAG = "GlobalPreferencesParser";
private GlobalPreferences mPreferences = null;
private boolean mInsideDayPrefs = false;
private int mDayOfWeek = 0;
private TimePreferences.TimeSpan mTempCpuTimeSpan = null;
private TimePreferences.TimeSpan mTempNetTimeSpan = null;
public GlobalPreferences getGlobalPreferences() {
return mPreferences;
}
public static GlobalPreferences parse(String rpcResult) {
try {
GlobalPreferencesParser parser = new GlobalPreferencesParser();
Xml.parse(rpcResult, parser);
return parser.getGlobalPreferences();
} catch (SAXException e) {
if (Logging.DEBUG) Log.d(TAG, "Malformed XML:\n" + rpcResult);
else if (Logging.INFO) Log.i(TAG, "Malformed XML");
return null;
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equalsIgnoreCase("global_preferences")) {
if (Logging.INFO) {
if (mPreferences!= null) {
// previous <global_preferences> not closed - dropping it!
Log.i(TAG, "Dropping unfinished <global_preferences> data");
}
}
mPreferences = new GlobalPreferences();
} else if (localName.equalsIgnoreCase("day_prefs")) {
if (mInsideDayPrefs)
if (Logging.INFO) Log.i(TAG, "Dropping all <day_prefs>");
mInsideDayPrefs = true;
} else {
// Another element, hopefully primitive and not constructor
// (although unknown constructor does not hurt, because there will be primitive start anyway)
mElementStarted = true;
mCurrentElement.setLength(0);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
try {
if (mPreferences != null) {
// we are inside <global_preferences>
if (localName.equalsIgnoreCase("global_preferences")) {
// Closing tag of <global_preferences> - nothing to do at the moment
} else if (localName.equalsIgnoreCase("day_prefs")) {
// closing <day_prefs>
if (mDayOfWeek >= 0 && mDayOfWeek <= 6) {
mPreferences.cpu_times.week_prefs[mDayOfWeek] = mTempCpuTimeSpan;
mPreferences.net_times.week_prefs[mDayOfWeek] = mTempNetTimeSpan;
}
mTempCpuTimeSpan = null;
mTempNetTimeSpan = null;
mInsideDayPrefs = false;
} else if (mInsideDayPrefs) {
trimEnd();
if (localName.equalsIgnoreCase("day_of_week")) {
mDayOfWeek = Integer.parseInt(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("start_hour")) {
if (mTempCpuTimeSpan == null)
mTempCpuTimeSpan = new TimePreferences.TimeSpan();
mTempCpuTimeSpan.start_hour = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("end_hour")) {
if (mTempCpuTimeSpan == null)
mTempCpuTimeSpan = new TimePreferences.TimeSpan();
mTempCpuTimeSpan.end_hour = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("net_start_hour")) {
if (mTempNetTimeSpan == null)
mTempNetTimeSpan = new TimePreferences.TimeSpan();
mTempNetTimeSpan.start_hour = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("net_end_hour")) {
if (mTempNetTimeSpan == null)
mTempNetTimeSpan = new TimePreferences.TimeSpan();
mTempNetTimeSpan.end_hour = Double.parseDouble(mCurrentElement.toString());
}
} else {
// Not the closing tag - we decode possible inner tags
trimEnd();
if (localName.equalsIgnoreCase("run_on_batteries")) {
mPreferences.run_on_batteries = Integer.parseInt(mCurrentElement.toString()) != 0;
} else if (localName.equalsIgnoreCase("run_gpu_if_user_active")) {
mPreferences.run_gpu_if_user_active = Integer.parseInt(mCurrentElement.toString()) != 0;
} else if (localName.equalsIgnoreCase("run_if_user_active")) {
mPreferences.run_if_user_active = Integer.parseInt(mCurrentElement.toString()) != 0;
} else if (localName.equalsIgnoreCase("idle_time_to_run")) {
mPreferences.idle_time_to_run = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("suspend_cpu_usage")) {
mPreferences.suspend_cpu_usage = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("leave_apps_in_memory")) {
mPreferences.leave_apps_in_memory = Integer.parseInt(mCurrentElement.toString()) != 0;
} else if (localName.equalsIgnoreCase("dont_verify_images")) {
mPreferences.dont_verify_images = Integer.parseInt(mCurrentElement.toString()) != 0;
} else if (localName.equalsIgnoreCase("work_buf_min_days")) {
mPreferences.work_buf_min_days = Double.parseDouble(mCurrentElement.toString());
if (mPreferences.work_buf_min_days < 0.00001)
mPreferences.work_buf_min_days = 0.00001;
} else if (localName.equalsIgnoreCase("work_buf_additional_days")) {
mPreferences.work_buf_additional_days = Double.parseDouble(mCurrentElement.toString());
if (mPreferences.work_buf_additional_days < 0.0)
mPreferences.work_buf_additional_days = 0.0;
} else if (localName.equalsIgnoreCase("max_ncpus_pct")) {
mPreferences.max_ncpus_pct = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("cpu_scheduling_period_minutes")) {
mPreferences.cpu_scheduling_period_minutes = Double.parseDouble(mCurrentElement.toString());
if (mPreferences.cpu_scheduling_period_minutes < 0.00001)
mPreferences.cpu_scheduling_period_minutes = 60;
} else if (localName.equalsIgnoreCase("disk_interval")) {
mPreferences.disk_interval = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("disk_max_used_gb")) {
mPreferences.disk_max_used_gb = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("disk_max_used_pct")) {
mPreferences.disk_max_used_pct = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("disk_min_free_gb")) {
mPreferences.disk_min_free_gb = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("ram_max_used_busy_pct")) {
mPreferences.ram_max_used_busy_frac = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("ram_max_used_idle_pct")) {
mPreferences.ram_max_used_idle_frac = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("max_bytes_sec_up")) {
mPreferences.max_bytes_sec_up = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("max_bytes_sec_down")) {
mPreferences.max_bytes_sec_down = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("cpu_usage_limit")) {
mPreferences.cpu_usage_limit = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("daily_xfer_limit_mb")) {
mPreferences.daily_xfer_limit_mb = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("daily_xfer_period_days")) {
mPreferences.daily_xfer_period_days = Integer.parseInt(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("start_hour")) {
mPreferences.cpu_times.start_hour = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("end_hour")) {
mPreferences.cpu_times.end_hour = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("net_start_hour")) {
mPreferences.net_times.start_hour = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("net_end_hour")) {
mPreferences.net_times.end_hour = Double.parseDouble(mCurrentElement.toString());
} else if (localName.equalsIgnoreCase("override_file_present")) {
mPreferences.override_file_present = Integer.parseInt(mCurrentElement.toString()) != 0;
} else if (localName.equalsIgnoreCase("network_wifi_only")) {
mPreferences.network_wifi_only = Integer.parseInt(mCurrentElement.toString()) != 0;
}
}
}
} catch (NumberFormatException e) {
if (Logging.INFO) Log.i(TAG, "Exception when decoding " + localName);
}
mElementStarted = false;
}
}
| gpl-3.0 |
MoofMonkey/Java-WAV-Tools | com/moofMonkey/utils/NativeTranslate.java | 873 | package com.moofMonkey.utils;
public class NativeTranslate {
public static byte[] int2bytes(int i) {
String str = Integer.toHexString(i);
while(str.length() < 8)
str = "0" + str;
return BigEndianHEXUtils.fromHex (
reverse (
str
)
);
}
public static byte[] short2bytes(short s) {
String str = Integer.toHexString((int) s);
while(str.length() < 4)
str = "0" + str;
return BigEndianHEXUtils.fromHex (
reverse (
str
)
);
}
public static int bytes2int(byte[] b) {
return Integer.parseInt (
BigEndianHEXUtils.toHex (
b
),
16
);
}
public static short bytes2short(byte[] b) {
return Short.parseShort (
BigEndianHEXUtils.toHex(b),
16
);
}
public static String reverse(String str) {
return new StringBuilder (
str
).reverse().toString();
}
}
| gpl-3.0 |
betancurdamian/GuraSoftJPA | src/model/Usuario.java | 2299 | /*
* 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 model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
*
* @author Ariel
*/
@Entity
@Table(name = "USUARIO")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "nombre")
private String nombre;
@Column(name = "clave")
private String clave;
@ManyToOne
@JoinColumn(name = "id_tipoUsuario")
private TipoUsuario tipoUsuario;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Usuario)) {
return false;
}
Usuario other = (Usuario) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "model.Usuario[ id=" + id + " ]";
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public TipoUsuario getTipoUsuario() {
return tipoUsuario;
}
public void setTipoUsuario(TipoUsuario tipoUsuario) {
this.tipoUsuario = tipoUsuario;
}
}
| gpl-3.0 |
sirekanyan/instaclimb | app/src/main/java/me/vadik/instaclimb/login/UserSession.java | 610 | package me.vadik.instaclimb.login;
/**
* User: vadik
* Date: 6/16/16
*/
public class UserSession {
private final String sessionId;
private final int userId;
private final UserCredentials credentials;
UserSession(String sessionId, int userId, UserCredentials credentials) {
this.sessionId = sessionId;
this.userId = userId;
this.credentials = credentials;
}
String getSessionId() {
return sessionId;
}
public int getUserId() {
return userId;
}
public UserCredentials getCredentials() {
return credentials;
}
}
| gpl-3.0 |
donatellosantoro/Llunatic | lunaticEngine/src/it/unibas/lunatic/exceptions/DAOException.java | 284 | package it.unibas.lunatic.exceptions;
public class DAOException extends RuntimeException {
public DAOException() {
super();
}
public DAOException(String s) {
super(s);
}
public DAOException(Exception e) {
super(e);
}
}
| gpl-3.0 |
cgd/pub-array | modules/pub-array-builder/src/java/org/jax/pubarray/builder/SelectAnnotationsPanel.java | 19950 | /*
* Copyright (c) 2010 The Jackson Laboratory
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jax.pubarray.builder;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.jax.util.gui.SwingUtilities;
import org.jax.util.gui.ValidatablePanel;
import org.jax.util.gui.WizardController;
import org.jax.util.gui.WizardDialog;
import org.jax.util.gui.WizardDialog.WizardDialogType;
import org.jax.util.io.FlatFileFormat;
/**
* Panel that allows users to add/remove/edit annotation info
* @author <A HREF="mailto:keith.sheppard@jax.org">Keith Sheppard</A>
*/
public class SelectAnnotationsPanel extends ValidatablePanel
{
/**
* every {@link java.io.Serializable} is supposed to have one of these
*/
private static final long serialVersionUID = 7122995572999350709L;
/**
* our logger
*/
private static final Logger LOG = Logger.getLogger(
SelectAnnotationsPanel.class.getName());
private final SharedDirectoryContainer startingDirectory;
private DefaultTableModel annotationsMetaTableModel;
/**
* Constructor
* @param startingDirectory the starting directory to use for browsing files
*/
public SelectAnnotationsPanel(SharedDirectoryContainer startingDirectory)
{
this.startingDirectory = startingDirectory;
this.initComponents();
this.postGuiInit();
}
/**
* take care of any initialization that isn't handled by the gui builder
*/
private void postGuiInit()
{
// make the buttons look pretty
this.addTableButton.setIcon(getIcon("/images/action/add-16x16.png"));
this.editSelectedButton.setIcon(getIcon("/images/action/edit-16x16.png"));
this.removeSelectedButton.setIcon(getIcon("/images/action/remove-16x16.png"));
this.addTableButton.addActionListener(new ActionListener()
{
/**
* {@inheritDoc}
*/
public void actionPerformed(ActionEvent e)
{
SelectAnnotationsPanel.this.addTable();
}
});
this.editSelectedButton.addActionListener(new ActionListener()
{
/**
* {@inheritDoc}
*/
public void actionPerformed(ActionEvent e)
{
SelectAnnotationsPanel.this.editSelectedTable();
}
});
this.removeSelectedButton.addActionListener(new ActionListener()
{
/**
* {@inheritDoc}
*/
public void actionPerformed(ActionEvent e)
{
SelectAnnotationsPanel.this.removeSelectedTables();
}
});
this.annotationsMetaTableModel = new DefaultTableModel(
new String[] {"File Name", "Table Name", "Format"},
0)
{
/**
* every serializable is supposed to have one of these
* fantastic serial UID thingies
*/
private static final long serialVersionUID = -6471892914094216189L;
/**
* {@inheritDoc}
*/
@Override
public boolean isCellEditable(int row, int column)
{
return false;
}
};
this.annotationsMetaTable.setModel(this.annotationsMetaTableModel);
this.annotationsMetaTable.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
this.annotationsMetaTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener()
{
/**
* {@inheritDoc}
*/
public void valueChanged(ListSelectionEvent e)
{
if(!e.getValueIsAdjusting())
{
SelectAnnotationsPanel.this.annotationsMetaTableSelectionChanged();
}
}
});
this.annotationsMetaTableSelectionChanged();
}
private void annotationsMetaTableSelectionChanged()
{
int selectionCount = this.annotationsMetaTable.getSelectedRowCount();
this.editSelectedButton.setEnabled(selectionCount == 1);
this.removeSelectedButton.setEnabled(selectionCount >= 1);
}
private void removeSelectedTables()
{
int[] selectedRows = this.annotationsMetaTable.getSelectedRows();
// this function depends on the order of the rows. this sort may not
// be needed but the javadoc doesn't claim any ordering property so lets
// just do it to be on the safe side
Arrays.sort(selectedRows);
for(int i = selectedRows.length - 1; i >= 0; i--)
{
this.annotationsMetaTableModel.removeRow(selectedRows[i]);
}
}
private void editSelectedTable()
{
if(this.annotationsMetaTable.getSelectedRowCount() == 1)
{
FlatFileDescriptionCell selectedCell =
(FlatFileDescriptionCell)this.annotationsMetaTable.getValueAt(
this.annotationsMetaTable.getSelectedRow(),
0);
this.showAddEditAnnotationDialog(
"Edit Annotation Table",
new AddEditAnnotationController(
selectedCell.getFlatFileDescription()));
}
else
{
throw new IllegalStateException(
"trying to edit an annotation table with " +
this.annotationsMetaTable.getSelectedRowCount() +
" rows selected");
}
}
private void addTable()
{
this.showAddEditAnnotationDialog(
"Add Annotation Table",
new AddEditAnnotationController());
}
private void showAddEditAnnotationDialog(
String title,
AddEditAnnotationController controller)
{
final WizardDialog wizardDialog;
Window parentWindow = SwingUtilities.getContainingWindow(this);
if(parentWindow instanceof JDialog)
{
wizardDialog = new WizardDialog(
controller,
controller.getFlatFilePanel(),
(JDialog)parentWindow,
title,
true,
WizardDialogType.OK_CANCEL_DIALOG);
}
else if(parentWindow instanceof JFrame)
{
wizardDialog = new WizardDialog(
controller,
controller.getFlatFilePanel(),
(JFrame)parentWindow,
title,
true,
WizardDialogType.OK_CANCEL_DIALOG);
}
else
{
throw new IllegalStateException(
"this panel must be attached to a JPanel or JDialog in " +
"order to show the add/edit annotation table dialog");
}
wizardDialog.setVisible(true);
}
private static ImageIcon getIcon(String classpath)
{
return new ImageIcon(SelectAnnotationsPanel.class.getResource(classpath));
}
private class AddEditAnnotationController implements WizardController
{
private final SelectAndPreviewFlatFilePanel flatFilePanel;
private final boolean isAddPanel;
/**
* Constructor for adding a new annotation flat file
*/
public AddEditAnnotationController()
{
this.flatFilePanel = new SelectAndPreviewFlatFilePanel(
SelectAnnotationsPanel.this.startingDirectory,
false);
this.isAddPanel = true;
}
/**
* Constructor for editing an existing flat file description
* @param descriptionToEdit it's all in the name isn't it :-)
*/
public AddEditAnnotationController(FlatFileDescription descriptionToEdit)
{
this.flatFilePanel = new SelectAndPreviewFlatFilePanel(
descriptionToEdit,
SelectAnnotationsPanel.this.startingDirectory,
false);
this.isAddPanel = false;
}
/**
* Getter for the flat file panel
* @return the flat file panel
*/
public SelectAndPreviewFlatFilePanel getFlatFilePanel()
{
return this.flatFilePanel;
}
/**
* {@inheritDoc}
*/
public boolean cancel()
{
return true;
}
/**
* {@inheritDoc}
*/
public boolean finish() throws IllegalStateException
{
if(this.flatFilePanel.validateData())
{
FlatFileDescription description =
this.flatFilePanel.getFlatFileDescription();
// if this is an add then add it. if it's an edit then update
// the current selection
if(this.isAddPanel)
{
SelectAnnotationsPanel.this.addFlatFileDescription(description);
}
else
{
SelectAnnotationsPanel.this.updateSelectedFlatFileDescription(description);
}
return true;
}
else
{
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean goNext() throws IllegalStateException
{
// this should never be called for this controller
return false;
}
/**
* {@inheritDoc}
*/
public boolean goPrevious() throws IllegalStateException
{
// this should never be called for this controller
return false;
}
/**
* {@inheritDoc}
*/
public void help()
{
// TODO Auto-generated method stub
}
/**
* {@inheritDoc}
*/
public boolean isFinishValid()
{
return true;
}
/**
* {@inheritDoc}
*/
public boolean isNextValid()
{
return false;
}
/**
* {@inheritDoc}
*/
public boolean isPreviousValid()
{
return false;
}
}
/**
* Create a table row for the given flat file description
* @param description
* the description to create a row for
* @return
* the row
*/
private FlatFileDescriptionCell[] descriptionToTableRow(FlatFileDescription description)
{
return new FlatFileDescriptionCell[] {
new FlatFileDescriptionCell(description, 0),
new FlatFileDescriptionCell(description, 1),
new FlatFileDescriptionCell(description, 2)};
}
private void addFlatFileDescription(FlatFileDescription description)
{
this.annotationsMetaTableModel.addRow(this.descriptionToTableRow(description));
}
private void updateSelectedFlatFileDescription(FlatFileDescription description)
{
if(this.annotationsMetaTable.getSelectedRowCount() == 1)
{
int selectedRowIndex = this.annotationsMetaTable.getSelectedRow();
FlatFileDescriptionCell[] updatedRow = this.descriptionToTableRow(description);
for(int colIndex = 0; colIndex < updatedRow.length; colIndex++)
{
this.annotationsMetaTableModel.setValueAt(
updatedRow[colIndex],
selectedRowIndex,
colIndex);
}
}
else
{
LOG.severe(
"Cannot update flat file description because the selected " +
"row count is: " + this.annotationsMetaTable.getSelectedRowCount());
}
}
private static final class FlatFileDescriptionCell
{
private final FlatFileDescription flatFileDescription;
private final int columnIndex;
/**
* Constructor
* @param flatFileDescription
* the description
* @param columnIndex
* the column index in the table
*/
public FlatFileDescriptionCell(
FlatFileDescription flatFileDescription,
int columnIndex)
{
if(columnIndex < 0 || columnIndex > 2)
{
throw new IndexOutOfBoundsException(
"Column index should be in the range [0, 2], not: " +
columnIndex);
}
this.flatFileDescription = flatFileDescription;
this.columnIndex = columnIndex;
}
/**
* Getter for the flat file description
* @return the description that this class encapsulates
*/
public FlatFileDescription getFlatFileDescription()
{
return this.flatFileDescription;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
// convert to a string based on the following column headers:
// "File Name", "Table Name", "Format"
switch(this.columnIndex)
{
case 0:
{
File file = this.flatFileDescription.getFlatFile();
if(file == null)
{
return "";
}
else
{
return file.getName();
}
}
case 1:
{
String tableName = this.flatFileDescription.getTableName();
if(tableName == null)
{
return "";
}
else
{
return tableName;
}
}
case 2:
{
FlatFileFormat format = this.flatFileDescription.getFormat();
if(format == null)
{
return "";
}
else
{
return format.toString();
}
}
default:
{
throw new IllegalStateException(
"Internal error: unexpected column index value: " +
this.columnIndex);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean validateData()
{
// the data is always valid in this panel
return true;
}
/**
* Get a list of all the flat file descriptions for annotation data
* @return
* the list
*/
public List<FlatFileDescription> getFlatFileDescriptions()
{
int descCount = this.annotationsMetaTableModel.getRowCount();
List<FlatFileDescription> descriptions =
new ArrayList<FlatFileDescription>(descCount);
for(int i = 0; i < descCount; i++)
{
FlatFileDescriptionCell selectedCell =
(FlatFileDescriptionCell)this.annotationsMetaTable.getValueAt(i, 0);
descriptions.add(selectedCell.getFlatFileDescription());
}
return descriptions;
}
/**
* 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("all")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
addTableButton = new javax.swing.JButton();
editSelectedButton = new javax.swing.JButton();
removeSelectedButton = new javax.swing.JButton();
javax.swing.JScrollPane scrollPane = new javax.swing.JScrollPane();
annotationsMetaTable = new javax.swing.JTable();
addTableButton.setText("Add Table...");
editSelectedButton.setText("Edit Selected...");
removeSelectedButton.setText("Remove Selected");
scrollPane.setViewportView(annotationsMetaTable);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(scrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.add(addTableButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(editSelectedButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(removeSelectedButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(addTableButton)
.add(editSelectedButton)
.add(removeSelectedButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(scrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addTableButton;
private javax.swing.JTable annotationsMetaTable;
private javax.swing.JButton editSelectedButton;
private javax.swing.JButton removeSelectedButton;
// End of variables declaration//GEN-END:variables
}
| gpl-3.0 |
MCTyler/CrafterNexus | src/main/java/org/eodsteven/CrafterNexus/listeners/EnderChestListener.java | 4338 | /*******************************************************************************
* Copyright 2014 stuntguy3000 (Luke Anderson) and coasterman10.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
******************************************************************************/
package org.eodsteven.CrafterNexus.listeners;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.eodsteven.CrafterNexus.object.GameTeam;
import org.eodsteven.CrafterNexus.object.PlayerMeta;
public class EnderChestListener implements Listener {
private final HashMap<GameTeam, Location> chests = new HashMap<>();
private final HashMap<String, Inventory> inventories = new HashMap<>();
@EventHandler
public void onChestOpen(PlayerInteractEvent e) {
if (e.getAction() != Action.RIGHT_CLICK_BLOCK)
return;
if (e.getClickedBlock().getType() != Material.ENDER_CHEST)
return;
Block clicked = e.getClickedBlock();
Player player = e.getPlayer();
GameTeam team = PlayerMeta.getMeta(player).getTeam();
if (team == GameTeam.NONE || !chests.containsKey(team))
return;
e.setCancelled(false);
if (chests.get(team).equals(clicked.getLocation())) {
openEnderChest(player);
} else {
GameTeam owner = getTeamWithChest(clicked.getLocation());
if (owner != GameTeam.NONE) {
openEnemyEnderChest(player, owner);
}
}
}
public void setEnderChestLocation(GameTeam team, Location loc) {
chests.put(team, loc);
}
private void openEnderChest(Player player) {
String name = player.getName();
if (!inventories.containsKey(name)) {
Inventory inv = Bukkit.createInventory(null, 9);
inventories.put(name, inv);
}
player.openInventory(inventories.get(name));
}
@EventHandler
public void onFurnaceBreak(BlockBreakEvent e) {
if (chests.values().contains(e.getBlock().getLocation()))
e.setCancelled(true);
}
private void openEnemyEnderChest(Player player, GameTeam owner) {
LinkedList<Inventory> shuffledInventories = new LinkedList<>();
for (Entry<String, Inventory> entry : inventories.entrySet())
if (PlayerMeta.getMeta(entry.getKey()).getTeam() == owner)
shuffledInventories.add(entry.getValue());
Collections.shuffle(shuffledInventories);
int inventories = Math.min(9, shuffledInventories.size());
if (inventories == 0)
return;
Inventory view = Bukkit.createInventory(null, inventories * 9);
for (Inventory inv : shuffledInventories.subList(0, inventories)) {
for (ItemStack stack : inv.getContents())
if (stack != null)
view.addItem(stack);
}
player.openInventory(view);
}
private GameTeam getTeamWithChest(Location loc) {
for (Entry<GameTeam, Location> entry : chests.entrySet())
if (entry.getValue().equals(loc))
return entry.getKey();
return GameTeam.NONE;
}
}
| gpl-3.0 |
qbicsoftware/qnavigator | QBiCMainPortlet/src/upload/MoveUploadsReadyRunnable.java | 563 | package upload;
import java.io.IOException;
import com.github.sardine.Sardine;
public class MoveUploadsReadyRunnable implements Runnable {
private UploadsPanel view;
private Sardine sardine;
public MoveUploadsReadyRunnable(UploadsPanel view) {
this.view = view;
}
@Override
public void run() {
try {
sardine.shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
view.commitDone();
}
public void setSardine(Sardine sardine) {
this.sardine = sardine;
}
}
| gpl-3.0 |
Boukefalos/jlibxinput | src/main/java/de/hardcode/jxinput/test/DirectionalListener.java | 1398 | //**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 20. Februar 2002, 22:19
//**********************************************************************************************
package de.hardcode.jxinput.test;
import de.hardcode.jxinput.event.JXInputEventManager;
import de.hardcode.jxinput.event.JXInputDirectionalEventListener;
import de.hardcode.jxinput.event.JXInputDirectionalEvent;
import de.hardcode.jxinput.Directional;
/**
* Sample directional listener.
*
* @author Herkules
*/
public class DirectionalListener implements JXInputDirectionalEventListener
{
/**
* Creates a new instance of AxisListener.
*/
public DirectionalListener( Directional directional )
{
JXInputEventManager.addListener( this, directional, 1.0 );
}
public void changed( JXInputDirectionalEvent ev )
{
System.out.println( "Directional " + ev.getDirectional().getName() + " changed : direction=" + ev.getDirectional().getDirection() + ", value=" + ev.getDirectional().getValue() + ", event causing delta=" + ev.getDirectionDelta() );
}
}
| gpl-3.0 |
NocBross/dec-net | Desktop-Client/RegisterAgent/src/main/java/RegisterAgent.java | 950 | package main.java;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import main.java.agent.CustomAgent;
import main.java.agent.CustomBottomAgent;
import main.java.agent.RootController;
import main.java.constants.AgentID;
import main.java.constants.ClientLogs;
public class RegisterAgent extends CustomBottomAgent {
public RegisterAgent(CustomAgent parent) throws Exception {
super(parent, AgentID.REGISTER_AGENT, ClientLogs.REGISTER_AGENT, "RegisterAgent");
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/ui/RegisterScene.fxml"));
rootSceneNode = loader.load();
agentSceneController = (RootController) loader.getController();
agentSceneController.setAgent(this);
agentSceneController.setLogger(logger);
} catch(IOException ioe) {
logger.writeLog(logID + " error while loading RegisterAgent", ioe);
}
}
}
| gpl-3.0 |
mndfcked/StudIPAndroidApp | StudIPAndroidApp/src/main/java/de/elanev/studip/android/app/backend/net/services/CustomJsonConverterApiService.java | 2509 | /*
* Copyright (c) 2015 ELAN e.V.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package de.elanev.studip.android.app.backend.net.services;
import android.content.Context;
import org.apache.http.HttpStatus;
import de.elanev.studip.android.app.backend.datamodel.Routes;
import de.elanev.studip.android.app.backend.datamodel.Server;
import retrofit.ErrorHandler;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.converter.Converter;
import retrofit.http.GET;
import rx.Observable;
import se.akerfeldt.signpost.retrofit.RetrofitHttpOAuthConsumer;
import se.akerfeldt.signpost.retrofit.SigningOkClient;
/**
* A Retrofit ApiService which can use custom JSON converters to be able to parse somewhat
* strange API Response JSON-Formats.
*
* @author joern
*/
public class CustomJsonConverterApiService {
private SpecialRestServiceForWrongJson mService;
public CustomJsonConverterApiService(Context context, Server server, Converter converter) {
if (context == null) {
throw new IllegalStateException("Converter must not be null!");
}
RetrofitHttpOAuthConsumer oAuthConsumer = new RetrofitHttpOAuthConsumer(server.getConsumerKey(),
server.getConsumerSecret());
oAuthConsumer.setTokenWithSecret(server.getAccessToken(), server.getAccessTokenSecret());
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(server.getApiUrl())
.setLogLevel(RestAdapter.LogLevel.FULL)
.setConverter(converter)
.setClient(new SigningOkClient(oAuthConsumer))
.setErrorHandler(new ErrorHandler() {
@Override public Throwable handleError(RetrofitError cause) {
Response response = cause.getResponse();
if (response.getUrl().contains("user")
&& cause.getResponse().getStatus() == HttpStatus.SC_NOT_FOUND) {
return new StudIpLegacyApiService.UserNotFoundException(cause);
}
return cause;
}
})
.build();
mService = restAdapter.create(SpecialRestServiceForWrongJson.class);
}
public Observable<Routes> discoverApi() {
return mService.discoverApi();
}
public interface SpecialRestServiceForWrongJson {
@GET("/discovery") Observable<Routes> discoverApi();
}
}
| gpl-3.0 |
zeminlu/comitaco | unittest/ar/edu/taco/AssertExampleTest.java | 501 | package ar.edu.taco;
import ar.edu.taco.regresion.GenericTestBase;
import ar.uba.dc.rfm.dynalloy.visualization.VizException;
public class AssertExampleTest extends GenericTestBase {
@Override
protected String getClassToCheck() {
return "ar.edu.taco.AssertExample";
}
public void test_assert_method() throws VizException {
setConfigKeyRelevantClasses("ar.edu.taco.AssertExample");
setConfigKeyRelevancyAnalysis(true);
runAndCheck(GENERIC_PROPERTIES,"assertion_method_0", true);
}
}
| gpl-3.0 |
Suatae/MechinasMagick | src/main/java/com/suatae/mechinasmagick/client/renders/core/TESRCoreTart.java | 1218 | package com.suatae.mechinasmagick.client.renders.core;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import com.suatae.mechinasmagick.client.models.MachineCore;
import com.suatae.mechinasmagick.common.core.lib.REF;
public class TESRCoreTart extends TileEntitySpecialRenderer {
private static final ResourceLocation texture = new ResourceLocation(
REF.MOD_ID.toLowerCase(),
"textures/models/core/Machine Core-Tartarite.png");
private MachineCore model;
public TESRCoreTart() {
this.model = new MachineCore();
}
@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {
GL11.glPushMatrix();
GL11.glTranslatef((float) x + 0.5F, (float) y + 0.626F, (float) z + 0.5F);
this.bindTexture(texture);
// GL11.glRotatef(-180F, 0F, 0F, 1F);
GL11.glScalef(0.25F, 0.25F, 0.25F);
this.model.render((Entity) null, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F);
GL11.glPopMatrix();
}
protected int shouldrenderPass() {
return 0;
}
}
| gpl-3.0 |
AndreasMaring/text2epc | dom4j-1.6.1/src/test/org/dom4j/XMLWriterTest.java | 20828 | /*
* Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
*
* This software is open source.
* See the bottom of this file for the licence.
*/
package org.dom4j;
import junit.textui.TestRunner;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.BaseElement;
import org.dom4j.tree.DefaultDocument;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* A simple test harness to check that the XML Writer works
*
* @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a>
* @version $Revision: 1.7.2.1 $
*/
public class XMLWriterTest extends AbstractTestCase {
protected static final boolean VERBOSE = false;
public static void main(String[] args) {
TestRunner.run(XMLWriterTest.class);
}
// Test case(s)
// -------------------------------------------------------------------------
public void testBug1180791() throws Exception {
String xml = "<?xml version=\"1.0\"?><root><foo>bar</foo></root>";
SAXReader reader = new SAXReader();
Document doc = reader.read(new StringReader(xml));
// of with newlines
OutputFormat format = new OutputFormat();
format.setNewlines(true);
//format.setTrimText(true);
// first time
StringWriter writer = new StringWriter();
XMLWriter xmlwriter = new XMLWriter(writer, format);
xmlwriter.write(doc);
System.out.println(writer.toString());
// 2nd time
doc = reader.read(new StringReader(writer.toString()));
writer = new StringWriter();
xmlwriter = new XMLWriter(writer, format);
xmlwriter.write(doc);
System.out.println(writer.toString());
}
public void testBug1119733() throws Exception {
Document doc = DocumentHelper
.parseText("<root><code>foo</code> bar</root>");
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
writer.write(doc);
writer.close();
String xml = out.toString();
System.out.println(xml);
assertEquals("whitespace problem", -1, xml.indexOf("</code>bar"));
}
public void testBug1119733WithSAXEvents() throws Exception {
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
writer.startDocument();
writer.startElement(null, "root", "root", new AttributesImpl());
writer.startElement(null, "code", "code", new AttributesImpl());
writer.characters(new char[] { 'f', 'o', 'o' }, 0, 3);
writer.endElement(null, "code", "code");
writer.characters(new char[] { ' ', 'b', 'a', 'r' }, 0, 4);
writer.endElement(null, "root", "root");
writer.endDocument();
writer.close();
String xml = out.toString();
System.out.println(xml);
assertEquals("whitespace problem", -1, xml.indexOf("</code>bar"));
}
public void testWriter() throws Exception {
Object object = document;
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out);
writer.write(object);
writer.close();
String text = out.toString();
if (VERBOSE) {
log("Text output is [");
log(text);
log("]. Done");
}
assertTrue("Output text is bigger than 10 characters",
text.length() > 10);
}
public void testEncodingFormats() throws Exception {
testEncoding("UTF-8");
testEncoding("UTF-16");
testEncoding("ISO-8859-1");
}
public void testWritingEmptyElement() throws Exception {
Document doc = DocumentFactory.getInstance().createDocument();
Element grandFather = doc.addElement("grandfather");
Element parent1 = grandFather.addElement("parent");
Element child1 = parent1.addElement("child1");
Element child2 = parent1.addElement("child2");
child2.setText("test");
Element parent2 = grandFather.addElement("parent");
Element child3 = parent2.addElement("child3");
child3.setText("test");
StringWriter buffer = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(buffer, format);
writer.write(doc);
String xml = buffer.toString();
System.out.println(xml);
assertTrue("child2 not present",
xml.indexOf("<child2>test</child2>") != -1);
}
protected void testEncoding(String encoding) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(encoding);
XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
writer.close();
log("Wrote to encoding: " + encoding);
}
public void testWriterBug() throws Exception {
Element project = new BaseElement("project");
Document doc = new DefaultDocument(project);
ByteArrayOutputStream out = new ByteArrayOutputStream();
XMLWriter writer = new XMLWriter(out, new OutputFormat("\t", true,
"ISO-8859-1"));
writer.write(doc);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
SAXReader reader = new SAXReader();
Document doc2 = reader.read(in);
assertTrue("Generated document has a root element", doc2
.getRootElement() != null);
assertEquals("Generated document has corrent named root element", doc2
.getRootElement().getName(), "project");
}
public void testNamespaceBug() throws Exception {
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root", "ns1");
Element child1 = root.addElement("joe", "ns2");
child1.addElement("zot", "ns1");
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
writer.write(doc);
String text = out.toString();
// System.out.println( "Generated:" + text );
Document doc2 = DocumentHelper.parseText(text);
root = doc2.getRootElement();
assertEquals("root has incorrect namespace", "ns1", root
.getNamespaceURI());
Element joe = (Element) root.elementIterator().next();
assertEquals("joe has correct namespace", "ns2", joe.getNamespaceURI());
Element zot = (Element) joe.elementIterator().next();
assertEquals("zot has correct namespace", "ns1", zot.getNamespaceURI());
}
/**
* This test harness was supplied by Lari Hotari
*
* @throws Exception DOCUMENT ME!
*/
public void testContentHandler() throws Exception {
StringWriter out = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("iso-8859-1");
XMLWriter writer = new XMLWriter(out, format);
generateXML(writer);
writer.close();
String text = out.toString();
if (VERBOSE) {
log("Created XML");
log(text);
}
// now lets parse the output and test it with XPath
Document doc = DocumentHelper.parseText(text);
String value = doc.valueOf("/processes[@name='arvojoo']");
assertEquals("Document contains the correct text", "jeejee", value);
}
/**
* This test was provided by Manfred Lotz
*
* @throws Exception DOCUMENT ME!
*/
public void testWhitespaceBug() throws Exception {
String notes = "<notes> This is a multiline\n\rentry</notes>";
Document doc = DocumentHelper.parseText(notes);
OutputFormat format = new OutputFormat();
format.setEncoding("UTF-8");
format.setIndentSize(4);
format.setNewlines(true);
format.setTrimText(true);
format.setExpandEmptyElements(true);
StringWriter buffer = new StringWriter();
XMLWriter writer = new XMLWriter(buffer, format);
writer.write(doc);
String xml = buffer.toString();
log(xml);
Document doc2 = DocumentHelper.parseText(xml);
String text = doc2.valueOf("/notes");
String expected = "This is a multiline entry";
assertEquals("valueOf() returns the correct text padding", expected,
text);
assertEquals("getText() returns the correct text padding", expected,
doc2.getRootElement().getText());
}
/**
* This test was provided by Manfred Lotz
*
* @throws Exception DOCUMENT ME!
*/
public void testWhitespaceBug2() throws Exception {
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
Element meaning = root.addElement("meaning");
meaning.addText("to li");
meaning.addText("ve");
OutputFormat format = new OutputFormat();
format.setEncoding("UTF-8");
format.setIndentSize(4);
format.setNewlines(true);
format.setTrimText(true);
format.setExpandEmptyElements(true);
StringWriter buffer = new StringWriter();
XMLWriter writer = new XMLWriter(buffer, format);
writer.write(doc);
String xml = buffer.toString();
log(xml);
Document doc2 = DocumentHelper.parseText(xml);
String text = doc2.valueOf("/root/meaning");
String expected = "to live";
assertEquals("valueOf() returns the correct text padding", expected,
text);
assertEquals("getText() returns the correct text padding", expected,
doc2.getRootElement().element("meaning").getText());
}
public void testPadding() throws Exception {
Document doc = DocumentFactory.getInstance().createDocument();
Element root = doc.addElement("root");
root.addText("prefix ");
root.addElement("b");
root.addText(" suffix");
OutputFormat format = new OutputFormat("", false);
format.setOmitEncoding(true);
format.setSuppressDeclaration(true);
format.setExpandEmptyElements(true);
format.setPadText(true);
format.setTrimText(true);
StringWriter buffer = new StringWriter();
XMLWriter writer = new XMLWriter(buffer, format);
writer.write(doc);
String xml = buffer.toString();
System.out.println("xml: " + xml);
String expected = "<root>prefix <b></b> suffix</root>";
assertEquals(expected, xml);
}
public void testPadding2() throws Exception {
Document doc = DocumentFactory.getInstance().createDocument();
Element root = doc.addElement("root");
root.addText("prefix");
root.addElement("b");
root.addText("suffix");
OutputFormat format = new OutputFormat("", false);
format.setOmitEncoding(true);
format.setSuppressDeclaration(true);
format.setExpandEmptyElements(true);
format.setPadText(true);
format.setTrimText(true);
StringWriter buffer = new StringWriter();
XMLWriter writer = new XMLWriter(buffer, format);
writer.write(doc);
String xml = buffer.toString();
System.out.println("xml: " + xml);
String expected = "<root>prefix<b></b>suffix</root>";
assertEquals(expected, xml);
}
/*
* This must be tested manually to see if the layout is correct.
*/
public void testPrettyPrinting() throws Exception {
Document doc = DocumentFactory.getInstance().createDocument();
doc.addElement("summary").addAttribute("date", "6/7/8").addElement(
"orderline").addText("puffins").addElement("ranjit")
.addComment("Ranjit is a happy Puffin");
XMLWriter writer = new XMLWriter(System.out, OutputFormat
.createPrettyPrint());
writer.write(doc);
doc = DocumentFactory.getInstance().createDocument();
doc.addElement("summary").addAttribute("date", "6/7/8").addElement(
"orderline").addText("puffins").addElement("ranjit")
.addComment("Ranjit is a happy Puffin").addComment(
"another comment").addElement("anotherElement");
writer.write(doc);
}
public void testAttributeQuotes() throws Exception {
Document doc = DocumentFactory.getInstance().createDocument();
doc.addElement("root").addAttribute("test", "text with ' in it");
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, OutputFormat
.createCompactFormat());
writer.write(doc);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<root test=\"text with ' in it\"/>";
assertEquals(expected, out.toString());
}
public void testBug868408() throws Exception {
Document doc = getDocument("/xml/web.xml");
Document doc2 = DocumentHelper.parseText(doc.asXML());
assertEquals(doc.asXML(), doc2.asXML());
}
public void testBug923882() throws Exception {
Document doc = DocumentFactory.getInstance().createDocument();
Element root = doc.addElement("root");
root.addText("this is ");
root.addText(" sim");
root.addText("ple text ");
root.addElement("child");
root.addText(" contai");
root.addText("ning spaces and");
root.addText(" multiple textnodes");
OutputFormat format = new OutputFormat();
format.setEncoding("UTF-8");
format.setIndentSize(4);
format.setNewlines(true);
format.setTrimText(true);
format.setExpandEmptyElements(true);
StringWriter buffer = new StringWriter();
XMLWriter writer = new XMLWriter(buffer, format);
writer.write(doc);
String xml = buffer.toString();
log(xml);
int start = xml.indexOf("<root");
int end = xml.indexOf("/root>") + 6;
String eol = "\n"; // System.getProperty("line.separator");
String expected = "<root>this is simple text" + eol
+ " <child></child>containing spaces and multiple textnodes"
+ eol + "</root>";
System.out.println("Expected:");
System.out.println(expected);
System.out.println("Obtained:");
System.out.println(xml.substring(start, end));
assertEquals(expected, xml.substring(start, end));
}
public void testEscapeXML() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
OutputFormat format = new OutputFormat(null, false, "ISO-8859-2");
format.setSuppressDeclaration(true);
XMLWriter writer = new XMLWriter(os, format);
Document document = DocumentFactory.getInstance().createDocument();
Element root = document.addElement("root");
root.setText("bla &#c bla");
writer.write(document);
String result = os.toString();
System.out.println(result);
Document doc2 = DocumentHelper.parseText(result);
doc2.normalize(); // merges adjacant Text nodes
System.out.println(doc2.getRootElement().getText());
assertNodesEqual(document, doc2);
}
public void testWriteEntities() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
+ "<!DOCTYPE xml [<!ENTITY copy \"©\"> "
+ "<!ENTITY trade \"™\"> "
+ "<!ENTITY deg \"°\"> " + "<!ENTITY gt \">\"> "
+ "<!ENTITY sup2 \"²\"> "
+ "<!ENTITY frac14 \"¼\"> "
+ "<!ENTITY quot \""\"> "
+ "<!ENTITY frac12 \"½\"> "
+ "<!ENTITY euro \"€\"> "
+ "<!ENTITY Omega \"Ω\"> ]>\n" + "<root />";
SAXReader reader = new SAXReader("org.apache.xerces.parsers.SAXParser");
reader.setIncludeInternalDTDDeclarations(true);
Document doc = reader.read(new StringReader(xml));
StringWriter wr = new StringWriter();
XMLWriter writer = new XMLWriter(wr);
writer.write(doc);
String xml2 = wr.toString();
System.out.println(xml2);
Document doc2 = DocumentHelper.parseText(xml2);
assertNodesEqual(doc, doc2);
}
public void testEscapeChars() throws Exception {
Document document = DocumentFactory.getInstance().createDocument();
Element root = document.addElement("root");
root.setText("blahblah " + '\u008f');
XMLWriter writer = new XMLWriter();
StringWriter strWriter = new StringWriter();
writer.setWriter(strWriter);
writer.setMaximumAllowedCharacter(127);
writer.write(document);
String xml = strWriter.toString();
}
public void testEscapeText() throws SAXException {
StringWriter writer = new StringWriter();
XMLWriter xmlWriter = new XMLWriter(writer);
xmlWriter.setEscapeText(false);
String txt = "<test></test>";
xmlWriter.startDocument();
xmlWriter.characters(txt.toCharArray(), 0, txt.length());
xmlWriter.endDocument();
String output = writer.toString();
System.out.println(output);
assertTrue(output.indexOf("<test>") != -1);
}
public void testNullCData() {
Element e = DocumentHelper.createElement("test");
e.add(DocumentHelper.createElement("another").addCDATA(null));
Document doc = DocumentHelper.createDocument(e);
assertEquals(-1, e.asXML().indexOf("null"));
assertEquals(-1, doc.asXML().indexOf("null"));
System.out.println(e.asXML());
System.out.println(doc.asXML());
}
protected void generateXML(ContentHandler handler) throws SAXException {
handler.startDocument();
AttributesImpl attrs = new AttributesImpl();
attrs.clear();
attrs.addAttribute("", "", "name", "CDATA", "arvojoo");
handler.startElement("", "", "processes", attrs);
String text = "jeejee";
char[] textch = text.toCharArray();
handler.characters(textch, 0, textch.length);
handler.endElement("", "", "processes");
handler.endDocument();
}
}
/*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain copyright statements and
* notices. Redistributions must also contain a copy of this document.
*
* 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.
*
* 3. The name "DOM4J" must not be used to endorse or promote products derived
* from this Software without prior written permission of MetaStuff, Ltd. For
* written permission, please contact dom4j-info@metastuff.com.
*
* 4. Products derived from this Software may not be called "DOM4J" nor may
* "DOM4J" appear in their names without prior written permission of MetaStuff,
* Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
*
* 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
*
* THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
*/
| gpl-3.0 |
otavanopisto/pyramus | pyramus/src/main/java/fi/otavanopisto/pyramus/views/system/setupwizard/StudentActivityTypeSetupWizardViewController.java | 2054 | package fi.otavanopisto.pyramus.views.system.setupwizard;
import java.util.List;
import fi.internetix.smvc.controllers.PageRequestContext;
import fi.otavanopisto.pyramus.dao.DAOFactory;
import fi.otavanopisto.pyramus.dao.students.StudentActivityTypeDAO;
import fi.otavanopisto.pyramus.domainmodel.students.StudentActivityType;
import fi.otavanopisto.pyramus.util.JSONArrayExtractor;
public class StudentActivityTypeSetupWizardViewController extends SetupWizardController {
public StudentActivityTypeSetupWizardViewController() {
super("studentactivitytypes");
}
@Override
public void setup(PageRequestContext requestContext) throws SetupWizardException{
StudentActivityTypeDAO studentActivityTypeDAO = DAOFactory.getInstance().getStudentActivityTypeDAO();
List<StudentActivityType> studentActivityTypes = studentActivityTypeDAO.listUnarchived();
setJsDataVariable(requestContext, "studentActivityTypes", new JSONArrayExtractor("name", "id").extractString(studentActivityTypes));
}
@Override
public void save(PageRequestContext requestContext) throws SetupWizardException {
StudentActivityTypeDAO studentActivityTypeDAO = DAOFactory.getInstance().getStudentActivityTypeDAO();
int rowCount = requestContext.getInteger("studentActivityTypesTable.rowCount");
for (int i = 0; i < rowCount; i++) {
String colPrefix = "studentActivityTypesTable." + i;
String name = requestContext.getString(colPrefix + ".name");
Long id = requestContext.getLong(colPrefix + ".id");
if (id == -1l) {
studentActivityTypeDAO.create(name);
}
}
if (studentActivityTypeDAO.listUnarchived().isEmpty()) {
throw new SetupWizardException("No Student Activity Types defined");
}
}
@Override
public boolean isInitialized(PageRequestContext requestContext) throws SetupWizardException {
StudentActivityTypeDAO studentActivityTypeDAO = DAOFactory.getInstance().getStudentActivityTypeDAO();
return !studentActivityTypeDAO.listUnarchived().isEmpty();
}
}
| gpl-3.0 |
ieugen/Teachingbox | src/org/hswgt/teachingbox/core/rl/network/adaption/AdaptionRule.java | 1349 | /**
*
* $Id: AdaptionRule.java 669 2010-06-14 14:53:38Z twanschik $
*
* @version $Rev: 669 $
* @author $Author: twanschik $
* @date $Date: 2010-06-14 16:53:38 +0200 (Mo, 14 Jun 2010) $
*
*/
package org.hswgt.teachingbox.core.rl.network.adaption;
import java.io.Serializable;
import org.hswgt.teachingbox.core.rl.network.*;
import cern.colt.matrix.DoubleMatrix1D;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
/**
* This is the abstract base class for an adaptive method to use in a network.
* Implement changeNet to specify when to add/delete/reshape network nodes.
* changeNet is called just before getFeatures so that the rule can
* change the network just in time.
*/
public abstract class AdaptionRule implements Serializable {
private static final long serialVersionUID = 708134800756309715L;
protected Network net;
public AdaptionRule() {
}
public AdaptionRule(Network net) {
this.net = net;
}
// implement changeNet to define when RBFs have to be added/deleted/reshaped
public abstract void changeNet(DoubleMatrix1D feat);
public void changeNet(double[] feat) {
changeNet(new DenseDoubleMatrix1D(feat));
}
// setter and getter
public Network getNet() {
return net;
}
public void setNet(Network net) {
this.net = net;
}
}
| gpl-3.0 |
shengqh/RcpaBioJava | src/cn/ac/rcpa/bio/proteomics/filter/IdentifiedProteinGroupUniquePeptideCountFilter.java | 1759 | package cn.ac.rcpa.bio.proteomics.filter;
import java.util.HashSet;
import java.util.List;
import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptide;
import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptideHit;
import cn.ac.rcpa.bio.proteomics.IIdentifiedProteinGroup;
import cn.ac.rcpa.bio.proteomics.utils.PeptideUtils;
import cn.ac.rcpa.filter.IFilter;
/**
* <p>Title: RCPA Package</p>
* <p>Description:
* Åж¨GroupÖÐÂú×ã¸ø¶¨filterµÄIdentifiedPeptideµÄUniquePeptide¸öÊýÊÇ·ñ´óÓÚ¸ø¶¨ÓòÖµminUniquePeptideCount</p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: RCPA.SIBS.AC.CN</p>
*
* @author Sheng Quanhu
* @version 1.0
*/
public class IdentifiedProteinGroupUniquePeptideCountFilter
implements IFilter<IIdentifiedProteinGroup> {
private int minUniquePeptideCount;
private IFilter<IIdentifiedPeptide> filter;
public IdentifiedProteinGroupUniquePeptideCountFilter(int count,
IFilter<IIdentifiedPeptide> filter) {
this.minUniquePeptideCount = count;
this.filter = filter;
}
@SuppressWarnings("unchecked")
public boolean accept(IIdentifiedProteinGroup group) {
List<? extends IIdentifiedPeptideHit> peptides = group.getPeptideHits();
HashSet<String> uniquePeptides = new HashSet<String> ();
for (IIdentifiedPeptideHit pephit : peptides) {
final IIdentifiedPeptide peptide = pephit.getPeptide(0);
if (filter == null || filter.accept(peptide)) {
uniquePeptides.add(PeptideUtils.getPurePeptideSequence(peptide.
getSequence()));
if (uniquePeptides.size() >= minUniquePeptideCount) {
return true;
}
}
}
return false;
}
public String getType() {
return "UniquePeptideCount";
}
}
| gpl-3.0 |
amaltson/maven-release-tool | src/main/java/org/mrt/shared/MavenModule.java | 875 | package org.mrt.shared;
import java.util.List;
/**
* Represents the physical Maven module with a {@link MavenTarget}, a list of
* {@link MavenTarget} dependencies and additional meta-data.
*
* @author Arthur Kalmenson
*/
public class MavenModule {
private MavenTarget mavenTarget;
private SourceCodeManagement scm;
private List<MavenTarget> dependencies;
public MavenTarget getMavenTarget() {
return mavenTarget;
}
public void setMavenTarget(MavenTarget mavenTarget) {
this.mavenTarget = mavenTarget;
}
public SourceCodeManagement getScm() {
return scm;
}
public void setScm(SourceCodeManagement scm) {
this.scm = scm;
}
public List<MavenTarget> getDependencies() {
return dependencies;
}
public void setDependencies(List<MavenTarget> dependencies) {
this.dependencies = dependencies;
}
}
| gpl-3.0 |
Minestar/MoneyPit | src/main/java/de/minestar/moneypit/listener/MonitorListener.java | 9132 | package de.minestar.moneypit.listener;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import com.bukkit.gemo.patchworking.BlockVector;
import de.minestar.minestarlibrary.utils.PlayerUtils;
import de.minestar.moneypit.MoneyPitCore;
import de.minestar.moneypit.manager.QueueManager;
import de.minestar.moneypit.queues.Queue;
import de.minestar.moneypit.queues.entity.EntityQueue;
public class MonitorListener implements Listener {
private QueueManager queueManager;
private BlockVector vector;
private Queue addQueue, removeQueue, interactQueue;
public MonitorListener() {
this.queueManager = MoneyPitCore.queueManager;
this.vector = new BlockVector("", 0, 0, 0);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockPlace(BlockPlaceEvent event) {
// update the BlockVector
this.vector.update(event.getBlock().getLocation());
// get the AddQueue
this.addQueue = this.queueManager.getAndRemoveQueue(this.vector);
if (this.addQueue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
if (!this.addQueue.execute()) {
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onBlockBreak(BlockBreakEvent event) {
// update the BlockVector
this.vector.update(event.getBlock().getLocation());
// get the AddQueue
this.removeQueue = this.queueManager.getAndRemoveQueue(this.vector);
if (this.removeQueue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
if (!this.removeQueue.execute()) {
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onHangingBreak(HangingBreakEvent event) {
// Only handle ItemFrames & Paintings
if (!event.getEntity().getType().equals(EntityType.ITEM_FRAME) && !event.getEntity().getType().equals(EntityType.PAINTING)) {
return;
}
// update the BlockVector
this.vector.update(event.getEntity().getLocation());
// get the AddQueue
this.removeQueue = this.queueManager.getAndRemoveQueue(this.vector);
if (this.removeQueue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
if (!this.removeQueue.execute()) {
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onHangingBreakByEntity(HangingBreakByEntityEvent event) {
// Only handle ItemFrames & Paintings
if (!event.getEntity().getType().equals(EntityType.ITEM_FRAME) && !event.getEntity().getType().equals(EntityType.PAINTING)) {
return;
}
// update the BlockVector
this.vector.update(event.getEntity().getLocation());
// get the AddQueue
this.removeQueue = this.queueManager.getAndRemoveQueue(this.vector);
if (this.removeQueue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
if (!this.removeQueue.execute()) {
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onHangingInteract(PlayerInteractEntityEvent event) {
// Only handle ItemFrames & Paintings
if (!event.getRightClicked().getType().equals(EntityType.ITEM_FRAME) && !event.getRightClicked().getType().equals(EntityType.PAINTING)) {
return;
}
// update the BlockVector
this.vector.update(event.getRightClicked().getLocation());
// get the AddQueue
this.interactQueue = this.queueManager.getAndRemoveQueue(this.vector);
if (this.interactQueue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
// execute the event
if (!this.interactQueue.execute()) {
event.setCancelled(true);
}
// cancel the event
event.setCancelled(true);
} else {
PlayerUtils.sendError(event.getPlayer(), MoneyPitCore.NAME, "Could not complete your interact request!");
PlayerUtils.sendInfo(event.getPlayer(), "The event was cancelled by another plugin.");
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerInteract(PlayerInteractEvent event) {
// Only handle Left- & Right-Click on a block
Action action = event.getAction();
if (action != Action.LEFT_CLICK_BLOCK && action != Action.RIGHT_CLICK_BLOCK) {
return;
}
// update the BlockVector
this.vector.update(event.getClickedBlock().getLocation());
// get the AddQueue
this.interactQueue = this.queueManager.getAndRemoveQueue(this.vector);
if (this.interactQueue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
// execute the event
if (!this.interactQueue.execute()) {
event.setCancelled(true);
}
// cancel the event
event.setCancelled(true);
} else {
PlayerUtils.sendError(event.getPlayer(), MoneyPitCore.NAME, "Could not complete your interact request!");
PlayerUtils.sendInfo(event.getPlayer(), "The event was cancelled by another plugin.");
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity interactedEntity = event.getEntity();
if (event.getDamager().getType().equals(EntityType.PLAYER)) {
Player player = (Player) event.getDamager();
// we need an entity and a player
if (interactedEntity == null || player == null) {
return;
}
// get the queue
EntityQueue queue = this.queueManager.getAndRemoveEntityQueue(interactedEntity.getUniqueId().toString());
if (queue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
// execute the event
if (!queue.execute()) {
event.setCancelled(true);
}
// cancel the event
event.setCancelled(true);
} else {
PlayerUtils.sendError(player, MoneyPitCore.NAME, "Could not complete your interact request!");
PlayerUtils.sendInfo(player, "The event was cancelled by another plugin.");
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityInteractAt(PlayerInteractAtEntityEvent event) {
Entity interactedEntity = event.getRightClicked();
if (event.getPlayer().getType().equals(EntityType.PLAYER)) {
Player player = (Player) event.getPlayer();
// we need an entity and a player
if (interactedEntity == null || player == null) {
return;
}
// get the queue
EntityQueue queue = this.queueManager.getAndRemoveEntityQueue(interactedEntity.getUniqueId().toString());
if (queue != null) {
// execute the queue, if the event was not cancelled
if (!event.isCancelled()) {
// execute the event
if (!queue.execute()) {
event.setCancelled(true);
}
// cancel the event
event.setCancelled(true);
} else {
PlayerUtils.sendError(player, MoneyPitCore.NAME, "Could not complete your interact request!");
PlayerUtils.sendInfo(player, "The event was cancelled by another plugin.");
}
}
}
}
}
| gpl-3.0 |
0x006EA1E5/oo6 | src/main/java/org/otherobjects/cms/site/TreeNode.java | 6134 | /*
* This file is part of the OTHERobjects Content Management System.
*
* Copyright 2007-2009 OTHER works Limited.
*
* OTHERobjects 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.
*
* OTHERobjects 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 OTHERobjects. If not, see <http://www.gnu.org/licenses/>.
*/
package org.otherobjects.cms.site;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TreeNode implements Cloneable, Comparable<TreeNode>
{
private String id;
private String path;
private String redirectPath;
private String label;
private int sortOrder;
private Object object;
private List<TreeNode> children = new ArrayList<TreeNode>();
private boolean selected = false;
private Date modificationTimestamp = new Date(); // For SEO sitemap
private List<String> requiredRoles; // For SiteController security checks
public TreeNode()
{
}
public TreeNode(String path)
{
this.path = path;
}
public TreeNode(String path, String id, String label, int sortOrder)
{
this.path = path;
this.id = id;
this.label = label;
this.sortOrder = sortOrder;
}
public TreeNode(String path, String id, String label, int sortOrder, String redirectPath)
{
this.path = path;
this.id = id;
this.label = label;
this.redirectPath = redirectPath;
this.sortOrder = sortOrder;
}
public TreeNode(String path, String id, String label, int sortOrder, Object object)
{
this.path = path;
this.id = id;
this.label = label;
this.object = object;
this.sortOrder = sortOrder;
}
public int compareTo(TreeNode node)
{
Integer nodeSortOrder = node.getSortOrder();
return - nodeSortOrder.compareTo(this.getSortOrder());
}
public int getSortOrder()
{
return sortOrder;
}
public void setSortOrder(int sortOrder)
{
this.sortOrder = sortOrder;
}
/**
* Clones the tree but only to the maximum depth specified.
* @param depth
* @return
*/
public TreeNode clone(int depth) throws CloneNotSupportedException
{
TreeNode clone = (TreeNode) super.clone();
if (depth > 0)
{
List<TreeNode> childrenClone = new ArrayList<TreeNode>();
for (TreeNode child : getChildren())
{
childrenClone.add((TreeNode) child.clone(depth - 1));
}
clone.setChildren(childrenClone);
}
else
{
// Remove pointer to original list of children
clone.setChildren(new ArrayList<TreeNode>());
}
return clone;
}
public TreeNode getNode(String string)
{
return getNode(string, this);
}
public TreeNode getNode(String path, TreeNode parent)
{
if (parent.getPath().equals(path))
return parent;
// TODO Optimize: Don't look in dead ends
// Search this item's children
for (TreeNode ti : parent.getChildren())
{
if (ti.getPath().equals(path))
return ti;
}
for (TreeNode ti : parent.getChildren())
{
TreeNode node = getNode(path, ti);
if (node != null)
return node;
}
return null;
}
public void print()
{
print(this, 0);
}
public void print(TreeNode node, int depth)
{
depth = depth + 1;
String pad = "";
for (int i = 0; i < depth; i++)
{
pad += ".";
}
System.out.println("[" + pad + (node.getPath()) + "]");
for (TreeNode ti : node.getChildren())
{
print(ti, depth);
}
}
public String getUrl()
{
// FIXME Deal with context path here?
if (getRedirectPath() != null)
return getRedirectPath();
else
return getPath();
}
@Override
public String toString()
{
return getPath();
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getPath()
{
return path;
}
public void setPath(String path)
{
this.path = path;
}
public String getLabel()
{
return label;
}
public void setLabel(String label)
{
this.label = label;
}
public List<TreeNode> getChildren()
{
return children;
}
public void setChildren(List<TreeNode> children)
{
this.children = children;
}
public Object getObject()
{
return object;
}
public void setObject(Object object)
{
this.object = object;
}
public boolean isSelected()
{
return selected;
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
public String getRedirectPath()
{
return redirectPath;
}
public void setRedirectPath(String redirectPath)
{
this.redirectPath = redirectPath;
}
public Date getModificationTimestamp()
{
return modificationTimestamp;
}
public void setModificationTimestamp(Date modificationTimestamp)
{
this.modificationTimestamp = modificationTimestamp;
}
public List<String> getRequiredRoles()
{
return requiredRoles;
}
public void setRequiredRoles(List<String> requiredRoles)
{
this.requiredRoles = requiredRoles;
}
}
| gpl-3.0 |
TypedScroll/LCPD | core/src/main/java/com/shatteredpixel/lovecraftpixeldungeon/ui/RedButton.java | 2761 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2016 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.lovecraftpixeldungeon.ui;
import com.shatteredpixel.lovecraftpixeldungeon.Assets;
import com.shatteredpixel.lovecraftpixeldungeon.Chrome;
import com.shatteredpixel.lovecraftpixeldungeon.scenes.PixelScene;
import com.watabou.noosa.Image;
import com.watabou.noosa.NinePatch;
import com.watabou.noosa.RenderedText;
import com.watabou.noosa.audio.Sample;
import com.watabou.noosa.ui.Button;
public class RedButton extends Button {
protected NinePatch bg;
protected RenderedText text;
protected Image icon;
public RedButton( String label ) {
this(label, 9);
}
public RedButton( String label, int size ){
super();
text = PixelScene.renderText( size );
text.text( label );
add( text );
}
@Override
protected void createChildren() {
super.createChildren();
bg = Chrome.get( Chrome.Type.BUTTON );
add( bg );
}
@Override
protected void layout() {
super.layout();
bg.x = x;
bg.y = y;
bg.size( width, height );
text.x = x + (width - text.width()) / 2;
text.y = y + (height - text.baseLine()) / 2;
PixelScene.align(text);
if (icon != null) {
icon.x = x + text.x - icon.width() - 2;
icon.y = y + (height - icon.height()) / 2;
PixelScene.align(icon);
}
}
@Override
protected void onTouchDown() {
bg.brightness( 1.2f );
Sample.INSTANCE.play( Assets.SND_CLICK );
}
@Override
protected void onTouchUp() {
bg.resetColor();
}
public void enable( boolean value ) {
active = value;
text.alpha( value ? 1.0f : 0.3f );
}
public void text( String value ) {
text.text( value );
layout();
}
public void textColor( int value ) {
text.hardlight( value );
}
public void icon( Image icon ) {
if (this.icon != null) {
remove( this.icon );
}
this.icon = icon;
if (this.icon != null) {
add( this.icon );
layout();
}
}
public float reqWidth() {
return text.width() + 2f;
}
public float reqHeight() {
return text.baseLine() + 4;
}
}
| gpl-3.0 |
mkbox/MKkbd | software/src/org/mkbox/projects/kbd/model/KeyList.java | 1649 | package org.mkbox.projects.kbd.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class KeyList {
private ArrayList<StringProperty> displayName;
private ArrayList<Key> keys;
public KeyList() {
this.keys = new ArrayList<Key>(4);
this.displayName = new ArrayList<StringProperty>(4);
}
public KeyList(ArrayList<Key> keys) {
this.keys = new ArrayList<Key>(4);
this.displayName = new ArrayList<StringProperty>(4);
this.keys.addAll(keys);
generateDisplayName();
}
public KeyList(Key key1, Key key2, Key key3, Key key4) {
this.keys = new ArrayList<Key>(4);
this.displayName = new ArrayList<StringProperty>(4);
this.keys.add(key1);
this.keys.add(key2);
this.keys.add(key3);
this.keys.add(key4);
generateDisplayName();
}
public void setKey(int num, Key key) {
keys.remove(num);
keys.add(num, key);
}
public StringProperty getNameCol1() {
return displayName.get(0);
}
public StringProperty getNameCol2() {
return displayName.get(1);
}
public StringProperty getNameCol3() {
return displayName.get(2);
}
public StringProperty getNameCol4() {
return displayName.get(3);
}
@XmlElement(name = "key")
public List<Key> getKeys() {
return keys;
}
public void generateDisplayName() {
displayName.clear();
for( int i = 0; i < 4; i++ ) {
displayName.add(new SimpleStringProperty(keys.get(i).getKeyNum() + ": " + keys.get(i).getKeyName()));
}
}
}
| gpl-3.0 |
sarxos/v4l4j | src/main/java/com/github/sarxos/v4l4j/NativeUtils.java | 4639 | package com.github.sarxos.v4l4j;
import java.io.*;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.ProviderNotFoundException;
import java.nio.file.StandardCopyOption;
/**
* A simple library class which helps with loading dynamic libraries stored in the
* JAR archive. These libraries usually contain implementation of some methods in
* native code (using JNI - Java Native Interface).
*
* @see <a href="http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar">http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar</a>
* @see <a href="https://github.com/adamheinrich/native-utils">https://github.com/adamheinrich/native-utils</a>
*
*/
public class NativeUtils {
/**
* The minimum length a prefix for a file has to have according to {@link File#createTempFile(String, String)}}.
*/
private static final int MIN_PREFIX_LENGTH = 3;
public static final String NATIVE_FOLDER_PATH_PREFIX = "nativeutils";
/**
* Temporary directory which will contain the DLLs.
*/
private static File temporaryDir;
/**
* Private constructor - this class will never be instanced
*/
private NativeUtils() {
}
/**
* Loads library from current JAR archive
*
* The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after
* exiting.
* Method uses String as filename because the pathname is "abstract", not system-dependent.
*
* @param path The path of file inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext
* @throws IOException If temporary file creation or read/write operation fails
* @throws IllegalArgumentException If source file (param path) does not exist
* @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters
* (restriction of {@link File#createTempFile(java.lang.String, java.lang.String)}).
* @throws FileNotFoundException If the file could not be found inside the JAR.
*/
public static void loadLibraryFromJar(String path) throws IOException {
if (null == path || !path.startsWith("/")) {
throw new IllegalArgumentException("The path has to be absolute (start with '/').");
}
// Obtain filename from path
String[] parts = path.split("/");
String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
// Check if the filename is okay
if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
}
// Prepare temporary file
if (temporaryDir == null) {
temporaryDir = createTempDirectory(NATIVE_FOLDER_PATH_PREFIX);
temporaryDir.deleteOnExit();
}
File temp = new File(temporaryDir, filename);
try (InputStream is = NativeUtils.class.getResourceAsStream(path)) {
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
temp.delete();
throw e;
} catch (NullPointerException e) {
temp.delete();
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
}
try {
System.load(temp.getAbsolutePath());
} finally {
if (isPosixCompliant()) {
// Assume POSIX compliant file system, can be deleted after loading
temp.delete();
} else {
// Assume non-POSIX, and don't delete until last file descriptor closed
temp.deleteOnExit();
}
}
}
private static boolean isPosixCompliant() {
try {
return FileSystems.getDefault()
.supportedFileAttributeViews()
.contains("posix");
} catch (FileSystemNotFoundException
| ProviderNotFoundException
| SecurityException e) {
return false;
}
}
private static File createTempDirectory(String prefix) throws IOException {
String tempDir = System.getProperty("java.io.tmpdir");
File generatedDir = new File(tempDir, prefix + System.nanoTime());
if (!generatedDir.mkdir())
throw new IOException("Failed to create temp directory " + generatedDir.getName());
return generatedDir;
}
| gpl-3.0 |
coderhousez/dataStructures | src/main/java/z/house/coder/datastructures/Position.java | 439 | package z.house.coder.datastructures;
import java.util.Optional;
/**
* Represent an element within a container
* by implementing this interface.
*
* @author coder
*
*/
public interface Position<T,C> {
/**
* Element at this position in
* the container.
* @return T
*/
public Optional<T> getElement();
/**
* Returns container that
* holds element at this positon.
* @return C
*/
public C getContainer();
}
| gpl-3.0 |
robpayn/resources | src/sandbox/java/org/payn/resources/particleold/cell/BehaviorConcTrackerLagrange.java | 600 | package org.payn.resources.particleold.cell;
import org.payn.chsm.values.ValueLong;
import org.payn.resources.particle.ResourceParticle;
public class BehaviorConcTrackerLagrange extends BehaviorConcTracker {
@Override
public ParticleOneDim createParticle(ParticleManager particleManager,
String currencyName)
{
return new ParticleOneDim(particleManager, currencyName);
}
@Override
protected void addProcessors()
{
addProcessor(ResourceParticle.NAME_MANAGER, ParticleManagerLagrange.class, ParticleManager.getValueClass());
}
}
| gpl-3.0 |
Relicum/Ipsum | src/main/java/com/relicum/ipsum/Menus/Region.java | 2424 | package com.relicum.ipsum.Menus;
import org.apache.commons.lang3.text.StrBuilder;
import org.bukkit.Bukkit;
import org.bukkit.util.Vector;
import com.relicum.ipsum.Utils.TextProcessor;
/**
* Name: Region.java Created: 04 February 2015
*
* @author Relicum
* @version 0.0.1
*/
public class Region {
private String min = "";
private String max = "";
private String cloneTo = "";
private String mask = "";
private String mode = "normal";
public Region() {
}
public Region setMask(MASK mask) {
this.mask = mask.get();
return this;
}
public Region setMax(Vector max) {
this.max = max.toString().replaceAll(",", " ");
return this;
}
public Region setMin(Vector min) {
this.min = min.toString().replaceAll(",", " ");
return this;
}
public Region setMode(MODE mode) {
this.mode = mode.get();
return this;
}
public Region setCloneTo(Vector cloneTo) {
this.cloneTo = cloneTo.toString().replaceAll(",", " ");
return this;
}
public String buildCmd() {
return "clone " + min + " " + max + " " + cloneTo + " " + mask + " " + mode;
}
public void runCmd() {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), buildCmd());
}
public String getCloneTo() {
return cloneTo;
}
public String getMode() {
return mode;
}
public String getMin() {
return min;
}
public String getMax() {
return max;
}
public String getMask() {
return mask;
}
@Override
public String toString() {
StrBuilder sb = new StrBuilder();
sb.setNewLineText("\n");
sb.appendNewLine();
sb.append("&6Clone Min Location: &b").append(min).appendNewLine();
sb.append("&6Clone Max Location: &b").append(max).appendNewLine();
sb.append("&aClone to Location: &5").append(cloneTo).appendNewLine();
sb.appendNewLine();
sb.append("&6Mask: ");
if (mask.isEmpty())
sb.append("&bNot Set");
else
sb.append("&b").append(mask);
sb.appendNewLine();
sb.append("&6Mode: ");
if (mode.isEmpty())
sb.append("&bNot Set");
else
sb.append("&b").append(mode);
sb.appendNewLine();
return TextProcessor.stripColor(sb.toString());
}
}
| gpl-3.0 |
social-computing/jmi-server | jmi-server/src/main/java/com/socialcomputing/wps/server/plandictionary/Model.java | 10042 | package com.socialcomputing.wps.server.plandictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import com.socialcomputing.wps.client.applet.ColorX;
import com.socialcomputing.wps.client.applet.Env;
import com.socialcomputing.wps.server.planDictionnary.connectors.JMIException;
import com.socialcomputing.wps.server.planDictionnary.connectors.utils.ConnectorHelper;
import com.socialcomputing.wps.server.planDictionnary.connectors.utils.NameValuePair;
import com.socialcomputing.wps.server.plandictionary.connectors.iEntityConnector;
import com.socialcomputing.wps.server.webservices.RequestingClassifyId;
/**
* Model is determined by connected user segmentation */
public class Model implements java.io.Serializable
{
static final long serialVersionUID = 7094708832902600585L;
public static final int MAX_SELECTION = 32;
public String m_Name = null;
public String m_Description = null;
// Param�tres de g�n�ration du plan
public boolean m_DisplayEntities = true;
public boolean m_DisplayEmptyLinks = true;
public boolean m_DisplayFakeLinks = true;
public int m_flags = 0;
public ColorX m_inCol = null;
public ColorX m_outCol = null;
public ColorX m_filterCol = null;
// A voir
public String m_Type;
// S�lections d'entit�s et/ou d'attributs (WPSSelection)
public WPSSelection m_EntitiesSelections[] = new WPSSelection[ Model.MAX_SELECTION];
public WPSSelection m_AttributesSelections[] = new WPSSelection[ Model.MAX_SELECTION];
private transient iEntityConnector m_EntitiesConnector = null;
// Matching RequestingEntity / Entity Swatch (normal, ref, norm cur, ref cur)
public ClassifierMapper m_EntityMapper[] = new ClassifierMapper[2];
// Matching RequestingEntity / Attribute Swatch (normal, ref, norm cur, ref cur)
public ClassifierMapper m_AttributeMapper[] = new ClassifierMapper[4];
// Matching RequestingEntity / Link Swatch (normal, ref)
public ClassifierMapper m_LinkMapper[] = new ClassifierMapper[4];
// Matching RequestingEntity / Cluster Swatch (normal, ref)
public ClassifierMapper m_ClusterMapper[] = new ClassifierMapper[2];
// Matching RequestingEntity / Reference Swatch (normal, cur)
public ClassifierMapper m_ReferenceMapper[] = new ClassifierMapper[2];
// Matching RequestingEntity / Advertising Swatch (normal, cur)
public ClassifierMapper m_AdvertisingMapper[] = new ClassifierMapper[2];
static public Model readObject( org.jdom.Element element) throws org.jdom.JDOMException
{
Model model = new Model( element.getAttributeValue( "name"));
model.m_Description = element.getChildText( "comment");
model.m_DisplayEntities = element.getAttributeValue( "display-entities").equalsIgnoreCase( "yes");
if( element.getAttributeValue( "display-empty-links") != null)
model.m_DisplayEmptyLinks = element.getAttributeValue( "display-empty-links").equalsIgnoreCase( "yes");
else
model.m_DisplayEmptyLinks = false;
if( element.getAttributeValue( "display-fake-links") != null)
model.m_DisplayFakeLinks = element.getAttributeValue( "display-fake-links").equalsIgnoreCase( "yes");
else
model.m_DisplayFakeLinks = false;
if( element.getAttributeValue( "in-color") != null)
model.m_inCol = Model.readColorX(element.getAttributeValue( "in-color"));
else
model.m_inCol = new ColorX( 0xFFFFFF);
if( element.getAttributeValue( "out-color") != null)
model.m_outCol = Model.readColorX(element.getAttributeValue( "out-color"));
else
model.m_outCol = new ColorX( 0xFFFFFF);
if( element.getAttributeValue( "filter-color") != null)
model.m_filterCol = Model.readColorX(element.getAttributeValue( "filter-color"));
else
model.m_filterCol = new ColorX( 0xFFFFFF);
{ // Swatchs
org.jdom.Element props = element.getChild( "swatch-segmentation");
org.jdom.Element subprops = props.getChild( "attribute-swatch");
// TODO (ON) Simplifier les swatch ICI : on peut n'avoir qu'un swatch
model.m_AttributeMapper[0] = ClassifierMapper.readObject( subprops.getChild( "norm-swatch"));
model.m_AttributeMapper[1] = ClassifierMapper.readObject( subprops.getChild( "ref-swatch"));
model.m_AttributeMapper[2] = ClassifierMapper.readObject( subprops.getChild( "active-norm-swatch"));
model.m_AttributeMapper[3] = ClassifierMapper.readObject( subprops.getChild( "active-ref-swatch"));
subprops = props.getChild( "link-swatch");
model.m_LinkMapper[0] = ClassifierMapper.readObject( subprops.getChild( "norm-swatch"));
model.m_LinkMapper[1] = ClassifierMapper.readObject( subprops.getChild( "ref-swatch"));
org.jdom.Element activeLinkElm = subprops.getChild( "active-norm-swatch");
if ( activeLinkElm != null )
{
model.m_LinkMapper[2] = ClassifierMapper.readObject( activeLinkElm );
model.m_LinkMapper[3] = ClassifierMapper.readObject( subprops.getChild( "active-ref-swatch"));
}
}
{ // S�lections
java.util.List lst = element.getChildren( "selection-swatch");
int size = lst.size();
if( size >= 32)
throw new org.jdom.JDOMException( "Display Profile '" + model.m_Name + "' : too many selections!");
for( int i = 0; i < size; ++i)
{
org.jdom.Element node = ( org.jdom.Element)lst.get( i);
//String name = node.getAttributeValue( "name");
model.m_AttributesSelections[ i] = WPSSelection.readObject( node, i);
}
}
return model;
}
static protected ColorX readColorX( String value) {
try {
return new ColorX( Integer.parseInt( value.startsWith("#") ? value.substring(1): value, 16));
}
catch (Exception e) {
}
return new ColorX( value);
}
// Constructor
public Model( String name)
{
m_Name = name;
for( int i = 0; i < 2; ++i)
m_EntityMapper[ i] = new ClassifierMapper();
for( int i = 0; i < 4; ++i)
m_AttributeMapper[ i] = new ClassifierMapper();
for( int i = 0; i < 4; ++i)
m_LinkMapper[ i] = new ClassifierMapper();
for( int i = 0; i < 2; ++i)
m_ClusterMapper[ i] = new ClassifierMapper();
for( int i = 0; i < 2; ++i)
m_ReferenceMapper[ i] = new ClassifierMapper();
for( int i = 0; i < 2; ++i)
m_AdvertisingMapper[ i] = new ClassifierMapper();
m_inCol = new ColorX( 127, 175, 31 );
m_outCol = new ColorX( 0, 0, 0 );
}
public void setEntitiesConnector( iEntityConnector connector)
{
m_EntitiesConnector = connector;
}
// Param�tres de g�n�ration du plan
public String getEntitySwatch( RequestingClassifyId classifyId, String entityId, int swatchType) throws JMIException
{ // La segmentation sur entityId n'est pas trait�e
return m_EntityMapper[ swatchType].getAssociatedName( m_EntitiesConnector, classifyId);
}
public String getAttributeSwatch( RequestingClassifyId classifyId, int swatchType) throws JMIException
{
return m_AttributeMapper[ swatchType].getAssociatedName( m_EntitiesConnector, classifyId);
}
public String getLinkSwatch( RequestingClassifyId classifyId, int swatchType) throws JMIException
{
return m_LinkMapper[ swatchType].getAssociatedName( m_EntitiesConnector, classifyId);
}
public String getClusterSwatch( RequestingClassifyId classifyId, int swatchType) throws JMIException
{
return m_ClusterMapper[ swatchType].getAssociatedName( m_EntitiesConnector, classifyId);
}
public String getReferenceSwatch( RequestingClassifyId classifyId, int swatchType) throws JMIException
{
return m_ReferenceMapper[ swatchType].getAssociatedName( m_EntitiesConnector, classifyId);
}
public String getAdvertisingSwatch( RequestingClassifyId classifyId, int swatchType) throws JMIException
{
return m_AdvertisingMapper[ swatchType].getAssociatedName( m_EntitiesConnector, classifyId);
}
public void initClientEnv( WPSDictionary dico, Hashtable<String, Object> wpsparams, Env env)
{
/*
public static final int AUDIO_BIT = 0x01;
public static final int JSCRIPT_BIT = 0x04;
public static final int EXTERN_SEL = 0x20;
*/
env.m_flags = 0;
if( m_DisplayEntities)
env.m_flags = Env.GROUP_BIT;
env.m_inCol = m_inCol;
env.m_outCol = m_outCol;
env.m_filterCol = m_filterCol;
env.m_transfo = null;
// Propriétés globales du plan
for( NameValuePair value : dico.m_EnvProperties) {
String name = value.getName();
if( !wpsparams.containsKey(name)) {
name = name.startsWith( "$") ? name : "$" + name;
env.m_props.put( name, ConnectorHelper.ReplaceParameter(value, wpsparams));
}
}
// S�lection Attributes
env.m_selections = new Hashtable();
WPSSelection selection;
int i, n = m_AttributesSelections.length;
for ( i = 0; i < n; i ++ )
{
selection = m_AttributesSelections[i];
if ( selection != null )
{
env.m_selections.put( selection.m_SelectionName, new Integer( i ));
}
}
}
// Check classifiers integrity
public void checkIntegrity( String m, iEntityConnector entities, String attributes) throws org.jdom.JDOMException, JMIException
{
for( int i = 0; i < Model.MAX_SELECTION; ++i)
{
if( m_EntitiesSelections[i] != null)
if( !m_EntitiesSelections[i].m_FreeSelection && entities.getSelection( m_EntitiesSelections[i].m_SelectionRef) == null)
throw new org.jdom.JDOMException( m + " : Unknown Entities Selection '" + m_EntitiesSelections[i].m_SelectionRef + "'");
}
for( int i = 0; i < Model.MAX_SELECTION; ++i)
{
if( m_AttributesSelections[i] != null)
if( !m_AttributesSelections[i].m_FreeSelection && entities.getProfile( attributes).getSelection( m_AttributesSelections[i].m_SelectionRef) == null)
throw new org.jdom.JDOMException( m + " : Unknown Attributes Selection '" + m_AttributesSelections[i].m_SelectionRef + "'");
}
}
}
| gpl-3.0 |
reasense/MSEA | src/com/mavlink/messages/ardupilotmega/msg_simstate.java | 1358 | package com.mavlink.messages.ardupilotmega;
import com.mavlink.messages.IMAVLinkMessage;
/**
* Class msg_simstate
* Status of simulation environment, if used
**/
public class msg_simstate extends IMAVLinkMessage {
public static final int MAVLINK_MSG_ID_SIMSTATE = 164;
private static final long serialVersionUID = MAVLINK_MSG_ID_SIMSTATE;
public msg_simstate() {
messageType = MAVLINK_MSG_ID_SIMSTATE;
}
/**
* Roll angle (rad)
*/
public float roll;
/**
* Pitch angle (rad)
*/
public float pitch;
/**
* Yaw angle (rad)
*/
public float yaw;
/**
* X acceleration m/s/s
*/
public float xacc;
/**
* Y acceleration m/s/s
*/
public float yacc;
/**
* Z acceleration m/s/s
*/
public float zacc;
/**
* Angular speed around X axis rad/s
*/
public float xgyro;
/**
* Angular speed around Y axis rad/s
*/
public float ygyro;
/**
* Angular speed around Z axis rad/s
*/
public float zgyro;
/**
* Latitude in degrees
*/
public float lat;
/**
* Longitude in degrees
*/
public float lng;
public String toString() {
return "MAVLINK_MSG_ID_SIMSTATE : " + " roll="+roll+ " pitch="+pitch+ " yaw="+yaw+ " xacc="+xacc+ " yacc="+yacc+ " zacc="+zacc+ " xgyro="+xgyro+ " ygyro="+ygyro+ " zgyro="+zgyro+ " lat="+lat+ " lng="+lng;}
}
| gpl-3.0 |
trackplus/Genji | src/main/java/com/aurel/track/beans/TActionBean.java | 1455 | /**
* Genji Scrum Tool and Issue Tracker
* Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions
* <a href="http://www.trackplus.com">Genji Scrum Tool</a>
*
* 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/>.
*/
/* $Id:$ */
package com.aurel.track.beans;
import java.io.Serializable;
import com.aurel.track.resources.LocalizationKeyPrefixes;
/**
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*/
public class TActionBean
extends com.aurel.track.beans.base.BaseTActionBean
implements Serializable, ILocalizedLabelBean
{
private static final long serialVersionUID = 1L;
@Override
public String getKeyPrefix() {
return LocalizationKeyPrefixes.ACTION_LABEL_KEY_PREFIX;
}
}
| gpl-3.0 |
nschudlo/RowingMod | src/main/java/com/republic/rowingmod/proxy/CommonProxy.java | 95 | package com.republic.rowingmod.proxy;
public abstract class CommonProxy implements IProxy
{
}
| gpl-3.0 |
JBKGraphics/CamoLights | src/main/java/com/jbkgraphics/camolights/block/wool/GrayWoolCamo.java | 535 | package com.jbkgraphics.camolights.block.wool;
import com.jbkgraphics.camolights.block.BlockCamoLights;
import com.jbkgraphics.camolights.creativetab.CreativeTabCL;
import net.minecraft.block.material.Material;
public class GrayWoolCamo extends BlockCamoLights {
public GrayWoolCamo() {
super(Material.cloth);
this.setBlockName("grayWoolCamo");
this.setHardness(2.0F);
this.setLightLevel(1.0F);
this.setStepSound(soundTypeCloth);
this.setCreativeTab(CreativeTabCL.CL_TAB);
}
}
| gpl-3.0 |
robworth/patientview | patientview-parent/patientview/src/main/java/org/patientview/patientview/ParseXml.java | 1985 | /*
* PatientView
*
* Copyright (c) Worth Solutions Limited 2004-2013
*
* This file is part of PatientView.
*
* PatientView 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.
* PatientView 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 PatientView in a file
* titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @package PatientView
* @link http://www.patientview.org
* @author PatientView <info@patientview.org>
* @copyright Copyright (c) 2004-2013, Worth Solutions Limited
* @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
*/
package org.patientview.patientview;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.patientview.patientview.logon.LogonUtils;
import org.patientview.utils.LegacySpringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
public class ParseXml extends Action {
public ActionForward execute(
ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
String xmlFileName = BeanUtils.getProperty(form, "src");
LegacySpringUtils.getImportManager().process(new File(xmlFileName));
FindXmlFiles.putXmlFilesInRequest(request);
return LogonUtils.logonChecks(mapping, request);
}
}
| gpl-3.0 |
icgc-dcc/pcawg-import | pcawg-import-client/src/main/java/org/icgc/dcc/pcawg/client/core/ObjectNodeConverter.java | 493 | package org.icgc.dcc.pcawg.client.core;
import com.fasterxml.jackson.databind.node.ObjectNode;
import static org.icgc.dcc.common.core.json.JsonNodeBuilders.array;
import static org.icgc.dcc.common.core.json.JsonNodeBuilders.object;
public interface ObjectNodeConverter {
ObjectNode toObjectNode();
default ObjectNode createIs(String ... values){
return object()
.with("is",
array()
.with(values)
.end())
.end();
}
}
| gpl-3.0 |
badabum007/hell_guardians | src/com/badabum007/hell_guardians/SpriteAnimation.java | 1631 | package com.badabum007.hell_guardians;
import javafx.animation.Interpolator;
import javafx.animation.Transition;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
/**
* class for making animation
*
* @author badabum007
*/
public class SpriteAnimation extends Transition {
private final ImageView imageView;
/** count of animation stages */
private final int count;
/** number of required sprite columns */
private final int columns;
/** sprite offset from the beginning of sprite list */
private final int offsetX;
private final int offsetY;
/** sprite width and height */
private final int width;
private final int height;
private int lastIndex;
public SpriteAnimation(ImageView imageView,
/** animation duration */
Duration duration, int count, int columns, int offsetX, int offsetY, int width, int height) {
this.imageView = imageView;
this.count = count;
this.columns = columns;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.width = width;
this.height = height;
setCycleDuration(duration);
setInterpolator(Interpolator.LINEAR);
}
/** finds our sprite position */
protected void interpolate(double k) {
final int index = Math.min((int) Math.floor(k * count), count - 1);
if (index != lastIndex) {
final int x = (index % columns) * width + offsetX;
final int y = (index / columns) * height + offsetY;
imageView.setViewport(new Rectangle2D(x, y, width, height));
lastIndex = index;
}
}
}
| gpl-3.0 |
pippokill/tri | src/main/java/di/uniba/it/tri/vectors/FileVectorReader.java | 6763 | /**
* Copyright (c) 2014, the Temporal Random Indexing AUTHORS.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the University of Bari nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007
*
*/
package di.uniba.it.tri.vectors;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author pierpaolo
*/
public class FileVectorReader implements VectorReader {
private static final Logger logger = Logger.getLogger(MemoryVectorReader.class.getName());
private final File inputFile;
private int dimension;
/**
*
* @param inputFile
*/
public FileVectorReader(File inputFile) {
this.inputFile = inputFile;
}
/**
*
* @throws IOException
*/
public void init() throws IOException {
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
//logger.log(Level.INFO, "Init vector store: {0}", inputFile.getAbsolutePath());
Properties props = VectorStoreUtils.readHeader(inputStream.readUTF());
dimension = Integer.parseInt(props.getProperty("-dim"));
inputStream.close();
}
/**
*
* @throws IOException
*/
@Override
public void close() throws IOException {
}
/**
*
* @param key
* @return
* @throws IOException
*/
@Override
public Vector getVector(String key) throws IOException {
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
inputStream.readUTF();
while (inputStream.available() > 0) {
String fkey = inputStream.readUTF();
if (fkey.equals(key)) {
Vector vector = VectorFactory.createZeroVector(VectorType.REAL, dimension);
vector.readFromStream(inputStream);
inputStream.close();
return vector;
} else {
inputStream.skipBytes(VectorFactory.getByteSize(VectorType.REAL, dimension));
}
}
inputStream.close();
return null;
}
/**
*
* @return
* @throws IOException
*/
@Override
public Iterator<String> getKeys() throws IOException {
Set<String> keySet = new HashSet<>();
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
inputStream.readUTF();
while (inputStream.available() > 0) {
String fkey = inputStream.readUTF();
keySet.add(fkey);
inputStream.skipBytes(VectorFactory.getByteSize(VectorType.REAL, dimension));
}
inputStream.close();
return keySet.iterator();
}
/**
*
* @return
* @throws IOException
*/
@Override
public Iterator<ObjectVector> getAllVectors() throws IOException {
return new FileVectorIterator(inputFile);
}
/**
*
* @return
*/
@Override
public int getDimension() {
return this.dimension;
}
/**
*
*/
public static class FileVectorIterator implements Iterator<ObjectVector> {
private final File file;
private DataInputStream inputStream;
private int dimension;
/**
*
* @param file
*/
public FileVectorIterator(File file) {
this.file = file;
try {
this.inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
Properties props = VectorStoreUtils.readHeader(inputStream.readUTF());
dimension = Integer.parseInt(props.getProperty("-dim"));
} catch (IOException ex) {
Logger.getLogger(FileVectorReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public boolean hasNext() {
try {
boolean hasNext = this.inputStream.available() > 0;
if (!hasNext) {
this.inputStream.close();
}
return hasNext;
} catch (IOException ex) {
Logger.getLogger(FileVectorReader.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
}
@Override
public ObjectVector next() {
try {
String key = this.inputStream.readUTF();
Vector vector = VectorFactory.createZeroVector(VectorType.REAL, dimension);
vector.readFromStream(inputStream);
return new ObjectVector(key, vector);
} catch (IOException ex) {
Logger.getLogger(FileVectorReader.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
}
| gpl-3.0 |
ksedgwic/BTCReceive | src/com/bonsai/btcreceive/BetterListPreference.java | 1217 | // Copyright (C) 2014 Bonsai Software, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 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.bonsai.btcreceive;
import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;
public class BetterListPreference extends ListPreference {
public BetterListPreference(Context context) {
super(context);
}
public BetterListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setValue(String value) {
super.setValue(value);
setSummary(getEntry());
}
}
| gpl-3.0 |
ethanpeng/openacs | acs-ejb/src/java/org/openacs/message/SetParameterAttributesResponse.java | 1308 | /*
*
* Copyright 2007-2012 Audrius Valunas
*
* This file is part of OpenACS.
* OpenACS 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.
*
* OpenACS 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 OpenACS. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openacs.message;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import org.openacs.Message;
public class SetParameterAttributesResponse extends Message {
/** Creates a new instance of RebootResponse */
public SetParameterAttributesResponse() {
name = "SetParameterAttributesResponse";
}
protected void createBody(SOAPBodyElement body, SOAPFactory spf) throws SOAPException {
}
protected void parseBody(SOAPBodyElement body, SOAPFactory f) throws SOAPException {
}
}
| gpl-3.0 |
wolfgang-ch/vtm-with-rcp | VTM_RCP_App/src/vtm/rcp/app/GdxMapApp.java | 5949 | package vtm.rcp.app;
import java.awt.Canvas;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.oscim.awt.AwtGraphics;
import org.oscim.backend.GLAdapter;
import org.oscim.core.MapPosition;
import org.oscim.gdx.GdxAssets;
import org.oscim.gdx.GdxMap;
import org.oscim.gdx.LwjglGL20;
import org.oscim.layers.tile.buildings.BuildingLayer;
import org.oscim.layers.tile.vector.VectorTileLayer;
import org.oscim.layers.tile.vector.labeling.LabelLayer;
import org.oscim.map.Layers;
import org.oscim.theme.ThemeFile;
import org.oscim.theme.VtmThemes;
import org.oscim.tiling.source.OkHttpEngine;
import org.oscim.tiling.source.UrlTileSource;
import org.oscim.tiling.source.oscimap4.OSciMap4TileSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.utils.SharedLibraryLoader;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
public class GdxMapApp extends GdxMap {
private static final String STATE_MAP_POS_X = "STATE_MAP_POS_X"; //$NON-NLS-1$
private static final String STATE_MAP_POS_Y = "STATE_MAP_POS_Y"; //$NON-NLS-1$
private static final String STATE_MAP_POS_ZOOM_LEVEL = "STATE_MAP_POS_ZOOM_LEVEL"; //$NON-NLS-1$
private static final String STATE_MAP_POS_BEARING = "STATE_MAP_POS_BEARING"; //$NON-NLS-1$
private static final String STATE_MAP_POS_SCALE = "STATE_MAP_POS_SCALE"; //$NON-NLS-1$
private static final String STATE_MAP_POS_TILT = "STATE_MAP_POS_TILT"; //$NON-NLS-1$
public static final Logger log = LoggerFactory.getLogger(GdxMapApp.class);
private IDialogSettings _state;
LwjglApplication _lwjglApp;
private enum TileSourceProvider {
CustomTileProvider, //
OpenScienceMap, //
Mapzen, //
}
public GdxMapApp(IDialogSettings state) {
_state = state;
}
protected static LwjglApplicationConfiguration getConfig(String title) {
LwjglApplicationConfiguration.disableAudio = true;
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.title = title != null ? title : "vtm-gdx";
cfg.width = 1200;
cfg.height = 1000;
cfg.stencil = 8;
cfg.samples = 2;
cfg.foregroundFPS = 30;
cfg.backgroundFPS = 10;
cfg.forceExit = false;
return cfg;
}
public static void init() {
// load native library
new SharedLibraryLoader().load("vtm-jni");
// init globals
AwtGraphics.init();
GdxAssets.init("assets/");
GLAdapter.init(new LwjglGL20());
GLAdapter.GDX_DESKTOP_QUIRKS = true;
}
@Override
public void dispose() {
saveState();
super.dispose();
}
private void saveState() {
final MapPosition mapPosition = mMap.getMapPosition();
_state.put(STATE_MAP_POS_X, mapPosition.x);
_state.put(STATE_MAP_POS_Y, mapPosition.y);
_state.put(STATE_MAP_POS_BEARING, mapPosition.bearing);
_state.put(STATE_MAP_POS_SCALE, mapPosition.scale);
_state.put(STATE_MAP_POS_TILT, mapPosition.tilt);
_state.put(STATE_MAP_POS_ZOOM_LEVEL, mapPosition.zoomLevel);
log.debug("Map position: " + mapPosition.toString());
}
void closeMap() {
_lwjglApp.stop();
}
private void restoreState() {
final MapPosition mapPosition = new MapPosition();
mapPosition.x = Util.getStateDouble(_state, STATE_MAP_POS_X, 0.5);
mapPosition.y = Util.getStateDouble(_state, STATE_MAP_POS_Y, 0.5);
mapPosition.bearing = Util.getStateFloat(_state, STATE_MAP_POS_BEARING, 0);
mapPosition.tilt = Util.getStateFloat(_state, STATE_MAP_POS_TILT, 0);
mapPosition.scale = Util.getStateDouble(_state, STATE_MAP_POS_SCALE, 1);
mapPosition.zoomLevel = Util.getStateInt(_state, STATE_MAP_POS_ZOOM_LEVEL, 1);
mMap.setMapPosition(mapPosition);
}
@Override
public void createLayers() {
final Cache cache = new Cache(new File(Util.getCacheDir()), Integer.MAX_VALUE);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.cache(cache)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS);
OkHttpEngine.OkHttpFactory httpFactory = new OkHttpEngine.OkHttpFactory(builder);
UrlTileSource tileSource;
ThemeFile mapTheme;
switch (TileSourceProvider.CustomTileProvider) {
// case CustomTileProvider:
//
// mapTheme = VtmThemes.MAPZEN;
//
// tileSource = CustomTileSource //
// .builder()
// .httpFactory(httpFactory)
// .build();
// break;
// case Mapzen:
//
// mapTheme = VtmThemes.MAPZEN;
//
// // Mapzen requires an API key that the tiles can be loaded
// String apiKey = System.getProperty("MapzenApiKey", "mapzen-xxxxxxx");
//
// tileSource = MapboxTileSource
// .builder()
// .apiKey(apiKey) // Put a proper API key
// .httpFactory(httpFactory)
// .build();
// break;
default:
mapTheme = VtmThemes.DEFAULT;
tileSource = OSciMap4TileSource//
.builder()
.httpFactory(httpFactory)
.build();
break;
}
VectorTileLayer mapLayer = mMap.setBaseMap(tileSource);
mMap.setTheme(mapTheme);
mMap.viewport().setMaxTilt(88);
Layers layers = mMap.layers();
layers.add(new BuildingLayer(mMap, mapLayer));
layers.add(new LabelLayer(mMap, mapLayer));
restoreState();
}
@Override
public void resize(final int w, final int h) {
if (h < 1) {
// Fix exception
//
// Exception in thread "LWJGL Application"
// java.lang.IllegalArgumentException: top == bottom
// at org.oscim.renderer.GLMatrix.frustumM(GLMatrix.java:331)
// at org.oscim.map.ViewController.setScreenSize(ViewController.java:50)
// at org.oscim.gdx.GdxMap.resize(GdxMap.java:122)
// at net.tourbook.map.vtm.VtmMap.resize(VtmMap.java:176)
return;
}
super.resize(w, h);
}
public void run(Canvas canvas) {
init();
_lwjglApp = new LwjglApplication(new GdxMapApp(_state), getConfig(null), canvas);
}
}
| gpl-3.0 |
infiniteautomation/BACnet4J | src/main/java/com/serotonin/bacnet4j/type/constructed/AccessRule.java | 9496 | /*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2015 Infinite Automation Software. All rights reserved.
*
* 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/>.
*
* When signing a commercial license with Infinite Automation Software,
* the following extension to GPL is made. A special exception to the GPL is
* included to allow you to distribute a combined work that includes BAcnet4J
* without being obliged to provide the source code for any proprietary components.
*
* See www.infiniteautomation.com for commercial license options.
*
* @author Matthew Lohbihler
*/
package com.serotonin.bacnet4j.type.constructed;
import com.serotonin.bacnet4j.exception.BACnetErrorException;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import java.util.Map;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.type.primitive.Boolean;
import com.serotonin.bacnet4j.type.primitive.Enumerated;
import com.serotonin.bacnet4j.util.sero.ByteQueue;
public class AccessRule extends BaseType {
private final TimeRangeSpecifier timeRangeSpecifier;
private final DeviceObjectPropertyReference timeRange;
private final LocationSpecifier locationSpecifier;
private final DeviceObjectReference location;
private final Boolean enable;
public AccessRule(final Boolean enable) {
this(TimeRangeSpecifier.always, null, LocationSpecifier.all, null, enable);
}
public AccessRule(final DeviceObjectPropertyReference timeRange, final Boolean enable) {
this(TimeRangeSpecifier.specified, timeRange, LocationSpecifier.all, null, enable);
}
public AccessRule(final DeviceObjectReference location, final Boolean enable) {
this(TimeRangeSpecifier.always, null, LocationSpecifier.specified, location, enable);
}
public AccessRule(final DeviceObjectPropertyReference timeRange, final DeviceObjectReference location,
final Boolean enable) {
this(TimeRangeSpecifier.specified, timeRange, LocationSpecifier.specified, location, enable);
}
private AccessRule(final TimeRangeSpecifier timeRangeSpecifier, final DeviceObjectPropertyReference timeRange,
final LocationSpecifier locationSpecifier, final DeviceObjectReference location, final Boolean enable) {
this.timeRangeSpecifier = timeRangeSpecifier;
this.timeRange = timeRange;
this.locationSpecifier = locationSpecifier;
this.location = location;
this.enable = enable;
}
@Override
public void write(final ByteQueue queue) {
write(queue, timeRangeSpecifier, 0);
writeOptional(queue, timeRange, 1);
write(queue, locationSpecifier, 2);
writeOptional(queue, location, 3);
write(queue, enable, 4);
}
public AccessRule(final ByteQueue queue) throws BACnetException {
timeRangeSpecifier = read(queue, TimeRangeSpecifier.class, 0);
timeRange = readOptional(queue, DeviceObjectPropertyReference.class, 1);
locationSpecifier = read(queue, LocationSpecifier.class, 2);
location = readOptional(queue, DeviceObjectReference.class, 3);
enable = read(queue, Boolean.class, 4);
}
public TimeRangeSpecifier getTimeRangeSpecifier() {
return timeRangeSpecifier;
}
public DeviceObjectPropertyReference getTimeRange() {
return timeRange;
}
public LocationSpecifier getLocationSpecifier() {
return locationSpecifier;
}
public DeviceObjectReference getLocation() {
return location;
}
public Boolean getEnable() {
return enable;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (enable == null ? 0 : enable.hashCode());
result = prime * result + (location == null ? 0 : location.hashCode());
result = prime * result + (locationSpecifier == null ? 0 : locationSpecifier.hashCode());
result = prime * result + (timeRange == null ? 0 : timeRange.hashCode());
result = prime * result + (timeRangeSpecifier == null ? 0 : timeRangeSpecifier.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final AccessRule other = (AccessRule) obj;
if (enable == null) {
if (other.enable != null)
return false;
} else if (!enable.equals(other.enable))
return false;
if (location == null) {
if (other.location != null)
return false;
} else if (!location.equals(other.location))
return false;
if (locationSpecifier == null) {
if (other.locationSpecifier != null)
return false;
} else if (!locationSpecifier.equals(other.locationSpecifier))
return false;
if (timeRange == null) {
if (other.timeRange != null)
return false;
} else if (!timeRange.equals(other.timeRange))
return false;
if (timeRangeSpecifier == null) {
if (other.timeRangeSpecifier != null)
return false;
} else if (!timeRangeSpecifier.equals(other.timeRangeSpecifier))
return false;
return true;
}
public static class TimeRangeSpecifier extends Enumerated {
public static final TimeRangeSpecifier specified = new TimeRangeSpecifier(0);
public static final TimeRangeSpecifier always = new TimeRangeSpecifier(1);
private static final Map<Integer, Enumerated> idMap = new HashMap<>();
private static final Map<String, Enumerated> nameMap = new HashMap<>();
private static final Map<Integer, String> prettyMap = new HashMap<>();
static {
Enumerated.init(MethodHandles.lookup().lookupClass(), idMap, nameMap, prettyMap);
}
public static TimeRangeSpecifier forId(final int id) {
TimeRangeSpecifier e = (TimeRangeSpecifier) idMap.get(id);
if (e == null)
e = new TimeRangeSpecifier(id);
return e;
}
public static String nameForId(final int id) {
return prettyMap.get(id);
}
public static TimeRangeSpecifier forName(final String name) {
return (TimeRangeSpecifier) Enumerated.forName(nameMap, name);
}
public static int size() {
return idMap.size();
}
private TimeRangeSpecifier(final int value) {
super(value);
}
public TimeRangeSpecifier(final ByteQueue queue) throws BACnetErrorException {
super(queue);
}
@Override
public String toString() {
return super.toString(prettyMap);
}
}
public static class LocationSpecifier extends Enumerated {
public static final LocationSpecifier specified = new LocationSpecifier(0);
public static final LocationSpecifier all = new LocationSpecifier(1);
private static final Map<Integer, Enumerated> idMap = new HashMap<>();
private static final Map<String, Enumerated> nameMap = new HashMap<>();
private static final Map<Integer, String> prettyMap = new HashMap<>();
static {
Enumerated.init(MethodHandles.lookup().lookupClass(), idMap, nameMap, prettyMap);
}
public static LocationSpecifier forId(final int id) {
LocationSpecifier e = (LocationSpecifier) idMap.get(id);
if (e == null)
e = new LocationSpecifier(id);
return e;
}
public static String nameForId(final int id) {
return prettyMap.get(id);
}
public static LocationSpecifier forName(final String name) {
return (LocationSpecifier) Enumerated.forName(nameMap, name);
}
public static int size() {
return idMap.size();
}
private LocationSpecifier(final int value) {
super(value);
}
public LocationSpecifier(final ByteQueue queue) throws BACnetErrorException {
super(queue);
}
@Override
public String toString() {
return super.toString(prettyMap);
}
}
@Override
public String toString() {
return "AccessRule [timeRangeSpecifier=" + timeRangeSpecifier + ", timeRange=" + timeRange + ", locationSpecifier=" + locationSpecifier + ", location=" + location + ", enable=" + enable + ']';
}
}
| gpl-3.0 |
goodcrypto/goodcrypto-oce | java/com/goodcrypto/crypto/key/GPGPluginConstants.java | 435 | /*
* GPGPluginConstants.java
*
* Last modified: 2003-12-23
*/
package com.goodcrypto.crypto.key;
/** Constant declarations for the GNU Privacy Guard key plugin.
*
* <p>Copyright 2002-2003 GoodCrypto
* <br>Last modified: 2004-01-18
*
* @author GoodCrypto
* @version 0.1
*/
public interface GPGPluginConstants {
/** Name of the plugin. */
static final String Name = "com.goodcrypto.crypto.key.GPGPlugin";
} | gpl-3.0 |
avdata99/SIAT | siat-1.0-SOURCE/src/iface/src/ar/gov/rosario/siat/exe/iface/util/ExeSecurityConstants.java | 2596 | //Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package ar.gov.rosario.siat.exe.iface.util;
/**
* En esta clase se definen las descripciones de los errores que estas asociaos a los VO.
*
* @author Tecso
*
*/
public class ExeSecurityConstants {
// ---> ABM Exencion
public static final String ABM_EXENCION = "ABM_Exencion";
public static final String ABM_EXENCION_ENC = "ABM_ExencionEnc";
// Conceptos de la exencion
public static final String ABM_EXERECCON = "ABM_ExeRecCon";
// <--- ABM Exencion
// ---> ABM Contrib. exento
public static final String ABM_CONTRIBEXE = "ABM_ContribExe";
// <--- ABM Contrib. exento
// ---> Administrar Exenciones
public static final String ABM_CUEEXE = "ABM_CueExe";
/** Para usuarios de emision, viene un idExencion preseteado */
public static final String ABM_CUEEXE_EMI = "ABM_CueExeEmi";
public static final String ABM_CUEEXE_ENC = "ABM_CueExeEnc";
public static final String MTD_MODIFICAR_HISESTCUEEXE = "modificarHisEstCueExe";
public static final String MTD_CAMBIARESTADO = "cambiarEstado";
public static final String MTD_AGREGARSOLICITUD = "agregarSolicitud";
public static final String ABM_HISESTCUEEXE = "ABM_HisEstCueExe";
public static final String ADM_DEUDA_EXENCION = "ADM_DeudaExencion";
// <--- Administrar Exenciones
// ---> ADM de envios de solicitud de exencion
public static final String ADM_SOLCUEEXE_ENVIOS = "ADM_SolCueExe_envios";
public static final String MTD_IMPRIMIR = "imprimir";
public static final String MTD_ENVIAR_CATASTRO = "enviarCatastro";
public static final String MTD_ENVIAR_SINTYS = "enviarSintys";
public static final String MTD_ENVIAR_DG = "enviarDG";
// <--- ADM de envios de solicitud de exencion
// ---> ABM Tipo Sujeto
public static final String ABM_TIPOSUJETO = "ABM_TipoSujeto";
public static final String ABM_TIPOSUJETO_ENC = "ABM_TipoSujetoEnc";
// <--- ABM Tipo Sujeto
// ---> ABM TipSujExe
public static final String ABM_TIPSUJEXE = "ABM_TipSujExe";
// <--- ABM TipSujExe
// ---> ABM SolCueExeConviv
public static final String ABM_CUEEXECONVIV = "ABM_CueExeConviv";
// <--- ABM SolCueExeConviv
// ---> ABM Estado Cuenta/Exencion
public static final String ABM_ESTADOCUEEXE = "ABM_EstadoCueExe";
public static final String ABM_ESTADOCUEEXE_ENC = "ABM_EstadoCueExeEnc";
// <--- ABM Estado Cuenta/Exencion
} | gpl-3.0 |
galme/ROLF-EV3 | EV3VideoControl_Android/app/src/main/java/com/galuu/ev3videocontrol/streaming/rtsp/RtspClient.java | 19888 | /*
* Copyright (C) 2011-2015 GUIGUI Simon, fyhertz@gmail.com
*
* This file is part of Spydroid (http://code.google.com/p/spydroid-ipcamera/)
*
* Spydroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.galuu.ev3videocontrol.streaming.rtsp;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.Semaphore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.galuu.ev3videocontrol.streaming.Session;
import com.galuu.ev3videocontrol.streaming.Stream;
import com.galuu.ev3videocontrol.streaming.rtp.RtpSocket;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
/**
* RFC 2326.
* A basic and asynchronous RTSP client.
* The original purpose of this class was to implement a small RTSP client compatible with Wowza.
* It implements Digest Access Authentication according to RFC 2069.
*/
public class RtspClient {
public final static String TAG = "RtspClient";
/** Message sent when the connection to the RTSP server failed. */
public final static int ERROR_CONNECTION_FAILED = 0x01;
/** Message sent when the credentials are wrong. */
public final static int ERROR_WRONG_CREDENTIALS = 0x03;
/** Use this to use UDP for the transport protocol. */
public final static int TRANSPORT_UDP = RtpSocket.TRANSPORT_UDP;
/** Use this to use TCP for the transport protocol. */
public final static int TRANSPORT_TCP = RtpSocket.TRANSPORT_TCP;
/**
* Message sent when the connection with the RTSP server has been lost for
* some reason (for example, the user is going under a bridge).
* When the connection with the server is lost, the client will automatically try to
* reconnect as long as {@link #stopStream()} is not called.
**/
public final static int ERROR_CONNECTION_LOST = 0x04;
/**
* Message sent when the connection with the RTSP server has been reestablished.
* When the connection with the server is lost, the client will automatically try to
* reconnect as long as {@link #stopStream()} is not called.
*/
public final static int MESSAGE_CONNECTION_RECOVERED = 0x05;
private final static int STATE_STARTED = 0x00;
private final static int STATE_STARTING = 0x01;
private final static int STATE_STOPPING = 0x02;
private final static int STATE_STOPPED = 0x03;
private int mState = 0;
private class Parameters {
public String host;
public String username;
public String password;
public String path;
public Session session;
public int port;
public int transport;
public Parameters clone() {
Parameters params = new Parameters();
params.host = host;
params.username = username;
params.password = password;
params.path = path;
params.session = session;
params.port = port;
params.transport = transport;
return params;
}
}
private Parameters mTmpParameters;
private Parameters mParameters;
private int mCSeq;
private Socket mSocket;
private String mSessionID;
private String mAuthorization;
private BufferedReader mBufferedReader;
private OutputStream mOutputStream;
private Callback mCallback;
private Handler mMainHandler;
private Handler mHandler;
/**
* The callback interface you need to implement to know what's going on with the
* RTSP server (for example your Wowza Media Server).
*/
public interface Callback {
public void onRtspUpdate(int message, Exception exception);
}
public RtspClient() {
mCSeq = 0;
mTmpParameters = new Parameters();
mTmpParameters.port = 1935;
mTmpParameters.path = "/";
mTmpParameters.transport = TRANSPORT_UDP;
mAuthorization = null;
mCallback = null;
mMainHandler = new Handler(Looper.getMainLooper());
mState = STATE_STOPPED;
final Semaphore signal = new Semaphore(0);
new HandlerThread("com.galuu.ev3videocontrol.streaming.RtspClient"){
@Override
protected void onLooperPrepared() {
mHandler = new Handler();
signal.release();
}
}.start();
signal.acquireUninterruptibly();
}
/**
* Sets the callback interface that will be called on status updates of the connection
* with the RTSP server.
* @param cb The implementation of the {@link Callback} interface
*/
public void setCallback(Callback cb) {
mCallback = cb;
}
/**
* The {@link Session} that will be used to stream to the server.
* If not called before {@link #startStream()}, a it will be created.
*/
public void setSession(Session session) {
mTmpParameters.session = session;
}
public Session getSession() {
return mTmpParameters.session;
}
/**
* Sets the destination address of the RTSP server.
* @param host The destination address
* @param port The destination port
*/
public void setServerAddress(String host, int port) {
mTmpParameters.port = port;
mTmpParameters.host = host;
}
/**
* If authentication is enabled on the server, you need to call this with a valid login/password pair.
* Only implements Digest Access Authentication according to RFC 2069.
* @param username The login
* @param password The password
*/
public void setCredentials(String username, String password) {
mTmpParameters.username = username;
mTmpParameters.password = password;
}
/**
* The path to which the stream will be sent to.
* @param path The path
*/
public void setStreamPath(String path) {
mTmpParameters.path = path;
}
/**
* Call this with {@link #TRANSPORT_TCP} or {@value #TRANSPORT_UDP} to choose the
* transport protocol that will be used to send RTP/RTCP packets.
* Not ready yet !
*/
public void setTransportMode(int mode) {
mTmpParameters.transport = mode;
}
public boolean isStreaming() {
return mState==STATE_STARTED|mState==STATE_STARTING;
}
/**
* Connects to the RTSP server to publish the stream, and the effectively starts streaming.
* You need to call {@link #setServerAddress(String, int)} and optionally {@link #setSession(Session)}
* and {@link #setCredentials(String, String)} before calling this.
* Should be called of the main thread !
*/
public void startStream() {
if (mTmpParameters.host == null) throw new IllegalStateException("setServerAddress(String,int) has not been called !");
if (mTmpParameters.session == null) throw new IllegalStateException("setSession() has not been called !");
mHandler.post(new Runnable () {
@Override
public void run() {
if (mState != STATE_STOPPED) return;
mState = STATE_STARTING;
Log.d(TAG,"Connecting to RTSP server...");
// If the user calls some methods to configure the client, it won't modify its behavior until the stream is restarted
mParameters = mTmpParameters.clone();
mParameters.session.setDestination(mTmpParameters.host);
try {
mParameters.session.syncConfigure();
} catch (Exception e) {
mParameters.session = null;
mState = STATE_STOPPED;
return;
}
try {
tryConnection();
} catch (Exception e) {
postError(ERROR_CONNECTION_FAILED, e);
abort();
return;
}
try {
mParameters.session.syncStart();
mState = STATE_STARTED;
if (mParameters.transport == TRANSPORT_UDP) {
mHandler.post(mConnectionMonitor);
}
} catch (Exception e) {
abort();
}
}
});
}
/**
* Stops the stream, and informs the RTSP server.
*/
public void stopStream() {
mHandler.post(new Runnable () {
@Override
public void run() {
if (mParameters != null && mParameters.session != null) {
mParameters.session.stop();
}
if (mState != STATE_STOPPED) {
mState = STATE_STOPPING;
abort();
}
}
});
}
public void release() {
stopStream();
mHandler.getLooper().quit();
}
private void abort() {
try {
sendRequestTeardown();
} catch (Exception ignore) {}
try {
mSocket.close();
} catch (Exception ignore) {}
mHandler.removeCallbacks(mConnectionMonitor);
mHandler.removeCallbacks(mRetryConnection);
mState = STATE_STOPPED;
}
private void tryConnection() throws IOException {
mCSeq = 0;
mSocket = new Socket(mParameters.host, mParameters.port);
mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
mOutputStream = new BufferedOutputStream(mSocket.getOutputStream());
sendRequestAnnounce();
sendRequestSetup();
sendRequestRecord();
}
/**
* Forges and sends the ANNOUNCE request
*/
private void sendRequestAnnounce() throws IllegalStateException, SocketException, IOException {
String body = mParameters.session.getSessionDescription();
String request = "ANNOUNCE rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" +
"CSeq: " + (++mCSeq) + "\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Content-Type: application/sdp\r\n\r\n" +
body;
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response response = Response.parseResponse(mBufferedReader);
if (response.headers.containsKey("server")) {
Log.v(TAG,"RTSP server name:" + response.headers.get("server"));
} else {
Log.v(TAG,"RTSP server name unknown");
}
if (response.headers.containsKey("session")) {
try {
Matcher m = Response.rexegSession.matcher(response.headers.get("session"));
m.find();
mSessionID = m.group(1);
} catch (Exception e) {
throw new IOException("Invalid response from server. Session id: "+mSessionID);
}
}
if (response.status == 401) {
String nonce, realm;
Matcher m;
if (mParameters.username == null || mParameters.password == null) throw new IllegalStateException("Authentication is enabled and setCredentials(String,String) was not called !");
try {
m = Response.rexegAuthenticate.matcher(response.headers.get("www-authenticate")); m.find();
nonce = m.group(2);
realm = m.group(1);
} catch (Exception e) {
throw new IOException("Invalid response from server");
}
String uri = "rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path;
String hash1 = computeMd5Hash(mParameters.username+":"+m.group(1)+":"+mParameters.password);
String hash2 = computeMd5Hash("ANNOUNCE"+":"+uri);
String hash3 = computeMd5Hash(hash1+":"+m.group(2)+":"+hash2);
mAuthorization = "Digest username=\""+mParameters.username+"\",realm=\""+realm+"\",nonce=\""+nonce+"\",uri=\""+uri+"\",response=\""+hash3+"\"";
request = "ANNOUNCE rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" +
"CSeq: " + (++mCSeq) + "\r\n" +
"Content-Length: " + body.length() + "\r\n" +
"Authorization: " + mAuthorization + "\r\n" +
"Session: " + mSessionID + "\r\n" +
"Content-Type: application/sdp\r\n\r\n" +
body;
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
response = Response.parseResponse(mBufferedReader);
if (response.status == 401) throw new RuntimeException("Bad credentials !");
} else if (response.status == 403) {
throw new RuntimeException("Access forbidden !");
}
}
/**
* Forges and sends the SETUP request
*/
private void sendRequestSetup() throws IllegalStateException, SocketException, IOException {
for (int i=0;i<2;i++) {
Stream stream = mParameters.session.getTrack(i);
if (stream != null) {
String params = mParameters.transport==TRANSPORT_TCP ?
("TCP;interleaved="+2*i+"-"+(2*i+1)) : ("UDP;unicast;client_port="+(5000+2*i)+"-"+(5000+2*i+1)+";mode=receive");
String request = "SETUP rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+"/trackID="+i+" RTSP/1.0\r\n" +
"Transport: RTP/AVP/"+params+"\r\n" +
addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response response = Response.parseResponse(mBufferedReader);
Matcher m;
if (response.headers.containsKey("session")) {
try {
m = Response.rexegSession.matcher(response.headers.get("session"));
m.find();
mSessionID = m.group(1);
} catch (Exception e) {
throw new IOException("Invalid response from server. Session id: "+mSessionID);
}
}
if (mParameters.transport == TRANSPORT_UDP) {
try {
m = Response.rexegTransport.matcher(response.headers.get("transport")); m.find();
stream.setDestinationPorts(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)));
Log.d(TAG, "Setting destination ports: "+Integer.parseInt(m.group(3))+", "+Integer.parseInt(m.group(4)));
} catch (Exception e) {
e.printStackTrace();
int[] ports = stream.getDestinationPorts();
Log.d(TAG,"Server did not specify ports, using default ports: "+ports[0]+"-"+ports[1]);
}
} else {
stream.setOutputStream(mOutputStream, (byte)(2*i));
}
}
}
}
/**
* Forges and sends the RECORD request
*/
private void sendRequestRecord() throws IllegalStateException, SocketException, IOException {
String request = "RECORD rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" +
"Range: npt=0.000-\r\n" +
addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response.parseResponse(mBufferedReader);
}
/**
* Forges and sends the TEARDOWN request
*/
private void sendRequestTeardown() throws IOException {
String request = "TEARDOWN rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" + addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
}
/**
* Forges and sends the OPTIONS request
*/
private void sendRequestOption() throws IOException {
String request = "OPTIONS rtsp://"+mParameters.host+":"+mParameters.port+mParameters.path+" RTSP/1.0\r\n" + addHeaders();
Log.i(TAG,request.substring(0, request.indexOf("\r\n")));
mOutputStream.write(request.getBytes("UTF-8"));
mOutputStream.flush();
Response.parseResponse(mBufferedReader);
}
private String addHeaders() {
return "CSeq: " + (++mCSeq) + "\r\n" +
"Content-Length: 0\r\n" +
"Session: " + mSessionID + "\r\n" +
// For some reason you may have to remove last "\r\n" in the next line to make the RTSP client work with your wowza server :/
(mAuthorization != null ? "Authorization: " + mAuthorization + "\r\n":"") + "\r\n";
}
/**
* If the connection with the RTSP server is lost, we try to reconnect to it as
* long as {@link #stopStream()} is not called.
*/
private Runnable mConnectionMonitor = new Runnable() {
@Override
public void run() {
if (mState == STATE_STARTED) {
try {
// We poll the RTSP server with OPTION requests
sendRequestOption();
mHandler.postDelayed(mConnectionMonitor, 6000);
} catch (IOException e) {
// Happens if the OPTION request fails
postMessage(ERROR_CONNECTION_LOST);
Log.e(TAG, "Connection lost with the server...");
mParameters.session.stop();
mHandler.post(mRetryConnection);
}
}
}
};
/** Here, we try to reconnect to the RTSP. */
private Runnable mRetryConnection = new Runnable() {
@Override
public void run() {
if (mState == STATE_STARTED) {
try {
Log.e(TAG, "Trying to reconnect...");
tryConnection();
try {
mParameters.session.start();
mHandler.post(mConnectionMonitor);
postMessage(MESSAGE_CONNECTION_RECOVERED);
} catch (Exception e) {
abort();
}
} catch (IOException e) {
mHandler.postDelayed(mRetryConnection,1000);
}
}
}
};
final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
/** Needed for the Digest Access Authentication. */
private String computeMd5Hash(String buffer) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
return bytesToHex(md.digest(buffer.getBytes("UTF-8")));
} catch (NoSuchAlgorithmException ignore) {
} catch (UnsupportedEncodingException e) {}
return "";
}
private void postMessage(final int message) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onRtspUpdate(message, null);
}
}
});
}
private void postError(final int message, final Exception e) {
mMainHandler.post(new Runnable() {
@Override
public void run() {
if (mCallback != null) {
mCallback.onRtspUpdate(message, e);
}
}
});
}
static class Response {
// Parses method & uri
public static final Pattern regexStatus = Pattern.compile("RTSP/\\d.\\d (\\d+) (\\w+)",Pattern.CASE_INSENSITIVE);
// Parses a request header
public static final Pattern rexegHeader = Pattern.compile("(\\S+):(.+)",Pattern.CASE_INSENSITIVE);
// Parses a WWW-Authenticate header
public static final Pattern rexegAuthenticate = Pattern.compile("realm=\"(.+)\",\\s+nonce=\"(\\w+)\"",Pattern.CASE_INSENSITIVE);
// Parses a Session header
public static final Pattern rexegSession = Pattern.compile("(\\d+)",Pattern.CASE_INSENSITIVE);
// Parses a Transport header
public static final Pattern rexegTransport = Pattern.compile("client_port=(\\d+)-(\\d+).+server_port=(\\d+)-(\\d+)",Pattern.CASE_INSENSITIVE);
public int status;
public HashMap<String,String> headers = new HashMap<String,String>();
/** Parse the method, URI & headers of a RTSP request */
public static Response parseResponse(BufferedReader input) throws IOException, IllegalStateException, SocketException {
Response response = new Response();
String line;
Matcher matcher;
// Parsing request method & URI
if ((line = input.readLine())==null) throw new SocketException("Connection lost");
matcher = regexStatus.matcher(line);
matcher.find();
response.status = Integer.parseInt(matcher.group(1));
// Parsing headers of the request
while ( (line = input.readLine()) != null) {
//Log.e(TAG,"l: "+line.length()+", c: "+line);
if (line.length()>3) {
matcher = rexegHeader.matcher(line);
matcher.find();
response.headers.put(matcher.group(1).toLowerCase(Locale.US),matcher.group(2));
} else {
break;
}
}
if (line==null) throw new SocketException("Connection lost");
Log.d(TAG, "Response from server: "+response.status);
return response;
}
}
}
| gpl-3.0 |
chrxn/wsdot-mobile-app | src/main/java/gov/wa/wsdot/mobile/client/activities/socialmedia/youtube/YouTubeDetailsViewGwtImpl.java | 3034 | /*
* Copyright (c) 2015 Washington State Department of Transportation
*
* 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 gov.wa.wsdot.mobile.client.activities.socialmedia.youtube;
import gov.wa.wsdot.mobile.client.widget.button.image.BackImageButton;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.mgwt.dom.client.event.tap.TapEvent;
import com.googlecode.mgwt.ui.client.MGWT;
import com.googlecode.mgwt.ui.client.widget.header.HeaderTitle;
import com.googlecode.mgwt.ui.client.widget.panel.flex.FlexSpacer;
import com.googlecode.mgwt.ui.client.widget.panel.scroll.ScrollPanel;
public class YouTubeDetailsViewGwtImpl extends Composite implements
YouTubeDetailsView {
/**
* The UiBinder interface.
*/
interface YouTubeDetailsViewGwtImplUiBinder extends
UiBinder<Widget, YouTubeDetailsViewGwtImpl> {
}
/**
* The UiBinder used to generate the view.
*/
private static YouTubeDetailsViewGwtImplUiBinder uiBinder = GWT
.create(YouTubeDetailsViewGwtImplUiBinder.class);
@UiField
BackImageButton backButton;
@UiField
FlexSpacer leftFlexSpacer;
@UiField
ScrollPanel scrollPanel;
@UiField
HeaderTitle title;
@UiField
HTML embedContent;
@UiField
HTML description;
private Presenter presenter;
public YouTubeDetailsViewGwtImpl() {
initWidget(uiBinder.createAndBindUi(this));
if (MGWT.getOsDetection().isAndroid()) {
leftFlexSpacer.setVisible(false);
scrollPanel.setBounce(false);
}
}
@UiHandler("backButton")
protected void onBackButtonPressed(TapEvent event) {
if (presenter != null) {
presenter.onBackButtonPressed();
}
}
@Override
public void setTitle(String title) {
this.title.setText(title);
}
@Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
@Override
public void setEmbedContent(String videoId) {
this.embedContent
.setHTML("<iframe id='ytplayer' type='text/html' src='http://www.youtube.com/embed/"
+ videoId + "' frameborder='0' />");
}
@Override
public void setDescription(String description) {
this.description.setHTML(description);
}
} | gpl-3.0 |
open-source-java/ElsuFoundation | TestValidation/src/filters/MapPointType.java | 976 | package filters;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class MapPointType implements Serializable {
private static final long serialVersionUID = 8330339909128827529L;
private Double longitude;
private Double latitude;
public MapPointType() { // needed for JAXB
initialize();
}
private void initialize() {
}
public Double getLongitude() {
return this.longitude;
}
public void setLongitude(Double pLongitude) {
this.longitude = pLongitude;
}
public Double getLatitude() {
return this.latitude;
}
public void setLatitude(Double pLatitude) {
this.latitude = pLatitude;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("{");
result.append("longitude: " + longitude.toString() + ", " );
result.append("latitude: " + latitude.toString() + ", " );
result.append("}");
return result.toString();
}
}
| gpl-3.0 |
sp-apertus/openpnp | src/main/java/org/openpnp/machine/reference/wizards/ReferenceMachineConfigurationWizard.java | 7532 | package org.openpnp.machine.reference.wizards;
import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.openpnp.gui.components.ComponentDecorators;
import org.openpnp.gui.components.LocationButtonsPanel;
import org.openpnp.gui.support.AbstractConfigurationWizard;
import org.openpnp.gui.support.DoubleConverter;
import org.openpnp.gui.support.LengthConverter;
import org.openpnp.gui.support.MessageBoxes;
import org.openpnp.gui.support.MutableLocationProxy;
import org.openpnp.machine.openbuilds.OpenBuildsDriver;
import org.openpnp.machine.reference.ReferenceDriver;
import org.openpnp.machine.reference.ReferenceMachine;
import org.openpnp.machine.reference.driver.GcodeDriver;
import org.openpnp.machine.reference.driver.LinuxCNC;
import org.openpnp.machine.reference.driver.NullDriver;
import org.openpnp.model.Configuration;
import org.simpleframework.xml.Element;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
public class ReferenceMachineConfigurationWizard extends AbstractConfigurationWizard {
private final ReferenceMachine machine;
private JComboBox comboBoxDriver;
private JCheckBox checkBoxHomeAfterEnabled;
private String driverClassName;
private JTextField discardXTf;
private JTextField discardYTf;
private JTextField discardZTf;
private JTextField discardCTf;
public ReferenceMachineConfigurationWizard(ReferenceMachine machine) {
this.machine = machine;
JPanel panelGeneral = new JPanel();
contentPanel.add(panelGeneral);
panelGeneral.setBorder(new TitledBorder(null, "General", TitledBorder.LEADING,
TitledBorder.TOP, null, null));
panelGeneral.setLayout(new FormLayout(new ColumnSpec[] {
FormSpecs.RELATED_GAP_COLSPEC,
FormSpecs.DEFAULT_COLSPEC,
FormSpecs.RELATED_GAP_COLSPEC,
FormSpecs.DEFAULT_COLSPEC,},
new RowSpec[] {
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,}));
JLabel lblDriver = new JLabel("Driver");
panelGeneral.add(lblDriver, "2, 2");
comboBoxDriver = new JComboBox();
panelGeneral.add(comboBoxDriver, "2, 4");
checkBoxHomeAfterEnabled = new JCheckBox("Home after ENABLED?");
panelGeneral.add(checkBoxHomeAfterEnabled, "2, 6");
comboBoxDriver.addItem(NullDriver.class.getCanonicalName());
comboBoxDriver.addItem(GcodeDriver.class.getCanonicalName());
comboBoxDriver.addItem(LinuxCNC.class.getCanonicalName());
comboBoxDriver.addItem(OpenBuildsDriver.class.getCanonicalName());
JPanel panelLocations = new JPanel();
panelLocations.setBorder(new TitledBorder(null, "Locations", TitledBorder.LEADING,
TitledBorder.TOP, null, null));
contentPanel.add(panelLocations);
panelLocations.setLayout(new FormLayout(
new ColumnSpec[] {FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,
FormSpecs.RELATED_GAP_COLSPEC, FormSpecs.DEFAULT_COLSPEC,},
new RowSpec[] {FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC,}));
JLabel lblX = new JLabel("X");
panelLocations.add(lblX, "4, 2");
lblX.setHorizontalAlignment(SwingConstants.CENTER);
JLabel lblY = new JLabel("Y");
panelLocations.add(lblY, "6, 2");
lblY.setHorizontalAlignment(SwingConstants.CENTER);
JLabel lblZ = new JLabel("Z");
panelLocations.add(lblZ, "8, 2");
lblZ.setHorizontalAlignment(SwingConstants.CENTER);
JLabel lblRotation = new JLabel("Rotation");
panelLocations.add(lblRotation, "10, 2");
lblRotation.setHorizontalAlignment(SwingConstants.CENTER);
JLabel lblDiscardPoint = new JLabel("Discard Location");
panelLocations.add(lblDiscardPoint, "2, 4");
discardXTf = new JTextField();
panelLocations.add(discardXTf, "4, 4");
discardXTf.setColumns(5);
discardYTf = new JTextField();
panelLocations.add(discardYTf, "6, 4");
discardYTf.setColumns(5);
discardZTf = new JTextField();
panelLocations.add(discardZTf, "8, 4");
discardZTf.setColumns(5);
discardCTf = new JTextField();
panelLocations.add(discardCTf, "10, 4");
discardCTf.setColumns(5);
LocationButtonsPanel locationButtonsPanel =
new LocationButtonsPanel(discardXTf, discardYTf, discardZTf, discardCTf);
panelLocations.add(locationButtonsPanel, "12, 4");
this.driverClassName = machine.getDriver().getClass().getCanonicalName();
}
@Override
public void createBindings() {
DoubleConverter doubleConverter =
new DoubleConverter(Configuration.get().getLengthDisplayFormat());
LengthConverter lengthConverter = new LengthConverter();
addWrappedBinding(this, "driverClassName", comboBoxDriver, "selectedItem");
addWrappedBinding(machine, "homeAfterEnabled", checkBoxHomeAfterEnabled, "selected");
MutableLocationProxy discardLocation = new MutableLocationProxy();
bind(UpdateStrategy.READ_WRITE, machine, "discardLocation", discardLocation, "location");
addWrappedBinding(discardLocation, "lengthX", discardXTf, "text", lengthConverter);
addWrappedBinding(discardLocation, "lengthY", discardYTf, "text", lengthConverter);
addWrappedBinding(discardLocation, "lengthZ", discardZTf, "text", lengthConverter);
addWrappedBinding(discardLocation, "rotation", discardCTf, "text", doubleConverter);
ComponentDecorators.decorateWithAutoSelectAndLengthConversion(discardXTf);
ComponentDecorators.decorateWithAutoSelectAndLengthConversion(discardYTf);
ComponentDecorators.decorateWithAutoSelectAndLengthConversion(discardZTf);
ComponentDecorators.decorateWithAutoSelectAndLengthConversion(discardCTf);
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) throws Exception {
if (machine.getDriver().getClass().getCanonicalName().equals(driverClassName)) {
return;
}
ReferenceDriver driver = (ReferenceDriver) Class.forName(driverClassName).newInstance();
driver.createDefaults();
machine.setDriver(driver);
this.driverClassName = driverClassName;
MessageBoxes.infoBox("Restart Required",
"Please restart OpenPnP for the changes to take effect.");
}
}
| gpl-3.0 |
wavesoft/karbon | src/KAnalyzer/Utils/GridPresenter.java | 8819 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* GridPresenter.java
*
* Created on 20 Αυγ 2010, 5:39:54 μμ
*/
package KAnalyzer.Utils;
import javax.swing.table.DefaultTableModel;
import KAnalyzer.Utils.ReportTools.ReportFormat;
import javax.swing.table.TableColumnModel;
/**
*
* @author Ioannis Charalampidis <johnys2@gmail.com>
*/
public class GridPresenter extends KAnalyzer.API.TPresenter {
DefaultTableModel tableModel;
private Object[][] columnInfo;
/** Creates new form GridPresenter */
public GridPresenter() {
initComponents();
tableModel = new DefaultTableModel();
jGridData.setModel(tableModel);
}
/** 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jGridData = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jToggleButton1 = new javax.swing.JToggleButton();
jGridData.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(jGridData);
jButton1.setText("Save to file");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jToggleButton1.setText("Include to report");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToggleButton1))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jToggleButton1)))
);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
ReportTools.saveReportDialog(this);
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
public javax.swing.JTable jGridData;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToggleButton jToggleButton1;
// End of variables declaration//GEN-END:variables
@Override
public void reset() {
while (tableModel.getRowCount() > 0) {
tableModel.removeRow(0);
}
}
/*
* Set the column information as a double-vector format:
* {
* { <String: Name>, <class: Data class>, <Integer: Width>
* }
*/
public void setColumnInfo(Object[][] Info) {
// Create new
for (int c = 0; c < Info.length; c++) {
if (Info[c].length == 0) {
Info[c] = new Object[]{ "", String.class, 400 };
} else if (Info[c].length == 1) {
Info[c] = new Object[]{ Info[c][0], String.class, 400 };
} else if (Info[c].length == 2) {
Info[c] = new Object[]{ Info[c][0], Info[c][1], 400 };
}
tableModel.addColumn((String)Info[c][0]);
}
columnInfo = Info;
}
public void addColumn(String Name) {
tableModel.addColumn(Name);
}
public void addColumn(String Name, Integer Width) {
tableModel.addColumn(Name);
TableColumnModel model = jGridData.getColumnModel();
int n = model.getColumnCount();
for (int i = 0; i < n; i++) {
if (i == n-1) {
model.getColumn(i).setPreferredWidth(Width);
}
}
}
public void addRow(Object[] Data) {
tableModel.addRow(Data);
}
private String padToLength(String src, Integer length) {
return String.format("%1$-" + length + "s", src);
}
@Override
public String getReport(ReportFormat format) {
String buffer = "", cellStr = "";
Integer cols = tableModel.getColumnCount();
Integer rows = tableModel.getRowCount();
Integer totalSize = 0;
Integer[] colSizes = new Integer[] { };
// Header and initializations
if (format == ReportFormat.Text) {
// Find out the maximum size of the contents per column
colSizes = new Integer[cols];
for (int x=0; x<cols; x++) {
colSizes[x] = tableModel.getColumnName(x).length();
for (int y=0; y<rows; y++) {
cellStr = tableModel.getValueAt(y, x).toString();
if (cellStr.length() > colSizes[x]) colSizes[x] = cellStr.length();
}
totalSize += colSizes[x]+1;
}
buffer += " ==[ " + Title + " ]==========================\n\n";
} else if (format == ReportFormat.HTML) {
buffer += "<h2>" + Title + "</h2>\n<table border=\"1\"><tr>\n";
} else if (format == ReportFormat.CSV) {
buffer += Title + "\n";
}
// Column headers
String colName, dataRow = "";
dataRow = "";
for (int i=0; i<cols; i++) {
colName = tableModel.getColumnName(i);
if (format == ReportFormat.Text) {
dataRow += " "+padToLength(colName, colSizes[i]);
} else if (format == ReportFormat.HTML) {
dataRow += " <th>"+colName+"</th>";
} else if (format == ReportFormat.CSV) {
if (!dataRow.equals("")) dataRow += ",";
dataRow += colName;
}
}
buffer += dataRow + "\n";
// Finalize headers
if (format == ReportFormat.HTML) {
buffer += "</tr>\n";
}
// Content processing
for (int r=0; r<rows; r++) {
dataRow = "";
// Initialize data row
if (format == ReportFormat.Text) {
} else if (format == ReportFormat.HTML) {
dataRow += "<tr>\n";
} else if (format == ReportFormat.CSV) {
}
// Create data row
for (int c=0; c<cols; c++) {
cellStr = tableModel.getValueAt(r, c).toString();
if (format == ReportFormat.Text) {
dataRow += " "+padToLength(cellStr, colSizes[c]);
} else if (format == ReportFormat.HTML) {
dataRow += " <td>"+cellStr+"</td>";
} else if (format == ReportFormat.CSV) {
if (!dataRow.equals("")) dataRow += ",";
dataRow += cellStr;
}
}
// Finalize data row
if (format == ReportFormat.Text) {
dataRow += "\n";
} else if (format == ReportFormat.HTML) {
dataRow += "</tr>\n";
} else if (format == ReportFormat.CSV) {
dataRow += "\n";
}
// Insert data row
buffer += dataRow;
}
// Footer
if (format == ReportFormat.Text) {
buffer += "\n";
} else if (format == ReportFormat.HTML) {
buffer += "</table>";
} else if (format == ReportFormat.CSV) {
buffer += "\n";
}
return buffer;
}
@Override
public boolean includeToReport() {
return jToggleButton1.isSelected();
}
}
| gpl-3.0 |
sociam/trends-observatory | src/sociam/observatory/trends/twitter/LocationChecker.java | 2262 | package sociam.observatory.trends.twitter;
import java.util.ArrayList;
import java.util.List;
import sociam.observatory.trends.Country;
import twitter4j.Location;
import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
public class LocationChecker {
private boolean worldwide;
private List<String> countries;
private List<String> towns; // ["town name, country code"]
public LocationChecker(boolean world, Country[] cs, String[] ts) {
worldwide = world;
countries = new ArrayList<String>();
for (Country c : cs) {
countries.add(c.isoCode);
}
towns = new ArrayList<String>();
for (String t : ts) {
towns.add(t);
}
}
public LocationChecker(boolean world, List<Country> cs) {
worldwide = world;
countries = new ArrayList<String>();
for (Country c : cs) {
countries.add(c.isoCode);
}
towns = new ArrayList<String>();
}
public List<Location> getAvailableLocations(Twitter twitter) {
List<Location> locations = new ArrayList<Location>();
if (worldwide) {
locations.add(Worldwide.getInstance());
}
try {
ResponseList<Location> available = twitter.getAvailableTrends();
for (Location loc : available) {
if (loc.getPlaceName().equals("Country")) {
if (countries.contains(loc.getCountryCode())) {
locations.add(loc);
}
} else {
if (towns.contains(loc.getName() + ", "
+ loc.getCountryCode())) {
locations.add(loc);
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
return locations;
}
public static class Worldwide implements Location {
private static Worldwide instance;
protected Worldwide() {
}
public static Worldwide getInstance() {
if (instance == null) {
instance = new Worldwide();
}
return instance;
}
@Override
public int getWoeid() {
return 1;
}
@Override
public String getCountryName() {
return "Worldwide";
}
@Override
public String getCountryCode() {
return "";
}
@Override
public String getPlaceName() {
return "World";
}
@Override
public int getPlaceCode() {
return 1;
}
@Override
public String getName() {
return "Worldwide";
}
@Override
public String getURL() {
return "";
}
}
}
| gpl-3.0 |
ihmc/nomads | aci/java/us/ihmc/aci/netSupervisor/inferenceModule/ClaspTraffic.java | 3943 | package us.ihmc.aci.netSupervisor.inferenceModule;
import com.google.protobuf.Duration;
import us.ihmc.aci.ddam.MicroFlow;
public class ClaspTraffic
{
private int _trafficId;
private String _destinationHostIp;
private String _sourceHostIp;
private String _destinationHostPort;
private String _sourceHostPort;
private String _protocol;
private int _priorityValue;
private long _duration;
public ClaspTraffic ()
{
}
public ClaspTraffic (MicroFlow microFlow)
{
_trafficId = microFlow.getId();
_sourceHostIp = microFlow.getIpSrc();
_destinationHostIp = microFlow.getIpDst();
_sourceHostPort = microFlow.getPortSrc();
_destinationHostPort = microFlow.getPortDst();
_protocol = microFlow.getProtocol();
_priorityValue = microFlow.getDSCP();
if (microFlow.getDuration().isInitialized()) {
_duration = microFlow.getDuration().getSeconds();
}
else {
_duration = Long.MAX_VALUE;
}
}
public ClaspTraffic (int trafficId, String sourceHostIp, String sourceHostPort, String destinationHostIp,
String destinationHostPort, String protocol, int priorityValue)
{
_trafficId = trafficId;
_destinationHostIp = destinationHostIp;
_sourceHostIp = sourceHostIp;
_destinationHostPort = destinationHostPort;
_sourceHostPort = sourceHostPort;
_protocol = protocol;
_priorityValue = priorityValue;
_duration = Long.MAX_VALUE;
}
public String getDestinationHostIp ()
{
return _destinationHostIp;
}
public String getSourceHostIp ()
{
return _sourceHostIp;
}
public String getDestinationHostPort ()
{
return _destinationHostPort;
}
public String getSourceHostPort ()
{
return _sourceHostPort;
}
public int getPriorityValue ()
{
return _priorityValue;
}
public String getProtocol ()
{
return _protocol;
}
public int getTrafficId()
{
return _trafficId;
}
public long getDuration()
{
return _duration;
}
public MicroFlow getMicroFlowFromClaspTraffic ()
{
MicroFlow.Builder microFlowBuilder = MicroFlow.newBuilder();
microFlowBuilder.setId(_trafficId);
microFlowBuilder.setIpSrc(_sourceHostIp);
microFlowBuilder.setIpDst(_destinationHostIp);
microFlowBuilder.setPortSrc(_sourceHostPort);
microFlowBuilder.setPortDst(_destinationHostPort);
microFlowBuilder.setProtocol(_protocol);
microFlowBuilder.setDSCP(_priorityValue);
microFlowBuilder.setDuration(Duration.newBuilder().setSeconds(_duration));
return microFlowBuilder.build();
}
public String print ()
{
return "(" + _trafficId + "," + _sourceHostIp + "," + _sourceHostPort + "," + _destinationHostIp + "," +
_destinationHostPort + "," + _protocol + "," + _priorityValue + "," + _duration + ")";
}
public void setDestinationHostIp (String destinationHostIp)
{
_destinationHostIp = destinationHostIp;
}
public void setSourceHostIp (String sourceHostIp)
{
_sourceHostIp = sourceHostIp;
}
public void setDestinationHostPort (String destinationHostPort)
{
_destinationHostPort = destinationHostPort;
}
public void setSourceHostPort (String sourceHostPort)
{
_sourceHostPort = sourceHostPort;
}
public void setProtocol (String protocol)
{
_protocol = protocol;
}
public void setPriorityValue (int priorityValue)
{
_priorityValue = priorityValue;
}
public void setTrafficId(int trafficId)
{
_trafficId = trafficId;
}
public void setDuration(long duration)
{
_duration = duration;
}
}
| gpl-3.0 |
LeoFCardoso/webfilesys | src/main/java/de/webfilesys/gui/ajax/calendar/XmlChangeAppointmentHandler.java | 8403 | package de.webfilesys.gui.ajax.calendar;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import de.webfilesys.calendar.Appointment;
import de.webfilesys.calendar.AppointmentManager;
import de.webfilesys.gui.ajax.XmlRequestHandlerBase;
import de.webfilesys.util.CommonUtils;
import de.webfilesys.util.XmlUtil;
public class XmlChangeAppointmentHandler extends XmlRequestHandlerBase {
public XmlChangeAppointmentHandler(
HttpServletRequest req,
HttpServletResponse resp,
HttpSession session,
PrintWriter output,
String uid)
{
super(req, resp, session, output, uid);
}
protected void process()
{
if (!checkWriteAccess())
{
return;
}
String appointmentId = getParameter("appointmentId");
if (CommonUtils.isEmpty(appointmentId))
{
Logger.getLogger(getClass()).warn("missing parameter appointmentId");
return;
}
Appointment appointment = AppointmentManager.getInstance().getAppointment(uid, appointmentId);
if (appointment == null)
{
Logger.getLogger(getClass()).warn("appointment for update not found with id " + appointmentId);
return;
}
String subject = getParameter("subject");
if (CommonUtils.isEmpty(subject)) {
subject = "no subject";
}
String description = getParameter("description");
String startHourParam = getParameter("startHour");
if (CommonUtils.isEmpty(startHourParam)) {
Logger.getLogger(getClass()).warn("missing parameter startHour");
return;
}
String startMinuteParam = getParameter("startMinute");
if (CommonUtils.isEmpty(startMinuteParam)) {
Logger.getLogger(getClass()).warn("missing parameter startMinute");
return;
}
String endHourParam = getParameter("endHour");
if (CommonUtils.isEmpty(endHourParam)) {
Logger.getLogger(getClass()).warn("missing parameter endHour");
return;
}
String endMinuteParam = getParameter("endMinute");
if (CommonUtils.isEmpty(endMinuteParam)) {
Logger.getLogger(getClass()).warn("missing parameter endMinute");
return;
}
String fullDayParam = getParameter("fullDay");
String multiDayParam = getParameter("multiDay");
String fullDayNumParam = getParameter("numOfDays");
String repeatPeriodParam = getParameter("repeatPeriod");
if (CommonUtils.isEmpty(repeatPeriodParam)) {
Logger.getLogger(getClass()).warn("missing parameter repeatPeriod");
return;
}
String alarmTypeParam = getParameter("alarmType");
if (CommonUtils.isEmpty(alarmTypeParam)) {
Logger.getLogger(getClass()).warn("missing parameter alarmType");
return;
}
String alarmAheadHoursParam = getParameter("alarmAheadHours");
if (CommonUtils.isEmpty(alarmAheadHoursParam)) {
alarmAheadHoursParam = "0";
}
String alarmAheadMinutesParam = getParameter("alarmAheadMinutes");
if (CommonUtils.isEmpty(alarmAheadMinutesParam)) {
alarmAheadMinutesParam = "0";
}
int startHour;
int endHour;
int startMinute;
int endMinute;
int repeatPeriod;
int alarmType;
int alarmAheadHours;
int alarmAheadMinutes;
int fullDayNum = 0;
try
{
startHour = Integer.parseInt(startHourParam);
startMinute = Integer.parseInt(startMinuteParam);
endHour = Integer.parseInt(endHourParam);
endMinute = Integer.parseInt(endMinuteParam);
repeatPeriod = Integer.parseInt(repeatPeriodParam);
alarmType = Integer.parseInt(alarmTypeParam);
alarmAheadHours = Integer.parseInt(alarmAheadHoursParam);
alarmAheadMinutes = Integer.parseInt(alarmAheadMinutesParam);
if (!CommonUtils.isEmpty(fullDayNumParam))
{
fullDayNum = Integer.parseInt(fullDayNumParam);
}
}
catch (NumberFormatException numEx)
{
Logger.getLogger(getClass()).warn("invalid parameter value", numEx);
return;
}
Date oldEventTime = appointment.getEventTime();
Calendar cal = GregorianCalendar.getInstance(req.getLocale());
cal.setTime(appointment.getEventTime());
cal.set(Calendar.HOUR_OF_DAY, startHour);
cal.set(Calendar.MINUTE, startMinute);
cal.set(Calendar.SECOND, 0);
appointment.setEventTime(cal.getTime());
if (appointment.getEventTime().getTime() > oldEventTime.getTime())
{
appointment.setAlarmed(false);
appointment.setMailAlarmed(false);
appointment.setLastMailAlarmed(oldEventTime);
}
long alarmAheadTime = (alarmAheadHours * 3600 * 1000) + (alarmAheadMinutes * 60 * 1000);
appointment.setAlarmTime(new Date(cal.getTime().getTime() - alarmAheadTime));
long startTime = cal.getTime().getTime();
if (fullDayParam != null)
{
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
}
else
{
cal.set(Calendar.HOUR_OF_DAY, endHour);
cal.set(Calendar.MINUTE, endMinute);
}
long endTime = cal.getTime().getTime();
long duration = endTime - startTime;
appointment.setDuration(duration);
appointment.setSubject(subject);
appointment.setContent(description);
appointment.setRepeatPeriod(repeatPeriod);
appointment.setAlarmType(alarmType);
if (fullDayParam != null)
{
appointment.setFullDay(true);
if ((multiDayParam != null) && (fullDayNum > 0))
{
appointment.setFullDayNum(fullDayNum);
}
else
{
appointment.setFullDayNum(0);
}
}
else
{
appointment.setFullDay(false);
}
AppointmentManager.getInstance().updateAppointment(uid, appointment, true);
Element resultElement = doc.createElement("result");
XmlUtil.setChildText(resultElement, "message", "appointment created");
XmlUtil.setChildText(resultElement, "success", "true");
Element appointmentElem = doc.createElement("appointment");
resultElement.appendChild(appointmentElem);
XmlUtil.setChildText(appointmentElem, "id", appointment.getId());
XmlUtil.setChildText(appointmentElem, "eventTime", Long.toString(appointment.getEventTime().getTime()));
XmlUtil.setChildText(appointmentElem, "duration", Long.toString(appointment.getDuration()));
cal.setTime(appointment.getEventTime());
String formattedStartTime = String.format("%2d:%2d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
XmlUtil.setChildText(appointmentElem, "startTime", formattedStartTime);
int startTimeMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
XmlUtil.setChildText(appointmentElem, "startMinuteOfDay", Integer.toString(startTimeMinuteOfDay));
long appointmentEndTime = appointment.getEventTime().getTime() + appointment.getDuration();
java.util.Date appointmentEndDate = new java.util.Date(appointmentEndTime);
cal.setTime(appointmentEndDate);
String formattedEndTime = String.format("%2d:%2d", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
XmlUtil.setChildText(appointmentElem, "endTime", formattedEndTime);
int endTimeMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
XmlUtil.setChildText(appointmentElem, "endMinuteOfDay", Integer.toString(endTimeMinuteOfDay));
XmlUtil.setChildText(appointmentElem, "startHour", Integer.toString(appointment.getEventTime().getHours()));
XmlUtil.setChildText(appointmentElem, "endHour", Integer.toString(appointmentEndDate.getHours()));
XmlUtil.setChildText(appointmentElem, "fullDay", Boolean.toString(appointment.isFullday()));
XmlUtil.setChildText(appointmentElem, "fullDayNum", Integer.toString(appointment.getFullDayNum()));
XmlUtil.setChildText(appointmentElem, "subject", appointment.getSubject(), true);
XmlUtil.setChildText(appointmentElem, "repeatPeriod", Integer.toString(appointment.getRepeatPeriod()));
XmlUtil.setChildText(appointmentElem, "alarmType", Integer.toString(appointment.getAlarmType()));
XmlUtil.setChildText(appointmentElem, "alarmAheadHours", Integer.toString(alarmAheadHours));
XmlUtil.setChildText(appointmentElem, "alarmAheadMinutes", Integer.toString(alarmAheadMinutes));
if ((appointment.getContent() != null) && (appointment.getContent().length() > 0))
{
XmlUtil.setChildText(appointmentElem, "description", appointment.getContent(), true);
}
doc.appendChild(resultElement);
this.processResponse();
}
}
| gpl-3.0 |
MadhankumarM/BMICALC | app/src/main/java/com/blogspot/madhanmmk/bmicalc/MainActivity.java | 3255 | package com.blogspot.madhanmmk.bmicalc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG="stepp";
Button btnrel;
EditText txtval1,txtval2;
Button k;
String s="http://www.nhlbi.nih.gov/health/educational/lose_wt/BMI/bmicalc.htm";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"onCreate");
btnrel=(Button)findViewById(R.id.btn);
txtval1=(EditText)findViewById(R.id.t1);
txtval2=(EditText)findViewById(R.id.t2);
btnrel.setOnClickListener(this);
addListenerOnButton();
}
public void onClick(View v) {
Log.i(TAG,"onClick");
float value1=Integer.parseInt(txtval1.getText().toString());
float value2=Integer.parseInt(txtval2.getText().toString());
float h=value2/100;
h=h*h;
float sum=value1/h;
EditText t=(EditText) findViewById(R.id.t3);
t.setText("BMI="+sum);
TextView f=(TextView)findViewById(R.id.v);
if(sum<18.5)
{
f.setText("You are Underweight");
s="http://www.freedieting.com/tools/calories_in_food.htm";
}
else if(sum<24.9)
{
f.setText("You have a Normal body");
s="http://www.freedieting.com/tools/calories_in_food.htm";
}
else if(sum<30)
{
f.setText("You are in overweight category");
s="http://www.freedieting.com/weight_loss_articles.htm";
}
else
{
f.setText("You have obecitys");
s="http://www.freedieting.com/weight_loss_articles.htm";
}
}
public void addListenerOnButton() {
k = (Button) findViewById(R.id.button);
k.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
intent.putExtra("string",s);
startActivity(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
Toast.makeText(getApplicationContext(),"Welocome",Toast.LENGTH_LONG);
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart");
}
}
| gpl-3.0 |
ihmc/nomads | chunking/src/android/java/us/ihmc/chunking/android/AndroidOoxmlTest.java | 4022 | package us.ihmc.chunking.android;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import android.content.Context;
import us.ihmc.chunking.ChunkWrapper;
import us.ihmc.chunking.Reassembler;
import us.ihmc.chunking.FileUtils;
/**
* Test for the Android open XML document reassembly.
*
* @author lbunch
*
*/
public class AndroidOoxmlTest {
// logging (replace with android Log)
private static Logger logger = Logger.getLogger(AndroidOoxmlTest.class.getName());
// Android application context used to access test resources from the file system
public static Context appContext = null;
/**
* Submit the total number of chunks the original file was fragmented into,
* followed by pairs of space-delimited parameters specifying the chunks to reassemble:
[total chunk count] [ooxml chunk file path] [chunk id] [ooxml chunk file path] [chunk id] ...
example: 4 resources/test_chunk1.pptx 1 resources/test_chunk2.pptx 2
which reassembles these 2 of 4 chunks to produce a result file "resources/test_out.pptx"
* @param argv space delimited argument list
*/
public static void main(String[] argv) {
logger.log(Level.INFO, "Usage: Submit the total number of chunks the original file was fragmented into\n"
+ "followed by space-delimited parameters specifying the chuncks to reassemble:"
+ "[total chunk count] [ooxml chunk file path] [chunk id] [ooxml chunk file path] [chunk id] ...\n"
+ "example: 4 \"resources/test_chunk1.pptx\" 1 \"resources/test_chunk2.pptx\" 2\n"
+ "which combines these chunks to produce a result file \"resources/test_out.pptx\"");
// the List of ChunkWrappers that will be reassembled
ArrayList<ChunkWrapper> chunkList = new ArrayList<ChunkWrapper>();
// the total number of chunks the original doc was fragmented into
byte totalChunkCount = Byte.parseByte(argv[0]);
// the path to the first chunk to reassemble
String firstChunkFilePathStr = null;
// parse the parameter pairs [ooxml chunk file path] [chunk id]
for (int a = 1; a < argv.length; a += 2) {
try {
String ooxmlFilePathStr = argv[a];
if (firstChunkFilePathStr == null) {
// save the path to the first chunk to use later for the resulting output file path
firstChunkFilePathStr =ooxmlFilePathStr;
}
byte chunkId = Byte.parseByte(argv[a + 1]);
// read in the chunk
byte[] originalFileData = OoxmlChunkUtils.readFileContents(ooxmlFilePathStr, appContext);
// create a ChunkWrapper representing this parameter
ChunkWrapper chunkWrapper = new ChunkWrapper(originalFileData, chunkId, totalChunkCount, FileUtils.getMimeTypeForFile(ooxmlFilePathStr));
// add the ChunkWrapper to the list of chunks to reassemble
chunkList.add(chunkWrapper);
} catch (Exception e) {
logger.log(Level.SEVERE, "", e);
}
}
// reassembled result will be written to a new file with suffix "_out" in the same location as the first chunk
String reassembledFilePathStr = FileUtils.getAllExceptExtension(firstChunkFilePathStr) + "_out." + FileUtils.getFileExtension(firstChunkFilePathStr);
Reassembler reassembler = new OoxmlReassembler();
// reassemble the list of chunks and get the bytes of the resulting document
// note: the AnnotationsWrapper parameter is null for now (no annotation handling)
// the compression quality is 100% (best/lossless)
byte[] reassembledFileData = reassembler.reassemble(chunkList, null, FileUtils.getMimeTypeForFile(firstChunkFilePathStr), totalChunkCount, (byte) 100);
try {
// write the result to the file system
OoxmlChunkUtils.writeFileContents(reassembledFilePathStr, reassembledFileData, appContext);
} catch (IOException e) {
logger.log(Level.SEVERE, "", e);
}
}
}
| gpl-3.0 |
thejoelpatrol/RTTApp | app/src/main/java/com/laserscorpion/rttapp/ui/TextEntryMonitor.java | 12633 | /* © 2016 Joel Cretan
*
* This is part of RTTAPP, an Android RFC 4103 real-time text app
*
* 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.laserscorpion.rttapp.ui;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import com.laserscorpion.rttapp.BuildConfig;
import com.laserscorpion.rttapp.sip.SipClient;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* <p>The TextEntryMonitor, one of which is created by the RTTCallActivity at a time,
* listens for input on the user's text field (EditText), and keeps track of which
* characters have changed. It sends those characters in the real-time call via the SipClient.</p>
*
* <p>There are two modes, real time and en bloc, specified in the constructor.</p>
*
* <p>Real-time mode:<br>
* If text is added or deleted at the end, TextEntryMonitor tells the SipClient to send
* the new characters (possibly '\b') in the real-time call. If edits are made earlier in the text,
* it undoes them, since the user is not allowed to add or remove text anywhere besides the
* end of the field. Keeping track of these edits is pretty annoying, and you need to understand how
* the Android.text.TextWatcher interface works before touching any of this.</p>
*
* <p>En bloc mode:<br>
* Text is not sent character by character. It is only sent as complete messages, when checkAndSend()
* is called.</p>
*/
public class TextEntryMonitor implements TextWatcher {
private static final String TAG = "TextWatcher";
private EditText fieldToMonitor;
private CharSequence currentText;
private SipClient texter;
private boolean makingManualEdit = false;
private boolean needManualEdit = false; // flag that indicates that we need to undo the text change the user made - not allowed to edit earlier text
private boolean screenRotated = false;
private boolean useRealTimeText; // real-time char-by-char mode vs. en bloc mode
/**
* The only constructor.
* @param watchThis the text field to monitor for changes
* @param realTime whether the text should be sent in real time, character by character, or only when checkAndSend() is called
* @param sipClient the global hub for all things SIP, and who is responsible for sending the real-time text chars
* @param startText initial text to populate the field with, to be ignored (likely put there because the activity is destroyed and recreated)
* @param screenRotated whether this new TextEntryMonitor is being created due to screen rotation, i.e. the activity is destroyed and recreated
*/
public TextEntryMonitor(EditText watchThis, boolean realTime, SipClient sipClient, CharSequence startText, boolean screenRotated) {
synchronized (watchThis) {
fieldToMonitor = watchThis;
useRealTimeText = realTime;
if (useRealTimeText)
fieldToMonitor.addTextChangedListener(this);
currentText = startText;
texter = sipClient;
this.screenRotated = screenRotated;
}
}
/**
* onTextChanged is the bulk of the logic to determine which characters to send to the other party when the user enters text.
* If useRealTimeText == false, these listener methods are never called. In turn, most methods total are never
* called. En bloc methods are at the end of the class. This method enforces the rule that the
* user may only enter and delete text at the end of the field, not earlier (as in SipCon1).
*
* The important thing to know here is that in beforeTextChanged(), we set currentText to the
* text in the field before the change occurs. Then, in onTextChanged(), s is the *new* text and
* currentText is the *old* text. If we edit the text programmatically (e.g. to undo a prohibited
* edit), these callbacks fire, so they need to know if they are being invoked due to a change
* made by this code, not by the user. Thus we have the flag makingManualEdit, which is set in
* afterTextChanged(), if it sees the flag needManualEdit.
*/
@Override
public synchronized void onTextChanged(CharSequence s, int start, int before, int count) {
if (makingManualEdit) {
if (BuildConfig.DEBUG) Log.d(TAG, "ignoring manual edit");
return;
}
if (screenRotated) {
screenRotated = false;
return; // ignore text addition due to destruction and recreation of activity
}
if (BuildConfig.DEBUG)
//Log.d(TAG, "text changed! start: " + start + " | before: " + before + " | count: " + count);
if (editOverlappedEnd(start, before, count)) {
if (charsOnlyAppended(s, start, before, count)) {
sendAppendedChars(s, start, before, count);
} else if (charsOnlyDeleted(s, start, before, count)) {
sendDeletionsFromEnd(s, start, before, count);
} else if (count == before) {
if (textActuallyChanged(s, start, before, count)) {
// when entering a space, the previous word is reported as changing for some reason, but it hasn't actually changed, so we must check
sendCompoundReplacementText(s, start, before, count);
}
} else {
if (BuildConfig.DEBUG) Log.d(TAG, "Some kind of complex edit occurred 1");
sendCompoundReplacementText(s, start, before, count);
}
} else {
if (editInLastWord(start, before, count)) {
if (BuildConfig.DEBUG) Log.d(TAG, "edit in last word");
sendLastWord(s, start, before, count);
} else {
if (BuildConfig.DEBUG) Log.d(TAG, "Some kind of complex edit occurred 2");
needManualEdit = true;
// we can't allow edits that occur earlier in the text, you can only edit the end
}
}
}
@Override
public synchronized void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (makingManualEdit)
return;
currentText = s.subSequence(0, s.length()); // deep copy the text before it is changed so we can compare before and after the edit
}
@Override
public synchronized void afterTextChanged(Editable s) {
if (needManualEdit) {
synchronized (fieldToMonitor) {
makingManualEdit = true;
needManualEdit = false;
s.replace(0, s.length(), currentText);
if (BuildConfig.DEBUG) Log.d(TAG, "initiating replacement to undo prohibited edit");
}
}
if (makingManualEdit) {
makingManualEdit = false;
}
}
private void sendLastWord(CharSequence now, int start, int before, int count) {
int len = currentText.length() - lastWordStart(currentText);
sendBackspaces(len);
int newLen = now.length() - lastWordStart(currentText);
CharSequence add = now.subSequence(now.length() - newLen, now.length());
texter.sendRTTChars(add.toString());
}
private boolean editInLastWord(int start, int before, int count) {
if (start >= lastWordStart(currentText))
return true;
return false;
}
private int lastWordStart(CharSequence text) {
int i = text.length() - 1;
for (; i >= 0; i--) {
char c = text.charAt(i);
if (Character.isWhitespace(c))
break;
}
return i + 1;
}
private void sendBackspaces(int howMany) {
byte[] del = new byte[howMany];
Arrays.fill(del, (byte) 0x08);
texter.sendRTTChars(new String(del, StandardCharsets.UTF_8));
}
/**
* Precondition: charsOnlyAppended()
*/
private void sendAppendedChars(CharSequence now, int start, int before, int count) {
//if (BuildConfig.DEBUG) Log.d(TAG, "chars appended");
CharSequence added = now.subSequence(start + before, now.length());
try {
texter.sendRTTChars(added.toString());
} catch (IllegalStateException e) {
synchronized (fieldToMonitor) {
makingManualEdit = true;
fieldToMonitor.setText(currentText); // "current" is updated in onBeforeTextChanged(), so it's actually "old" by the time this is called
}
}
}
/**
* Precondition: charsOnlyDeleted()
*/
private void sendDeletionsFromEnd(CharSequence now, int start, int before, int count) {
//Log.d(TAG, "chars deleted from end - " + start + " - " + before + " - " + count);
sendBackspaces(before - count);
}
/**
*
*/
private void sendCompoundReplacementText(CharSequence now, int start, int before, int count) {
sendBackspaces(before);
CharSequence seq = now.subSequence(start, start + count);
texter.sendRTTChars(seq.toString());
}
/**
* Check whether the text that changed included the end of the entire text.
* If not, we can't allow the edit. You must only add and delete chars
* at the end of the text.
*/
private boolean editOverlappedEnd(int start, int before, int count) {
if (currentText == null)
return true;
return (start + before == currentText.length());
}
/**
* Precondition: editOverlappedEnd()
*/
private boolean charsOnlyAppended(CharSequence now, int start, int before, int count) {
if (before == 0)
return true;
if (before >= count)
return false; // if before == count, the last word was changed, but no additional chars appended
CharSequence origSeq = currentText.subSequence(start, start + before);
CharSequence newSeq = now.subSequence(start, start + before);
String origString = origSeq.toString();
String newString = newSeq.toString();
if (origString.equals(newString))
return true;
return false;
}
/**
* Precondition: editOverlappedEnd()
*/
private boolean charsOnlyDeleted(CharSequence s, int start, int before, int count) {
if (before <= count)
return false; // if before == count, the last word was changed, but no net chars deleted
if (count == 0)
return true;
String origString = currentText.subSequence(start, start + count).toString();
String newString = s.subSequence(start, start + count).toString();
if (origString.equals(newString))
return true;
return false;
}
/**
* Precondition: before == count
* <p>
* for some reason, when spaces are added, the previous word is reported as changing, but it doesn't really,
* so we are checking that here
*/
private boolean textActuallyChanged(CharSequence now, int start, int before, int count) {
if (currentText == null)
return true;
String changed = now.subSequence(start, start + count).toString();
String origStr = currentText.toString();
if (origStr.regionMatches(start, changed, 0, before))
return false;
return true;
}
/*
* end RTT methods ... following methods are for en bloc mode
*/
/**
* Used in the case when the user has chosen to send entire messages, not individual characters,
* i.e. en bloc mode. The text in the field is sent to the other party and removed from the field.
*/
public void checkAndSend() {
synchronized (fieldToMonitor) {
CharSequence text = fieldToMonitor.getText();
if (text.length() > 0) {
String toSend = text.toString() + '\n';
texter.sendRTTChars(toSend);
fieldToMonitor.setText(null);
}
}
}
}
| gpl-3.0 |
senbox-org/snap-desktop | snap-ui/src/main/java/org/esa/snap/ui/product/ProductChooser.java | 6289 | /*
* 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 org.esa.snap.ui.product;
import com.bc.ceres.swing.TableLayout;
import com.jidesoft.swing.CheckBoxList;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.ModalDialog;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
/**
* @author Thomas Storm
*/
class ProductChooser extends ModalDialog {
private final CheckBoxList productsList;
private final JCheckBox selectAll;
private final JCheckBox selectNone;
ProductChooser(Window parent, String title, int buttonMask, String helpID, Product[] products) {
super(parent, title, buttonMask, helpID);
TableLayout layout = new TableLayout(1);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setRowWeightY(0, 1.0);
layout.setRowWeightY(1, 0.0);
layout.setTableWeightX(1.0);
JPanel panel = new JPanel(layout);
ProductListModel listModel = new ProductListModel();
selectAll = new JCheckBox("Select all");
selectNone = new JCheckBox("Select none", true);
selectNone.setEnabled(false);
productsList = new CheckBoxList(listModel);
productsList.setCellRenderer(new ProductListCellRenderer());
productsList.getCheckBoxListSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
final int length = productsList.getCheckBoxListSelectedIndices().length;
if (length == 0) {
selectNone.setSelected(true);
selectAll.setSelected(false);
} else if (length == productsList.getModel().getSize()) {
selectAll.setSelected(true);
selectNone.setSelected(false);
} else {
selectAll.setSelected(false);
selectNone.setSelected(false);
}
selectAll.setEnabled(!selectAll.isSelected());
selectNone.setEnabled(!selectNone.isSelected());
}
});
for (Product product : products) {
listModel.addElement(product);
}
panel.add(new JScrollPane(productsList));
panel.add(createButtonsPanel());
setContent(panel);
}
List<Product> getSelectedProducts() {
List<Product> selectedProducts = new ArrayList<>();
for (int i = 0; i < productsList.getModel().getSize(); i++) {
if (productsList.getCheckBoxListSelectionModel().isSelectedIndex(i)) {
selectedProducts.add((Product) productsList.getModel().getElementAt(i));
}
}
return selectedProducts;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
selectAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectNone.setSelected(false);
selectAll.setEnabled(false);
selectNone.setEnabled(true);
productsList.getCheckBoxListSelectionModel().setSelectionInterval(0,
productsList.getModel().getSize() - 1);
}
});
selectNone.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectAll.setSelected(false);
selectAll.setEnabled(true);
selectNone.setEnabled(false);
productsList.getCheckBoxListSelectionModel().clearSelection();
}
});
selectAll.setMnemonic('a');
selectNone.setMnemonic('n');
buttonsPanel.add(selectAll);
buttonsPanel.add(selectNone);
return buttonsPanel;
}
private static class ProductListCellRenderer implements ListCellRenderer<Product> {
private DefaultListCellRenderer delegate = new DefaultListCellRenderer();
@Override
public Component getListCellRendererComponent(JList list, Product value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) delegate.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setText(value.getDisplayName());
return label;
}
}
private static class ProductListModel extends DefaultListModel<Product> {
@Override
public void addElement(Product product) {
boolean alreadyContained = false;
for (int i = 0; i < getSize(); i++) {
String currentProductName = get(i).getName();
String newProductName = product.getName();
alreadyContained |= currentProductName.equals(newProductName);
}
if (!alreadyContained) {
super.addElement(product);
}
}
}
}
| gpl-3.0 |
ImagoTrigger/sdrtrunk | src/main/java/io/github/dsheirer/module/decode/mpt1327/MPT1327Decoder.java | 4714 | /*
* ******************************************************************************
* sdrtrunk
* Copyright (C) 2014-2018 Dennis Sheirer
*
* 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 io.github.dsheirer.module.decode.mpt1327;
import io.github.dsheirer.bits.IBinarySymbolProcessor;
import io.github.dsheirer.bits.MessageFramer;
import io.github.dsheirer.dsp.afsk.AFSK1200Decoder;
import io.github.dsheirer.dsp.symbol.BinaryToByteBufferAssembler;
import io.github.dsheirer.module.decode.DecoderType;
import io.github.dsheirer.module.decode.afsk.AbstractAFSKDecoder;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.buffer.IReusableByteBufferProvider;
import io.github.dsheirer.sample.buffer.ReusableByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Instrumented version of the MPT1327 decoder. Exposes properties for instrumented manual decoding of a signal.
*/
public class MPT1327Decoder extends AbstractAFSKDecoder implements IBinarySymbolProcessor, IReusableByteBufferProvider
{
private final static Logger mLog = LoggerFactory.getLogger(MPT1327Decoder.class);
/* Message length -- longest possible message is:
* 4xREVS + 16xSYNC + 64xADD1 + 64xDCW1 + 64xDCW2 + 64xDCW3 + 64xDCW4 */
private static final int MESSAGE_LENGTH = 350;
private MessageFramer mControlMessageFramer;
private MessageFramer mTrafficMessageFramer;
private MPT1327MessageProcessor mMessageProcessor;
private BinaryToByteBufferAssembler mBinaryToByteBufferAssembler = new BinaryToByteBufferAssembler(512);
protected MPT1327Decoder(AFSK1200Decoder decoder, Sync sync)
{
super(decoder);
init(sync);
}
public MPT1327Decoder(Sync sync)
{
super((sync == Sync.NORMAL ? AFSK1200Decoder.Output.NORMAL : AFSK1200Decoder.Output.INVERTED));
init(sync);
}
private void init(Sync sync)
{
getDecoder().setSymbolProcessor(this);
//Message framer for control channel messages
mControlMessageFramer = new MessageFramer(sync.getControlSyncPattern().getPattern(), MESSAGE_LENGTH);
//Message framer for traffic channel massages
mTrafficMessageFramer = new MessageFramer(sync.getTrafficSyncPattern().getPattern(), MESSAGE_LENGTH);
//Fully decoded and framed messages processor
mMessageProcessor = new MPT1327MessageProcessor();
mMessageProcessor.setMessageListener(getMessageListener());
mControlMessageFramer.addMessageListener(mMessageProcessor);
mTrafficMessageFramer.addMessageListener(mMessageProcessor);
}
public void process(boolean symbol)
{
mControlMessageFramer.process(symbol);
mTrafficMessageFramer.process(symbol);
mBinaryToByteBufferAssembler.process(symbol);
}
@Override
public DecoderType getDecoderType()
{
return DecoderType.MPT1327;
}
@Override
public void reset()
{
}
@Override
public void start()
{
super.start();
mControlMessageFramer.reset();
mTrafficMessageFramer.reset();
}
/**
* Cleanup method
*/
public void dispose()
{
super.dispose();
mMessageProcessor.dispose();
mControlMessageFramer.dispose();
mTrafficMessageFramer.dispose();
}
public MessageFramer getControlMessageFramer()
{
return mControlMessageFramer;
}
public MessageFramer getTrafficMessageFramer()
{
return mTrafficMessageFramer;
}
@Override
public void setBufferListener(Listener<ReusableByteBuffer> listener)
{
mBinaryToByteBufferAssembler.setBufferListener(listener);
}
@Override
public void removeBufferListener(Listener<ReusableByteBuffer> listener)
{
mBinaryToByteBufferAssembler.removeBufferListener(listener);
}
@Override
public boolean hasBufferListeners()
{
return mBinaryToByteBufferAssembler.hasBufferListeners();
}
}
| gpl-3.0 |
micromata/projectforge | projectforge-business/src/test/java/org/projectforge/framework/utils/ClassHelperTest.java | 1740 | /////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2022 Micromata GmbH, Germany (www.micromata.com)
//
// ProjectForge is dual-licensed.
//
// This community edition is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// This community edition 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.projectforge.framework.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class ClassHelperTest
{
@Test
public void testGetDefaultType()
{
assertEquals(false, ClassHelper.getDefaultType(Boolean.TYPE));
assertNull(ClassHelper.getDefaultType(Boolean.class));
assertEquals(0, ClassHelper.getDefaultType(Integer.TYPE));
assertNull(ClassHelper.getDefaultType(Integer.class));
}
@Test
public void testIsDefaultType()
{
assertTrue(ClassHelper.isDefaultType(Boolean.TYPE, null));
assertTrue(ClassHelper.isDefaultType(Boolean.TYPE, false));
assertTrue(ClassHelper.isDefaultType(Boolean.TYPE, Boolean.FALSE));
assertFalse(ClassHelper.isDefaultType(Boolean.TYPE, true));
}
}
| gpl-3.0 |
Caellian/CaellianCore | src/main/java/hr/caellian/core/processManagement/ExecutionTimeline.java | 980 | /*******************************************************************************
* Copyright (c) 2015 Contributors.
* All rights reserved. This program and the accompanying materials are made available under
* the terms of the GNU Lesser General Public
* License v3.0 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
******************************************************************************/
package hr.caellian.core.processManagement;
import java.util.Stack;
/**
* @author Caellian
*/
public class ExecutionTimeline {
private Stack<Command> past = new Stack<>();
private Stack<Command> future = new Stack<>();
public void commandExecuted(Command command) {
past.push(command);
future.clear();
}
public void redo() {
future.pop().redo();
}
public void undo() {
Command command = past.pop();
future.push(command);
command.undo();
}
}
| gpl-3.0 |
jrc436/executors | Executors/src/util/data/maps/filter/UserListFilterProcessor.java | 1280 | package util.data.maps.filter;
import java.io.File;
import filter.Filter;
import util.data.maps.UserList;
import util.sys.FileProcessor;
public class UserListFilterProcessor extends FileProcessor<UserList, UserList> {
private final Filter filter;
public UserListFilterProcessor() {
super();
this.filter = null;
}
public UserListFilterProcessor(String inp, String out, String[] filterArgs) {
super(inp, out, new UserList());
filter = Filter.getFilter(filterArgs);
}
@Override
public int getNumFixedArgs() {
return 0;
}
@Override
public boolean hasNArgs() {
return true;
}
@Override
public String getConstructionErrorMsg() {
return "Please specify one or more fully qualified filters or nicknames: "+Filter.getKnownFilters();
}
@Override
public UserList getNextData() {
File f = super.getNextFile();
if ( f == null) {
return null;
}
return UserList.createFromFile(f);
}
@Override
public void reduce(UserList data) {
synchronized (processAggregate) {
for (String key : data.keySet()) {
processAggregate.put(key, data.get(key));
}
}
}
@Override
public void map(UserList dataIn, UserList workerAgg) {
filter.filter(dataIn);
for (String key : dataIn.keySet()) {
workerAgg.put(key, dataIn.get(key));
}
}
}
| gpl-3.0 |
ando182/curl-maven-plugin | src/main/java/ro/edea/maven/plugins/http/common/Constants.java | 235 | package ro.edea.maven.plugins.http.common;
/**
* Created by vlada on 18.10.2016.
*/
public interface Constants {
String SKIP = "http.skip";
String URL = "http.url";
String OUTPUT_FILE = "http.output.file";
}
| gpl-3.0 |
hlim/studio | cstudio-share-war/src/main/java/org/craftercms/cstudio/share/servlet/GZIPResponseStream.java | 2872 | /*******************************************************************************
* Crafter Studio Web-content authoring solution
* Copyright (C) 2007-2013 Crafter Software Corporation.
*
* 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.craftercms.cstudio.share.servlet;
import java.io.*;
import java.util.zip.GZIPOutputStream;
import javax.servlet.*;
import javax.servlet.http.*;
public class GZIPResponseStream extends ServletOutputStream {
protected ByteArrayOutputStream baos = null;
protected GZIPOutputStream gzipstream = null;
protected boolean closed = false;
protected HttpServletResponse response = null;
protected ServletOutputStream output = null;
public GZIPResponseStream(HttpServletResponse response) throws IOException {
super();
closed = false;
this.response = response;
this.output = response.getOutputStream();
baos = new ByteArrayOutputStream();
gzipstream = new GZIPOutputStream(baos);
}
public void close() throws IOException {
if (closed) {
throw new IOException("This output stream has already been closed");
}
gzipstream.finish();
byte[] bytes = baos.toByteArray();
response.addHeader("Content-Length",
Integer.toString(bytes.length));
response.addHeader("Content-Encoding", "gzip");
output.write(bytes);
output.flush();
output.close();
closed = true;
}
public void flush() throws IOException {
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
gzipstream.flush();
}
public void write(int b) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
gzipstream.write((byte)b);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
gzipstream.write(b, off, len);
}
public boolean closed() {
return (this.closed);
}
public void reset() {
//noop
}
}
| gpl-3.0 |
fa1th09/ModTutorials | src/main/java/com/fa1th/modtutorials/proxy/IProxy.java | 111 | package com.fa1th.modtutorials.proxy;
/**
* Created by Kieran on 26/07/2014.
*/
public interface IProxy {
}
| gpl-3.0 |
romejoe/WildMap | src/main/java/com/stantonj/WildMap/WalkController/iWalkController.java | 727 | package com.stantonj.WildMap.WalkController;
import com.stantonj.WildMap.MapNode;
import com.stantonj.WildMap.Walker.iWalker;
/**
* Interface used to walk the internal graph of the WildMap.
* @param <V> type of walker and map
* @since 0.1
* @author Joe Stanton
* @version 0.1
*/
public interface iWalkController<V> {
/**
* Walks the map using the Visitor pattern and starting at the initial node.
* @param initialNode Node to begin traversal at
* @param Key Key to use as traversal "guide"
* @param walker Visitor object used to operate on each node
* @return result of walker's operation on final node
*/
public V WalkMap(MapNode<V> initialNode, String Key, iWalker<V> walker);
}
| mpl-2.0 |
mil-oss/fgsms | fgsms-server/fgsms-reporting-service/src/main/java/org/miloss/fgsms/services/rs/impl/reports/ServiceLevelAgreementReport.java | 5904 | /*
* 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.miloss.fgsms.services.rs.impl.reports;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.WebServiceContext;
import org.apache.log4j.Level;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.miloss.fgsms.common.DBUtils;
import org.miloss.fgsms.common.UserIdentityUtil;
import org.miloss.fgsms.common.Utility;
import org.miloss.fgsms.services.interfaces.common.PolicyType;
import org.miloss.fgsms.services.interfaces.common.SecurityWrapper;
import org.miloss.fgsms.services.interfaces.common.TimeRange;
import org.miloss.fgsms.services.rs.impl.Reporting;
import static org.miloss.fgsms.services.rs.impl.Reporting.getFilePathDelimitor;
import static org.miloss.fgsms.services.rs.impl.reports.BaseReportGenerator.isPolicyTypeOf;
/**
*
* @author AO
*/
public class ServiceLevelAgreementReport extends BaseReportGenerator {
@Override
public String GetDisplayName() {
return "Service Level Agreement violations";
}
@Override
public String GetHtmlFormattedHelp() {
return "Applies to all service policy types. This report generates a table and bar chart outlining all SLA violations for a given service. An SLA is basically"
+ " a rule and action based on recorded data. An SLA Fault is not necessarily a performance and"
+ " are based on the rules configured for each service.";
}
@Override
public List<PolicyType> GetAppliesTo() {
ArrayList<PolicyType> ret = new ArrayList<PolicyType>();
ret.add(PolicyType.TRANSACTIONAL);
ret.add(PolicyType.MACHINE);
ret.add(PolicyType.PROCESS);
ret.add(PolicyType.STATISTICAL);
ret.add(PolicyType.STATUS);
return ret;
}
@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException {
Connection con = Utility.getPerformanceDBConnection();
try {
PreparedStatement cmd = null;
ResultSet rs = null;
DefaultCategoryDataset set = new DefaultCategoryDataset();
JFreeChart chart = null;
data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
data.append(GetHtmlFormattedHelp() + "<br />");
data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>SLA Violations</th></tr>");
for (int i = 0; i < urls.size(); i++) {
if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
continue;
}
//https://github.com/mil-oss/fgsms/issues/112
if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
continue;
}
String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
data.append("<tr><td>").append(url).append("</td><td>");
try {
cmd = con.prepareStatement(
"select count(*) from slaviolations where uri = ? and "
+ "(utcdatetime > ?) and (utcdatetime < ?);");
cmd.setString(1, urls.get(i));
cmd.setLong(2, range.getStart().getTimeInMillis());
cmd.setLong(3, range.getEnd().getTimeInMillis());
rs = cmd.executeQuery();
long count = -1;
try {
if (rs.next()) {
count = rs.getLong(1);
}
} catch (Exception ex) {
log.log(Level.DEBUG, " error querying database url:" + urls.get(i), ex);
}
if (count >= 0) {
data.append(count + "");
} else {
data.append("N/A");
}
if (count > 0) {
set.addValue(count, url, url);
}
} catch (Exception ex) {
log.log(Level.ERROR, "Error opening or querying the database." + GetDisplayName(), ex);
} finally {
DBUtils.safeClose(rs);
DBUtils.safeClose(cmd);
}
data.append("</td></tr>");
}
chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set, PlotOrientation.HORIZONTAL, true, false, false);
data.append("</table>");
try {
ChartUtilities.saveChartAsPNG(new File(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, Reporting.pixelHeightCalc(urls.size()));
} catch (Exception ex) {
log.log(Level.ERROR, "Error saving chart image for request", ex);
}
data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName()+ ".png");
} catch (Exception ex) {
log.log(Level.ERROR, null, ex);
} finally {
DBUtils.safeClose(con);
}
}
}
| mpl-2.0 |