hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
1b29c87e0623767aa73418cedb6eec0ba90e5939 | 18,808 | package net.polybugger.apollot;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import net.polybugger.apollot.db.ClassDbAdapter;
import net.polybugger.apollot.db.ClassItemDbAdapter;
import net.polybugger.apollot.db.ClassItemTypeDbAdapter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class ClassItemsFragment extends Fragment implements ClassItemNewEditDialogFragment.NewEditListener {
public static final String CLASS_ARG = "net.polybugger.apollot.class_arg";
private Activity mActivity;
private ClassDbAdapter.Class mClass;
private ListView mListView;
private ListArrayAdapter mListAdapter;
private DbQueryTask mTask;
private DbRequeryTask mRequeryTask;
public ClassItemsFragment() { }
public static ClassItemsFragment newInstance(ClassDbAdapter.Class class_) {
ClassItemsFragment f = new ClassItemsFragment();
Bundle args = new Bundle();
args.putSerializable(CLASS_ARG, class_);
f.setArguments(args);
return f;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof Activity){
mActivity = (Activity) context;
}
}
@Override
public void onDetach() {
mActivity = null;
super.onDetach();
}
@Override
public void onDestroyView() {
mTask.cancel(true);
if(mRequeryTask != null)
mRequeryTask.cancel(true);
super.onDestroyView();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
Bundle args = getArguments();
mClass = (ClassDbAdapter.Class) args.getSerializable(CLASS_ARG);
View view = inflater.inflate(R.layout.fragment_class_items, container, false);
mListView = (ListView) view.findViewById(R.id.list_view);
mListAdapter = new ListArrayAdapter(mActivity, new ArrayList<ClassItemDbAdapter.ClassItem>());
mListView.setAdapter(mListAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ClassItemDbAdapter.ClassItem classItem = (ClassItemDbAdapter.ClassItem) view.findViewById(R.id.description_text_view).getTag();
startClassItemActivity(classItem);
}
});
mTask = new DbQueryTask();
mTask.execute(mClass.getClassId());
return view;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.action_new_item:
FragmentManager fm = getFragmentManager();
ClassItemNewEditDialogFragment df = (ClassItemNewEditDialogFragment) fm.findFragmentByTag(ClassItemNewEditDialogFragment.TAG);
if(df == null) {
df = ClassItemNewEditDialogFragment.newInstance(getString(R.string.new_class_item), getString(R.string.add_button), null, getTag());
df.show(fm, ClassItemNewEditDialogFragment.TAG);
}
return true;
case R.id.action_sort_description:
mListAdapter.sortBy(R.id.action_sort_description);
return true;
case R.id.action_sort_date:
mListAdapter.sortBy(R.id.action_sort_date);
return true;
case R.id.action_sort_activity:
mListAdapter.sortBy(R.id.action_sort_activity);
return true;
case R.id.action_sort_check_attendance:
mListAdapter.sortBy(R.id.action_sort_check_attendance);
return true;
case R.id.action_sort_perfect_score:
mListAdapter.sortBy(R.id.action_sort_perfect_score);
return true;
case R.id.action_sort_submission_due_date:
mListAdapter.sortBy(R.id.action_sort_submission_due_date);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_class_items, menu);
}
private void startClassItemActivity(ClassItemDbAdapter.ClassItem classItem) {
Intent intent = new Intent(mActivity, ClassItemActivity.class);
Bundle args = new Bundle();
args.putSerializable(ClassItemActivity.CLASS_ARG, mClass);
args.putSerializable(ClassItemActivity.CLASS_ITEM_ARG, classItem);
intent.putExtras(args);
startActivity(intent);
}
public void requeryClassItem(ClassItemDbAdapter.ClassItem classItem) {
mRequeryTask = new DbRequeryTask(classItem);
mRequeryTask.execute(classItem);
}
public void requeryClassItems() {
mTask = new DbQueryTask();
mTask.execute(mClass.getClassId());
}
@Override
public void onNewEditItem(ClassItemDbAdapter.ClassItem item, String fragmentTag) {
long classId = mClass.getClassId();
ClassItemTypeDbAdapter.ItemType itemType = item.getItemType();
long itemTypeId = itemType == null ? -1 : itemType.getId();
long itemId = ClassItemDbAdapter.insert(classId, item.getDescription(), itemTypeId, item.getItemDate(), item.getCheckAttendance(), item.getRecordScores(), item.getPerfectScore(), item.getRecordSubmissions(), item.getSubmissionDueDate());
if(itemId != -1) {
item.setClassId(classId);
item.setItemId(itemId);
mListAdapter.add(item);
mListAdapter.notifyDataSetChanged();
startClassItemActivity(item);
}
}
private class ListArrayAdapter extends ArrayAdapter<ClassItemDbAdapter.ClassItem> {
final private SimpleDateFormat sdf = new SimpleDateFormat(ClassItemDbAdapter.SDF_DISPLAY_TEMPLATE, getResources().getConfiguration().locale);
public void sortBy(int id) {
sortId = (sortId == id) ? -id : id;
sort(comp);
}
private int sortId;
final private Comparator<ClassItemDbAdapter.ClassItem> comp = new Comparator<ClassItemDbAdapter.ClassItem>() {
@Override
public int compare(ClassItemDbAdapter.ClassItem arg0, ClassItemDbAdapter.ClassItem arg1) {
if(sortId == R.id.action_sort_description) {
return arg0.getDescription().compareToIgnoreCase(arg1.getDescription());
}
else if(-sortId == R.id.action_sort_description) {
return -arg0.getDescription().compareToIgnoreCase(arg1.getDescription());
}
else if(sortId == R.id.action_sort_date) {
Date d0 = arg0.getItemDate();
Date d1 = arg1.getItemDate();
if(d0 == null)
return 1;
if(d1 == null)
return -1;
Calendar cal0 = Calendar.getInstance();
cal0.setTime(d0);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
return cal0.compareTo(cal1);
}
else if(-sortId == R.id.action_sort_date) {
Date d0 = arg0.getItemDate();
Date d1 = arg1.getItemDate();
if(d0 == null)
return 1;
if(d1 == null)
return -1;
Calendar cal0 = Calendar.getInstance();
cal0.setTime(d0);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
return -cal0.compareTo(cal1);
}
else if(sortId == R.id.action_sort_activity) {
ClassItemTypeDbAdapter.ItemType i0 = arg0.getItemType();
ClassItemTypeDbAdapter.ItemType i1 = arg1.getItemType();
if(i0 == null)
return 1;
if(i1 == null)
return -1;
return i0.getDescription().compareToIgnoreCase(i1.getDescription());
}
else if(-sortId == R.id.action_sort_activity) {
ClassItemTypeDbAdapter.ItemType i0 = arg0.getItemType();
ClassItemTypeDbAdapter.ItemType i1 = arg1.getItemType();
if(i0 == null)
return 1;
if(i1 == null)
return -1;
return -i0.getDescription().compareToIgnoreCase(i1.getDescription());
}
else if(sortId == R.id.action_sort_check_attendance) {
Boolean b0 = arg0.getCheckAttendance();
Boolean b1 = arg1.getCheckAttendance();
if(b0 == null)
return 1;
if(b1 == null)
return -1;
return (b0 ? -1 : b1 ? 1 : 0);
}
else if(-sortId == R.id.action_sort_check_attendance) {
Boolean b0 = arg0.getCheckAttendance();
Boolean b1 = arg1.getCheckAttendance();
if(b0 == null)
return 1;
if(b1 == null)
return -1;
return (b0 ? 1 : b1 ? -1 : 0);
}
else if(sortId == R.id.action_sort_perfect_score) {
Float f0 = arg0.getPerfectScore();
Float f1 = arg1.getPerfectScore();
if(f0 == null)
return 1;
if(f1 == null)
return -1;
return (f0 < f1 ? -1 : 1);
}
else if(-sortId == R.id.action_sort_perfect_score) {
Float f0 = arg0.getPerfectScore();
Float f1 = arg1.getPerfectScore();
if(f0 == null)
return 1;
if(f1 == null)
return -1;
return (f0 < f1 ? 1 : -1);
}
else if(sortId == R.id.action_sort_submission_due_date) {
Date d0 = arg0.getSubmissionDueDate();
Date d1 = arg1.getSubmissionDueDate();
if(d0 == null)
return 1;
if(d1 == null)
return -1;
Calendar cal0 = Calendar.getInstance();
cal0.setTime(d0);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
return cal0.compareTo(cal1);
}
else if(-sortId == R.id.action_sort_submission_due_date) {
Date d0 = arg0.getSubmissionDueDate();
Date d1 = arg1.getSubmissionDueDate();
if(d0 == null)
return 1;
if(d1 == null)
return -1;
Calendar cal0 = Calendar.getInstance();
cal0.setTime(d0);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
return -cal0.compareTo(cal1);
}
return 0;
}
};
private class ViewHolder {
RelativeLayout relativeLayout;
TextView description;
TextView itemDate;
TextView itemType;
TextView checkAttendance;
TextView perfectScore;
TextView dueDate;
}
private String perfectScoreLabel;
private String dueDateLabel;
public ListArrayAdapter(Context context, List<ClassItemDbAdapter.ClassItem> objects) {
super(context, R.layout.fragment_class_items_row, objects);
perfectScoreLabel = getString(R.string.perfect_score_label);
dueDateLabel = getString(R.string.submission_due_date_label);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ClassItemDbAdapter.ClassItem classItem = getItem(position);
ViewHolder viewHolder;
if(convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(mActivity).inflate(R.layout.fragment_class_items_row, parent, false);
viewHolder.relativeLayout = (RelativeLayout) convertView.findViewById(R.id.relative_layout);
viewHolder.description = (TextView) convertView.findViewById(R.id.description_text_view);
viewHolder.itemDate = (TextView) convertView.findViewById(R.id.item_date_text_view);
viewHolder.itemType = (TextView) convertView.findViewById(R.id.item_type_text_view);
viewHolder.checkAttendance = (TextView) convertView.findViewById(R.id.check_attendance_text_view);
viewHolder.perfectScore = (TextView) convertView.findViewById(R.id.perfect_score_text_view);
viewHolder.dueDate = (TextView) convertView.findViewById(R.id.submission_due_date_text_view);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.description.setText(classItem.getDescription());
viewHolder.description.setTag(classItem);
Date itemDate = classItem.getItemDate();
viewHolder.itemDate.setText(itemDate == null ? null : sdf.format(itemDate));
ClassItemTypeDbAdapter.ItemType itemType = classItem.getItemType();
viewHolder.relativeLayout.setBackgroundColor(itemType.getColorInt());
if(itemType != null) {
viewHolder.itemType.setText(itemType.getDescription());
viewHolder.itemType.setVisibility(View.VISIBLE);
}
else
viewHolder.itemType.setVisibility(View.GONE);
if(classItem.getCheckAttendance())
viewHolder.checkAttendance.setVisibility(View.VISIBLE);
else
viewHolder.checkAttendance.setVisibility(View.GONE);
if(classItem.getRecordScores()) {
Float perfectScore = classItem.getPerfectScore();
viewHolder.perfectScore.setText(perfectScore == null ? null : perfectScoreLabel + " " + String.valueOf(perfectScore));
viewHolder.perfectScore.setVisibility(View.VISIBLE);
}
else
viewHolder.perfectScore.setVisibility(View.GONE);
if(classItem.getRecordSubmissions()) {
Date dueDate = classItem.getSubmissionDueDate();
viewHolder.dueDate.setText(dueDate == null ? null : dueDateLabel + " " + sdf.format(dueDate));
viewHolder.dueDate.setVisibility(View.VISIBLE);
}
else
viewHolder.dueDate.setVisibility(View.GONE);
return convertView;
}
}
private class DbQueryTask extends AsyncTask<Long, Integer, ArrayList<ClassItemDbAdapter.ClassItem>> {
@Override
protected void onPreExecute() {
// TODO initialize loader
}
@Override
protected ArrayList<ClassItemDbAdapter.ClassItem> doInBackground(Long... classId) {
ArrayList<ClassItemDbAdapter.ClassItem> classItems = ClassItemDbAdapter.getClassItems(classId[0]);
// TODO dbquery for student count and class items summary
return classItems;
}
@Override
protected void onProgressUpdate(Integer... percent) {
// TODO updates loader
}
@Override
protected void onCancelled() {
// TODO cleanup loader on cancel
}
@Override
protected void onPostExecute(ArrayList<ClassItemDbAdapter.ClassItem> list) {
// TODO cleanup loader on finish
mListAdapter.clear();
mListAdapter.addAll(list);
mListAdapter.notifyDataSetChanged();
}
}
private class DbRequeryTask extends AsyncTask<ClassItemDbAdapter.ClassItem, Integer, ClassItemDbAdapter.ClassItem> {
private ClassItemDbAdapter.ClassItem oldClassItem;
public DbRequeryTask(ClassItemDbAdapter.ClassItem oldItem) {
oldClassItem = oldItem;
}
@Override
protected void onPreExecute() {
// TODO initialize loader
}
@Override
protected ClassItemDbAdapter.ClassItem doInBackground(ClassItemDbAdapter.ClassItem... classItem) {
ClassItemDbAdapter.ClassItem classItem_ = classItem[0];
ClassItemDbAdapter.ClassItem requeriedClassItem = ClassItemDbAdapter.getClassItem(classItem_.getClassId(), classItem_.getItemId());
// TODO dbquery for student count and class items summary
return requeriedClassItem;
}
@Override
protected void onProgressUpdate(Integer... percent) {
// TODO updates loader
}
@Override
protected void onCancelled() {
// TODO cleanup loader on cancel
}
@Override
protected void onPostExecute(ClassItemDbAdapter.ClassItem classItem) {
// TODO cleanup loader on finish
int currentPosition = mListAdapter.getPosition(oldClassItem);
if(currentPosition != -1) {
mListAdapter.remove(oldClassItem);
if(classItem != null)
mListAdapter.insert(classItem, currentPosition);
mListAdapter.notifyDataSetChanged();
}
}
}
}
| 41.065502 | 245 | 0.587835 |
3f275a74a0fbf38952d2e097a96bc60cf505b518 | 1,855 | package sirttas.alchemytech.block.instrument.extractor;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import sirttas.alchemytech.block.instrument.extractor.ConfigExtractor.NBT;
import sirttas.alchemytech.block.tile.api.IIngredientContainer;
import sirttas.alchemytech.block.tile.api.IIngredientSender;
import sirttas.alchemytech.block.tile.instrument.TileSingleSlotInstrument;
import sirttas.alchemytech.ingredient.Ingredient;
public class TileExtractor extends TileSingleSlotInstrument implements IIngredientContainer, IIngredientSender {
private Ingredient ingredient;
@Override
public String getName() {
return ConfigExtractor.UNLOCALIZED_NAME;
}
@Override
public void addIngredient(Ingredient ingredient) {
if (this.ingredient == null) {
this.ingredient = ingredient;
}
}
@Override
public boolean canReceive(Ingredient ingredient) {
return this.ingredient == null;
}
@Override
public Ingredient removeIngredient(int index) {
Ingredient ingredient = this.ingredient;
this.ingredient = null;
return ingredient;
}
@Override
public boolean canExtract(int index) {
return this.ingredient != null;
}
@Override
public Ingredient getIngredient(int index) {
return this.ingredient;
}
@Override
public void clear() {
super.clear();
ingredient = null;
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
ingredient = Ingredient.REGISTRY.getObject(new ResourceLocation(compound.getString(NBT.INGREDIENT)));
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
if (ingredient != null) {
compound.setString(NBT.INGREDIENT, ingredient.getRegistryName().toString());
}
return compound;
}
}
| 26.126761 | 113 | 0.754178 |
104428b63cf7866bbfb78c13a04d1880ab5eff26 | 26,260 | /*
* <pre> The TauP Toolkit: Flexible Seismic Travel-Time and Raypath Utilities.
* Copyright (C) 1998-2000 University of South Carolina 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. The current version can be found at <A
* HREF="www.seis.sc.edu">http://www.seis.sc.edu </A> Bug reports and comments
* should be directed to H. Philip Crotwell, crotwell@seis.sc.edu or Tom Owens,
* owens@seis.sc.edu </pre>
*/
/**
* ReflTransCoefficient.java Reflection and transmission coefficients for body
* waves. Methods for calculating coefficients for each of the possible
* interactions are provided. Calculations are done using the
* com.visualnumerics.javagrande.Complex class from VisualNumerics. It is
* further assume that the incoming ray is coming from the "top" for solid-solid
* interactions and from the bottom for free surface interactions. If the ray is
* actually coming from the bottom, the flip the velocities. The convention for
* free surface and solid solid is a little strange, but can be thought of as
* the top velocities correspond to the layer that they ray starts in.
*
* @see "Aki and Richards page 144-151"
* @see "Lay and Wallace page 98 "
* @see <A HREF="http://math.nist.gov/javanumerics/">Java Numerics </A> Created:
* Wed Feb 17 12:25:27 1999
* @author Philip Crotwell
* @version 1.1.3 Wed Jul 18 15:00:35 GMT 2001
*/
package edu.sc.seis.TauP;
import java.io.Serializable;
public class ReflTransCoefficient implements Serializable {
// IMPORTANT!!!!
// Where ever "CX" appears in this class, it is used as a shorthand for
// the Complex class, so CX.times() is the same as Complex.times, but
// the code is, IMHO, less cluttered.
/** just to avoid having Complex all over the place. */
private static final Complex CX = new Complex();
protected double topVp;
protected double topVs;
protected double topDensity;
protected double botVp;
protected double botVs;
protected double botDensity;
// "flat earth" ray parameter
protected double rp;
// temp variables to make calculations less ugly
// first 3 lines follow both Aki and Richards and Lay and Wallace
protected double a, b, c, d;
protected Complex det, E, F, G, H;
/** used only in free surface calculations */
protected Complex fsA;
/**
* delta for SH-SH equations
*/
protected Complex shDelta;
// store the vertical slownesses for both the top and bottom halfspaces
// for both P and S waves
protected Complex topVertSlownessP, topVertSlownessS;
protected Complex botVertSlownessP, botVertSlownessS;
// we need the squared terms so often that it is worthwhile to store them
protected double sqBotVs; // botVs squared
protected double sqTopVs; // topVs squared
protected double sqBotVp; // botVp squared
protected double sqTopVp; // topVp squared
protected double sqRP; // rp squared
// remember last calculated ray param and wave type to avoid repeating
protected double lastRayParam = -1.0;
protected boolean lastInIsPWave = true;
// CM
protected boolean firstTime = true;
// CM
public ReflTransCoefficient(double topVp,
double topVs,
double topDensity,
double botVp,
double botVs,
double botDensity) {
this.topVp = topVp;
this.topVs = topVs;
this.topDensity = topDensity;
this.botVp = botVp;
this.botVs = botVs;
this.botDensity = botDensity;
}
/**
* Flips the sense of the layers, useful when you have a ray going through
* the same layer in the opposite direction.
*/
public ReflTransCoefficient flip() {
return new ReflTransCoefficient(botVp,
botVs,
botDensity,
topVp,
topVs,
topDensity);
}
protected void calcTempVars(double rayParam, boolean inIsPWave) {
if(rayParam < 0) {
throw new IllegalArgumentException("rayParam cannot be negative");
}
this.rp = rayParam; // ray parameter
// CM
// if (rayParam != lastRayParam && inIsPWave == lastInIsPWave ) {
// if ( (rayParam != lastRayParam || inIsPWave != lastInIsPWave ) ||
// firstTime ) {
if(rayParam != lastRayParam || inIsPWave != lastInIsPWave) {
lastRayParam = -1.0; // in case of failure in method
// CM
firstTime = false;
sqBotVs = botVs * botVs; // botVs squared
sqTopVs = topVs * topVs; // topVs squared
sqBotVp = botVp * botVp; // botVp squared
sqTopVp = topVp * topVp; // topVp squared
sqRP = rp * rp; // rp squared
topVertSlownessP = Complex.sqrt(new Complex(1.0 / sqTopVp - sqRP));
topVertSlownessS = Complex.sqrt(new Complex(1.0 / sqTopVs - sqRP));
botVertSlownessP = Complex.sqrt(new Complex(1.0 / sqBotVp - sqRP));
botVertSlownessS = Complex.sqrt(new Complex(1.0 / sqBotVs - sqRP));
a = botDensity * (1.0 - 2 * sqBotVs * sqRP) - topDensity
* (1.0 - 2 * sqTopVs * sqRP);
b = botDensity * (1.0 - 2 * sqBotVs * sqRP) + 2 * topDensity
* sqTopVs * sqRP;
c = topDensity * (1.0 - 2 * sqTopVs * sqRP) + 2 * botDensity
* sqBotVs * sqRP;
d = 2 * (botDensity * sqBotVs - topDensity * sqTopVs);
// math with complex objects is hard to read, so we give
// the formulas as comments
// E = b * topVertSlownessP + c * botVertSlownessP
// CM E = b * cos(i1)/alpha1 + c * cos(i2)/alpha2
E = CX.plus(topVertSlownessP.times(b), botVertSlownessP.times(c));
// F = b * topVertSlownessS + c * botVertSlownessS
F = CX.plus(topVertSlownessS.times(b), botVertSlownessS.times(c));
// G = a - d * topVertSlownessP * botVertSlownessS
G = CX.minus(new Complex(a),
CX.times(d, CX.times(topVertSlownessP,
botVertSlownessS)));
// H = a - d * botVertSlownessP * topVertSlownessS
H = CX.minus(new Complex(a),
CX.times(d, CX.times(botVertSlownessP,
topVertSlownessS)));
// det = E * F + G * H * sqRP
det = CX.plus(CX.times(E, F), CX.times(G, H).times(sqRP));
// free surface denominator
// fsA = ((1/sqBotVs) - 2 * sqRP)^2 +
// 4 * sqRP * botVertSlownessP * botVertSlownessS
fsA = CX.plus(new Complex(((1 / sqTopVs) - 2 * sqRP)
* ((1 / sqTopVs) - 2 * sqRP)), CX.times(topVertSlownessP,
topVertSlownessS)
.times(4 * sqRP));
// SH delta
shDelta = CX.plus(CX.plus(topDensity * topVs * topVs,
topVertSlownessS), CX.plus(botDensity
* botVs * botVs, botVertSlownessS));
lastRayParam = rayParam;
lastInIsPWave = inIsPWave;
}
}
// FREE SURFACE
/**
* Calculates incident P wave to reflected P wave complex coefficient at
* free surface. Only topVp, topVs, and topDensity are used, the bottom
* values are ignored. This is a little strange as free surface rays are
* always upgoing, but it mantains consistency with the solid-solid
* calculations.
* <P>= (-1*((1/sqTopVs) - 2 * sqRP)^2 +<BR>
* 4 * sqRP * topVertSlownessP * topVertSlownessS) / A
*/
public Complex getComplexFreePtoPRefl(double rayParam) {
calcTempVars(rayParam, true);
Complex numerator = CX.plus(-1.0 * ((1 / sqTopVs) - 2 * sqRP)
* ((1 / sqTopVs) - 2 * sqRP), CX.times(topVertSlownessP,
topVertSlownessS)
.times(4 * sqRP));
return CX.over(numerator, fsA);
}
/**
* Calculates incident P wave to reflected P wave coefficient at free
* surface. This just returns the real part, assuming the imaginary part is
* zero.
*
* @see #getComplexFreePtoPRefl(double)
*/
public double getFreePtoPRefl(double rayParam) {
return CX.real(getComplexFreePtoPRefl(rayParam));
}
/**
* Calculates incident P wave to reflected SV wave complex coefficient at
* free surface. = (4 * (topVp/topVs) * rp * topVertSlownessP * ((1/sqTopVs) -
* 2 * sqRP)) / fsA
*/
public Complex getComplexFreePtoSVRefl(double rayParam) {
calcTempVars(rayParam, true);
double realNumerator = 4 * (topVp / topVs) * rp
* ((1 / sqTopVs) - 2 * sqRP);
return CX.over(CX.times(realNumerator, topVertSlownessP), fsA);
}
/**
* Calculates incident P wave to reflected SV wave coefficient at free
* surface.
*
* @see #getComplexFreePtoSVRefl(double)
*/
public double getFreePtoSVRefl(double rayParam) {
return CX.real(getComplexFreePtoSVRefl(rayParam));
}
/**
* Calculates incident SV wave to reflected P wave complex coefficient at
* free surface.
* <P>= (4 * (topVs/topVp) * rp * topVertSlownessS *<BR>
* ((1/sqTopVs) - 2 * sqRP)) / fsA
*/
public Complex getComplexFreeSVtoPRefl(double rayParam) {
calcTempVars(rayParam, false);
double realNumerator = 4 * (topVs / topVp) * rp
* ((1 / sqTopVs) - 2 * sqRP);
return CX.over(CX.times(realNumerator, topVertSlownessS), fsA);
}
/**
* Calculates incident SV wave to reflected P wave coefficient at free
* surface.
*
* @see #getComplexFreeSVtoPRefl(double)
*/
public double getFreeSVtoPRefl(double rayParam) {
return CX.real(getComplexFreeSVtoPRefl(rayParam));
}
/**
* Calculates incident SV wave to reflected SV wave complex coefficient at
* free surface.
* <P>= (-1 * ((1/sqTopVs) - 2 * sqRP)^2 +<BR>
* 4 * sqRP * topVertSlownessP * topVertSlownessS) / fsA
*/
public Complex getComplexFreeSVtoSVRefl(double rayParam) {
calcTempVars(rayParam, false);
// Aki and Richards don't have -1
double realNumerator = ((1 / sqTopVs) - 2 * sqRP)
* ((1 / sqTopVs) - 2 * sqRP);
Complex numerator = CX.plus(realNumerator,
CX.times(4 * sqRP,
CX.times(topVertSlownessP,
topVertSlownessS)));
return CX.over(numerator, fsA);
}
/**
* Calculates incident SV wave to reflected SV wave coefficient at free
* surface.
*/
public double getFreeSVtoSVRefl(double rayParam) {
return CX.real(getComplexFreeSVtoSVRefl(rayParam));
}
/**
* Calculates incident SH wave to reflected SH wave complex coefficient at
* free surface. Free surface SH is always 1.
*/
public Complex getComplexFreeSHtoSHRefl(double rayParam) {
return new Complex(1);
}
/**
* Calculates incident SH wave to reflected SH wave coefficient at free
* surface. Free surface SH is always 1.
*/
public double getFreeSHtoSHRefl(double rayParam) {
return 1;
}
// Solid-Solid interface
/**
* Calculates incident P wave to reflected P wave Complex coefficient.
* <P>= ((b*topVertSlownessP - c*botVertSlownessP)*F -<BR>
* (a + d*topVertSlownessP * botVertSlownessS)*H*sqRP) / det
*/
public Complex getComplexPtoPRefl(double rayParam) {
calcTempVars(rayParam, true);
Complex FTerm = CX.times(CX.minus(CX.times(b, topVertSlownessP),
CX.times(c, botVertSlownessP)), F);
Complex HTerm = CX.times(CX.plus(a,
CX.times(d, CX.times(topVertSlownessP,
botVertSlownessS))),
CX.times(H, sqRP));
return CX.over(CX.minus(FTerm, HTerm), det);
}
/**
* Calculates incident P wave to reflected P wave coefficient.
*/
public double getPtoPRefl(double rayParam) {
// return CX.abs(getComplexPtoPRefl(rayParam));
return CX.real(getComplexPtoPRefl(rayParam));
}
/**
* Calculates incident P wave to reflected SV wave Complex coefficient.
* <P>= -2 * topVertSlownessP *<BR>
* (a * b + c * d *botVertSlownessP *botVertSlownessS) *<BR>
* rp * (topVp/topVs)) / det
*/
public Complex getComplexPtoSVRefl(double rayParam) {
calcTempVars(rayParam, true);
double realNumerator = -2 * rp * (topVp / topVs);
Complex middleTerm = CX.plus(a * b,
CX.times(c * d, CX.times(botVertSlownessP,
botVertSlownessS)));
Complex numerator = CX.times(CX.times(realNumerator, topVertSlownessP),
middleTerm);
return CX.over(numerator, det);
}
/**
* Calculates incident P wave to reflected SV wave coefficient.
*/
public double getPtoSVRefl(double rayParam) {
return CX.real(getComplexPtoSVRefl(rayParam));
}
/**
* Calculates incident P wave to transmitted P wave Complex coefficient.
* <P>= ( 2 * topDensity * topVertSlownessP * F *<BR>
* (topVp / botVp)) / det
*/
public Complex getComplexPtoPTrans(double rayParam) {
calcTempVars(rayParam, true);
double realNumerator = 2 * topDensity * (topVp / botVp);
return CX.over(CX.times(realNumerator, CX.times(topVertSlownessP, F)),
det);
}
/**
* Calculates incident P wave to transmitted P wave coefficient.
*/
public double getPtoPTrans(double rayParam) {
// return CX.abs(getComplexPtoPTrans(rayParam));
return CX.real(getComplexPtoPTrans(rayParam));
}
/**
* Calculates incident P wave to transmitted SV wave Complex coefficient.
* <P>= (2 * topDensity * topVertSlownessP * H * rp * (topVp / botVs)) /
* <BR>
* det
*/
public Complex getComplexPtoSVTrans(double rayParam) {
calcTempVars(rayParam, true);
double realNumerator = 2 * topDensity * rp * (topVp / botVs);
Complex numerator = CX.times(realNumerator, CX.times(topVertSlownessP,
H));
return CX.over(numerator, det);
}
/**
* Calculates incident P wave to transmitted SV wave coefficient.
*/
public double getPtoSVTrans(double rayParam) {
// return CX.abs(getComplexPtoSVTrans(rayParam));
return CX.real(getComplexPtoSVTrans(rayParam));
}
/**
* Calculates incident SV wave to reflected P wave Complex coefficient.
* <P>= (-2 * topVertSlownessS *<BR>
* (a * b + c * d * botVertSlownessP * botVertSlownessS) *<BR>
* rp * (topVs / topVp)) /<BR>
* det
*/
public Complex getComplexSVtoPRefl(double rayParam) {
calcTempVars(rayParam, false);
double realNumerator = -2 * rp * (topVs / topVp);
// double realNumerator = -2 * rp * (topVs / topVp);
Complex middleTerm = CX.plus(a * b,
CX.times(c * d, CX.times(botVertSlownessP,
botVertSlownessS)));
Complex numerator = CX.times(realNumerator, CX.times(topVertSlownessS,
middleTerm));
return CX.over(numerator, det);
}
/**
* Calculates incident SV wave to reflected P wave coefficient.
*/
public double getSVtoPRefl(double rayParam) {
// return CX.abs(getComplexSVtoPRefl(rayParam));
return CX.real(getComplexSVtoPRefl(rayParam));
}
/**
* Calculates incident SV wave to reflected SV wave Complex coefficient.
* <P>= -1 * ((b * topVertSlownessS - c * botVertSlownessS) * E -<BR>
* (a + b * botVertSlownessP * topVertSlownessS) * G * sqRP) /<BR>
* det
*/
public Complex getComplexSVtoSVRefl(double rayParam) {
calcTempVars(rayParam, false);
Complex adNumerator = CX.times(CX.plus(a,
CX.times(d,
CX.times(botVertSlownessP,
topVertSlownessS))),
CX.times(G, sqRP));
Complex bcNumerator = CX.times(CX.minus(CX.times(b, topVertSlownessS),
CX.times(c, botVertSlownessS)),
E);
return CX.over(CX.minus(adNumerator, bcNumerator), det);
}
/**
* Calculates incident SV wave to reflected SV wave coefficient.
*/
public double getSVtoSVRefl(double rayParam) {
// return CX.abs(getComplexSVtoSVRefl(rayParam));
return CX.real(getComplexSVtoSVRefl(rayParam));
}
/**
* Calculates incident SV wave to transmitted P wave Complex coefficient.
* <P>= -2 * topDensity * topVertSlownessS * G * rp * (topVs / botVp) /
* <BR>
* det
*/
public Complex getComplexSVtoPTrans(double rayParam) {
calcTempVars(rayParam, false);
double realNumerator = -2 * topDensity * rp * (topVs / botVp);
Complex numerator = CX.times(realNumerator, CX.times(topVertSlownessS,
G));
return CX.over(numerator, det);
}
/**
* Calculates incident SV wave to transmitted P wave coefficient.
*/
public double getSVtoPTrans(double rayParam) {
// return CX.abs(getComplexSVtoPTrans(rayParam));
return CX.real(getComplexSVtoPTrans(rayParam));
}
/**
* Calculates incident SV wave to transmitted SV wave Complex coefficient.
* <P>= 2 * topDensity * topVertSlownessS * E * (topVs / botVs) /<BR>
* det
*/
public Complex getComplexSVtoSVTrans(double rayParam) {
calcTempVars(rayParam, false);
double realNumerator = 2 * topDensity * rp * (topVs / botVs);
Complex numerator = CX.times(realNumerator, CX.times(topVertSlownessS,
E));
return CX.over(numerator, det);
}
/**
* Calculates incident SV wave to transmitted SV wave coefficient.
*/
public double getSVtoSVTrans(double rayParam) {
// return CX.abs(getComplexSVtoSVTrans(rayParam));
return CX.real(getComplexSVtoSVTrans(rayParam));
}
// SH waves
/**
* Calculates incident SH wave to reflected SH wave Complex coefficient.
* <P>
* mu = Vs * Vs * density
* <P>= (topMu * topVertSlownessS - botMu * botVertSlownessS) /<BR>
* (topMu * topVertSlownessS + botMu * botVertSlownessS)
*/
public Complex getComplexSHtoSHRefl(double rayParam) {
calcTempVars(rayParam, false);
double topMu = topVs * topVs * topDensity;
double botMu = botVs * botVs * botDensity;
Complex topTerm = CX.times(topMu, topVertSlownessS);
Complex botTerm = CX.times(botMu, botVertSlownessS);
return CX.over(CX.minus(topTerm, botTerm), CX.plus(topTerm, botTerm));
}
/**
* Calculates incident SH wave to reflected SH wave coefficient.
*/
public double getSHtoSHRefl(double rayParam) {
// return CX.abs(getComplexSHtoSHRefl(rayParam));
return CX.real(getComplexSHtoSHRefl(rayParam));
}
/**
* Calculates incident SH wave to transmitted SH wave Complex coefficient.
* <P>
* mu = Vs * Vs * density
* <P>= 2 * topMu * topVertSlownessS /<BR>
* (topMu * topVertSlownessS + botMu * botVertSlownessS)
*/
public Complex getComplexSHtoSHTrans(double rayParam) {
calcTempVars(rayParam, false);
double topMu = topVs * topVs * topDensity;
double botMu = botVs * botVs * botDensity;
Complex topTerm = CX.times(topMu, topVertSlownessS);
Complex botTerm = CX.times(botMu, botVertSlownessS);
return CX.over(CX.times(topTerm, 2), CX.plus(topTerm, botTerm));
}
/**
* Calculates incident SH wave to transmitted SH wave coefficient.
*/
public double getSHtoSHTrans(double rayParam) {
// return CX.abs(getComplexSHtoSHTrans(rayParam));
return CX.real(getComplexSHtoSHTrans(rayParam));
}
public static void main(String[] args) {
double topVp = 4.98;
double topVs = 2.9;
double topDensity = 2.667;
double botVp = 8.0;
double botVs = 4.6;
double botDensity = 3.38;
double depth;
double radiusOfEarth;
double DtoR = Math.PI / 180.0;
double RtoD = 180.0 / Math.PI;
double[] RPP = new double[91];
double[] RPS = new double[91];
double[] RSP = new double[91];
double[] RSS = new double[91];
double[] TPP = new double[91];
double[] TPS = new double[91];
double[] TSP = new double[91];
double[] TSS = new double[91];
ReflTransCoefficient coeff = new ReflTransCoefficient(topVp,
topVs,
topDensity,
botVp,
botVs,
botDensity);
double rayParam;
for(int i = 0; i <= 90; i++) {
rayParam = Math.sin(DtoR * i) / topVp;
RPP[i] = coeff.getPtoPRefl(rayParam);
RPS[i] = coeff.getPtoSVRefl(rayParam);
TPP[i] = coeff.getPtoPTrans(rayParam);
TPS[i] = coeff.getPtoSVTrans(rayParam);
rayParam = Math.sin(DtoR * i) / topVs;
RSP[i] = coeff.getSVtoPRefl(rayParam);
RSS[i] = coeff.getSVtoSVRefl(rayParam);
TSP[i] = coeff.getSVtoPTrans(rayParam);
TSS[i] = coeff.getSVtoSVTrans(rayParam);
}
try {
java.io.Writer out = new java.io.BufferedWriter(new java.io.FileWriter("refltrans.gmt"));
out.write("#!/bin/sh\n\n");
out.write("/bin/rm -f refltrans.ps\n\n");
out.write("psbasemap -K -P -JX6 -R0/90/0/2 -B10/1 > refltrans.ps\n");
// out.write("psxy -K -O -JX -R -M -W1/255/0/0 >> refltrans.ps
// <<END\n");
// for (int i=0; i<=90; i++) {
// out.write(i+" "+RPP[i]+"\n");
// }
// out.write("END\n");
// out.write("psxy -K -O -JX -R -M -W1/0/255/0 >> refltrans.ps
// <<END\n");
// for (int i=0; i<=90; i++) {
// out.write(i+" "+RPS[i]+"\n");
// }
// out.write("END\n");
// out.write("psxy -K -O -JX -R -M -W1/0/0/255 >> refltrans.ps
// <<END\n");
// for (int i=0; i<=90; i++) {
// out.write(i+" "+TPP[i]+"\n");
// }
// out.write("END\n");
// out.write("psxy -K -O -JX -R -M -W1/255/255/0 >> refltrans.ps
// <<END\n");
// for (int i=0; i<=90; i++) {
// out.write(i+" "+TPS[i]+"\n");
// }
// out.write("END\n");
out.write("psxy -K -O -JX -R -M -W1/255/0/0 >> refltrans.ps <<END\n");
for(int i = 0; i <= 90; i++) {
out.write(i + " " + RSP[i] + "\n");
}
out.write("END\n");
out.write("psxy -K -O -JX -R -M -W1/0/255/0 >> refltrans.ps <<END\n");
for(int i = 0; i <= 90; i++) {
out.write(i + " " + RSS[i] + "\n");
}
out.write("END\n");
out.write("psxy -K -O -JX -R -M -W1/0/0/255 >> refltrans.ps <<END\n");
for(int i = 0; i <= 90; i++) {
out.write(i + " " + TSP[i] + "\n");
}
out.write("END\n");
out.write("psxy -O -JX -R -M -W1/255/0/255 >> refltrans.ps <<END\n");
for(int i = 0; i <= 90; i++) {
out.write(i + " " + TSS[i] + "\n");
}
out.write("END\n");
out.close();
} catch(java.io.IOException e) {
System.err.println(e);
}
}
public Complex getBotVertSlownessP(double rayParam) {
calcTempVars(rayParam, true);
return botVertSlownessP;
}
public Complex getBotVertSlownessS(double rayParam) {
calcTempVars(rayParam, false);
return botVertSlownessS;
}
public Complex getTopVertSlownessP(double rayParam) {
calcTempVars(rayParam, true);
return topVertSlownessP;
}
public Complex getTopVertSlownessS(double rayParam) {
calcTempVars(rayParam, false);
return topVertSlownessS;
}
} // ReflTransCoefficient
| 39.848255 | 101 | 0.55933 |
28cd081ce5c7a1d5b19d5993b7d9976386bf9c77 | 5,824 | /**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.compute.strategy.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.util.Map;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* @author Adrian Cole
*
*/
@Singleton
public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWithTagStrategy, DestroyNodeStrategy,
GetNodeMetadataStrategy, ListNodesStrategy, RebootNodeStrategy, ResumeNodeStrategy, SuspendNodeStrategy {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Map<String, Credentials> credentialStore;
private final ComputeServiceAdapter<N, H, I, L> client;
private final Function<N, NodeMetadata> nodeMetadataAdapter;
@Inject
public AdaptingComputeServiceStrategies(Map<String, Credentials> credentialStore,
ComputeServiceAdapter<N, H, I, L> client, Function<N, NodeMetadata> nodeMetadataAdapter) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.client = checkNotNull(client, "client");
this.nodeMetadataAdapter = checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter");
}
@Override
public Iterable<? extends ComputeMetadata> listNodes() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listNodes(), nodeMetadataAdapter), filter);
}
@Override
public NodeMetadata getNode(String id) {
N node = client.getNode(id);
return node == null ? null : nodeMetadataAdapter.apply(node);
}
@Override
public NodeMetadata rebootNode(String id) {
NodeMetadata node = getNode(id);
if (node == null || node.getState() == NodeState.TERMINATED)
return node;
logger.debug(">> rebooting node(%s)", id);
client.rebootNode(id);
logger.debug("<< rebooted node(%s)", id);
return node;
}
@Override
public NodeMetadata resumeNode(String id) {
NodeMetadata node = getNode(id);
if (node == null || node.getState() == NodeState.TERMINATED || node.getState() == NodeState.RUNNING)
return node;
logger.debug(">> resuming node(%s)", id);
client.resumeNode(id);
logger.debug("<< resumed node(%s)", id);
return node;
}
@Override
public NodeMetadata suspendNode(String id) {
NodeMetadata node = getNode(id);
if (node == null || node.getState() == NodeState.TERMINATED || node.getState() == NodeState.SUSPENDED)
return node;
logger.debug(">> suspending node(%s)", id);
client.suspendNode(id);
logger.debug("<< suspended node(%s)", id);
return node;
}
@Override
public NodeMetadata destroyNode(String id) {
NodeMetadata node = getNode(id);
if (node == null)
return node;
logger.debug(">> destroying node(%s)", id);
client.destroyNode(id);
logger.debug("<< destroyed node(%s)", id);
return node;
}
/**
* {@inheritDoc}
*/
@Override
public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
checkState(tag != null, "tag (that which groups identical nodes together) must be specified");
checkState(name != null && name.indexOf(tag) != -1, "name should have %s encoded into it", tag);
logger.debug(">> instantiating node location(%s) name(%s) image(%s) hardware(%s)",
template.getLocation().getId(), name, template.getImage().getProviderId(), template.getHardware()
.getProviderId());
N from = client.runNodeWithTagAndNameAndStoreCredentials(tag, name, template, credentialStore);
NodeMetadata node = nodeMetadataAdapter.apply(from);
logger.debug("<< instantiated node(%s)", node.getId());
return node;
}
} | 35.084337 | 114 | 0.699863 |
e04dee92f4366b3f6ae2b1a240130f4b55de450a | 10,388 | package com.xceptance.loadtest.posters.configuration;
import java.text.MessageFormat;
import org.junit.Assert;
import com.xceptance.loadtest.api.configuration.ConfigDistribution;
import com.xceptance.loadtest.api.configuration.ConfigList;
import com.xceptance.loadtest.api.configuration.ConfigProbability;
import com.xceptance.loadtest.api.configuration.ConfigRange;
import com.xceptance.loadtest.api.configuration.EnumConfigList;
import com.xceptance.loadtest.api.configuration.LTProperties;
import com.xceptance.loadtest.api.configuration.annotations.EnumProperty;
import com.xceptance.loadtest.api.configuration.annotations.Property;
import com.xceptance.loadtest.api.data.Account;
import com.xceptance.loadtest.api.data.Address;
import com.xceptance.loadtest.api.data.CreditCard;
/**
* Represents the test suite configuration.
*
* @author Xceptance Software Technologies
*/
public class Configuration
{
/**
* The name of the current running TestCase' class
*/
public LTProperties properties;
// ===============================================================
// General
@Property(key = "general.url")
public String siteUrlHomepage;
// Basic authentication username
@Property(key = "general.credentials.username", required = false)
public String credentialsUserName;
// Basic authentication password
@Property(key = "general.credentials.password", required = false)
public String credentialsPassword;
// Loads the first page twice to avoid problems with the inline JS/CSS and
// authentication, this will double the measured homepage requests. Only needed
// with auth in place
@Property(key = "general.preloadAuthentication")
public boolean preloadAuthentication;
// URL exclude filter patterns
@Property(key = "com.xceptance.xlt.http.filter.exclude", required = false, fallback = "")
public ConfigList excludeUrlPatterns;
// URL include filter patterns
@Property(key = "com.xceptance.xlt.http.filter.include", required = false, fallback = "")
public ConfigList includeUrlPatterns;
// URL: To start with the direct order scenario
@Property(key = "general.direct.order.url")
public String directOrderUrl;
// ===============================================================
// Selenide
@Property(key = "selenide.recordScreenshots", fallback = "false", required = false)
public boolean selenideRecordScreenshots;
@Property(key = "selenide.pageLoadStrategy", fallback = "chrome", required = false)
public String selenidePageLoadStrategy;
@Property(key = "selenide.savePageSource", fallback = "true", required = false)
public boolean selenideSavePageSource;
@Property(key = "selenide.timeout", fallback = "30000", required = false)
public long selenideTimeout;
// ================================================================
// Email
// Email domain
@Property(key = "general.email.domain")
public String emailDomain;
@Property(key = "general.email.localpart.prefix")
public String emailLocalPartPrefix;
@Property(key = "general.email.localpart.length")
public int emailLocalPartLength;
// Request gzipped resources
@Property(key = "com.xceptance.xlt.http.gzip")
public boolean applyHeaderGzip;
// Puts additional actions into the result browser
@Property(key = "general.debug.actions")
public boolean useDebugActions;
// Generate totally random emails by using the UUID generator or use the XltRandom generator to create a reproducible stream of emails
@Property(key = "general.email.stronglyRandom")
public boolean stronglyRandomEmails;
// ================================================================
// URL Filter
@EnumProperty(key = "filter.product.url", clazz = String.class, from = 0, to = 100, stopOnGap = false, required = false)
public EnumConfigList<String> filterProductUrls;
@EnumProperty(key = "filter.category.url", clazz = String.class, from = 0, to = 100, stopOnGap = false, required = false)
public EnumConfigList<String> filterCategoryUrls;
// ================================================================
// Search
// Range of product searches
@Property(key = "search.count", immutable = false)
public ConfigRange searchesCount;
// File with search terms
@Property(key = "search.hitTermsFile")
public String searchHitTermsFile;
// Probability to execute a 'no-hits' search
@Property(key = "search.noHits", immutable = false)
public ConfigProbability searchNoHitsProbability;
// A list of search params which should result in a no hits page.
@EnumProperty(key = "search.noHitsTerms", clazz = String.class, from = 0, to = 100, stopOnGap = false, required = false, immutable = false)
public EnumConfigList<String> searchNoHitsTerms;
// Shall we try to bypass pagecache for searches
@Property(key = "search.cacheBusting")
public boolean searchCacheBusting;
// How many different variations of the dynamic part do we want?
@Property(key = "search.cacheBusting.count")
public int searchCacheBustingCount;
// Probability to execute an article search
@Property(key = "search.deriveNewPhrases", immutable = false)
public ConfigProbability searchNewPhraseDeriveProbability;
// ==========================================================
// Browsing
// How often do we want to walk the catalog path from the top
@Property(key = "browsing.flow")
public ConfigRange fullBrowseFlow;
// How often do we need the categories touched per browsing flow before refining
@Property(key = "browsing.flow.categories.flow")
public ConfigRange browseCategoriesFlow;
// How often do we refine within the larger browse flow per round
@Property(key = "browsing.flow.refine.flow")
public ConfigRange browseRefineFlow;
// Top category browsing probability
@Property(key = "browsing.category.top", immutable = false)
public ConfigProbability topCategoryBrowsing;
// Probability for display more
@Property(key = "browsing.displaymore", immutable = false)
public ConfigProbability displayMoreProbability;
// Minimum number of products to view when viewing product details
@Property(key = "browsing.product.view.count", immutable = false)
public ConfigRange productViewCount;
// ===========================================================
// Cart
// Probability to execute a 'search' instead of using the navigation menu.
@Property(key = "cart.search", immutable = false)
public ConfigProbability searchOnAddToCartProbability;
// Add to cart as distribution
@Property(key = "cart.add.count")
public ConfigDistribution addToCartCount;
// How often should the cart be shown after an add to cart
@Property(key = "cart.view", immutable = false)
public ConfigProbability viewCartProbability;
// Do we need a counter for add2cart and view cart, mainly for performance debugging
//@Property(key = "cart.report.bySize")
//public boolean reportCartBySize;
// how many product do we want per add to cart?
@Property(key = "cart.product.quantity", immutable = false)
public ConfigRange cartProductQuantity;
// =========================================================
// Account
// where should we take it from
@Property(key = "account.source", required = true)
public String accountSource;
// A list of accounts
@EnumProperty(key = "account", clazz = Account.class, from = 0, to = 20, stopOnGap = false)
public EnumConfigList<Account> accounts;
// A list of addresses to select from, this can grown if needed
@EnumProperty(key = "addresses", clazz = Address.class, from = 0, to = 20, stopOnGap = false)
public EnumConfigList<Address> addresses;
@Property(key = "account.predefined.file", required = false)
public String predefinedAccountsFile;
// ================================================================
// Account Pool
// Whether or not to separate account pools
@Property(key = "account.pool.separator", required = false, fallback = "default")
public String accountPoolSiteSeparator;
// Pools size
@Property(key = "account.pool.size", required = false, fallback = "500")
public int accountPoolSize;
// Probability to reuse an account
@Property(key = "account.pool.reuse", required = false, fallback = "0")
public ConfigProbability accountPoolReuseProbability;
// ===========================================================
// Payment
// Credit card definitions
@EnumProperty(key = "creditcards", clazz = CreditCard.class, from = 0, to = 100, stopOnGap = true)
public EnumConfigList<CreditCard> creditcards;
// ===========================================================
// All data files to be used... this is all for sites aka with hierarchy lookup
// Data file first names
@Property(key = "data.file.firstNames")
public String dataFileFirstNames;
// Data file last names
@Property(key = "data.file.lastNames")
public String dataFileLastNames;
// Search phrases and result counts
@Property(key = "data.file.searchPhrases")
public String dataFileSearchPhrases;
/**
* Return text from the localization section, fails if the text is not available
*
* @param key
* the key to search for including hierarchy excluding "localization."
* @return the found localized
*/
public String localizedText(final String key)
{
final String result = properties.getProperty("localization." + key);
if (result == null)
{
// no result, we fail to be safe for the setup of tests
Assert.fail(MessageFormat.format("Localization key {0} not found", key));
}
return result;
}
/**
* Returns the properties that are current for this context and the source of this
* configuration. You can also directly access them, if you like.
*
* @return the property set
*/
public LTProperties getProperties()
{
return properties;
}
/**
* Constructor
*/
public Configuration()
{
super();
}
} | 36.449123 | 143 | 0.656334 |
5972ab75b16eff447dc43dfd029dd4f6b2054b8f | 5,432 | // Copyright 2000-2021 Nokia
//
// Licensed under the Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
//
package com.nextenso.proxylet.diameter.util;
import java.math.BigInteger;
/**
* The Unsigned64 AVP Format.
* <p>
* See RFC 3588 paragraph 4.2 for information.
* <p>
* Since no Java primitive can wrap a 64 bit unsigned integer, the methods are
* available for 3 types of representation:
* <ul>
* <li>2 ints : 1 for the higher 32 bits, 1 for the lower 32 bits
* <li>a BigInteger
* <li>a long : only valid when the value is positive
* </ul>
*/
public class Unsigned64Format
extends DiameterAVPFormat {
/**
* <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 1L;
/**
* The single static instance.
*/
public static final Unsigned64Format INSTANCE = new Unsigned64Format();
protected Unsigned64Format() {}
/**
* @see com.nextenso.proxylet.diameter.util.DiameterAVPFormat#toString(byte[], int, int, int)
*/
@Override
public String toString(byte[] data, int off, int len, int level) {
return "Unsigned64=" + getUnsigned64BigInteger(data, off).toString();
}
/**
* Decodes an Unsigned64 AVP value.
*
* @param data The data to decode.
* @param offset The offset in the provided data.
* @return The decoded value represented as 2 integers : the first one for the
* higher 32 bits and the second for the lower 32 bits.
*/
public static final int[] getUnsigned64Bytes(byte[] data, int offset) {
return new int[] { Integer32Format.getInteger32(data, offset), Integer32Format.getInteger32(data, offset + 4) };
}
/**
* Encodes into an Unsigned64 AVP value.
*
* @param big The 32 higher bits of the value to encode.
* @param small The 32 lower bits of the value to encode.
* @return The encoded value.
*/
public static final byte[] toUnsigned64(int big, int small) {
byte[] res = new byte[8];
toUnsigned64(res, 0, big, small);
return res;
}
/**
* Encodes into an Unsigned64 AVP value.
*
* @param destination The destination array where the encoded value should be placed.
* @param destinationOffset The offset in the destination array.
* @param big The 32 higher bits of the value to encode.
* @param small The 32 lower bits of the value to encode.
* @return The length of the encoded value.
*/
public static final int toUnsigned64(byte[] destination, int destinationOffset, int big, int small) {
Integer32Format.toInteger32(destination, destinationOffset, big);
Integer32Format.toInteger32(destination, destinationOffset + 4, small);
return 8;
}
/**
* Decodes an Unsigned64 AVP value.
*
* @param data The data to decode.
* @param offset The offset in the provided data.
* @return The decoded value represented as a long : <b>be careful with the
* sign of the returned value</b>.
*/
public static final long getUnsigned64Long(byte[] data, int offset) {
return Integer64Format.getInteger64(data, offset);
}
/**
* Encodes into an Unsigned64 AVP value.
*
* @param value The value to encode.
* @return The encoded value.
*/
public static final byte[] toUnsigned64(long value) {
return Integer64Format.toInteger64(value);
}
/**
* Encodes into an Unsigned64 AVP value.
*
* @param destination The destination array where the encoded value should be placed.
* @param destinationOffset The offset in the destination array.
* @param value The value to encode.
* @return The length of the encoded value.
*/
public static final int toUnsigned64(byte[] destination, int destinationOffset, long value) {
return Integer64Format.toInteger64(destination, destinationOffset, value);
}
/**
* Decodes an Unsigned64 AVP value.
*
* @param data The data to decode.
* @param offset The offset in the provided data.
* @return The decoded value represented as a BigInteger.
*/
public static final BigInteger getUnsigned64BigInteger(byte[] data, int offset) {
long l = getUnsigned64Long(data, offset);
return new BigInteger(new byte[] { (byte) (l >>> 56), (byte) (l >>> 48), (byte) (l >>> 40), (byte) (l >>> 32), (byte) (l >>> 24),
(byte) (l >>> 16), (byte) (l >>> 8), (byte) (l), });
}
/**
* Encodes into an Unsigned64 AVP value.
*
* @param value The value to encode.
* @return The encoded value.
*/
public static final byte[] toUnsigned64(BigInteger value) {
byte[] res = new byte[8];
toUnsigned64(res, 0, value);
return res;
}
/**
* Encodes into an Unsigned64 AVP value.
*
* @param destination The destination array where the encoded value should be placed.
* @param destinationOffset The offset in the destination array.
* @param value the value to encode.
* @return the encoded value.
*/
public static final int toUnsigned64(byte[] destination, int destinationOffset, BigInteger value) {
byte[] b = value.toByteArray();
int length = (b.length < 8 ? b.length : 8);
System.arraycopy(b, 0, destination, destinationOffset + 8 - length, length);
return length;
}
@Override
public byte[] encode(Object value) throws IllegalArgumentException {
if(value instanceof BigInteger) {
return toUnsigned64((BigInteger) value);
} else if(value instanceof Long) {
return toUnsigned64((Long) value);
} else {
throw new IllegalArgumentException("cannot encode value "
+ "of type " + value.getClass() + ". "
+ "A BigInteger or Long is expected");
}
}
}
| 31.04 | 131 | 0.692747 |
b19af257a3b425dac6012c7b9d8bf2df339e5e90 | 3,064 | package com.edison;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author TSN
* @date 2019/12/26
*/
public class CommentGenerator extends EmptyCommentGenerator {
private final Collection<Annotations> annotations;
private String author;
/**
* 当前时间
*/
private String currentDateStr;
public CommentGenerator() {
currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
annotations = new LinkedHashSet<Annotations>(Annotations.values().length);
}
@Override
public void addConfigurationProperties(Properties properties) {
annotations.add(Annotations.DATA);
for (String stringPropertyName : properties.stringPropertyNames()) {
if (stringPropertyName.contains(".")) {
continue;
}
if (!Boolean.parseBoolean(properties.getProperty(stringPropertyName))) {
continue;
}
Annotations annotation = Annotations.getValueOf(stringPropertyName);
if (annotation == null) {
continue;
}
String optionsPrefix = stringPropertyName + ".";
for (String propertyName : properties.stringPropertyNames()) {
if (!propertyName.startsWith(optionsPrefix)) {
continue;
}
String propertyValue = properties.getProperty(propertyName);
annotation.appendOptions(propertyName, propertyValue);
annotations.add(annotation);
annotations.addAll(Annotations.getDependencies(annotation));
}
annotations.add(annotation);
}
author = properties.getProperty("author");
}
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
String remarks = introspectedTable.getRemarks();
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * " + remarks);
topLevelClass.addJavaDocLine(" * @author " + author);
topLevelClass.addJavaDocLine(" * @date " + currentDateStr);
topLevelClass.addJavaDocLine(" */");
addClassAnnotation(topLevelClass);
}
private void addClassAnnotation(TopLevelClass topLevelClass) {
for (Annotations annotation : annotations) {
topLevelClass.addImportedType(annotation.javaType);
topLevelClass.addAnnotation(annotation.asAnnotation());
}
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
field.addJavaDocLine("/**");
field.addJavaDocLine(" * " + remarks);
field.addJavaDocLine(" */");
}
}
| 35.218391 | 122 | 0.650131 |
d2074dd42475a9cbe0859b714fcd864cfe5a3d95 | 1,212 | package seedu.organizer.logic.parser;
//@@author aguss787
import static seedu.organizer.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import seedu.organizer.commons.core.index.Index;
import seedu.organizer.commons.exceptions.IllegalValueException;
import seedu.organizer.logic.commands.DeleteSubtaskCommand;
import seedu.organizer.logic.parser.exceptions.ParseException;
/**
* Parses input arguments and creates a new DeleteCommand object
*/
public class DeleteSubtaskCommandParser implements Parser<DeleteSubtaskCommand> {
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns an DeleteCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public DeleteSubtaskCommand parse(String args) throws ParseException {
try {
Index[] indexs = ParserUtil.parseSubtaskIndex(args);
return new DeleteSubtaskCommand(indexs[0], indexs[1]);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteSubtaskCommand.MESSAGE_USAGE));
}
}
}
| 39.096774 | 103 | 0.744224 |
0ae3cc537147a4383de5203ca46d997ec8269f1f | 4,120 | package com.carlo.question;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.aiwolf.client.lib.TemplateTalkFactory.TalkType;
import org.aiwolf.client.lib.Utterance;
import org.aiwolf.common.data.Agent;
import org.aiwolf.common.data.Role;
import org.aiwolf.common.data.Species;
import org.aiwolf.common.data.Talk;
import org.aiwolf.common.net.GameInfo;
import com.carlo.bayes.trust.Correct;
import com.carlo.bayes.trust.TrustListManager;
import com.carlo.lib.AIMAssister;
import com.carlo.lib.AbilityResult;
import com.carlo.lib.AgentInformationManager;
import jp.halfmoon.inaba.aiwolf.log.DayLog;
import jp.halfmoon.inaba.aiwolf.log.TalkLog;
/**
* ログで動作するように、TrustListManagerのメソッドをオーバーライドしたもの
* @author carlo
*
*/
public class TrustListMngForLog extends TrustListManager{
private DayLog dayLog;
public TrustListMngForLog(List<Agent> agentList, Agent myAgent, AgentInformationManager agentInfo) {
super(agentList, myAgent, agentInfo);
setShowConsoleLog(false);
}
public void dayStart(DayLog dayLog){
this.dayLog=dayLog;
super.dayStart();
//trustList.getTrustPoint(Agent.getAgent(1));
}
@Override
protected int getDay(){
return dayLog.getDay();
}
/** ログからRoleMapを生成して、動作させる<br>
* isShowConsoleLogを無視して表示 */
public void printTrustListForCreatingData(){
HashMap<Agent,Role> roleMap=new HashMap();
//map生成
for(int i=1;i<=15;i++){
roleMap.put(Agent.getAgent(i), dayLog.getStatus().get(i).getRole());
}
trustList.printTrustListForCreatingData(roleMap);
}
@Override
protected void readTalkList(){
dayLog.getTalk();
//talkLog-List変換
ArrayList<Talk> talkList=new ArrayList<Talk>();
for(TalkLog talkLog:dayLog.getTalk()){
if(talkLog.getTalkType()==TalkType.TALK){
Talk talk=new Talk(talkLog.getIdx(),talkLog.getDay(),Agent.getAgent(talkLog.getAgentNo()),talkLog.getContent());
talkList.add(talk);
}
}
//後は一緒
for(int i=readTalkNum;i<talkList.size();i++){
Talk talk=talkList.get(i);
Utterance utterance=new Utterance(talk.getContent());
switch (utterance.getTopic()){
case COMINGOUT:
switch (utterance.getRole()){
case MEDIUM:
break;
default:
break;
}
break;
case DIVINED:
Agent seer=talk.getAgent();
int day=talk.getDay();
Species species=utterance.getResult();
trustList.changeSeerTrust(seer,day, species, Correct.UNKNOWN,utterance.getTarget(),Correct.UNKNOWN);
break;
case INQUESTED:
Agent medium=talk.getAgent();
//霊能者のネットワーク計算
trustList.changeMediumTrust(medium, utterance.getResult(), talk.getDay());
//霊能COが一人だけなら、霊能を真と仮定して各占いとラインが繋がっているかで信用度の計算
if(agentInfo.countCoAgent(Role.MEDIUM)==1){
Species inquestedResult=utterance.getResult();
//投票結果から計算
for(Entry<Agent,Integer> voteEntry : agentInfo.searchVoterMap(utterance.getTarget()).entrySet()) {
int voteDay=voteEntry.getValue();
Agent voteAgent=voteEntry.getKey();
Agent executedAgent=utterance.getTarget();
boolean assist= (executedAgent==agentInfo.getVoteTarget(voteDay, voteAgent));
trustList.changeVoterTrust(voteEntry.getKey(), utterance.getResult(),voteDay,String.valueOf(assist));
}
//霊媒先と一致する占い結果を探す
for(AbilityResult abilityResult:AIMAssister.searchDivinedAgent(agentInfo, utterance.getTarget())){
//まず前回の結果を戻す
//if(isShowConsoleLog) System.out.println("back trust ");
trustList.changeSeerTrust(abilityResult.getAgent(),abilityResult.getTalkedDay(), abilityResult.getSpecies(), Correct.UNKNOWN,true,utterance.getTarget(),Correct.UNKNOWN);
//判明した結果を入れて計算
Correct correct=Correct.UNKNOWN;
if(inquestedResult==abilityResult.getSpecies()) correct=Correct.YES;
else correct=Correct.NO;
//if(isShowConsoleLog) System.out.println("recalc trust ");
trustList.changeSeerTrust(abilityResult.getAgent(),abilityResult.getTalkedDay(), abilityResult.getSpecies(), correct,utterance.getTarget(),Correct.UNKNOWN);
}
}
break;
default:
break;
}
readTalkNum++;
}
}
}
| 31.937984 | 175 | 0.729369 |
873d541196ca237456a90559f28d278a90717d2a | 666 | package br.com.zup.proposta.config.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfiguration {
@Bean
public Docket proposalApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("br.com.zup.proposta"))
.paths(PathSelectors.ant("/**"))
.build();
}
}
| 30.272727 | 69 | 0.809309 |
92b64e04acfa6bcbbd0575293a7d4b6a53106c7b | 2,393 | package com.ara.project_common.data.util;
import android.text.TextUtils;
import com.ara.common.util.GsonUtils;
import com.ara.common.util.MMKVUtils;
import com.ara.network.RetrofitHolder;
import com.ara.project_common.data.bean.AccountBean;
import com.ara.project_common.data.config.Configs;
/**
* Created by XieXin on 2018/12/27.
* 账户 工具类
*/
public class AccountUtils {
/*** 是否登录 登录-true 未登录-false */
private static boolean isLogin = false;
/*** 登录账号 */
private static String loginAccount = "";
/*** Token */
private static String token = "";
/*** 账户 */
private static AccountBean account;
public static boolean isLogin() {
isLogin = MMKVUtils.decodeBoolean(Configs.ACCOUNT_IS_LOGIN, false);
return isLogin;
}
public static void setIsLogin(boolean isLogin) {
AccountUtils.isLogin = isLogin;
MMKVUtils.encode(Configs.ACCOUNT_IS_LOGIN, isLogin);
}
public static String getLoginAccount() {
if (TextUtils.isEmpty(loginAccount))
loginAccount = MMKVUtils.decodeString(Configs.LOGIN_ACCOUNT, "");
return loginAccount;
}
public static void setLoginAccount(String loginAccount) {
AccountUtils.loginAccount = loginAccount;
MMKVUtils.encode(Configs.LOGIN_ACCOUNT, loginAccount);
}
public static String getToken() {
if (TextUtils.isEmpty(token))
token = MMKVUtils.decodeString(RetrofitHolder.TOKEN_KEY, "");
return token;
}
public static void setToken(String token) {
AccountUtils.token = token;
MMKVUtils.encode(RetrofitHolder.TOKEN_KEY, token);
}
public static AccountBean getAccount() {
if (account == null) {
String json = MMKVUtils.decodeString(Configs.ACCOUNT, "");
if (TextUtils.isEmpty(json)) return new AccountBean();
account = GsonUtils.toBean(json, AccountBean.class);
}
return account;
}
public static void setAccount(AccountBean account) {
if (account == null) return;
AccountUtils.account = account;
MMKVUtils.encode(Configs.ACCOUNT, GsonUtils.toString(account));
}
public static void logout() {
MMKVUtils.remove(Configs.ACCOUNT_IS_LOGIN);
MMKVUtils.remove(Configs.ACCOUNT);
isLogin = false;
account = null;
setToken("");
}
}
| 29.54321 | 77 | 0.658588 |
e719d942c3eddfb2a4bc7cb779acd39afed36f01 | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:8950c125550d69e1feafb8ea7c902b64156fcf50bb2fb1d0b272b30bce0478bd
size 7799
| 32.25 | 75 | 0.883721 |
5d48462f6684169ced6e960748b4f86c5e1dfb7b | 46 | package Classes;
public class Montadora {
}
| 7.666667 | 24 | 0.73913 |
7a1927434b84c31e0c53fabee7bb7e01f7d73193 | 1,954 | package net.kamradtfamily.servertrack.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.Date;
import net.kamradtfamily.servertrack.spi.AverageLoadValues;
import net.kamradtfamily.servertrack.spi.LoadValue;
import net.kamradtfamily.servertrack.spi.ServerTrack;
/**
* A RESTful Webservice object. Two entry points POST and GET. Both take a
* servername as the last-leg of the path. POST creates a timestamped load
* entry, and GET will return a list of load entries in hourly and minute buckets.
*
* @author randalkamradt
* @since 1.0
*/
@Path("/servertrack")
public class ServerTrackRest {
/**
* Get the list of load entries for this server
* @param server the server name
* @return the JSON document with the lists of averaged loads.
*/
@GET
@Path("/{server}")
@Produces("application/json")
public Response getLoad(@PathParam("server") String server) {
ServerTrack serverTrack = ServerTrackSingleton.getTheServerTrack();
AverageLoadValues value = serverTrack.getLoad(server, new Date().getTime());
return Response.ok().entity(value).build();
}
/**
*
* Add a single load record to the store.
*
* @param server the name of the server
* @param input a JSON object that has the cpu and ram load.
* @return a JSON object that has the cpu and ram load, and a timestamp.
*/
@POST
@Produces("application/json")
@Consumes("application/json")
@Path("/{server}")
public Response record(@PathParam("server") String server, LoadValue input) {
ServerTrack serverTrack = ServerTrackSingleton.getTheServerTrack();
LoadValue lv = serverTrack.record(server, input, new Date().getTime());
return Response.ok().entity(lv).build();
}
}
| 33.689655 | 84 | 0.696008 |
8812ca7636f0a6652daa4a6caf1fe78f4a3ced8c | 1,021 | package com.github.instagram4j.instagram4j.requests.live;
import com.github.instagram4j.instagram4j.IGClient;
import com.github.instagram4j.instagram4j.requests.IGGetRequest;
import com.github.instagram4j.instagram4j.responses.live.LiveBroadcastLikeResponse.LiveBroadcastGetLikeCountResponse;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@AllArgsConstructor
public class LiveBroadcastGetLikeCountRequest extends IGGetRequest<LiveBroadcastGetLikeCountResponse> {
@NonNull
private String broadcast_id;
private long like_ts;
@Override
public String path() {
return "live/" + broadcast_id + "/get_like_count/";
}
@Override
public String getQueryString(IGClient client) {
return mapQueryString("like_ts", String.valueOf(like_ts));
}
@Override
public Class<LiveBroadcastGetLikeCountResponse> getResponseType() {
return LiveBroadcastGetLikeCountResponse.class;
}
}
| 30.029412 | 117 | 0.779628 |
26c5ca9b7a9fcdb10a974210fb8c9a719249e64a | 1,550 | package com.codingblocks;
public class Maze {
public static void main(String[] args) {
int row = 100;
int col = 100;
long[][] mem = new long[row+1][col+1];
System.out.println(mazeCountItrDP(100, 100, mem));
}
public static int mazeCount(int row, int col){
if (row == 1 || col == 1){
return 1;
}
return mazeCount(row-1, col) + mazeCount(row, col-1);
}
public static long mazeCountDP(int row, int col, long[][] mem){
if (row == 1 || col == 1){
return 1;
}
if (mem[row][col] != 0){
return mem[row][col];
}
mem[row][col] = mazeCountDP(row-1, col, mem) + mazeCountDP(row, col-1, mem);
return mem[row][col];
}
public static long mazeCountItrDP(int row, int col, long[][] mem){
for (int r = 1; r <= row; r++) {
for (int c = 1; c <= col; c++) {
if ( r==1 || c == 1){
mem[r][c] = 1;
} else {
mem[r][c] = mem[r-1][c] + mem[r][c-1];
}
}
}
return mem[row][col];
}
public static long mazeCountItrSS(int row, int col, long[] mem){
for (int r = 1; r <= row; r++) {
for (int c = 1; c <= col; c++) {
if ( r==1 || c == 1){
mem[c] = 1;
} else {
mem[c] = mem[c-1] + mem[c];
}
}
}
return mem[col];
}
}
| 23.134328 | 84 | 0.407097 |
424c6e8ca57aefae43f53b2d932410cdab287038 | 501 | package com.poc.pucmg.descartevencidos.agendadores;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.poc.pucmg.descartevencidos.servicos.ProdutoService;
@Component
public class JobVencimento {
@Autowired
private ProdutoService produtoService;
@Scheduled(fixedRate = 5000)
public void avaliarVencimento() {
produtoService.avaliarVencimento();
}
}
| 23.857143 | 62 | 0.814371 |
6829b392b265c2c33f14006ea31fcb89f65d9cc9 | 501 | package ru.autometry.obd.commands.adaptor.honda;
import ru.autometry.obd.commands.Answer;
import ru.autometry.obd.commands.adaptor.FormulaAdaptor;
import ru.autometry.obd.exception.OBDException;
/**
* Created by jeck on 14/08/14
*/
public class CtLtCorrection extends FormulaAdaptor {
@Override
protected Object adapt(Integer value, Answer response) throws OBDException {
double res;
if (value == 0)
value = 128;
res = ((double) value / 128 - 1) * 100;
return res;
}
}
| 25.05 | 78 | 0.716567 |
ac28c26eedaed2157c3fd0b92d94095bba686bf8 | 2,869 | /*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.connector.vitess;
import java.time.ZoneOffset;
import org.apache.kafka.connect.data.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.relational.RelationalDatabaseSchema;
import io.debezium.relational.Table;
import io.debezium.relational.TableId;
import io.debezium.relational.TableSchemaBuilder;
import io.debezium.schema.TopicSelector;
import io.debezium.util.SchemaNameAdjuster;
/**
* Logical in-memory representation of Vitess schema (a.k.a Vitess keyspace). It is used to create
* kafka connect {@link Schema} for all tables.
*/
public class VitessDatabaseSchema extends RelationalDatabaseSchema {
private static final Logger LOGGER = LoggerFactory.getLogger(VitessDatabaseSchema.class);
public VitessDatabaseSchema(
VitessConnectorConfig config,
SchemaNameAdjuster schemaNameAdjuster,
TopicSelector<TableId> topicSelector) {
super(
config,
topicSelector,
new Filters(config).tableFilter(),
new Filters(config).columnFilter(),
new TableSchemaBuilder(
new VitessValueConverter(
config.getDecimalMode(),
config.getTemporalPrecisionMode(),
ZoneOffset.UTC,
config.includeUnknownDatatypes()),
schemaNameAdjuster,
config.customConverterRegistry(),
config.getSourceInfoStructMaker().schema(),
config.getSanitizeFieldNames()),
false,
config.getKeyMapper());
}
/** Applies schema changes for the specified table. */
public void applySchemaChangesForTable(Table table) {
if (isFilteredOut(table.id())) {
LOGGER.trace("Skipping schema refresh for table '{}' as table is filtered", table.id());
return;
}
refresh(table);
}
private boolean isFilteredOut(TableId id) {
return !getTableFilter().isIncluded(id);
}
/** Refreshes the schema content with a table constructed externally */
private void refresh(Table table) {
tables().overwriteTable(table);
refreshSchema(table.id());
}
private void refreshSchema(TableId id) {
LOGGER.trace("refreshing DB schema for table '{}'", id);
Table table = tableFor(id);
buildAndRegisterSchema(table);
}
public static TableId parse(String table) {
return TableId.parse(table, false);
}
}
| 34.566265 | 114 | 0.617985 |
ab7f6c49ec1c01f59aaab6189e5ade7edce8f614 | 9,447 | /**
* Copyright (c) 2013-2022 Contributors to the Eclipse Foundation
*
* <p> See the NOTICE file distributed with this work for additional information regarding copyright
* ownership. All rights reserved. This program and the accompanying materials are made available
* under the terms of the Apache License, Version 2.0 which accompanies this distribution and is
* available at http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package org.locationtech.geowave.analytic.mapreduce.kmeans.runner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
import org.apache.hadoop.conf.Configuration;
import org.locationtech.geowave.analytic.AnalyticItemWrapper;
import org.locationtech.geowave.analytic.PropertyManagement;
import org.locationtech.geowave.analytic.clustering.CentroidManager;
import org.locationtech.geowave.analytic.clustering.CentroidManager.CentroidProcessingFn;
import org.locationtech.geowave.analytic.clustering.CentroidManagerGeoWave;
import org.locationtech.geowave.analytic.mapreduce.MapReduceJobRunner;
import org.locationtech.geowave.core.index.FloatCompareUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Remove weak centers. Looking for a large gaps of distances AND retain a minimum set. */
public class StripWeakCentroidsRunner<T> implements MapReduceJobRunner {
protected static final Logger LOGGER = LoggerFactory.getLogger(StripWeakCentroidsRunner.class);
private int minimum = 1;
private int maximum = 1000;
private int currentCentroidCount = 0;
private BreakStrategy<T> breakStrategy = new TailMaxBreakStrategy<>();
public StripWeakCentroidsRunner() {}
public void setBreakStrategy(final BreakStrategy<T> breakStrategy) {
this.breakStrategy = breakStrategy;
}
/** @param minimum new minimum number of centroids to retain, regardless of weak center; */
public void setRange(final int minimum, final int maximum) {
this.minimum = minimum;
this.maximum = maximum;
}
/**
* Available only after execution.
*
* @return The count of current centroids after execution
*/
public int getCurrentCentroidCount() {
return currentCentroidCount;
}
protected CentroidManager<T> constructCentroidManager(
final Configuration config,
final PropertyManagement runTimeProperties) throws IOException {
return new CentroidManagerGeoWave<>(runTimeProperties);
}
@Override
public int run(final Configuration config, final PropertyManagement runTimeProperties)
throws Exception {
currentCentroidCount = 0;
final CentroidManager<T> centroidManager = constructCentroidManager(config, runTimeProperties);
return centroidManager.processForAllGroups(new CentroidProcessingFn<T>() {
@Override
public int processGroup(final String groupID, final List<AnalyticItemWrapper<T>> centroids) {
if (centroids.size() <= minimum) {
currentCentroidCount = centroids.size();
return 0;
}
Collections.sort(centroids, new Comparator<AnalyticItemWrapper<T>>() {
@Override
public int compare(final AnalyticItemWrapper<T> arg0, final AnalyticItemWrapper<T> arg1) {
// be careful of overflow
// also, descending
return (arg1.getAssociationCount() - arg0.getAssociationCount()) < 0 ? -1 : 1;
}
});
int position = breakStrategy.getBreakPoint(centroids);
// make sure we do not delete too many
// trim bottom third
position = Math.min(Math.max(minimum, position), maximum);
final String toDelete[] = new String[centroids.size() - position];
LOGGER.info("Deleting {} out of {}", toDelete.length, centroids.size());
int count = 0;
final Iterator<AnalyticItemWrapper<T>> it = centroids.iterator();
while (it.hasNext()) {
final AnalyticItemWrapper<T> centroid = it.next();
if (count++ >= position) {
toDelete[count - position - 1] = centroid.getID();
}
}
try {
centroidManager.delete(toDelete);
} catch (final IOException e) {
LOGGER.warn("Unable to delete the centriod mamager", e);
return -1;
}
currentCentroidCount += position;
return 0;
}
});
}
public static class MaxChangeBreakStrategy<T> implements BreakStrategy<T> {
@Override
public int getBreakPoint(final List<AnalyticItemWrapper<T>> centroids) {
int position = centroids.size();
int count = 0;
final StandardDeviation st = new StandardDeviation();
double total = 0.0;
double prior = Double.NaN;
for (final AnalyticItemWrapper<T> centroid : centroids) {
if (!Double.isNaN(prior)) {
final double chg = Math.abs(prior - centroid.getAssociationCount());
st.increment(chg);
total += chg;
}
prior = centroid.getAssociationCount();
}
double max = getInitialMaximum(st, total);
prior = Double.NaN;
// look for largest change
for (final AnalyticItemWrapper<T> centroid : centroids) {
if (centroid.getAssociationCount() <= 1) {
if (position == 0) {
position = count;
}
break;
}
if (!Double.isNaN(prior)) {
final double chg = Math.abs(prior - centroid.getAssociationCount());
if (FloatCompareUtils.checkDoublesEqual(Math.max(max, chg), chg)) {
position = count;
max = chg;
}
}
prior = centroid.getAssociationCount();
count++;
}
return position;
}
protected double getInitialMaximum(final StandardDeviation stats, final double total) {
return 0.0;
}
}
private static class ChangeFromLast implements Comparable<ChangeFromLast> {
int position;
double chg;
public ChangeFromLast(final int position, final double chg) {
super();
this.position = position;
this.chg = chg;
}
@Override
public String toString() {
return "ChangeFromLast [position=" + position + ", chg=" + chg + "]";
}
@Override
public int compareTo(final ChangeFromLast arg0) {
return new Double((arg0).chg).compareTo(chg);
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof ChangeFromLast)) {
return false;
}
return compareTo((ChangeFromLast) obj) == 0;
}
@Override
public int hashCode() {
return Double.valueOf(chg).hashCode();
}
}
public static class StableChangeBreakStrategy<T> implements BreakStrategy<T> {
@Override
public int getBreakPoint(final List<AnalyticItemWrapper<T>> centroids) {
final List<ChangeFromLast> changes = new ArrayList<>(centroids.size());
final StandardDeviation st = new StandardDeviation();
double prior = Double.NaN;
double total = 0;
int count = 0;
// look for largest change
for (final AnalyticItemWrapper<T> centroid : centroids) {
final double chgValue =
(!Double.isNaN(prior)) ? Math.abs(prior - centroid.getAssociationCount()) : 0.0;
changes.add(new ChangeFromLast(count, chgValue));
prior = centroid.getAssociationCount();
count++;
}
Collections.sort(changes);
int position = centroids.size();
count = 0;
ChangeFromLast priorChg = null;
for (final ChangeFromLast changeFromLast : changes) {
if (priorChg != null) {
final double chgOfChg = Math.abs(priorChg.chg - changeFromLast.chg);
total += chgOfChg;
st.increment(chgOfChg);
}
priorChg = changeFromLast;
count++;
}
double max = getInitialMaximum(st, total);
position = changes.get(0).position;
if (changes.get(0).chg < max) {
return centroids.size();
}
priorChg = null;
// look for largest change
for (final ChangeFromLast changeFromLast : changes) {
if (priorChg != null) {
final double chgOfChg = Math.abs(priorChg.chg - changeFromLast.chg);
if (chgOfChg > max) {
position = Math.max(position, changeFromLast.position);
max = chgOfChg;
}
}
priorChg = changeFromLast;
}
return position;
}
protected double getInitialMaximum(final StandardDeviation stats, final double total) {
return 0.0;
}
}
public static class TailMaxBreakStrategy<T> extends MaxChangeBreakStrategy<T> implements
BreakStrategy<T> {
@Override
protected double getInitialMaximum(final StandardDeviation stats, final double total) {
return (total / stats.getN()) + stats.getResult();
}
}
public static class TailStableChangeBreakStrategy<T> extends StableChangeBreakStrategy<T>
implements
BreakStrategy<T> {
@Override
protected double getInitialMaximum(final StandardDeviation stats, final double total) {
return (total / stats.getN()) + stats.getResult();
}
}
public interface BreakStrategy<T> {
public int getBreakPoint(List<AnalyticItemWrapper<T>> centroids);
}
}
| 32.132653 | 100 | 0.663809 |
020897e8e3796d42ebdf4dd53ee29e5924ef199b | 2,088 | /**
*
* Copyright 2009,2010,2011,2012 RickCeeNet
*
* 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.
*
* Created on Feb 22, 2012
*
*/
package net.rickcee.swingxs.ui;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
public class JXSTableHeaderRenderer implements TableCellRenderer {
// This method is called each time a column header
// using this renderer needs to be rendered.
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int rowIndex, int vColIndex) {
TableCellRenderer tcr = table.getTableHeader().getDefaultRenderer();
Component c = tcr.getTableCellRendererComponent(table, value, isSelected, hasFocus, rowIndex, vColIndex);
DefaultTableCellRenderer r = (DefaultTableCellRenderer) c;
Integer sortIndex = 1;
for (RowSorter.SortKey sk : table.getRowSorter().getSortKeys()) {
if (sk.getColumn() == table.convertColumnIndexToModel(vColIndex)) {
// System.out.println("SortColumn: " + sk.getColumn() + " / " +
// sortIndex);
if (sk.getSortOrder().equals(SortOrder.ASCENDING)) {
r.setIcon(new JXSColumnControlIcon(sortIndex, SortOrder.ASCENDING));
} else {
r.setIcon(new JXSColumnControlIcon(sortIndex, SortOrder.DESCENDING));
}
}
sortIndex++;
}
// Set tool tip if desired
r.setToolTipText((String) value);
// Since the renderer is a component, return itself
return r;
}
}
| 33.677419 | 113 | 0.740421 |
a88d2f0238c1cab99e94b4aeeed1d94addb6683f | 635 | package com.springboot.training.spaceover.spacemission.manager.utils.validators;
import com.springboot.training.spaceover.spacemission.manager.utils.annotatations.NullOrNotBlank;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class NullOrNotBlankValidator implements ConstraintValidator<NullOrNotBlank, String> {
@Override
public void initialize(final NullOrNotBlank constraintAnnotation) {
}
@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
return value == null || !value.trim().isEmpty();
}
} | 37.352941 | 97 | 0.8 |
eb9ff7073818756cbe54dcd0fdf041bda6b9a050 | 593 | package com.castle.store;
import java.util.Collection;
import java.util.function.Predicate;
public interface SafeWritableStore<T> extends WritableStore<T> {
@Override
boolean insert(T element);
@Override
boolean insertIfAbsent(T element);
@Override
boolean insertAll(Collection<? extends T> collection);
@Override
boolean delete(T element);
@Override
boolean deleteFirst(Predicate<T> filter);
@Override
boolean deleteAll(Predicate<T> filter);
@Override
boolean deleteAll(Collection<T> collection);
@Override
void clear();
}
| 21.962963 | 64 | 0.709949 |
83041e866c6c3cc4e94fb4edcc4c72b0978edccf | 4,348 | package cn.gyw.middleware.zk.lock;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import cn.gyw.platform.common.util.PrintUtil;
import cn.gyw.platform.common.util.PropertiesUtil;
/**
* 基于永久顺序节点的分布式锁
*
* 说明: 如果有一把锁,多个人竞争,多个人会排队,第一个拿到锁执行,然后释放锁,每个人排队只监听前一个节点,
* 一旦有人释放了锁,会通知后一个节点,公平锁的思想
*
* 类似:AQS
*/
public class ZookeeperDistributedLock implements Watcher {
private static final String CONFIG_FILE = "config.properties";
private ZooKeeper zk;
private String locksRoot = "/locks";
private String id;
private String waitNode;
private String selfNode;
private int sessionTimeout = 3000000;
// 执行栅栏
private CountDownLatch latch;
// 保证连接成功后进行操作
private CountDownLatch connectedLatch = new CountDownLatch(1);
public ZookeeperDistributedLock(String id) {
this.id = id;
Properties properties = PropertiesUtil.readConfig(CONFIG_FILE);
try {
zk = new ZooKeeper(properties.getProperty("zk.connect.addr"), sessionTimeout, this);
connectedLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取分布式锁
*
* 阻塞
*/
public void acquireDistributedLock() {
PrintUtil.print("this object :" + this);
try {
if (this.tryLock()) {
return;
}
waitForLock(waitNode, sessionTimeout);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 尝试获取锁
*
* @return
*/
private Boolean tryLock() {
try {
selfNode = zk.create(locksRoot + "/" + id, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL);
// 找到最早的节点
List<String> locks = zk.getChildren(locksRoot, false);
Collections.sort(locks);
if (selfNode.equals(locksRoot + "/" + locks.get(0))) {
// 最早的节点,获取锁成功
PrintUtil.print(" 获取锁:" + selfNode);
return true;
}
// 非最小节点,找到前一个节点
int previousLockIndex = -1;
for (int i = 1, len = locks.size(); i < len; i++) {
if (selfNode.equals(locksRoot + "/" + locks.get(i))) {
previousLockIndex = i - 1;
break;
}
}
// 需要等待释放锁的节点
this.waitNode = locks.get(previousLockIndex);
PrintUtil.print(" 等待节点释放锁:" + waitNode);
// 判断等待节点是否存在,避免遍历时,锁已释放
if (this.waitNode == null) {
// 节点已经释放锁
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 等待锁
*
* @param waitNode
* @param timeout
* @return
* @throws KeeperException
* @throws InterruptedException
*/
private boolean waitForLock(String waitNode, int timeout) throws KeeperException, InterruptedException {
Stat stat = zk.exists(locksRoot + "/" + waitNode, true);
if (stat != null) {
latch = new CountDownLatch(1);
PrintUtil.print("latch init :" + this.latch);
latch.await(timeout, TimeUnit.MILLISECONDS);
latch = null;
}
return true;
}
/**
* 释放锁
*/
public void unlock() {
try {
PrintUtil.print("Unlock " + this.selfNode);
zk.delete(selfNode, -1);
selfNode = null;
zk.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 执行在 EventThread 线程中
*/
@Override
public void process(WatchedEvent event) {
Event.KeeperState keeperState = event.getState();
Event.EventType eventType = event.getType();
switch (keeperState) {
case SyncConnected:
if (EventType.None == eventType) {
PrintUtil.print(" 连接zk 服务器");
connectedLatch.countDown();
break;
}
PrintUtil.print("keeperState:" + keeperState, "EventType:" + eventType, "Path:" + event.getPath(),
"waitNode:" + this.waitNode);
// 节点删除,且是自己等待的节点
if (EventType.NodeDeleted == eventType && event.getPath().equals(locksRoot + "/" + this.waitNode)) {
if (this.latch != null) {
this.latch.countDown();
}
}
break;
case Disconnected:
PrintUtil.print("与zk服务器断开连接");
break;
case AuthFailed:
PrintUtil.print("权限验证失败");
break;
case Expired:
PrintUtil.print("会话失败");
break;
default:
PrintUtil.print("不处理的状态:" + keeperState);
}
}
}
| 23.502703 | 105 | 0.675023 |
7c308c4a8a2fff2ddda48178c696543245bbc33d | 2,964 | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.awaitility;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Duration.FIVE_SECONDS;
import static org.hamcrest.CoreMatchers.equalTo;
public class WaitForAtomicBooleanTest {
private AtomicBoolean wasAdded;
private AtomicBoolean wasAddedWithDefaultValue;
@Before
public void setup() {
wasAdded = new AtomicBoolean(false);
wasAddedWithDefaultValue = new AtomicBoolean();
}
@Test(timeout = 2000L)
public void atomicBooleanExample() throws Exception {
new WasAddedModifier().start();
await().atMost(FIVE_SECONDS).until(wasAdded(), equalTo(true));
}
@Test(timeout = 2000L)
public void atomicBooleanWithUntilTrueWhenBooleanUsesDefaultValue() throws Exception {
new WasAddedWithDefaultValue().start();
await().atMost(FIVE_SECONDS).untilTrue(wasAddedWithDefaultValue);
}
@Test(timeout = 2000L)
public void atomicBooleanWithUntilTrue() throws Exception {
new WasAddedModifier().start();
await().atMost(FIVE_SECONDS).untilTrue(wasAdded);
}
@Test(timeout = 2000L)
public void atomicBooleanWithUntilFalse() throws Exception {
wasAdded.set(true);
new WasAddedModifier().start();
await().atMost(FIVE_SECONDS).untilFalse(wasAdded);
}
private Callable<Boolean> wasAdded() {
return new Callable<Boolean>() {
public Boolean call() throws Exception {
return wasAdded.get();
}
};
}
private class WasAddedModifier extends Thread {
@Override
public void run() {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
wasAdded.set(!wasAdded.get());
}
}
private class WasAddedWithDefaultValue extends Thread {
@Override
public void run() {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
wasAddedWithDefaultValue.set(true);
}
}
}
| 29.64 | 90 | 0.657895 |
f6c9053b0c519a2e4de812f48494b1eb5662a5a0 | 3,339 | package com.plusub.lib.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.plusub.lib.util.NetStateUtils;
/**
* 从web获取内容的dialog
* <p>可以设置监听器,如果载入失败{@link #setOnWebDialogErrorListener(OnWebDialogErrorListener)}</>
* @author blakequ Blakequ@gmail.com
*
*/
public class WebDialog extends BaseDialog {
private WebView mWebView;
private View mLoadingView;
private Context mContext;
private NetStateUtils mNetWorkUtils;
private boolean isCache = false;
private OnWebDialogErrorListener mOnWebDialogErrorListener;
/**
* 是否设置缓存
* @param context
* @param isCache
*/
public WebDialog(Context context, boolean isCache) {
super(context);
this.isCache = isCache;
mContext = context;
setDialogContentView(R.layout.include_dialog_webview);
mLoadingView = findViewById(R.id.dialog_web_loading_indicator);
mWebView = (WebView) findViewById(R.id.dialog_web_webview);
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
});
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mWebView.loadUrl(url);
return true;
}
public void onReceivedSslError(WebView view,
SslErrorHandler handler, android.net.http.SslError error) {
handler.proceed();
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
showProgress();
}
private void showProgress() {
mLoadingView.setVisibility(View.VISIBLE);
}
private void dismissProgress() {
mLoadingView.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dismissProgress();
}
});
}
public void init(CharSequence title, CharSequence button1,
OnClickListener listener) {
super.setTitle(title);
super.setButton1(button1, listener);
}
public void loadUrl(String url) {
if (url == null) {
if (mOnWebDialogErrorListener != null) {
mOnWebDialogErrorListener.urlError();
}
return;
}
if (mNetWorkUtils.getNetWorkConnectionType(mContext) == NetStateUtils.NetWorkState.NONE) {
if (mOnWebDialogErrorListener != null) {
mOnWebDialogErrorListener.networkError();
}
// return;
}
mWebView.getSettings().setJavaScriptEnabled(true);
if (isCache){
if (NetStateUtils.hasNetWorkConnection(this.mContext)){
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}else{
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
}else{
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}
mWebView.getSettings().setLayoutAlgorithm(
WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
mWebView.loadUrl(url);
}
public void setOnWebDialogErrorListener(OnWebDialogErrorListener listener) {
mOnWebDialogErrorListener = listener;
}
/**
* 载入错误异常家庭器
*/
public interface OnWebDialogErrorListener {
void urlError();
void networkError();
}
}
| 25.684615 | 92 | 0.746331 |
f3d6069223a9b448dd6031ab907b8858281cf04f | 1,340 | package com.agileengine.imageparser.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageDto {
@JsonProperty("pictures")
private List<PictureDto> pictures = null;
@JsonProperty("page")
private Integer page;
@JsonProperty("pageCount")
private Integer pageCount;
@JsonProperty("hasMore")
private Boolean hasMore;
@JsonProperty("pictures")
public List<PictureDto> getPictures() {
return pictures;
}
@JsonProperty("pictures")
public void setPictures(List<PictureDto> pictures) {
this.pictures = pictures;
}
@JsonProperty("page")
public Integer getPage() {
return page;
}
@JsonProperty("page")
public void setPage(Integer page) {
this.page = page;
}
@JsonProperty("pageCount")
public Integer getPageCount() {
return pageCount;
}
@JsonProperty("pageCount")
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
@JsonProperty("hasMore")
public Boolean getHasMore() {
return hasMore;
}
@JsonProperty("hasMore")
public void setHasMore(Boolean hasMore) {
this.hasMore = hasMore;
}
} | 22.711864 | 56 | 0.664179 |
31ca1ebdadd27b8f9fa1af7affab11820258b1ac | 3,313 | package dominio;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellRenderer;
public class tablaCellRender {
private prodsCellRender render;
private ButtonEditor btnEditor;
//private estadoEditor listEditor;
private util ut;
private int fila;
private String[] estados = { "En preparacion", "Preparado", "Completado" };
private Pedido ped;
public prodsCellRender getRender() {
return render;
}
public ButtonEditor getEditor() {
return btnEditor;
}
/*
* public estadoEditor getEditorList() {
* return listEditor;
* }
*/
public tablaCellRender(String tipo, util uti, Pedido p) {
this.ut = uti;
this.ped = p;
if (tipo.equalsIgnoreCase("productos")) {
initProd();
} else {
// initPedidos();
}
}
private void initProd() {
prodsCellRender model = new prodsCellRender();
this.render = model;
ButtonEditor btn = new ButtonEditor(new JCheckBox());
this.btnEditor = btn;
}
public class prodsCellRender extends JButton implements TableCellRenderer {
public prodsCellRender() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(Color.WHITE);
}
setText((value == null) ? "Borrar" : value.toString());
return this;
}
}// Fin class
class ButtonEditor extends DefaultCellEditor {
protected JButton btnMenos;
private String label;
private boolean isPushed;
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
btnMenos = new JButton("Borrar");
btnMenos.setOpaque(true);
btnMenos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
int column) {
fila = row;
if (isSelected) {
btnMenos.setForeground(Color.BLACK);
btnMenos.setBackground(Color.white);
} else {
btnMenos.setForeground(table.getForeground());
btnMenos.setBackground(table.getBackground());
}
btnMenos.setText("Borrar");
label = "Borrar";
isPushed = true;
if (fila != table.getRowCount() - 1) {
return btnMenos;
} else {
return new JLabel();
}
}
public Object getCellEditorValue() {
if (isPushed) {
ut.borrarProd(getRow());
}
isPushed = false;
return new String(label);
}
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
public int getRow() {
return fila;
}
}
| 23.330986 | 113 | 0.693329 |
43291f9cdca616b1642757e561e8ad1037ad8fd8 | 2,695 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.php.spi.testing.run;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.annotations.common.NullAllowed;
import org.netbeans.modules.php.spi.testing.coverage.Coverage;
import org.openide.filesystems.FileObject;
/**
* Interface for a test session.
*/
public interface TestSession {
/**
* Add new test suite to this test session.
* @param name name of the test suite
* @param location location of the test suite, can be {@code null}
* @return new test suite
* @see TestSuite#finish(long)
* @since 0.2
*/
TestSuite addTestSuite(@NonNull String name, @NullAllowed FileObject location);
/**
* Set line handler to use for printing while running tests.
* <p>
* This method should be called before first test suite is {@link #addTestSuite(String, FileObject) added}.
* @param outputLineHandler line handler to use for printing while running tests
* @since 0.2
*/
void setOutputLineHandler(@NonNull OutputLineHandler outputLineHandler);
/**
* Print message.
* @param message message that is print, can be empty but never {@code null}
* @param error {@code true} if the given message is an error message
* @since 0.2
*/
void printMessage(@NonNull String message, boolean error);
/**
* Set code coverage data, compulsory to call if
* {@link org.netbeans.modules.php.spi.testing.PhpTestingProvider#isCoverageSupported(org.netbeans.modules.php.api.phpmodule.PhpModule) supported} by this testing provider.
* @param coverage code coverage data, can be {@code null} if any error occured
* @see org.netbeans.modules.php.spi.testing.PhpTestingProvider#isCoverageSupported(org.netbeans.modules.php.api.phpmodule.PhpModule)
* @since 0.2
*/
void setCoverage(@NullAllowed Coverage coverage);
}
| 39.632353 | 176 | 0.722078 |
04141a18dc5d0b632a814f7a487689e8451eeb23 | 4,228 | /*
* Created by JFormDesigner on Sun Aug 10 15:35:49 CEST 2014
*/
package drusy.ui.panels;
import aurelienribon.ui.css.Style;
import java.awt.*;
import javax.swing.*;
/**
* @author Kévin Renella
*/
public class AlertPanel extends JPanel {
public AlertPanel() {
initComponents();
Style.registerCssClasses(headerPanel, ".header");
}
public void anyNotif() {
iconLabel.setIcon(new ImageIcon(getClass().getResource("/res/img/ic_ok.png")));
label2.setText("Any notification");
}
public void downloadNotif() {
iconLabel.setIcon(new ImageIcon(getClass().getResource("/res/img/ic_error.png")));
label2.setText("Download rate saturated");
}
public void uploadNotif() {
iconLabel.setIcon(new ImageIcon(getClass().getResource("/res/img/ic_error.png")));
label2.setText("Upload rate saturated");
}
public void desynchronizedNotif() {
iconLabel.setIcon(new ImageIcon(getClass().getResource("/res/img/ic_error.png")));
label2.setText("Freebox desynchronized");
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - Kévin Renella
headerPanel = new JPanel();
label1 = new JLabel();
mainPanel = new JPanel();
vSpacer2 = new JPanel(null);
panel1 = new JPanel();
hSpacer1 = new JPanel(null);
iconLabel = new JLabel();
hSpacer3 = new JPanel(null);
label2 = new JLabel();
hSpacer2 = new JPanel(null);
vSpacer1 = new JPanel(null);
//======== this ========
setLayout(new BorderLayout());
//======== headerPanel ========
{
headerPanel.setLayout(new BorderLayout());
//---- label1 ----
label1.setText("This panel notifies you for important alerts");
label1.setHorizontalAlignment(SwingConstants.CENTER);
headerPanel.add(label1, BorderLayout.CENTER);
}
add(headerPanel, BorderLayout.NORTH);
//======== mainPanel ========
{
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//---- vSpacer2 ----
vSpacer2.setMaximumSize(new Dimension(10, 15));
vSpacer2.setMinimumSize(new Dimension(10, 15));
vSpacer2.setPreferredSize(new Dimension(10, 15));
mainPanel.add(vSpacer2);
//======== panel1 ========
{
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel1.add(hSpacer1);
//---- iconLabel ----
iconLabel.setIcon(new ImageIcon(getClass().getResource("/res/img/ic_ok.png")));
panel1.add(iconLabel);
//---- hSpacer3 ----
hSpacer3.setMaximumSize(new Dimension(10, 10));
hSpacer3.setMinimumSize(new Dimension(10, 10));
panel1.add(hSpacer3);
//---- label2 ----
label2.setText("Any notification");
panel1.add(label2);
panel1.add(hSpacer2);
}
mainPanel.add(panel1);
//---- vSpacer1 ----
vSpacer1.setMinimumSize(new Dimension(10, 15));
vSpacer1.setMaximumSize(new Dimension(10, 15));
vSpacer1.setPreferredSize(new Dimension(10, 15));
mainPanel.add(vSpacer1);
}
add(mainPanel, BorderLayout.CENTER);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - Kévin Renella
private JPanel headerPanel;
private JLabel label1;
private JPanel mainPanel;
private JPanel vSpacer2;
private JPanel panel1;
private JPanel hSpacer1;
private JLabel iconLabel;
private JPanel hSpacer3;
private JLabel label2;
private JPanel hSpacer2;
private JPanel vSpacer1;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| 33.03125 | 95 | 0.593188 |
1a2bbefcc4eb1a4e20b19c0a9244ed81056897cc | 11,891 | /*
* Copyright (c) 2015 Ondrej Kuzelka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* Combinatorics.java
*
* Created on 11. duben 2007, 13:01
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package cz.cvut.fel.ida.utils.math;
import cz.cvut.fel.ida.utils.generic.tuples.Tuple;
import java.util.*;
/**
* Class providing several useful combinatorics operations.
*
* @author Ondra
*/
public class Combinatorics {
private static Random random = new Random();
private Combinatorics() {
}
/**
* Creates a random combination of <em>k</em> elements from the given <em>list</em>
* @param <T> type of the elenments iterable the list
* @param list the list from which the elements should be selected
* @param k number of elements iterable the combination
* @return random combination of <em>k</em> elements from <em>list</em>
*/
public static <T> Tuple<T> randomCombination(List<T> list, int k){
return randomCombination(list, k, random);
}
/**
*
* Creates a random combination of <em>k</em> elements from the given <em>list</em>
* @param <T> type of the elenments iterable the list
* @param list the list from which the elements should be selected
* @param k number of elements iterable the combination
* @param rand random number generator which should be used to select the random combination
* @return random combination of <em>k</em> elements from <em>list</em>
*/
public static <T> Tuple<T> randomCombination(List<T> list, int k, Random rand){
if (list.size() < k){
throw new IllegalArgumentException("Illegal arguments: list.size() < k.");
}
if (k == 0){
return new Tuple<T>(0);
}
Set<Integer> s = new HashSet<Integer>();
int n = list.size();
for (int j = n-k+1; j <= n; j++){
int t = rand.nextInt(j)+1;
if (!s.contains(t)){
s.add(t);
} else {
s.add(j);
}
}
Tuple<T> t = new Tuple<T>(k);
int index = 0;
for (Integer i : s){
t.set(list.get(i-1), index);
index++;
}
return t;
}
public static <T> Tuple<T> randomCombination(List<T> list){
return randomCombination(list, random);
}
public static <T> Tuple<T> randomCombination(List<T> list, Random random){
List<T> ret = new ArrayList<T>();
for (T t : list){
if (random.nextBoolean()){
ret.add(t);
}
}
return new Tuple<T>(ret);
}
/**
* Creates a list which contains all sub-sequences of the given <em>list</em>.
* The sub-sequences preserve the order of the elements iterable the original list.
* @param <T> the type of the elements iterable the list (and iterable the resulting sub-sequences)
* @param list the list from which the sub-sequences should be generated
* @return list of all sub-sequences (sub-sequences are represented as instances
* of class Tuple<T>)
*/
public static <T> List<Tuple<T>> allSubsequences(List<T> list){
ArrayList<Tuple<T>> ret = new ArrayList<Tuple<T>>(1 << list.size());
int listsize = list.size();
ArrayList temp = new ArrayList();
for (int i = 0; i < 1 << listsize; i++){
for (int j = 0; j < listsize; j++){
if ((i / (1 << j)) % 2 == 0)
temp.add(list.get(j));
}
ret.add(new Tuple(temp));
temp.clear();
}
return ret;
}
/**
* Creates a list which contains all sub-sequences of length <em>k</em> from the given <em>list</em>.
* The sub-sequences preserve the order of the elements iterable the original list.
* @param <T> the type of the elements iterable the list (and iterable the resulting sub-sequences)
* @param list the list from which the sub-sequences should be generated
* @param k
* @return list of all sub-sequences (sub-sequences are represented as instances
* of class Tuple<T>)
*/
public static <T> List<Tuple<T>> allSubsequences(List<T> list, int k){
List<Tuple<T>> retVal = new ArrayList<Tuple<T>>();
List<int[]> ints = new ArrayList<int[]>();
int n = list.size();
for (int i = 0; i < k; i++){
ints = allNextSubsequences(ints, n);
}
for (int[] i : ints){
Tuple t = new Tuple(i.length);
for (int j = 0; j < i.length; j++){
t.set(list.get(i[j]), j);
}
retVal.add(t);
}
return retVal;
}
private static List<int[]> allNextSubsequences(List<int[]> list, int n){
List<int[]> tuples = new ArrayList<int[]>();
if (list.isEmpty()){
for (int i = 0; i < n; i++){
int[] tuple = new int[1];
tuple[0] = i;
tuples.add(tuple);
}
} else {
for (int i = 0; i < list.size(); i++){
int[] oldCombination = list.get(i);
for (int j = oldCombination[oldCombination.length-1]+1; j < n; j++){
int[] newCombination = new int[oldCombination.length+1];
System.arraycopy(oldCombination, 0, newCombination, 0, oldCombination.length);
newCombination[oldCombination.length] = j;
tuples.add(newCombination);
}
}
}
return tuples;
}
public static List<int[]> allPartitions(int sum, int groups){
return allPartitions_impl(Sugar.list(new int[]{}), 0, sum, groups);
}
private static List<int[]> allPartitions_impl(List<int[]> prefix, int curGroups, int sum, int groups){
if (curGroups == groups){
return prefix;
}
List<int[]> extended = new ArrayList<int[]>();
if (curGroups+1 < groups) {
for (int[] p : prefix) {
int s = VectorUtils.sum(p);
for (int i = 0; i <= sum - s; i++) {
extended.add(VectorUtils.concat(p, new int[]{i}));
}
}
} else {
for (int[] p : prefix) {
int s = VectorUtils.sum(p);
extended.add(VectorUtils.concat(p, new int[]{sum-s}));
}
}
return allPartitions_impl(extended, curGroups + 1, sum, groups);
}
/**
* Computes factorial of the given number
* @param n the number
* @return <em>n!</em>
*/
public static double factorial(int n){
if (n < 0)
return -1;
double fact = 1;
for (int i = 1; i <= n; i++){
fact *= i;
}
return fact;
}
/**
* Computes logarithm of factorial of the given number
* @param n the number
* @return <em>ln(n!)</em>
*/
public static double logFactorial(int n){
if (n < 0)
return Double.NaN;
double fact = 0;
for (int i = 1; i <= n; i++){
fact += Math.log(i);
}
return fact;
}
/**
* Computes the value of the binomial number "<em>n</em> over <em>k</em>".
* @param n the number <em>n</em>
* @param k the number <em>k</em>
* @return the value of the binomial number "<em>n</em> over <em>k</em>"
*/
public static double binomial(int n, int k){
return factorial(n)/(factorial(k)*factorial(n-k));
}
/**
* Computes value of the logarithm of the binomial number "<em>n</em> over <em>k</em>".
* @param n the number <em>n</em>
* @param k the number <em>k</em>
* @return the value of the binomial number ln("<em>n</em> over <em>k</em>")
*/
public static double logBinomial(int n, int k){
return logFactorial(n) - logFactorial(k) - logFactorial(n-k);
}
public static <T> List<Tuple<T>> cartesianPower(List<T> elements, int d){
List<Tuple<T>> retVal = new ArrayList<Tuple<T>>();
retVal.add(new Tuple<T>());
for (int i = 0; i < d; i++){
List<Tuple<T>> newlist = new ArrayList<Tuple<T>>();
for (Tuple<T> oldtuple : retVal){
for (T t : elements){
newlist.add(Tuple.append(oldtuple, t));
}
}
retVal = newlist;
}
return retVal;
}
public static <T> List<Tuple<T>> cartesianPower(List<T> elements, int d, Sugar.Fun<Tuple<T>,Boolean> test){
List<Tuple<T>> retVal = new ArrayList<Tuple<T>>();
retVal.add(new Tuple<T>());
for (int i = 0; i < d; i++){
List<Tuple<T>> newlist = new ArrayList<Tuple<T>>();
for (Tuple<T> oldtuple : retVal){
for (T t : elements){
Tuple<T> newtuple = Tuple.append(oldtuple, t);
if (Boolean.TRUE.equals(test.apply(newtuple))) {
newlist.add(newtuple);
}
}
}
retVal = newlist;
}
return retVal;
}
public static <T> List<Tuple<T>> cartesianProduct(List<Collection<T>> collections){
return cartesianProduct(collections, new Sugar.Fun<Tuple<T>,Boolean>(){
@Override
public Boolean apply(Tuple<T> tTuple) {
return true;
}
});
}
public static <T> List<Tuple<T>> cartesianProduct(List<Collection<T>> collections, Sugar.Fun<Tuple<T>,Boolean> test){
List<Tuple<T>> retVal = new ArrayList<Tuple<T>>();
retVal.add(new Tuple<T>());
for (int i = 0; i < collections.size(); i++){
List<Tuple<T>> newList = new ArrayList<Tuple<T>>();
for (Tuple<T> oldTuple : retVal){
for (T t : collections.get(i)){
Tuple<T> newTuple = Tuple.append(oldTuple, t);
if (Boolean.TRUE.equals(test.apply(newTuple))) {
newList.add(newTuple);
}
}
}
retVal = newList;
}
return retVal;
}
public static double binomialProbability(int observed, double p, int n){
return Math.exp(logBinomialProbability(observed, p, n));
}
public static double logBinomialProbability(int observed, double p, int n){
return logBinomial(n, observed) + observed*Math.log(p) + (n-observed)*Math.log(1-p);
}
public static void main(String[] args){
System.out.println(cartesianProduct(Sugar.<Collection<String>>list(
Sugar.<String>list("a","b","c"),
Sugar.<String>list("d","e")
)));
}
}
| 37.275862 | 463 | 0.554369 |
46747a994da43fecbc32cbb39d831596667190c7 | 4,699 | package day_02;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class IntCodeComputer
{
public static int[] intComputer(String path, Integer noun, Integer verb, boolean silent) throws ArrayIndexOutOfBoundsException
{
List<String> allLines = new ArrayList<String>();
try
{
allLines = Files.readAllLines(Paths.get(path));
}
catch (IOException e)
{
e.printStackTrace();
}
for (String line : allLines)
{
String[] inputData = line.split(",");
if (allLines.size() == 1)
{
return calculate(inputData, noun, verb, silent);
}
}
return new int[]
{};
}
public static int[] calculate(String[] computer, Integer noun, Integer verb, boolean silent) throws ArrayIndexOutOfBoundsException
{
int[] input = parse_input(computer);
// System.out.println("************************\nNEW
// CODE\n************************");
// System.out.println("Code before calculations: " +
// Arrays.toString(input));
int programCounter = 0;
if (noun != null && verb != null)
{
input[1] = noun.intValue();
input[2] = verb.intValue();
}
while (programCounter < input.length)
{
switch (input[programCounter])
{
case 1:
input = parseOpCode_1(input, programCounter);
programCounter += 4;
// System.out.println("Step during calculations: " +
// Arrays.toString(input));
break;
case 2:
input = parseOpCode_2(input, programCounter);
programCounter += 4;
// System.out.println("Step during calculations: " +
// Arrays.toString(input));
break;
case 99:
default:
if (!silent)
{
System.out.println("Code after calculations: " + Arrays.toString(input));
System.out.println("Result at Position 0: " + input[0]);
}
programCounter = input.length;
break;
}
}
return input;
}
public static int[] parse_input(String[] inputData)
{
int[] input = new int[inputData.length];
for (int i = 0; i < inputData.length; i++)
{
input[i] = Integer.parseInt(inputData[i]);
}
return input;
}
public static int[] parseOpCode_1(int[] code, int counter) throws ArrayIndexOutOfBoundsException
{
int a = code[code[counter + 1]];
int b = code[code[counter + 2]];
// System.out.println(String.format("Reading %d from %d and %d from %d.
// Putting %d in %d", a, code[counter + 1], b, code[counter + 2], a + b,
// code[counter + 3]));
code[code[counter + 3]] = a + b;
return code;
}
public static int[] parseOpCode_2(int[] code, int counter) throws ArrayIndexOutOfBoundsException
{
int a = code[code[counter + 1]];
int b = code[code[counter + 2]];
// System.out.println(String.format("Reading %d from %d and %d from %d.
// Putting %d in %d", a, code[counter + 1], b, code[counter + 2], a * b,
// code[counter + 3]));
code[code[counter + 3]] = a * b;
return code;
}
public static int[] find_pair(int result)
{
int[] resultPair = new int[2];
for (int noun = 0; noun < 100; noun++)
{
for (int verb = 0; verb < 100; verb++)
{
try
{
int[] temp = intComputer("./src/day_02/IntCode.txt", noun, verb, true);
if (temp[0] == result)
{
resultPair[0] = noun;
resultPair[1] = verb;
return resultPair;
}
}
catch (ArrayIndexOutOfBoundsException e)
{
}
}
}
return resultPair;
}
public static void main(String[] args)
{
intComputer("./src/day_02/TestExamples.txt", null, null, false);
intComputer("./src/day_02/IntCode.txt", 12, 2, false);
System.out.println(Arrays.toString(find_pair(19690720)));
}
}
| 31.536913 | 134 | 0.487976 |
6316cad21d957d6c12ef9fbd6c1c062ca86b5944 | 8,899 | package net.sf.sahi.command;
import java.util.Properties;
import net.sf.sahi.config.Configuration;
import net.sf.sahi.nashorn.NashornScriptRunner;
import net.sf.sahi.request.HttpRequest;
import net.sf.sahi.response.HttpFileResponse;
import net.sf.sahi.response.HttpModifiedResponse2;
import net.sf.sahi.response.HttpResponse;
import net.sf.sahi.response.SimpleHttpResponse;
import net.sf.sahi.session.Session;
import net.sf.sahi.session.Status;
import net.sf.sahi.test.BrowserLauncher;
import net.sf.sahi.util.BrowserType;
import net.sf.sahi.util.BrowserTypesLoader;
import net.sf.sahi.util.Utils;
import org.apache.log4j.Logger;
/**
* Sahi - Web Automation and Test Tool
* <p/>
* Copyright 2006 V Narayan Raman
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.
*/
public class Driver {
private static Logger logger = Logger.getLogger(Driver.class);
private Boolean useSystemProxy = false;
public static final String INITIALIZE_CALL = "/_s_/dyn/Driver_initialized";
public void setControllerMode(final HttpRequest request) {
String mode = request.getParameter("mode");
Configuration.setControllerMode(mode);
}
public void launchAndRecord(final HttpRequest request) throws Exception {
launchBrowser(request);
record(request);
}
public void launchAndPlayback(final HttpRequest request) throws Exception {
launchBrowser(request);
}
private void launchBrowser(final HttpRequest request) throws Exception {
String browser = request.getParameter("browser");
String browserOption = request.getParameter("browserOption");
String browserProcessName = request.getParameter("browserProcessName");
launch(browser, browserProcessName, browserOption, "true".equals(request.getParameter("useSystemProxy")), request);
}
public void launchPreconfiguredBrowser(final HttpRequest request) throws Exception {
BrowserTypesLoader browserLoader = new BrowserTypesLoader();
BrowserType browserType = browserLoader.getBrowserType(request);
// launches browser with pre configured browser settings
if (browserType != null) {
launch(browserType.path(), browserType.processName(),
browserType.options(), browserType.useSystemProxy(), request);
}
}
private void launch(String browser, String browserProcessName, String browserOption, boolean useProxy, HttpRequest request) throws Exception {
Session session = request.session();
String startUrl = request.getParameter("startUrl");
if (startUrl == null) startUrl = "";
// if (useProxy) {
// this.useSystemProxy = true;
// enableIEProxy(request);
// }
//
final BrowserLauncher launcher = new BrowserLauncher(browser, browserProcessName, browserOption, useProxy);
String url = "http://" + Configuration.getCommonDomain() + "/_s_/dyn/Driver_start" + "?sahisid="
+ session.id()
+ "&startUrl="
+ Utils.encode("http://" + Configuration.getCommonDomain() + INITIALIZE_CALL + "?startUrl=" + Utils.encode(startUrl));
launcher.openURL(url);
session.setLauncher(launcher);
}
public void kill(final HttpRequest request) {
Session session = request.session();
BrowserLauncher launcher = session.getLauncher();
if (launcher != null) {
launcher.kill();
// if (useSystemProxy){
// disableIEProxy(request);
// }
}
}
public HttpResponse start(final HttpRequest request) {
Session session = request.session();
session.setScriptRunner(new NashornScriptRunner());
return new Player().autoJava(request);
}
public void restart(final HttpRequest request) {
Session session = request.session();
session.setScriptRunner(new NashornScriptRunner());
session.setIsPlaying(true);
session.setIsReadyForDriver(true);
}
public HttpResponse initialized(final HttpRequest request) {
Session session = request.session();
session.setIsPlaying(true);
session.setIsReadyForDriver(true);
String startUrl = request.getParameter("startUrl");
Properties properties = new Properties();
if (startUrl == null) startUrl = "";
properties.setProperty("startUrl", Utils.replaceLocalhostWithMachineName(startUrl));
HttpFileResponse httpFileResponse = new HttpFileResponse(Configuration.getHtdocsRoot() + "spr/initialized.htm", properties, false, true);
HttpModifiedResponse2 response = new HttpModifiedResponse2(httpFileResponse, false, "htm");
// response.addFilter(new ChunkedFilter());
return response;
}
public HttpResponse isReady(final HttpRequest request) {
return new SimpleHttpResponse("" + request.session().isReadyForDriver());
}
public void setStep(final HttpRequest request) {
String step = request.getParameter("step");
setStep(request, step);
}
public void setBrowserJS(final HttpRequest request) {
Session session = request.session();
String browserJS = request.getParameter("browserJS");
session.getScriptRunner().setBrowserJS(browserJS);
}
public HttpResponse getVariable(final HttpRequest request) {
String key = request.getParameter("key");
logger.debug("key="+key);
Session session = request.session();
String val = session.getVariable(key);
logger.debug("val="+val);
return new SimpleHttpResponse(val != null ? val : "");
}
public HttpResponse doneStep(final HttpRequest request) {
Session session = request.session();
NashornScriptRunner scriptRunner = session.getScriptRunner();
if (scriptRunner == null) {
return new SimpleHttpResponse("error:Playback session not started. Verify that proxy is set on the browser.");
}
boolean done = scriptRunner.doneStep("") || scriptRunner.isStopped();
if (done) {
Status status = scriptRunner.getStatus();
String browserException = scriptRunner.getBrowserException();
if (browserException == null) browserException = "";
if (status == Status.ERROR) {
return new SimpleHttpResponse("error:" + browserException);
} else if (status == Status.FAILURE) {
return new SimpleHttpResponse("failure:" + browserException);
}
}
return new SimpleHttpResponse("" + done);
}
public SimpleHttpResponse getRecordedSteps(final HttpRequest request) {
return new StepWiseRecorder().getSteps(request);
}
public void setLastIdentifiedElement(final HttpRequest request) {
Session session = request.session();
session.setVariable("__sahi__lastIdentifiedElement", request.getParameter("element"));
}
public SimpleHttpResponse getLastIdentifiedElement(final HttpRequest request) {
Session session = request.session();
String val = session.getVariable("__sahi__lastIdentifiedElement");
session.setVariable("__sahi__lastIdentifiedElement", null);
return new SimpleHttpResponse(val == null ? "" : val);
}
public SimpleHttpResponse getAllRecordedSteps(final HttpRequest request) {
return new StepWiseRecorder().getAllSteps(request);
}
public void startRecording(final HttpRequest request) {
record(request);
request.session().setIsWindowOpen(true);
if (!"true".equals(request.getParameter("fromBrowser")))
setStep(request, "_sahi.openController()");
}
private void record(final HttpRequest request) {
Session session = request.session();
session.setIsRecording(true);
new StepWiseRecorder().start(request);
session.setIsPlaying(false);
}
public void stopRecording(final HttpRequest request) {
new StepWiseRecorder().stop(request);
Session session = request.session();
session.setIsWindowOpen(false);
if (!"true".equals(request.getParameter("fromBrowser")))
setStep(request, "_sahi.closeController()");
session.setIsRecording(false);
session.setIsPlaying(true);
}
public SimpleHttpResponse isRecording(final HttpRequest request) {
return new SimpleHttpResponse("" + request.session().isRecording());
}
private void setStep(final HttpRequest request, String step) {
Session session = request.session();
session.getScriptRunner().setStep(step, "");
}
public void setSpeed(final HttpRequest request) {
try {
String speed = request.getParameter("speed");
logger.debug("setTimeBetweenSteps to " + speed);
Configuration.setTimeBetweenSteps(Integer.parseInt(speed));
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 36.174797 | 144 | 0.725587 |
22466be089aaa4b1ad3b915f64b2c7e7aebf989b | 12,727 | /*
* Copyright 2015-2017 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.opencga.storage.core.variant.annotation.annotators;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.VariantBuilder;
import org.opencb.biodata.models.variant.avro.AdditionalAttribute;
import org.opencb.biodata.models.variant.avro.VariantAnnotation;
import org.opencb.cellbase.core.result.CellBaseDataResult;
import org.opencb.commons.datastore.core.ObjectMap;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.opencga.core.common.TimeUtils;
import org.opencb.opencga.core.config.storage.StorageConfiguration;
import org.opencb.opencga.storage.core.metadata.models.ProjectMetadata;
import org.opencb.opencga.storage.core.variant.VariantStorageOptions;
import org.opencb.opencga.storage.core.variant.annotation.VariantAnnotatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.GROUP_NAME;
import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.VARIANT_ID;
/**
* Created by jacobo on 9/01/15.
*/
public abstract class AbstractCellBaseVariantAnnotator extends VariantAnnotator {
public static final int SLOW_CELLBASE_SECONDS = 60;
protected static Logger logger = LoggerFactory.getLogger(AbstractCellBaseVariantAnnotator.class);
protected final String species;
protected final String assembly;
protected final String cellbaseVersion;
protected final QueryOptions queryOptions;
protected final boolean supportImpreciseVariants;
protected final boolean supportStarAlternate;
protected final int variantLengthThreshold;
protected final Function<Variant, String> variantSerializer;
public AbstractCellBaseVariantAnnotator(StorageConfiguration storageConfiguration, ProjectMetadata projectMetadata, ObjectMap params)
throws VariantAnnotatorException {
super(storageConfiguration, projectMetadata, params);
// species = toCellBaseSpeciesName(params.getString(VariantAnnotationManager.SPECIES));
// assembly = params.getString(VariantAnnotationManager.ASSEMBLY);
species = projectMetadata.getSpecies();
assembly = projectMetadata.getAssembly();
cellbaseVersion = storageConfiguration.getCellbase().getVersion();
queryOptions = new QueryOptions();
if (StringUtils.isNotEmpty(params.getString(VariantStorageOptions.ANNOTATOR_CELLBASE_INCLUDE.key()))) {
queryOptions.put(QueryOptions.INCLUDE, params.getString(VariantStorageOptions.ANNOTATOR_CELLBASE_INCLUDE.key()));
} else if (StringUtils.isNotEmpty(params.getString(VariantStorageOptions.ANNOTATOR_CELLBASE_EXCLUDE.key()))) {
queryOptions.put(QueryOptions.EXCLUDE, params.getString(VariantStorageOptions.ANNOTATOR_CELLBASE_EXCLUDE.key()));
}
if (!params.getBoolean(VariantStorageOptions.ANNOTATOR_CELLBASE_USE_CACHE.key())) {
queryOptions.append("useCache", false);
}
variantLengthThreshold = params.getInt(
VariantStorageOptions.ANNOTATOR_CELLBASE_VARIANT_LENGTH_THRESHOLD.key(),
VariantStorageOptions.ANNOTATOR_CELLBASE_VARIANT_LENGTH_THRESHOLD.defaultValue());
supportImpreciseVariants = params.getBoolean(VariantStorageOptions.ANNOTATOR_CELLBASE_IMPRECISE_VARIANTS.key(),
VariantStorageOptions.ANNOTATOR_CELLBASE_IMPRECISE_VARIANTS.defaultValue());
supportStarAlternate = params.getBoolean(VariantStorageOptions.ANNOTATOR_CELLBASE_STAR_ALTERNATE.key(),
VariantStorageOptions.ANNOTATOR_CELLBASE_STAR_ALTERNATE.defaultValue());
if (supportImpreciseVariants) {
// If the cellbase sever supports imprecise variants, use the original toString, which adds the CIPOS and CIEND
variantSerializer = Variant::toString;
} else {
variantSerializer = variant -> variant.getChromosome()
+ ':' + variant.getStart()
+ ':' + (variant.getReference().isEmpty() ? "-" : variant.getReference())
+ ':' + (variant.getAlternate().isEmpty() ? "-" : variant.getAlternate());
}
checkNotNull(cellbaseVersion, "cellbase version");
checkNotNull(species, "species");
checkNotNull(assembly, "assembly");
}
protected static void checkNotNull(String value, String name) throws VariantAnnotatorException {
if (value == null || value.isEmpty()) {
throw new VariantAnnotatorException("Missing defaultValue: " + name);
}
}
public static String toCellBaseSpeciesName(String scientificName) {
if (scientificName != null && scientificName.contains(" ")) {
String[] split = scientificName.split(" ", 2);
scientificName = (split[0].charAt(0) + split[1]).toLowerCase();
}
return scientificName;
}
@Override
public final List<VariantAnnotation> annotate(List<Variant> variants) throws VariantAnnotatorException {
List<Variant> filteredVariants = filterVariants(variants);
StopWatch stopWatch = StopWatch.createStarted();
List<CellBaseDataResult<VariantAnnotation>> queryResults = annotateFiltered(filteredVariants);
stopWatch.stop();
if (stopWatch.getTime(TimeUnit.SECONDS) > SLOW_CELLBASE_SECONDS) {
logger.warn("Slow annotation from CellBase."
+ " Annotating " + variants.size() + " variants took " + TimeUtils.durationToString(stopWatch));
}
return getVariantAnnotationList(filteredVariants, queryResults);
}
protected abstract List<CellBaseDataResult<VariantAnnotation>> annotateFiltered(List<Variant> variants)
throws VariantAnnotatorException;
private List<Variant> filterVariants(List<Variant> variants) {
List<Variant> nonStructuralVariants = new ArrayList<>(variants.size());
for (Variant variant : variants) {
// If Variant is SV some work is needed
// TODO:Manage larger SV variants
int length = Math.max(variant.getLength(), variant.getAlternate().length() + variant.getReference().length());
boolean skipLength = length > variantLengthThreshold;
boolean skipStarAlternate = !supportStarAlternate && variant.getAlternate().equals("*");
if (skipLength) {
// logger.info("Skip variant! {}", genomicVariant);
logger.info("Skip variant! {}", variant.getChromosome() + ":" + variant.getStart() + "-" + variant.getEnd() + ":"
+ (variant.getReference().length() > 10
? variant.getReference().substring(0, 10) + "...[" + variant.getReference().length() + "]"
: variant.getReference()) + ":"
+ (variant.getAlternate().length() > 10
? variant.getAlternate().substring(0, 10) + "...[" + variant.getAlternate().length() + "]"
: variant.getAlternate())
);
logger.debug("Skip variant! {}", variant);
} else if (skipStarAlternate) {
logger.debug("Skip variant! {}", variant);
} else {
nonStructuralVariants.add(variant);
}
}
return nonStructuralVariants;
}
protected List<VariantAnnotation> getVariantAnnotationList(List<Variant> variants,
List<CellBaseDataResult<VariantAnnotation>> queryResults) {
List<VariantAnnotation> variantAnnotationList = new ArrayList<>(variants.size());
Iterator<Variant> iterator = variants.iterator();
if (queryResults != null) {
for (CellBaseDataResult<VariantAnnotation> queryResult : queryResults) {
// If the QueryResult is empty, assume that the variant was skipped
// Check that the skipped variant matches with the expected variant
if (queryResult.getResults().isEmpty()) {
Variant variant = iterator.next();
if (variantSerializer.apply(variant).equals(queryResult.getId())
|| variant.toString().equals(queryResult.getId())
|| variant.toStringSimple().equals(queryResult.getId())) {
logger.warn("Skip annotation for variant " + variant);
} else {
Variant variantId = new Variant(queryResult.getId());
if (!variant.getChromosome().equals(variantId.getChromosome())
|| !variant.getStart().equals(variantId.getStart())
|| !variant.getReference().equals(variantId.getReference())
|| !variant.getAlternate().equals(variantId.getAlternate())) {
throw unexpectedVariantOrderException(variant, variantId);
} else {
logger.warn("Skip annotation for variant " + variant);
}
}
}
for (VariantAnnotation variantAnnotation : queryResult.getResults()) {
Variant variant = iterator.next();
String annotationAlternate = variantAnnotation.getAlternate();
if (annotationAlternate.equals(VariantBuilder.DUP_ALT)
&& variant.getAlternate().equals(VariantBuilder.DUP_TANDEM_ALT)) {
// Annotator might remove the ":TANDEM". Put it back
annotationAlternate = VariantBuilder.DUP_TANDEM_ALT;
}
if (!variant.getChromosome().equals(variantAnnotation.getChromosome())
|| !variant.getStart().equals(variantAnnotation.getStart())
|| !variant.getReference().equals(variantAnnotation.getReference())
|| !variant.getAlternate().equals(annotationAlternate)) {
throw unexpectedVariantOrderException(variant, variantAnnotation.getChromosome() + ':'
+ variantAnnotation.getStart() + ':'
+ variantAnnotation.getReference() + ':'
+ variantAnnotation.getAlternate());
}
if (variant.isSV() || variant.getSv() != null) {
// Variant annotation class does not have information about Structural Variations.
// Store the original Variant.toString as an additional attribute.
AdditionalAttribute additionalAttribute =
new AdditionalAttribute(Collections.singletonMap(VARIANT_ID.key(), variant.toString()));
if (variantAnnotation.getAdditionalAttributes() == null) {
variantAnnotation
.setAdditionalAttributes(Collections.singletonMap(GROUP_NAME.key(), additionalAttribute));
} else {
variantAnnotation.getAdditionalAttributes().put(GROUP_NAME.key(), additionalAttribute);
}
}
variantAnnotationList.add(variantAnnotation);
}
}
}
return variantAnnotationList;
}
static RuntimeException unexpectedVariantOrderException(Object expected, Object actual) {
return new IllegalArgumentException("Variants not in the expected order! "
+ "Expected '" + expected + "', " + "but got '" + actual + "'.");
}
}
| 55.095238 | 137 | 0.644221 |
28126c73e1717dc244eea72eb14efc423f0976cd | 208 | package org.broadinstitute.hellbender.utils.pairhmm;
public interface PairHMMInputScoreImputation {
byte[] delOpenPenalties();
byte[] insOpenPenalties();
byte[] gapContinuationPenalties();
}
| 17.333333 | 52 | 0.75 |
4da60e5a196d7e3114fc72f584e53878bdd50193 | 1,081 | /*
* 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 lab3_juanguevarap2;
/**
*
* @author HP
*/
public class Portero extends Jugador {
public int aereo;
public int pies;
public Portero() {
super();
}
public Portero(int aereo, int pies, String nombre, String apellido, int edad, int estado, String pais, String pie, int numero, double precio, String equipo) {
super(nombre, apellido, edad, estado, pais, pie, numero, precio, equipo);
this.aereo = aereo;
this.pies = pies;
}
public int getAereo() {
return aereo;
}
public void setAereo(int aereo) {
this.aereo = aereo;
}
public int getPies() {
return pies;
}
public void setPies(int pies) {
this.pies = pies;
}
@Override
public String toString() {
return super.toString() + "\nPortero{" + "aereo=" + aereo + ", \npies=" + pies + '}';
}
}
| 22.520833 | 162 | 0.60407 |
2d5b797217cf454b10ec72c675f3b94ada28a3fd | 2,216 | package com.fu.group10.capstone.apps.teachermobileapp.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
import com.fu.group10.capstone.apps.teachermobileapp.DummyApplication;
import com.fu.group10.capstone.apps.teachermobileapp.model.Result;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
/**
* Created by QuangTV on 5/30/2015.
*
* @author TrungDQ
*/
public class Utils {
static boolean isOnline;
public static boolean isOnline() {
try {
ConnectivityManager cm =
(ConnectivityManager) DummyApplication.
getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnected();
// if (netInfo != null && netInfo.isConnected()) {
// RequestSender sender = new RequestSender();
// String url = Constants.API_CHECK_CONNECTION;
// sender.start(url, new RequestSender.IRequestSenderComplete() {
// @Override
// public void onRequestComplete(String result) {
// try {
// Result res = ParseUtils.parseResult(result);
// if (res != null) {
// isOnline = true;
// } else {
// isOnline = false;
// }
// }catch (Exception e) {
// e.printStackTrace();
// isOnline = false;
// }
// }
// });
//
// return isOnline;
// }
// Log.d("isOnline", isOnline + "");
// //return false;
// return false;
} catch (Exception e) {
// Handle your exceptions
return false;
}
}
}
| 30.777778 | 92 | 0.496841 |
310955767dc9f63c734e39014b306ca5d5c33b26 | 220 | package dev.mrsterner.bewitchmentplus.common.block.yew;
import net.minecraft.block.DoorBlock;
public class YewDoorBlock extends DoorBlock {
public YewDoorBlock(Settings settings) {
super(settings);
}
}
| 22 | 55 | 0.754545 |
60ed8811b95a22d4571292bb5156cf2faff53cf4 | 3,783 | package io.github.spair.controller;
import io.github.spair.service.config.ConfigService;
import io.github.spair.service.config.entity.HandlerConfig;
import io.github.spair.service.config.entity.HandlerConfigStatus;
import io.github.spair.service.github.GitHubRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/config/rest")
public class ConfigRestController {
private final String logName;
private final ConfigService configService;
private final GitHubRepository gitHubRepository;
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRestController.class);
@Autowired
public ConfigRestController(
final ConfigService configService,
final Environment env,
final GitHubRepository gitHubRepository) {
this.configService = configService;
this.logName = env.getProperty("logging.file");
this.gitHubRepository = gitHubRepository;
}
@GetMapping("/current")
public HandlerConfig getCurrentConfig() {
return configService.getConfig();
}
@PutMapping("/current")
public void saveConfig(@RequestBody final HandlerConfig configuration) throws IOException {
configService.importConfig(configuration);
}
@GetMapping("/file")
public FileSystemResource downloadConfigFile(final HttpServletResponse response) {
LOGGER.info("Configuration file downloaded");
setResponseAsFile(response, ConfigService.CONFIG_NAME);
return new FileSystemResource(configService.exportConfig());
}
@GetMapping("/log")
public FileSystemResource downloadLogFile(final HttpServletResponse response) {
LOGGER.info("Log file downloaded");
setResponseAsFile(response, logName);
return new FileSystemResource(new File(logName));
}
@PostMapping("/validation")
public ResponseEntity validateConfig(@RequestBody final HandlerConfig config) {
HandlerConfigStatus configStatus = configService.validateConfig(config);
HttpStatus responseStatus = configStatus.allOk ? HttpStatus.OK : HttpStatus.NOT_ACCEPTABLE;
return new ResponseEntity<>(configStatus, responseStatus);
}
@GetMapping("/repos/master")
public String getMasterRepoInitStatus() {
return gitHubRepository.getMasterRepoInitStatus().name();
}
@PutMapping("/repos/master")
public void initializeMasterRepo() {
gitHubRepository.initMasterRepository();
}
@DeleteMapping("/repos")
public void cleanAllRepos() {
gitHubRepository.cleanReposFolder();
}
private void setResponseAsFile(final HttpServletResponse response, final String fileName) {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=".concat(fileName));
}
}
| 37.455446 | 102 | 0.765001 |
7fb0c1497896d127e4b9a5f5bb6f4532498cf375 | 5,571 | /**
* An implementation of the traveling salesman problem in Java using dynamic
* programming to improve the time complexity from O(n!) to O(n^2 * 2^n).
*
* Time Complexity: O(n^2 * 2^n)
* Space Complexity: O(n * 2^n)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
**/
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class TspDynamicProgrammingIterative {
private final int N, start;
private final double[][] distance;
private List<Integer> tour = new ArrayList<>();
private double minTourCost = Double.POSITIVE_INFINITY;
private boolean ranSolver = false;
public TspDynamicProgrammingIterative(double[][] distance) {
this(0, distance);
}
public TspDynamicProgrammingIterative(int start, double[][] distance) {
N = distance.length;
if (N <= 2) throw new IllegalStateException("N <= 2 not yet supported.");
if (N != distance[0].length) throw new IllegalStateException("Matrix must be square (n x n)");
if (start < 0 || start >= N) throw new IllegalArgumentException("Invalid start node.");
this.start = start;
this.distance = distance;
}
// Returns the optimal tour for the traveling salesman problem.
public List<Integer> getTour() {
if (!ranSolver) solve();
return tour;
}
// Returns the minimal tour cost.
public double getTourCost() {
if (!ranSolver) solve();
return minTourCost;
}
// Solves the traveling salesman problem and caches solution.
public void solve() {
if (ranSolver) return;
final int END_STATE = (1 << N) - 1;
Double[][] memo = new Double[N][1 << N];
// Add all outgoing edges from the starting node to memo table.
for (int end = 0; end < N; end++) {
if (end == start) continue;
memo[end][(1 << start) | (1 << end)] = distance[start][end];
}
for (int r = 3; r <= N; r++) {
for (int subset : combinations(r, N)) {
if (notIn(start, subset)) continue;
for (int next = 0; next < N; next++) {
if (next == start || notIn(next, subset)) continue;
int subsetWithoutNext = subset ^ (1 << next);
double minDist = Double.POSITIVE_INFINITY;
for (int end = 0; end < N; end++) {
if (end == start || end == next || notIn(end, subset)) continue;
double newDistance = memo[end][subsetWithoutNext] + distance[end][next];
if (newDistance < minDist) {
minDist = newDistance;
}
}
memo[next][subset] = minDist;
}
}
}
// Connect tour back to starting node and minimize cost.
for (int i = 0; i < N; i++) {
if (i == start) continue;
double tourCost = memo[i][END_STATE] + distance[i][start];
if (tourCost < minTourCost) {
minTourCost = tourCost;
}
}
int lastIndex = start;
int state = END_STATE;
tour.add(start);
// Reconstruct TSP path from memo table.
for (int i = 1; i < N; i++) {
int index = -1;
for (int j = 0; j < N; j++) {
if (j == start || notIn(j, state)) continue;
if (index == -1) index = j;
double prevDist = memo[index][state] + distance[index][lastIndex];
double newDist = memo[j][state] + distance[j][lastIndex];
if (newDist < prevDist) {
index = j;
}
}
tour.add(index);
state = state ^ (1 << index);
lastIndex = index;
}
tour.add(start);
Collections.reverse(tour);
ranSolver = true;
}
private static boolean notIn(int elem, int subset) {
return ((1 << elem) & subset) == 0;
}
// This method generates all bit sets of size n where r bits
// are set to one. The result is returned as a list of integer masks.
public static List<Integer> combinations(int r, int n) {
List<Integer> subsets = new ArrayList<>();
combinations(0, 0, r, n, subsets);
return subsets;
}
// To find all the combinations of size r we need to recurse until we have
// selected r elements (aka r = 0), otherwise if r != 0 then we still need to select
// an element which is found after the position of our last selected element
private static void combinations(int set, int at, int r, int n, List<Integer> subsets) {
// Return early if there are more elements left to select than what is available.
int elementsLeftToPick = n - at;
if (elementsLeftToPick < r) return;
// We selected 'r' elements so we found a valid subset!
if (r == 0) {
subsets.add(set);
} else {
for (int i = at; i < n; i++) {
// Try including this element
set |= 1 << i;
combinations(set, i + 1, r - 1, n, subsets);
// Backtrack and try the instance where we did not include this element
set &= ~(1 << i);
}
}
}
public static void main(String[] args) {
// Create adjacency matrix
int n = 6;
double[][] distanceMatrix = new double[n][n];
for (double[] row : distanceMatrix) java.util.Arrays.fill(row, 10000);
distanceMatrix[5][0] = 10;
distanceMatrix[1][5] = 12;
distanceMatrix[4][1] = 2;
distanceMatrix[2][4] = 4;
distanceMatrix[3][2] = 6;
distanceMatrix[0][3] = 8;
int startNode = 0;
TspDynamicProgrammingIterative solver = new TspDynamicProgrammingIterative(startNode, distanceMatrix);
// Prints: [0, 3, 2, 4, 1, 5, 0]
System.out.println("Tour: " + solver.getTour());
// Print: 42.0
System.out.println("Tour cost: " + solver.getTourCost());
}
}
| 29.015625 | 106 | 0.601149 |
0d6acd0af84aea8fe106ed5c58f2eb1adb984697 | 295 | package com.feritbolezek.lth.constants;
public class Colors {
public final static String TILE_COLOR = "#e37e53";
public final static String BACKGROUND_COLOR = "#2c3e50";
public final static String TILE_COLOR_TWO = "#1abc9c";
public final static String TEXT_COLOR = "#ffffff";
}
| 32.777778 | 60 | 0.735593 |
de9b23de17b29cc23ecb58643b08c6958643c667 | 5,500 | /*
* Copyright 2010-2013 Ning, Inc.
* Copyright 2014-2016 Groupon, Inc
* Copyright 2014-2016 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.beatrix.integration.overdue;
import java.math.BigDecimal;
import org.joda.time.LocalDate;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.api.TestApiListener.NextEvent;
import org.killbill.billing.beatrix.integration.TestIntegrationBase;
import org.killbill.billing.beatrix.util.InvoiceChecker.ExpectedInvoiceItemCheck;
import org.killbill.billing.catalog.api.BillingPeriod;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.entitlement.api.DefaultEntitlement;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.subscription.api.user.SubscriptionBaseTransition;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.testng.Assert.assertNotNull;
public class TestBillingAlignment extends TestIntegrationBase {
@Test(groups = "slow")
public void testTransitionAccountBAToSubscriptionBA() throws Exception {
// We take april as it has 30 days (easier to play with BCD)
// Set clock to the initial start date - we implicitly assume here that the account timezone is UTC
clock.setDay(new LocalDate(2012, 4, 1));
// Set the BCD to the 25th
final Account account = createAccountWithNonOsgiPaymentMethod(getAccountData(25));
//
// CREATE SUBSCRIPTION AND EXPECT BOTH EVENTS: NextEvent.CREATE NextEvent.INVOICE
// (Start with monthly that has an 'Account' billing alignment)
//
final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
assertNotNull(bpEntitlement);
invoiceChecker.checkInvoice(account.getId(), 1, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 4, 1), null, InvoiceItemType.FIXED, new BigDecimal("0")));
invoiceChecker.checkChargedThroughDate(bpEntitlement.getId(), new LocalDate(2012, 4, 1), callContext);
// GET OUT TRIAL (moving clock to 2012-05-04)
addDaysAndCheckForCompletion(33, NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 1), new LocalDate(2012, 5, 25), InvoiceItemType.RECURRING, new BigDecimal("199.96")));
invoiceChecker.checkChargedThroughDate(bpEntitlement.getId(), new LocalDate(2012, 5, 25), callContext);
// Change plan to annual that has been configured to have a 'Subscription' billing alignment
final DefaultEntitlement changedBpEntitlement = changeEntitlementAndCheckForCompletion(bpEntitlement, "Shotgun", BillingPeriod.ANNUAL, null, NextEvent.CHANGE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
invoiceChecker.checkInvoice(account.getId(),
3,
callContext,
new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 4), new LocalDate(2013, 5, 1), InvoiceItemType.RECURRING, new BigDecimal("2380.22")),
new ExpectedInvoiceItemCheck(new LocalDate(2012, 5, 4), new LocalDate(2012, 5, 25), InvoiceItemType.REPAIR_ADJ, new BigDecimal("-174.97")));
invoiceChecker.checkChargedThroughDate(bpEntitlement.getId(), new LocalDate(2013, 5, 1), callContext);
Assert.assertEquals(changedBpEntitlement.getSubscriptionBase().getAllTransitions().size(), 3);
final SubscriptionBaseTransition trial = changedBpEntitlement.getSubscriptionBase().getAllTransitions().get(0);
Assert.assertEquals(trial.getEffectiveTransitionTime().toLocalDate().compareTo(new LocalDate(2012, 4, 1)), 0);
Assert.assertEquals(trial.getNextPhase().getName(), "shotgun-monthly-trial");
final SubscriptionBaseTransition smEvergreen = changedBpEntitlement.getSubscriptionBase().getAllTransitions().get(1);
Assert.assertEquals(smEvergreen.getEffectiveTransitionTime().toLocalDate().compareTo(new LocalDate(2012, 5, 1)), 0);
Assert.assertEquals(smEvergreen.getNextPhase().getName(), "shotgun-monthly-evergreen");
final SubscriptionBaseTransition saEvergreen = changedBpEntitlement.getSubscriptionBase().getAllTransitions().get(2);
// Verify the IMMEDIATE policy
Assert.assertEquals(saEvergreen.getEffectiveTransitionTime().toLocalDate().compareTo(new LocalDate(2012, 5, 4)), 0);
// Verify the START_OF_SUBSCRIPTION alignment (both plans have the same 30 days trial)
Assert.assertEquals(saEvergreen.getNextPhase().getName(), "shotgun-annual-evergreen");
}
}
| 59.782609 | 234 | 0.743091 |
3e2b3939e79c72ca593846aafaa339c0ec18575c | 2,592 | package com.asterxis.main;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.entity.WolfRenderer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.asterxis.entity.NewUndeadHorseRenderer;
import com.asterxis.init.EntityInit;
import com.asterxis.init.ItemInit;
// The value here should match an entry in the META-INF/mods.toml file
@Mod("undead_horse_re")
public class UndeadHorseMain
{
// Directly reference a log4j logger.
private static final Logger LOGGER = LogManager.getLogger();
public UndeadHorseMain() {
final IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
ItemInit.ITEMS.register(modEventBus);
EntityInit.ENTITY_TYPES.register(modEventBus);
MinecraftForge.EVENT_BUS.register(this);
}
private void setup(final FMLCommonSetupEvent event)
{
}
private void enqueueIMC(final InterModEnqueueEvent event)
{
}
private void doClientStuff(final FMLClientSetupEvent event) {
RenderingRegistry.registerEntityRenderingHandler(EntityInit.SKELETON_HORSE, NewUndeadHorseRenderer::new);
RenderingRegistry.registerEntityRenderingHandler(EntityInit.ZOMBIE_HORSE, NewUndeadHorseRenderer::new);
}
private void processIMC(final InterModProcessEvent event)
{
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
@SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event) {
}
}
| 39.876923 | 110 | 0.790895 |
6725f5d92214699f08802b7ecaf5dcbd941ccfdc | 1,495 | package at.tugraz.ist.stracke.jsr;
import java.util.Objects;
public class Message {
private String recipient;
private String subject;
private String msg;
public Message(String recipient, String subject, String msg) {
this.recipient = recipient;
this.subject = subject;
this.msg = msg;
}
@Override
public int hashCode() {
int h = Objects.hash(this.recipient, this.subject, msg);
h = h * 100 + 666;
if (h > 1000) {
h -= 1000;
}
return h;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Message message = (Message) o;
return recipient.equals(message.recipient) &&
subject.equals(message.subject) &&
msg.equals(message.msg);
}
@Override
public String toString() {
return "{\n" +
String.format(" recipient: %s,\n", this.recipient) +
String.format(" subject: %s,\n", this.subject) +
String.format(" message: %s\n", this.msg) +
"}";
}
public String getRecipient() {
return recipient;
}
public String getSubject() {
return subject;
}
public String getMsg() {
return msg;
}
public String getShortMessage() {
String str = this.msg.substring(0, 5);
str = str + "...";
return str;
}
}
| 23.730159 | 66 | 0.542475 |
567c1286c8883f18bf6ff904129e1dc3565ccef1 | 2,177 | /**
* Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caintegrator/LICENSE.txt for details.
*/
package gov.nih.nci.caintegrator.domain.genomic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import gov.nih.nci.caintegrator.application.study.AbstractTestDataGenerator;
import gov.nih.nci.caintegrator.domain.AbstractCaIntegrator2Object;
import java.util.Set;
public final class SegmentDataGenerator extends AbstractTestDataGenerator<SegmentData> {
public static final SegmentDataGenerator INSTANCE = new SegmentDataGenerator();
private SegmentDataGenerator() {
super();
}
@Override
public void compareFields(SegmentData original, SegmentData retrieved) {
assertEquals(original.getArrayData(), retrieved.getArrayData());
assertEquals(original.getNumberOfMarkers(), retrieved.getNumberOfMarkers());
assertEquals(original.getSegmentValue(), retrieved.getSegmentValue(), 0.0);
if (original.getLocation() == null) {
assertNull(retrieved.getLocation());
} else {
assertEquals(original.getLocation().getChromosome(), retrieved.getLocation().getChromosome());
assertEquals(original.getLocation().getStartPosition(), retrieved.getLocation().getStartPosition());
assertEquals(original.getLocation().getEndPosition(), retrieved.getLocation().getEndPosition());
}
}
@Override
public SegmentData createPersistentObject() {
return new SegmentData();
}
@Override
public void setValues(SegmentData segmentData, Set<AbstractCaIntegrator2Object> nonCascadedObjects) {
segmentData.setNumberOfMarkers(getUniqueInt());
segmentData.setSegmentValue(getUniqueFloat());
segmentData.setLocation(new ChromosomalLocation());
segmentData.getLocation().setChromosome(getUniqueString(2));
segmentData.getLocation().setStartPosition(getUniqueInt());
segmentData.getLocation().setEndPosition(getUniqueInt());
}
}
| 39.581818 | 113 | 0.717501 |
c3b935604989725fcfcdf428060ef250a78ec34a | 7,889 | package im.dacer.mrghllghghllghg;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView tvMurkEye;
private TextView tvBluegill;
private TextView tvWarleader;
private TextView tvGrimscale;
private TextView tvBabyMurloc;
private TextView tvDamage;
private TextView tvMinions;
private VerticalSeekBar seekBarMinions;
private int numDamage;
private int numAvailableMinions;
private ArrayList<Integer> murlocList;
private ArrayList<ArrayList<Integer>> murlocHistoryList; //For undo
public final static int MURLOC_MURK_EYE = 0;
public final static int MURLOC_BLUEGILL = 1;
public final static int MURLOC_WARLEADER = 2;
public final static int MURLOC_GRIMSCALE = 3;
public final static int MURLOC_BABYMURLOC = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
tvDamage = (TextView) findViewById(R.id.tv_damage);
tvMurkEye = (TextView) findViewById(R.id.tv_murkeye);
tvBluegill = (TextView) findViewById(R.id.tv_bluegill);
tvWarleader = (TextView) findViewById(R.id.tv_warleader);
tvGrimscale = (TextView) findViewById(R.id.tv_grimscale);
tvBabyMurloc = (TextView) findViewById(R.id.tv_baby_murloc);
seekBarMinions = (VerticalSeekBar) findViewById(R.id.mySeekBar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
tvMinions = (TextView) findViewById(R.id.tv_minions);
tvMurkEye.setTag(0);
tvBluegill.setTag(1);
tvWarleader.setTag(2);
tvGrimscale.setTag(3);
tvBabyMurloc.setTag(4);
tvMurkEye.setOnClickListener(this);
tvBluegill.setOnClickListener(this);
tvWarleader.setOnClickListener(this);
tvGrimscale.setOnClickListener(this);
tvBabyMurloc.setOnClickListener(this);
murlocList = new ArrayList<>();
murlocHistoryList = new ArrayList<>();
setSupportActionBar(toolbar);
init();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
init();
}
});
seekBarMinions.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
numAvailableMinions = progress;
tvMinions.setText(String.valueOf(progress));
calculateDamageAndShowNumbers();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void init() {
if (!murlocList.isEmpty()) {
murlocHistoryList.add(new ArrayList<>(murlocList));
}
murlocList.clear();
numAvailableMinions = 7;
seekBarMinions.setProgress(numAvailableMinions);
tvMinions.setText(String.valueOf(numAvailableMinions));
calculateDamageAndShowNumbers();
}
@Override
public void onClick(View v) {
int tag = (int)v.getTag();
murlocList.add(tag);
calculateDamageAndShowNumbers();
}
private void calculateDamageAndShowNumbers() {
calculateDamage();
showNumbers();
}
private void calculateDamage(){
int[] murlocNumList = getMurlocNumList(murlocList, numAvailableMinions);
int mNumMurkEye = murlocNumList[0];
int mNumBluegill = murlocNumList[1];
int mNumWarleader = murlocNumList[2];
int mNumGrimscale = murlocNumList[3];
int mNumBabyMurloc = murlocNumList[4];
int bluegillAttack = 2 + 2 * mNumWarleader + mNumGrimscale;
int murkEyeAttack = 2 + 2 * mNumWarleader + mNumGrimscale +
(mNumMurkEye + mNumBluegill + mNumWarleader + mNumGrimscale + mNumBabyMurloc - 1);
numDamage = bluegillAttack * mNumBluegill + murkEyeAttack * mNumMurkEye;
}
private void showNumbers() {
int[] murlocNumList = getMurlocNumList(murlocList);
tvMurkEye.setText(String.valueOf(murlocNumList[0]));
tvBluegill.setText(String.valueOf(murlocNumList[1]));
tvWarleader.setText(String.valueOf(murlocNumList[2]));
tvGrimscale.setText(String.valueOf(murlocNumList[3]));
tvBabyMurloc.setText(String.valueOf(murlocNumList[4]));
tvDamage.setText(String.valueOf(numDamage));
}
private int[] getMurlocNumList(ArrayList<Integer> list) {
return getMurlocNumList(list, -1);
}
private int[] getMurlocNumList(ArrayList<Integer> list, int limit) {
int numMurkEye = 0;
int numBluegill = 0;
int numWarleader = 0;
int numGrimscale = 0;
int numBabyMurloc = 0;
int numMinion = list.size();
if(limit != -1){
numMinion = Math.min(list.size(), limit);
}
for (int i=0; i<numMinion; i++) {
int murloc = list.get(i);
switch (murloc){
case MURLOC_MURK_EYE:
numMurkEye++;
break;
case MURLOC_BLUEGILL:
numBluegill++;
break;
case MURLOC_WARLEADER:
numWarleader++;
break;
case MURLOC_GRIMSCALE:
numGrimscale++;
break;
case MURLOC_BABYMURLOC:
numBabyMurloc++;
break;
}
}
return new int[]{numMurkEye, numBluegill, numWarleader, numGrimscale, numBabyMurloc};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_about) {
startActivity(new Intent(this, AboutActivity.class));
return true;
}else if (id == R.id.action_undo) {
if (!murlocList.isEmpty()) {
murlocList.remove(murlocList.size() - 1);
}else if(!murlocHistoryList.isEmpty()) {
murlocList = new ArrayList<>(murlocHistoryList.get(murlocHistoryList.size()-1));
murlocHistoryList.remove(murlocHistoryList.size() - 1);
}else {
Toast.makeText(this, R.string.nothing_undo, Toast.LENGTH_SHORT).show();
}
calculateDamageAndShowNumbers();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 35.062222 | 98 | 0.634174 |
2618b7601953313a390fcd2a31b48e319220bd0d | 63,946 | // Copyright 2007-2010 Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.acre.script;
import static log.Log.DEBUG;
import static log.Log.ERROR;
import static log.Log.INFO;
import static log.Log.WARN;
import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import log.Log;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import com.google.acre.AcreFactory;
import com.google.acre.Configuration;
import com.google.acre.javascript.JSON;
import com.google.acre.javascript.JSONException;
import com.google.acre.javascript.JSUtil;
import com.google.acre.javascript.DOM.JSAttr;
import com.google.acre.javascript.DOM.JSCDATASection;
import com.google.acre.javascript.DOM.JSCharacterData;
import com.google.acre.javascript.DOM.JSComment;
import com.google.acre.javascript.DOM.JSDOMException;
import com.google.acre.javascript.DOM.JSDOMImplementation;
import com.google.acre.javascript.DOM.JSDOMParser;
import com.google.acre.javascript.DOM.JSDOMParserException;
import com.google.acre.javascript.DOM.JSDocument;
import com.google.acre.javascript.DOM.JSDocumentFragment;
import com.google.acre.javascript.DOM.JSDocumentType;
import com.google.acre.javascript.DOM.JSElement;
import com.google.acre.javascript.DOM.JSEntity;
import com.google.acre.javascript.DOM.JSEntityReference;
import com.google.acre.javascript.DOM.JSNamedNodeMap;
import com.google.acre.javascript.DOM.JSNode;
import com.google.acre.javascript.DOM.JSNodeList;
import com.google.acre.javascript.DOM.JSNotation;
import com.google.acre.javascript.DOM.JSProcessingInstruction;
import com.google.acre.javascript.DOM.JSText;
import com.google.acre.script.AcreContextFactory.AcreContext;
import com.google.acre.script.exceptions.AcreDeadlineError;
import com.google.acre.script.exceptions.AcreInternalError;
import com.google.acre.script.exceptions.AcreScriptError;
import com.google.acre.script.exceptions.AcreThreadDeath;
import com.google.acre.script.exceptions.AcreURLFetchException;
import com.google.acre.script.exceptions.JSConvertableException;
import com.google.acre.thread.AllocationLimitedThread;
import com.google.acre.util.CostCollector;
import com.google.acre.util.Supervisor;
import com.google.acre.util.resource.ResourceSource;
public class HostEnv extends ScriptableObject implements AnnotatedForJS {
private static final long serialVersionUID = 4916701464804733869L;
public static final String ACRE_QUOTAS_HEADER = "X-acre-quotas";
private final static Log _logger = new Log(HostEnv.class);
private static String ACRE_METAWEB_API_ADDR = Configuration.Values.ACRE_METAWEB_API_ADDR.getValue();
private static int ACRE_METAWEB_API_ADDR_PORT = Configuration.Values.ACRE_METAWEB_API_ADDR_PORT.getInteger();
private static String ACRE_SITE_HOST = Configuration.Values.ACRE_SITE_HOST.getValue();
private static int ACRE_SITE_HOST_PORT = Configuration.Values.ACRE_SITE_HOST_PORT.getInteger();
private static String ACRE_FREEBASE_SITE_ADDR = Configuration.Values.ACRE_FREEBASE_SITE_ADDR.getValue();
private static int ACRE_FREEBASE_SITE_ADDR_PORT = Configuration.Values.ACRE_FREEBASE_SITE_ADDR_PORT.getInteger();
private static String ACRE_GOOGLEAPIS_HOST = Configuration.Values.ACRE_GOOGLEAPIS_HOST.getValue();
private static String ACRE_GOOGLEAPIS_KEY = Configuration.Values.ACRE_GOOGLEAPIS_KEY.getValue();
private static String ACRE_GOOGLEAPIS_RPC = Configuration.Values.ACRE_GOOGLEAPIS_RPC.getValue();
private static String ACRE_GOOGLEAPIS_FREEBASE_VERSION = Configuration.Values.ACRE_GOOGLEAPIS_FREEBASE_VERSION.getValue();
private static String ACRE_HOST_BASE = Configuration.Values.ACRE_HOST_BASE.getValue();
private static String ACRE_HOST_DELIMITER_PATH = Configuration.Values.ACRE_HOST_DELIMITER_PATH.getValue();
private static boolean ACRE_DEVELOPER_MODE = Configuration.Values.ACRE_DEVELOPER_MODE.getBoolean();
private static boolean ACRE_REMOTE_REQUIRE = Configuration.Values.ACRE_REMOTE_REQUIRE.getBoolean();
private static final String DEFAULT_HOST_PATH = "//default." + ACRE_HOST_DELIMITER_PATH;
public static boolean LIMIT_EXECUTION_TIME = Configuration.Values.ACRE_LIMIT_EXECUTION_TIME.getBoolean();
public static final int ACRE_URLFETCH_TIMEOUT = Configuration.Values.ACRE_URLFETCH_TIMEOUT.getInteger();
// in order to allow error scripts to handle timeouts in the main
// script, we extend their deadline by this many msec.
public static final int ERROR_DEADLINE_EXTENSION = 20000;
// any urlfetch should be timed out this many msec
// before the current request's deadline, so there
// is time for the script to handle the failure.
// for this to work it must be set high enough to
// gracefully handle (e.g. with an error page)
// any connection timeouts.
// setting this to 0 means that scripts will rarely
// have time to handle urlfetch connection timeouts
// gracefully.
// setting this higher effectively limits the maximum
// re-entry depth. this is necessary to limit the
// number of threads that may be occupied to handle
// a single request.
// a single external request may occupy
// (ACRE_URLFETCH_TIMEOUT / NETWORK_DEADLINE_ADVANCE) threads
//
public static final int NETWORK_DEADLINE_ADVANCE = 4000;
// when passing on a deadline to a subrequest, bring it
// in a little bit more than the network deadline so
// that it will complete with a timeout before the
// network deadline. this is in addition to
// NETWORK_DEADLINE_ADVANCE.
// for this to work it must be set high enough to handle
// the subrequest 500 response (possibly by handling an error page)
// otherwise the urlfetch will fail with a connection timeout
// instead of receiving a 500.
// setting this to 0 ought to guarantee a connection
// timeout when a subrequest chain runs out of resources,
// (since the penultimate subrequest should get a connection
// timeout just as the final subrequest times out).
// this does not seem to be the case - the final
// request is able to return a 500 error before
// the penultimate request gives up. possibly
// other padding on the network timeout somewhere?
// in any case, the fetching script will have time to handle
// the connection timeout if NETWORK_DEADLINE_ADVANCE is
// high enough.
public static final int SUBREQUEST_DEADLINE_ADVANCE = 0; //500;
// we prefer to avoid the supervisor thread, so delay the
// Thread.stop() from the "normal" deadline by this many msec.
// this is due to concerns about the safety of Thread.stop() -
// we need this as a backstop for the worst case (e.g. regexps)
// but we would prefer to fail within the request handling thread.
public static final int SUPERVISOR_GRACE_PERIOD = 1000;
private static final AcreContextFactory _contextFactory = new AcreContextFactory();
// XXX: this could be redone with individual ScriptManagers per application domain / SecurityDomain objects etc.
// with an instance of ScriptManager per domain - the ScriptManager having a Compiler/Loader and class cache
private static ScriptManager _scriptManager = new ScriptManager();
private transient Context _context;
private Scriptable _scope;
// if this HostEnv was created to show an error page (or other internal redirect),
// this will point at the original HostEnv. try to avoid using this.
@SuppressWarnings("unused")
private HostEnv _parent_hostenv;
@SuppressWarnings("unused")
private transient AcreExceptionInfo _exceptionInfo;
private transient ResourceSource _resourceSource;
private transient Supervisor _supervisor;
private boolean _supervised;
// this is the per-request cache of packages imported
private Map<String, Scriptable> _scriptResults = new HashMap<String, Scriptable>();
transient AcreRequest req;
transient AcreResponse res;
private transient AsyncUrlfetch _async_fetch;
long allocationLimit;
boolean _is_open;
private CostCollector _costCollector;
static {
ContextFactory.initGlobal(_contextFactory);
}
public HostEnv(ResourceSource resources, AcreRequest request, AcreResponse response, Supervisor supervisor) throws IOException {
_resourceSource = resources;
req = request;
res = response;
_supervisor = supervisor;
_supervised = false;
_costCollector = CostCollector.getInstance();
allocationLimit = Configuration.Values.ACRE_MAX_OBJECT_COUNT_PER_SCRIPT.getInteger();
JSUtil.populateScriptable(this, this);
syslog(INFO, "hostenv.init", "");
}
public String getClassName() {
return "HostEnv";
}
/**
* create a fresh request scope with rhino + acre standard objects
*/
private Scriptable initAcreStandardObjects() {
Scriptable scope = _context.initStandardObjects();
try {
ScriptableObject.defineClass(scope, JSJSON.class, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.jsonobj.init.failed", "Failed to load JSON object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.jsonobj.init.failed", "Failed to load JSON object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.jsonobj.init.failed", "Failed to load JSON object: " + e);
}
try {
ScriptableObject.defineClass(scope, JSBinary.class, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.binaryobj.init.failed", "Failed to load Binary object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.binaryobj.init.failed", "Failed to load Binary object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.binaryobj.init.failed", "Failed to load Binary object: " + e);
}
try {
ScriptableObject.defineClass(scope, JSFile.class, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.fileobj.init.failed", "Failed to load File object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.fileobj.init.failed", "Failed to load File object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.fileobj.init.failed", "Failed to load File object: " + e);
}
try {
ScriptableObject.defineClass(scope, JSKeyStore.class, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.keystore.init.failed", "Failed to load KeyStore object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.keystore.init.failed", "Failed to load KeyStore object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.keystore.init.failed", "Failed to load KeyStore object: " + e);
}
try {
ScriptableObject.defineClass(scope, JSCache.class, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.cache.init.failed", "Failed to load Cache object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.cache.init.failed", "Failed to load Cache object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.cache.init.failed", "Failed to load Cache object: " + e);
}
try {
ScriptableObject.defineClass(scope, JSAttr.class, false, true);
ScriptableObject.defineClass(scope, JSCDATASection.class, false, true);
ScriptableObject.defineClass(scope, JSCharacterData.class, false, true);
ScriptableObject.defineClass(scope, JSComment.class, false, true);
ScriptableObject.defineClass(scope, JSDOMException.class, false, true);
ScriptableObject.defineClass(scope, JSDOMImplementation.class, false, true);
ScriptableObject.defineClass(scope, JSDocument.class, false, true);
ScriptableObject.defineClass(scope, JSDocumentFragment.class, false, true);
ScriptableObject.defineClass(scope, JSDocumentType.class, false, true);
ScriptableObject.defineClass(scope, JSElement.class, false, true);
ScriptableObject.defineClass(scope, JSEntity.class, false, true);
ScriptableObject.defineClass(scope, JSEntityReference.class, false, true);
ScriptableObject.defineClass(scope, JSNamedNodeMap.class, false, true);
ScriptableObject.defineClass(scope, JSNode.class, false, true);
ScriptableObject.defineClass(scope, JSNodeList.class, false, true);
ScriptableObject.defineClass(scope, JSNotation.class, false, true);
ScriptableObject.defineClass(scope, JSProcessingInstruction.class, false, true);
ScriptableObject.defineClass(scope, JSText.class, false, true);
ScriptableObject.defineClass(scope, JSDOMParser.class, false, true);
ScriptableObject.defineClass(scope, JSDOMParserException.class, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.dom.init.failed", "Failed to load DOM: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.dom.init.failed", "Failed to load DOM: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.dom.init.failed", "Failed to load DOM: " + e);
}
try {
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsDataStoreClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSDataStore");
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsDataStoreResultsClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSDataStoreResults");
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsDataStoreResultsIteratorClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSDataStoreResultsIterator");
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsDataStoreTransactionClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSDataStoreTransaction");
try {
ScriptableObject.defineClass(scope, jsDataStoreClass, false, true);
ScriptableObject.defineClass(scope, jsDataStoreResultsClass, false, true);
ScriptableObject.defineClass(scope, jsDataStoreResultsIteratorClass, false, true);
ScriptableObject.defineClass(scope, jsDataStoreTransactionClass, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.datastore.init.failed", "Failed to load DataStore object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.datastore.init.failed", "Failed to load DataStore object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.datastore.init.failed", "Failed to load DataStore object: " + e);
}
} catch (ClassNotFoundException e1) {
syslog(DEBUG, "hostenv.datastore.init.failed", "DataStore provider not found and will not be available");
}
try {
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsTaskQueueClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSTaskQueue");
try {
ScriptableObject.defineClass(scope, jsTaskQueueClass, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.taskqueue.init.failed", "Failed to load TaskQueue object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.taskqueue.init.failed", "Failed to load TaskQueue object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.taskqueue.init.failed", "Failed to load TaskQueue object: " + e);
}
} catch (ClassNotFoundException e1) {
syslog(DEBUG, "hostenv.taskqueue.init.failed", "TaskQueue provider not found and will not be available");
}
try {
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsMailServiceClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSMailService");
try {
ScriptableObject.defineClass(scope, jsMailServiceClass, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.appcache.init.failed", "Failed to load MailService object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.appcache.init.failed", "Failed to load MailService object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.appcache.init.failed", "Failed to load MailService object: " + e);
}
} catch (ClassNotFoundException e1) {
syslog(DEBUG, "hostenv.mailer.init.failed", "MailService provider not found and will not be available");
}
try {
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsUserServiceClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSUserService");
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsUserClass = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSUser");
try {
ScriptableObject.defineClass(scope, jsUserServiceClass, false, true);
ScriptableObject.defineClass(scope, jsUserClass, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.userservice.init.failed", "Failed to load UserService object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.userservice.init.failed", "Failed to load UserService object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.userservice.init.failed", "Failed to load UserService object: " + e);
}
} catch (ClassNotFoundException e1) {
syslog(DEBUG, "hostenv.userservice.init.failed", "UserService provider not found and will not be available");
}
try {
@SuppressWarnings("unchecked")
Class<? extends Scriptable> jsAppEngineOAuthService = (Class<? extends Scriptable>) Class.forName("com.google.acre.appengine.script.JSAppEngineOAuthService");
try {
ScriptableObject.defineClass(scope, jsAppEngineOAuthService, false, true);
} catch (IllegalAccessException e) {
syslog(ERROR, "hostenv.appcache.init.failed", "Failed to load AppEngineOAuthService object: " + e);
} catch (InstantiationException e) {
syslog(ERROR, "hostenv.appcache.init.failed", "Failed to load AppEngineOAuthService object: " + e);
} catch (InvocationTargetException e) {
syslog(ERROR, "hostenv.appcache.init.failed", "Failed to load AppEngineOAuthService object: " + e);
}
} catch (ClassNotFoundException e1) {
syslog(DEBUG, "hostenv.appengineoauth.init.failed", "AppEngineOAuthService provider not found and will not be available");
}
return scope;
}
// note that this may be called re-entrantly to handle error pages
public void run() {
Thread thread = Thread.currentThread();
// if the supervisor is there and enabled,
// schedule the thread to be stopped after a certain time
if (_supervisor != null && LIMIT_EXECUTION_TIME) {
_supervisor.watch(thread, req._deadline + SUPERVISOR_GRACE_PERIOD);
_supervised = true;
}
// if the thread supports it, set the memory usage limit
AllocationLimitedThread athread = null;
if (thread instanceof AllocationLimitedThread) {
athread = (AllocationLimitedThread) thread;
athread.setThreadAllocationLimit(allocationLimit);
}
try {
_context = _contextFactory.enterContext();
if (_context instanceof AcreContext) {
((AcreContext) _context).deadline = req._deadline;
}
_scope = initAcreStandardObjects();
_async_fetch = AcreFactory.getAsyncUrlfetch();
_async_fetch.response(res);
_async_fetch.scope(_scope);
// let's do it!
bootScript();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// if the thread supports it, clear the memory quota and log the memory costs
if (athread != null) {
long remains = athread.getThreadAllocationLimit();
if (res._used_memory < 0) {
throw new RuntimeException("Nice try"); // this is just a paranoid check, should happen only if we get hacked
}
if (remains != 0 || res._used_memory > 0) {
long memory_used = (allocationLimit - remains) + res._used_memory;
int pctused = (int) ((100 * memory_used) / allocationLimit);
String msg = "script used " + pctused + "% of memory quota";
userlog("debug", msg);
syslog(DEBUG, "hostenv.script.memory", msg);
_costCollector.collect("am", (float) memory_used);
athread.setThreadAllocationLimit(0);
}
}
// if the supervisor is there and enabled, release the scheduled killer
if (_supervised) {
_supervisor.release(thread);
_supervised = false;
}
if (_context != null) {
Context.exit();
_context = null;
}
}
}
public void bootScript() {
req.server_host = ACRE_HOST_DELIMITER_PATH + "." + ACRE_HOST_BASE;
req.server_host_base = ACRE_HOST_BASE;
req.freebase_service_url = "http://" + ACRE_METAWEB_API_ADDR;
if (ACRE_METAWEB_API_ADDR_PORT != 80) req.freebase_service_url += ":" + ACRE_METAWEB_API_ADDR_PORT;
req.freebase_site_host = "http://" + ACRE_FREEBASE_SITE_ADDR;
if (ACRE_FREEBASE_SITE_ADDR_PORT != 80) req.freebase_site_host += ":" + ACRE_FREEBASE_SITE_ADDR_PORT;
req.site_host = "http://" + ACRE_SITE_HOST;
if (ACRE_SITE_HOST_PORT != 80) req.site_host += ":" + ACRE_SITE_HOST;
req.googleapis_host = ACRE_GOOGLEAPIS_HOST;
req.googleapis_key = ACRE_GOOGLEAPIS_KEY;
req.googleapis_rpc = ACRE_GOOGLEAPIS_RPC;
req.googleapis_freebase_version = ACRE_GOOGLEAPIS_FREEBASE_VERSION;
_scope.put("PROTECTED_HOSTENV", _scope, this);
this.put("ACRE_HOST_BASE", this,
Configuration.Values.ACRE_HOST_BASE.getValue());
this.put("ACRE_HOST_DELIMITER_HOST", this,
Configuration.Values.ACRE_HOST_DELIMITER_HOST.getValue());
this.put("ACRE_HOST_DELIMITER_PATH", this,
Configuration.Values.ACRE_HOST_DELIMITER_PATH.getValue());
this.put("STATIC_SCRIPT_PATH", this,
Configuration.Values.STATIC_SCRIPT_PATH.getValue());
this.put("ACRE_DEVELOPER_MODE", this, ACRE_DEVELOPER_MODE);
this.put("ACRE_REMOTE_REQUIRE", this, ACRE_REMOTE_REQUIRE);
this.put("DEFAULT_HOST_PATH", this, DEFAULT_HOST_PATH);
_scope.put("ACRE_REQUEST", _scope, req.toJsObject(_scope));
try {
syslog(INFO, "hostenv.script.start", "");
// we ought to make sure acreboot has initialized before
// throwing this error
if (LIMIT_EXECUTION_TIME && System.currentTimeMillis() > req._deadline) {
throw new AcreDeadlineError("Request chain time quota expired");
}
if (_scope.has("acre", _scope)) {
throw new RuntimeException("FATAL: bootScript() re-entered with same scope");
}
try {
load_system_script("acreboot.js", _scope);
} catch (JavaScriptException jsexc) {
Object exit_exception_obj = this.get("AcreExitException", this);
if (exit_exception_obj instanceof Scriptable) {
Object val = jsexc.getValue();
Scriptable exit_exception = (Scriptable) exit_exception_obj;
if ((val instanceof Scriptable && !exit_exception.hasInstance((Scriptable) val)) || !(val instanceof Scriptable)) {
renderErrorPage("JS exception", jsexc, "hostenv.script.error.jsexception");
return;
} else if (val instanceof Scriptable && exit_exception.hasInstance((Scriptable) val)) {
Object spath = ((Scriptable) val).get("route_to", (Scriptable) val);
Object skip_routes = ((Scriptable) val).get("skip_routes", (Scriptable) val);
if (spath instanceof String) {
internalRedirect((String)spath, (Boolean) skip_routes);
return;
}
}
} else {
throw jsexc;
}
}
try {
Object finisher = this.get("finish_response", this);
if (finisher != null) {
Object[] args = {};
// throw away result
((Callable)finisher).call(_context, _scope, _scope, args);
}
} catch (JavaScriptException jsexc) {
// not even AcreExitException is ok here.
renderErrorPage("JS exception closing response", jsexc, "hostenv.script.error.jsexception");
return;
}
closeResponse();
} catch (RhinoException rexc) {
renderErrorPage("Unhandled exception", rexc, "hostenv.script.error.jsexception");
} catch (AcreScriptError ase) {
renderErrorPage("Unrecoverable error: " + ase.getMessage(), ase, "hostenv.script.error.acrescripterror");
} catch (StackOverflowError soe) {
renderErrorPage("Stack overflow", soe, "hostenv.script.error.stackoverflowerror");
} catch (OutOfMemoryError oome) {
if (oome.getMessage().matches("PermGen space")) {
reportDisaster("Unhandlable java OutOfMemoryError", oome);
System.exit(1);
}
// record the fact that we have exceeded the memory quota in the regular call
// this is done because the error page will reset the memory quota and lose
// this information. This is needed to record the real amount of memory used.
res._used_memory = allocationLimit;
renderErrorPage("Memory limit exceeded", oome, "hostenv.script.error.outofmemoryerror");
} catch (AcreThreadDeath td) {
renderErrorPage("Execution time limit exceeded", td, "hostenv.script.error.threaddeath");
} catch (AcreDeadlineError td) {
renderErrorPage("Execution time limit exceeded", td, "hostenv.script.error.deadline");
} catch (IOException ioe) {
reportDisaster("I/O exception reached toplevel", ioe);
if (ioe.getMessage().matches("Too many open files")) {
System.exit(1);
}
} catch (Throwable t) {
reportDisaster("Fatal exception reached toplevel", t);
} finally {
_async_fetch = null;
// clean up after running a user script.
}
}
/**
* create a fresh request scope.
* we re-use the old AcreRequest object after augmenting it with
* information about the redirect.
* for isolation reasons we create a complete new HostEnv and
* js context - only the information on AcreRequest is carried through.
*
* NOTE it is the caller's responsibility to exit after calling this
* function
*
* @returns the new HostEnv
*/
public HostEnv internalRedirect(String script_path, boolean skip_routes) throws IOException {
syslog(DEBUG, "hostenv.script.internalredirect", "internal redirect to " + script_path);
// reset the request path_info and query_string
URL url;
try {
url = new URL("http:" + script_path);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
String query_string = url.getQuery();
if (query_string == null) {
query_string = "";
}
req.setPathInfo(url.getPath());
req.setQueryString(query_string);
// reset the response
res.reset();
// create a new HostEnv and populate it from this
// we re-use the same AcreRequest
// NOTE: keep checking for time quota for all error pages
// that are not the default one
HostEnv newenv = new HostEnv(_resourceSource, req, res, _supervisor);
newenv._parent_hostenv = this;
// modify the AcreRequest to add any additional info
req.handler_script_path = script_path;
req.skip_routes = skip_routes;
// if the script is an error script, add additional time to the quota for the error script
// to be executed. Note that urlfetches by user error scripts are restricted
// so that this extended time does not get passed on further.
if (req.error_info != null) {
req._deadline += ERROR_DEADLINE_EXTENSION;
}
// exit the old Context (which is stored thread-local by rhino)
if (_context != null) {
Context.exit();
_context = null;
}
// remove any supervisor watch on this thread
// (it will be re-established for the error page)
if (_supervised) {
Thread thread = Thread.currentThread();
_supervisor.release(thread);
_supervised = false;
}
// run the request using a fresh js context but the same thread
newenv.run();
return newenv;
}
/**
* @return the global context factory of {@link AcreContextFactory} type<br>
* initialized and set into the Rhino in the static initializer
*/
public static ContextFactory getGlobal() {
return _contextFactory;
}
public Scriptable getScope() {
return _scope;
}
// ------------------------------- JavaScript Functions --------------------------------------
@JSFunction
public Scriptable load_system_script(String script, Scriptable scope) {
int pathIndex = script.lastIndexOf('/');
String script_name = (pathIndex == -1) ? script : script.substring(pathIndex + 1);
//String script_id = (ACRE_AUTORELOADING) ? script + lastModifiedTime(script) : script;
String script_id = script + lastModifiedTime(script);
String script_id_hash = Integer.toHexString(script_id.hashCode());
Scriptable newScope = load_script_from_cache(script_name, script_id_hash, scope, true);
if (newScope == null) {
String content = openResourceFile(script);
newScope = load_script_from_string(content, script_name, script_id_hash, scope, null, true);
}
return newScope;
}
@JSFunction
public Scriptable load_script_from_cache(String script_name,
String content_id,
Object scopearg,
boolean system) {
// because rhino won't convert js null to match a Scriptable arg on a
// java method.
Scriptable scope = (Scriptable) scopearg;
// obtain the right class name from the name and content ID
String className = CachedScript.getClassName(script_name, content_id);
// see if we can look up the cached script by class name
CachedScript script = _scriptManager.getScriptByClassName(className);
if (script == null) {
syslog4j(DEBUG, "hostenv.script.load.from_cache.not_found",
"script_name", script_name,
"cache_key", className,
"content_id", content_id
);
return null;
} else {
// if the script had syntax errors, the compiling process threw
// and left the compiled script null, so we need to make sure that
// doesn't happen
if (script.getCompiledScript() == null) {
syslog4j(DEBUG, "hostenv.script.load.from_cache.invalid",
"script_name", script_name,
"cache_key", className,
"content_id", content_id
);
// make sure we purge the script manager cache
// in case the cached script wasn't properly initialized
// to avoid leaking memory
_scriptManager.invalidate(className);
return null;
}
}
return execute(script, scope, system);
}
@JSFunction
public Scriptable load_script_from_string(String js_text,
String script_name,
String content_id,
Object scopearg,
Object linemaparg,
boolean system) {
// because rhino won't convert js null to match a Scriptable arg on a
// java method.
Scriptable scope = (Scriptable) scopearg;
Scriptable linemap = (Scriptable) linemaparg;
// set the script up before compiling it, so we have the linemap
// and filename map in case of compiler errors.
CachedScript script = new CachedScript(script_name, js_text, content_id);
if (linemap != null) {
Double d = (Double) linemap.get("length", linemap);
if (d != null) {
int nlines = d.intValue();
int[] jlinemap = new int[nlines];
for (int i = 0; i < nlines; i++) {
try {
d = (Double) linemap.get(i, linemap);
jlinemap[i] = (d != null) ? d.intValue() : 0;
} catch (ClassCastException e) {
syslog(WARN, "hostenv.script.bad_linemap_entry",
"bad linemap entry for script " + script_name);
jlinemap[i] = 0;
}
}
script.setLinemap(jlinemap);
}
}
// get the script (this will compile it if it wasn't done before)
script = _scriptManager.getScript(script, res);
syslog(DEBUG, "hostenv.script.load.from_string", "loading script '" + script.getScriptName() + "'");
return execute(script, scope, system);
}
@SuppressWarnings("unused")
@JSFunction
public Scriptable urlOpen(String url,
String method,
Object content,
Scriptable headers,
boolean system,
boolean log_to_user,
String response_encoding,
boolean no_redirect) {
//System.out.println((system ? "[system] " : "") + "sync: " + url.split("\\?")[0] + " [reentries: " + req._reentries + "]");
if (req._reentries > 1) {
throw new JSConvertableException("Urlfetch is allowed to re-enter only once").newJSException(this);
}
if (LIMIT_EXECUTION_TIME && (System.currentTimeMillis() > req._deadline)) {
throw new RuntimeException("Cannot call urlfetch, the script ran out of time");
}
try {
new URL(url);
} catch (MalformedURLException e) {
throw new JSURLError("Malformed URL: " + url).newJSException(this);
}
// give the subrequest a shorter deadline so this request can handle any failure
long net_deadline = (LIMIT_EXECUTION_TIME) ? req._deadline - NETWORK_DEADLINE_ADVANCE : System.currentTimeMillis() + ACRE_URLFETCH_TIMEOUT;
AcreFetch fetch = new AcreFetch(url, method, net_deadline, req._reentries, res, AcreFactory.getClientConnectionManager());
if (headers != null) {
Object[] ids = headers.getIds();
for (int i = 0; i < ids.length; i++) {
String id = ids[i].toString();
fetch.request_headers.put(id, headers.get(id, headers).toString());
}
}
fetch.request_body = content;
try {
if (response_encoding == null) response_encoding = "ISO-8859-1";
fetch.fetch(system, response_encoding, log_to_user, no_redirect);
return fetch.toJsObject(_scope);
} catch (AcreURLFetchException e) {
throw new JSURLError(e.getMessage()).newJSException(this);
}
}
@SuppressWarnings("unused")
@JSFunction
public void urlOpenAsync(String url,
String method,
Object content,
Scriptable headers,
Double timeout_ms,
boolean system,
boolean log_to_user,
String response_encoding,
boolean no_redirect,
Function callback) {
//System.out.println((system ? "[system] " : "") + "async: " + url.split("\\?")[0] + " [reentries: " + req._reentries + "]");
if (_async_fetch == null) {
throw new JSConvertableException(
"Async Urlfetch not supported in this enviornment"
).newJSException(this);
}
if (req._reentries > 1) {
throw new JSConvertableException("Urlfetch is allowed to re-enter only once").newJSException(this);
}
if (LIMIT_EXECUTION_TIME && System.currentTimeMillis() > req._deadline) {
throw new RuntimeException("Cannot call urlfetch, the script ran out of time");
}
// if execution is limited, give the subrequest a shorter deadline so this request can
// handle any failure
long timeout = (LIMIT_EXECUTION_TIME) ? req._deadline - NETWORK_DEADLINE_ADVANCE : System.currentTimeMillis() + ACRE_URLFETCH_TIMEOUT;
if (!timeout_ms.isNaN() && timeout_ms.longValue() < timeout) {
timeout = timeout_ms.longValue();
}
if (response_encoding == null) response_encoding = "ISO-8859-1";
Map<String, String> header_map = new HashMap<String, String>();
if (headers != null) {
Object[] ids = headers.getIds();
for (int i = 0; i < ids.length; i++) {
String id = ids[i].toString();
header_map.put(id, headers.get(id, headers).toString());
}
}
try {
new URL(url);
} catch (MalformedURLException e) {
throw new JSURLError("Malformed URL: " + url).newJSException(this);
}
long sub_deadline = (LIMIT_EXECUTION_TIME) ? req._deadline - HostEnv.SUBREQUEST_DEADLINE_ADVANCE : ACRE_URLFETCH_TIMEOUT;
int reentrances = req._reentries + 1;
header_map.put(HostEnv.ACRE_QUOTAS_HEADER, "td=" + sub_deadline + ",r=" + reentrances);
try {
_async_fetch.make_request(url, method, timeout, header_map, content, system, log_to_user, response_encoding, no_redirect, callback);
} catch (Exception e) {
throw new JSConvertableException(e.getMessage()).newJSException(this);
}
}
@JSFunction
public void async_wait(Double timeout_ms) {
long timeout = (LIMIT_EXECUTION_TIME) ? req._deadline - System.currentTimeMillis() - NETWORK_DEADLINE_ADVANCE : ACRE_URLFETCH_TIMEOUT;
// XXX consider throwing, or at least warning if this condition fails
if (!timeout_ms.isNaN() && timeout_ms.longValue() < timeout) {
timeout = timeout_ms.longValue();
}
_async_fetch.wait_on_result(timeout, TimeUnit.MILLISECONDS);
}
/**
* Appends str to the output stream
* NOTE: everything is ALWAYS buffered until the very end of the request
* handling.
*/
@JSFunction
public void write(Object data) throws IOException {
if (data instanceof String) {
res.write((String)data);
} else if (data instanceof JSBinary) {
res.write((JSBinary)data);
} else {
// NOTE: it's impossible for any other types to get here
}
}
/**
* this is for user logging but from the java code
*/
@SuppressWarnings("unchecked")
@JSFunction
public void userlog(String level, Object msg) {
if (msg instanceof String) {
String msg_str = (String) msg;
msg = new ArrayList<String>();
((ArrayList<String>) msg).add(msg_str);
}
if (msg instanceof List || msg instanceof Scriptable) {
res.log(level, msg);
}
}
public void syslog4j(byte level, String event_name, Object... msgparts) {
HashMap<String, String> msg = new HashMap<String, String>();
String key = null;
for (Object p : msgparts) {
if (key == null) {
key = (String)p;
continue;
}
if (p instanceof String) {
msg.put(key, (String)p);
} else if (p instanceof Scriptable ||
p instanceof Map ||
p instanceof List) {
try {
msg.put(key, JSON.stringify(p));
} catch (JSONException e) {
msg.put(key, "INVALID JSON");
}
} else if (p == null) {
msg.put(key, null);
} else {
msg.put(key, p.toString());
}
key = null;
}
syslog(level, event_name, msg);
}
/**
* this is for logging internal errors
*/
@JSFunction
public void syslog(Object level, Object event_name, Object msgarg) {
byte lvl = INFO;
if (level instanceof String) {
lvl = Log.toLevel((String) level);
} else if (level instanceof Number) {
lvl = ((Number) level).byteValue();
} else {
throw new JSConvertableException("Log levels can only be strings").newJSException(this);
}
if (event_name == null) event_name = "system";
if (msgarg instanceof Scriptable) {
HashMap<String,String> msg = new HashMap<String, String>();
Object[] ids = ((Scriptable)msgarg).getIds();
for (int i = 0; i < ids.length; i++) {
Object id = ids[i];
String key = id.toString();
Object value = ((Scriptable) msgarg).get(key, (Scriptable) msgarg);
if (value instanceof String) {
msg.put(key, (String) value);
} else if (value == null) {
msg.put(key, null);
} else {
msg.put(key, value.toString());
}
}
_logger.log(event_name.toString(), lvl, msg);
} else {
_logger.log(event_name.toString(), lvl, msgarg);
}
}
@JSFunction
public void start_response(int status, Scriptable headers, Scriptable cookies) {
_is_open = true;
res._response_status = status;
Object[] ids = headers.getIds();
for (int i = 0; i < ids.length; i++) {
Object id = ids[i];
String key = id.toString();
Object value = headers.get(key, headers);
res._response_headers.put(key, value.toString());
}
ids = cookies.getIds();
for (int i = 0; i < ids.length; i++) {
Object id = ids[i];
String key = id.toString();
Scriptable jsvalue = (Scriptable) cookies.get(key, cookies);
AcreCookie cookie = new AcreCookie(jsvalue);
if (cookie.name != null && !cookie.name.equals(key)) {
throw new JSConvertableException("Cookie name mismatch: " + key + " vs " + cookie.name).newJSException(this);
}
cookie.name = key;
res._response_cookies.put(key, cookie);
}
}
@JSFunction
public void do_wait(int millis) {
synchronized (this) {
try {
this.wait(millis);
} catch (InterruptedException e) {
// not much to do here, so ignore
}
}
}
// ------------------------------------- private methods --------------------------------------------
private void startErrorPage() {
// allocate new response headers so any previous start_response
// is wiped out. this is necessary for handling startErrorPage()
// after acre.start_response is called.
res.reset();
res._response_status = 500;
res._response_headers.put("content-type", "text/plain; charset=utf-8");
}
private void signalAcreError(String msg) {
try {
res._response_headers.put("X-Acre-Error", URLEncoder.encode(msg,"UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding: UTF-8"); // this should never happen
}
}
private String expandJavascriptPath(String file) {
return "/WEB-INF/js/" + file;
}
private long lastModifiedTime(String file) {
String path = expandJavascriptPath(file);
try {
return _resourceSource.getLastModifiedTime(path);
} catch (IOException e) {
throw new JSConvertableException("error reading resource: " + path).newJSException(this);
}
}
private String openResourceFile(String file) {
String path = expandJavascriptPath(file);
InputStream in = null;
BufferedReader reader = null;
StringBuilder buf = new StringBuilder();
try {
in = _resourceSource.getResourceAsStream(path);
if (in == null) {
throw new JSURLError("unable to open resource: " + path).newJSException(this);
}
reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
String line;
while ( (line = reader.readLine()) != null) {
buf.append(line);
buf.append("\n");
}
} catch (IOException e) {
throw new JSConvertableException("error reading resource: " + path).newJSException(this);
} finally {
try {
if (reader != null) reader.close();
if (in != null) in.close();
} catch (IOException e) {
throw new JSConvertableException("error closing file: " + path).newJSException(this);
}
}
return buf.toString();
}
private void simpleReportRhinoException(String msg, RhinoException e) throws IOException {
syslog(WARN, "hostenv.script.error.rhinoexception.fallback", "JS exception " + e);
String errmsg = "Unhandled exception in acre error handler: " + e.getMessage();
userlog("error", errmsg);
startErrorPage();
signalAcreError(errmsg);
write(errmsg);
}
/**
* called for successful js responses only
*/
private void closeResponse() throws IOException {
if (!_is_open) {
// this is a user error in which the user script failed to call start_response
renderErrorPage("Error in script: acre.start_response was never called", null, "hostenv.script.start_response.not_called");
return;
}
String script_path = "ACREBOOT";
if (has("script_path", this))
script_path = (String)get("script_path", this);
syslog(DEBUG, "hostenv.script.finish", "Done with script " + script_path);
}
/**
* This implies an internal problem in acreboot.js, since it should
* be handling any user errors.
*/
private void reportDisaster(String message, Throwable exc) {
// we hit a java exception. all
// bare java exception should have been trapped
// and hidden by now, so this is a serious internal
// error.
try {
syslog(ERROR, "hostenv.internal.error", "Internal error in script boot: " + message);
startErrorPage();
signalAcreError(message);
CharArrayWriter cw = new CharArrayWriter();
PrintWriter pw = new PrintWriter(cw);
exc.printStackTrace(pw);
if (null != exc.getCause()) {
pw.write("Caused by:\n");
pw.write(exc.getCause().getMessage() + "\n");
exc.getCause().printStackTrace(pw);
}
pw.flush();
String excdump = cw.toString();
syslog(ERROR, "hostenv.internal.error.msg", "ACRE INTERNAL ERROR: \n" + excdump);
write("ACRE INTERNAL ERROR -- Please Report to irc://irc.freenode.net/#freebase\n");
write("Request Id: " + req._metaweb_tid + "\n\n");
write(excdump + "\n");
} catch (Throwable e) {
syslog(ERROR, "hostenv.internal.error.fatal", "Dispatch: Acre Last chance error, giving up" + exc);
syslog(ERROR, "hostenv.internal.error.fatal.failed_on", "Failed reporting the error above" + e);
// XXX this should be replaced with an exception class that is unique to this case
// and will never be caught.
throw new AcreInternalError("Failed while reporting a disaster", e);
}
}
// page to use for handling errors, it must be a script, not a template.
private static final String ERROR_PAGE = "error";
private static final String DEFAULT_ERROR_PAGE = DEFAULT_HOST_PATH + "/" + ERROR_PAGE;
/**
* render the error page using /freebase/apps/default/error
*/
private void renderErrorPage(String message, Throwable t, String logevent) {
String error_script_path = null;
try {
try {
// uncomment to log java stack traces for js errors
// t.printStackTrace(new PrintWriter(exc_log));
// fetch metadata computed by acreboot.js
// get fresh script_name, script_path, script_host_path
String script_name = "UNKNOWN";
String script_path = "UNKNOWN";
String script_host_path = "UNKNOWN";
String error_handler_path = "UNKNOWN";
if (has("script_name", this))
script_name = (String)this.get("script_name", this);
if (has("script_path", this))
script_path = (String)this.get("script_path", this);
if (has("script_host_path", this))
script_host_path = (String)this.get("script_host_path", this);
if (has("error_handler_path", this))
error_handler_path = (String)this.get("error_handler_path", this);
String log_msg = message;
if (t != null) {
if (t instanceof RhinoException) {
log_msg += ": " + ((RhinoException) t).details();
} else {
String msg = t.getMessage();
if (msg != null && !"".equals(msg)) {
log_msg += ": " + msg;
}
}
}
// handle the error using the local error handler for the script
// this will fall back to the default error handler if no local handler is found
if ("UNKNOWN".equals(script_host_path) || "UNKNOWN".equals(script_name)) {
if (log_msg.indexOf("syntax error") > -1) {
reportDisaster("Syntax Error in acreboot.js", t);
return;
}
if (req.handler_script_path != null &&
req.handler_script_path.equals(DEFAULT_ERROR_PAGE)) {
reportDisaster("Fatal error in acreboot.js", t);
return;
}
syslog(ERROR, logevent, "Error in acreboot.js, no error context available");
error_script_path = DEFAULT_ERROR_PAGE;
// this is a hack to handle huge request bodies, which can choke acreboot.js
// in the error script
req.request_body = "";
} else if (req.error_info == null) {
// try the app's error handler or one specified by the app
// using acre.response.set_error_page(path)
// or error_page in metadata file
if ("UNKNOWN".equals(error_handler_path)) {
error_script_path = script_host_path + "/" + ERROR_PAGE;
} else {
error_script_path = error_handler_path;
}
} else {
// if we were handling an error in a user error handler, fall back to the system one.
// if there is an error in the system-wide error handler we have serious problems.
if (script_host_path.equals(DEFAULT_HOST_PATH)) {
// prevent infinite loops in error scripts
reportDisaster("Error while rendering default error page", t);
return;
}
// if it's already some other error script, force it to the default error script
error_script_path = DEFAULT_ERROR_PAGE;
}
userlog("error", log_msg);
AcreExceptionInfo einfo = new AcreExceptionInfo(script_path, message, t, _scriptManager, _scope);
// build the stacktrace
StringBuilder b = new StringBuilder();
for (AcreStackFrame frame : einfo.stack) {
b.append("\n ");
b.append(frame.filename);
b.append(": ");
b.append(frame.line);
}
// log the error + stacktrace to the syslog
syslog(ERROR, logevent, log_msg + b.toString());
// pass the exception info to the error script
req.error_info = einfo;
// if this request is an appengine task, there is no point exeucting the error page
// since the output of a task is lost anyway, so just initialize the error headers
// in the response
if (isAppEngineTask()) {
startErrorPage();
} else {
internalRedirect(error_script_path, true);
}
} catch (RhinoException e) {
simpleReportRhinoException("error running error script " + error_script_path, e);
}
} catch (Throwable e) {
reportDisaster("Internal error in error page", e);
}
}
/**
* Returns true if this request is an AppEngine task
*/
private boolean isAppEngineTask() {
return req.headers.containsKey("x-appengine-taskname");
}
/**
* Execute the script and save it in the map to enable stack trace "legend" <br>
* something <b>should</b> known about the script that we were asked to execute.<br>
* so we remember all there was and provide access to it when the sh.t crashes.<br>
*
* @param script
*/
private Scriptable execute(CachedScript script, Scriptable scope, boolean system) {
String className = script.getClassName();
// check if this script (package) has already been included
// XXX note that the scope passed in is ignored in this case!
Scriptable result = _scriptResults.get(className);
if (null != result) {
return result;
}
// save the scope-in-progress before running the script.
// this means that if there is a recursive acre.require() call
// it will return the incomplete scope object rather then trying
// to create a new scope when one is already under construction.
_scriptResults.put(className, scope);
// increment 'file count' cost header
_costCollector.collect((system) ? "afsc" : "afuc");
Script compiledScript = script.getCompiledScript();
if (compiledScript != null) {
compiledScript.exec(_context, scope);
} else {
throw new RuntimeException("cache contains invalid state for script " + script.getScriptName());
}
return scope;
}
@JSFunction
public String hmac(String algorithm, String key, String data, boolean to_hex) {
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(signingKey);
if (to_hex) {
return new String(Hex.encodeHex(mac.doFinal(data.getBytes())));
} else {
return new String(Base64.encodeBase64(mac.doFinal(data.getBytes())));
}
} catch (InvalidKeyException e) {
throw new JSConvertableException("Invalid key: " +
key).newJSException(this);
} catch (NoSuchAlgorithmException e) {
throw new JSConvertableException("Unable to load algoritm: " +
algorithm).newJSException(this);
}
}
// XXX to_hex should be like an enum or something, but since we only
// care about two formats for now..
@JSFunction
public String hash(String algorithm, String str, boolean to_hex) {
try {
MessageDigest alg = MessageDigest.getInstance(algorithm);
alg.reset();
alg.update(str.getBytes());
byte digest[] = alg.digest();
if (to_hex) {
return new String(Hex.encodeHex(digest));
} else {
return new String(Base64.encodeBase64(digest));
}
} catch (NoSuchAlgorithmException e) {
throw new JSConvertableException("Unable to load algoritm: " +
algorithm).newJSException(this);
}
}
// developer-only entrypoint for triggering error handlers
@SuppressWarnings("null")
@JSFunction
public String dev_test_internal(String name) {
// the js entry point shouldn't be visible to user scripts
// unless developer mode is enabled, but double-check it
// here too.
if (!ACRE_DEVELOPER_MODE) {
return "";
}
if (name.equals("OutOfMemoryError")) {
throw new OutOfMemoryError("this is an OutOfMemoryError message");
}
if (name.equals("StackOverflowError")) {
throw new StackOverflowError("this is an StackOverflowError message");
}
if (name.equals("ThreadDeath")) {
throw new ThreadDeath();
}
if (name.equals("RuntimeException")) {
throw new RuntimeException("this is a RuntimeException message");
}
if (name.equals("Error")) {
throw new Error("this is an Error message");
}
if (name.equals("AcreScriptError")) {
throw new AcreScriptError("AcreScriptError - faked script was taking too long");
}
if (name.equals("NullPointerException")) {
Object n = null;
n.toString();
}
// not really "throw", so the different naming style is deliberate
if (name.equals("java_infinite_loop")) {
boolean a = true;
while (a) {}
}
// quick-and-dirty reflecton of options to this function
// so they aren't duplicated in test code
if (name.equals("list")) {
return "OutOfMemoryError StackOverflowError ThreadDeath RuntimeException Error AcreScriptError NullPointerException java_infinite_loop";
}
// TODO add more options to test potential java failures
// log_spew to try to overwhelm the log system
// ...
// if you add more cases, update the "list" case above too!
return "";
}
}
| 43.003362 | 181 | 0.6034 |
257e8a8b4a57748aae82e6f277fc4b905bf3250f | 409 | package jp.fieldnotes.demo.vscode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloContoroller {
@RequestMapping(path="/hello", method = RequestMethod.GET)
public String hello() {
return "Hello, Azure!";
}
}
| 27.266667 | 62 | 0.762836 |
5f8a1ee825b7c2e2e1cfddc4ddd34b391d9f3005 | 1,275 | package com.dtp.starter.cloud.consul.autoconfigure;
import com.dtp.common.constant.DynamicTpConst;
import com.dtp.starter.cloud.consul.refresh.CloudConsulRefresher;
import com.dtp.starter.common.autoconfigure.BaseBeanAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.consul.config.ConsulConfigProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Redick01
*/
@Configuration
@ConditionalOnClass(ConsulConfigProperties.class)
@ConditionalOnProperty(value = DynamicTpConst.DTP_ENABLED_PROP, matchIfMissing = true, havingValue = "true")
@ImportAutoConfiguration({BaseBeanAutoConfiguration.class})
public class DtpAutoConfiguration {
@Bean
@ConditionalOnMissingBean()
@ConditionalOnProperty(value = "spring.cloud.consul.config.enabled", matchIfMissing = true)
public CloudConsulRefresher cloudConsulRefresher() {
return new CloudConsulRefresher();
}
}
| 42.5 | 108 | 0.835294 |
4eb60d1500da964f93232b401e2248119bd8f4e9 | 983 | package net.anotheria.moskito.core.decorators.counter;
import net.anotheria.moskito.core.counter.CounterStats;
/**
* Decorator for counter stats object.
*
* @author lrosenberg
* @since 19.11.12 12:01
*/
public class CounterStatsDecorator extends GenericCounterDecorator{
/**
* Caption(s).
*/
private static final String CAPTIONS[] = {
"Counter",
};
/**
* Short explanations.
*/
private static final String SHORT_EXPLANATIONS[] = {
"Counter",
};
/**
* Explanations.
*/
private static final String EXPLANATIONS[] = {
"Number of calls, clicks, payments - whatever you wanted to count",
};
/**
* Pattern.
*/
private static final CounterStats PATTERN = new CounterStats("pattern");
/**
* Creates a new counter stats decorator by calling super constructor with pattern, captions, short_explanations and
* explanations as parameter.
*/
public CounterStatsDecorator(){
super(PATTERN, CAPTIONS, SHORT_EXPLANATIONS, EXPLANATIONS);
}
}
| 21.369565 | 117 | 0.704985 |
260b13885612ee7f8797e35d8d55e73f33ae8b66 | 7,254 | /*
* 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 co.edu.uniandes.csw.turismo.resources;
import co.edu.uniandes.csw.turismo.dtos.SitioTuristicosDTO;
import co.edu.uniandes.csw.turismo.ejb.SitioTuristicoLogic;
import co.edu.uniandes.csw.turismo.entities.SitioTuristicoEntity;
import co.edu.uniandes.csw.turismo.exceptions.BusinessLogicException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
/**
*
* @author David Fonseca
*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class SitioTuristicoResource {
private static final Logger LOGGER=Logger.getLogger(SitioTuristicoResource.class.getName());
@Inject
private SitioTuristicoLogic logic;
@POST
public SitioTuristicosDTO createSitioTuristico(@PathParam("ciudadId") Long booksId, SitioTuristicosDTO sitio) throws BusinessLogicException {
LOGGER.log(Level.INFO, "SitioTuristicoResource createSitioTuristico: input: {0}", sitio);
SitioTuristicosDTO nuevoSitioTuristicoDTO = new SitioTuristicosDTO(logic.createSitioTuritico(booksId, sitio.toEntity()));
LOGGER.log(Level.INFO, "SitioTuristicoResource createSitioTuristico: output: {0}", nuevoSitioTuristicoDTO);
return nuevoSitioTuristicoDTO;
}
/**
* Busca y devuelve todas las reseñas que existen en un libro.
*
* @param ciudadId
* @return JSONArray {@link SitioTuristicoDTO} - Las reseñas encontradas en el
* libro. Si no hay ninguna retorna una lista vacía.
*/
@GET
public List<SitioTuristicosDTO> getSitioTuristicos(@PathParam("ciudadId") Long ciudadId) {
LOGGER.log(Level.INFO, "SitioTuristicoResource getSitioTuristicos: input: {0}", ciudadId);
List<SitioTuristicosDTO> listaDTOs = listEntity2DTO(logic.getSitioTuriticos(ciudadId));
LOGGER.log(Level.INFO, "EditorialBooksResource getBooks: output: {0}", listaDTOs);
return listaDTOs;
}
/**
* Busca y devuelve la reseña con el ID recibido en la URL, relativa a un
* libro.
*
* @param booksId El ID del libro del cual se buscan las reseñas
* @param sitiosId El ID de la reseña que se busca
* @return {@link SitioTuristicoDTO} - La reseña encontradas en el libro.
* @throws BusinessLogicException {@link BusinessLogicExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra el libro.
* @throws WebApplicationException {@link WebApplicationExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra la reseña.
*/
@GET
@Path("{sitios: \\d+}")
public SitioTuristicosDTO getSitioTuristico(@PathParam("ciudadId") Long booksId, @PathParam("sitios") Long sitiosId) throws BusinessLogicException {
LOGGER.log(Level.INFO, "SitioTuristicoResource getSitioTuristico: input: {0}", sitiosId);
SitioTuristicoEntity entity = logic.getSitioTuritico(booksId, sitiosId);
if (entity == null) {
throw new WebApplicationException("El recurso /books/" + booksId + "/sitios/" + sitiosId + " no existe.", 404);
}
SitioTuristicosDTO sitioDTO = new SitioTuristicosDTO(entity);
LOGGER.log(Level.INFO, "SitioTuristicoResource getSitioTuristico: output: {0}", sitioDTO);
return sitioDTO;
}
/**
* Actualiza una reseña con la informacion que se recibe en el cuerpo de la
* petición y se regresa el objeto actualizado.
*
* @param booksId El ID del libro del cual se guarda la reseña
* @param sitiosId El ID de la reseña que se va a actualizar
* @param sitio {@link SitioTuristicoDTO} - La reseña que se desea guardar.
* @return JSON {@link SitioTuristicoDTO} - La reseña actualizada.
* @throws BusinessLogicException {@link BusinessLogicExceptionMapper} -
* Error de lógica que se genera cuando ya existe la reseña.
* @throws WebApplicationException {@link WebApplicationExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra la reseña.
*/
@PUT
@Path("{sitiosId: \\d+}")
public SitioTuristicosDTO updateSitioTuristico(@PathParam("ciudadId") Long booksId, @PathParam("sitiosId") Long sitiosId, SitioTuristicosDTO sitio) throws BusinessLogicException {
LOGGER.log(Level.INFO, "SitioTuristicoResource updateSitioTuristico: input: booksId: {0} , sitiosId: {1} , sitio:{2}", new Object[]{booksId, sitiosId, sitio});
if (sitiosId.equals(sitio.getId())) {
throw new BusinessLogicException("Los ids del SitioTuristico no coinciden.");
}
SitioTuristicoEntity entity = logic.getSitioTuritico(booksId, sitiosId);
if (entity == null) {
throw new WebApplicationException("El recurso /books/" + booksId + "/sitios/" + sitiosId + " no existe.", 404);
}
SitioTuristicosDTO sitioDTO = new SitioTuristicosDTO(logic.updateSitioTuritico(booksId, sitio.toEntity()));
LOGGER.log(Level.INFO, "SitioTuristicoResource updateSitioTuristico: output:{0}", sitioDTO);
return sitioDTO;
}
/**
* Borra la reseña con el id asociado recibido en la URL.
*
* @param booksId El ID del libro del cual se va a eliminar la reseña.
* @param sitiosId El ID de la reseña que se va a eliminar.
* @throws BusinessLogicException {@link BusinessLogicExceptionMapper} -
* Error de lógica que se genera cuando no se puede eliminar la reseña.
* @throws WebApplicationException {@link WebApplicationExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra la reseña.
*/
@DELETE
@Path("{sitiosId: \\d+}")
public void deleteSitioTuristico(@PathParam("ciudadId") Long booksId, @PathParam("sitiosId") Long sitiosId) throws BusinessLogicException {
SitioTuristicoEntity entity = logic.getSitioTuritico(booksId, sitiosId);
if (entity == null) {
throw new WebApplicationException("El recurso /books/" + booksId + "/sitios/" + sitiosId + " no existe.", 404);
}
logic.deleteSitioTuritico(booksId, sitiosId);
}
/**
* Lista de entidades a DTO.
*
* Este método convierte una lista de objetos PrizeEntity a una lista de
* objetos SitioTuristicoDTO (json)
*
* @param entityList corresponde a la lista de reseñas de tipo Entity que
* vamos a convertir a DTO.
* @return la lista de reseñas en forma DTO (json)
*/
private List<SitioTuristicosDTO> listEntity2DTO(List<SitioTuristicoEntity> entityList) {
List<SitioTuristicosDTO> list = new ArrayList<>();
for (SitioTuristicoEntity entity : entityList) {
list.add(new SitioTuristicosDTO(entity));
}
return list;
}
}
| 44.503067 | 183 | 0.704577 |
8857f194aa6a853425a973c27283a59b360a96bb | 2,546 | package org.biopax.paxtools.query.wrapperL3;
import org.biopax.paxtools.model.BioPAXElement;
import org.biopax.paxtools.model.level3.PhysicalEntity;
import org.biopax.paxtools.query.model.AbstractNode;
import org.biopax.paxtools.query.model.Edge;
import org.biopax.paxtools.query.model.Graph;
import org.biopax.paxtools.query.model.Node;
import java.util.Collection;
import java.util.Collections;
/**
* This is the parent wrapper class for both Conversion and TemplateReaction objects.
*
* @author Ozgun Babur
*/
public abstract class EventWrapper extends AbstractNode
{
/**
* Constructor with the owner graph.
* @param graph Owner graph
*/
protected EventWrapper(GraphL3 graph)
{
super(graph);
}
/**
* Events are not breadth nodes.
* @return False
*/
public boolean isBreadthNode()
{
return false;
}
/**
* Events have a positive sign.
* @return POSITIVE (1)
*/
public int getSign()
{
return POSITIVE;
}
/**
* Events are not ubiquitous molecules.
* @return False
*/
public boolean isUbique()
{
return false;
}
/**
* Say if the event is a transcription.
* @return Whether the event is a transcription
*/
public abstract boolean isTranscription();
/**
* Bind the wrapper of the given element to the upstream.
* @param ele Element to bind
* @param graph Owner graph.
*/
protected void addToUpstream(BioPAXElement ele, Graph graph)
{
AbstractNode node = (AbstractNode) graph.getGraphObject(ele);
if (node == null) return;
Edge edge = new EdgeL3(node, this, graph);
if (isTranscription())
{
if (node instanceof ControlWrapper)
{
((ControlWrapper) node).setTranscription(true);
}
}
node.getDownstreamNoInit().add(edge);
this.getUpstreamNoInit().add(edge);
}
/**
* Bind the wrapper of the given PhysicalEntity to the downstream.
* @param pe PhysicalEntity to bind
* @param graph Owner graph.
*/
protected void addToDownstream(PhysicalEntity pe, Graph graph)
{
AbstractNode node = (AbstractNode) graph.getGraphObject(pe);
if (node == null) return;
Edge edge = new EdgeL3(this, node, graph);
node.getUpstreamNoInit().add(edge);
this.getDownstreamNoInit().add(edge);
}
/**
* Events do not have equivalent objects.
* @return Empty set
*/
@Override
public Collection<Node> getUpperEquivalent()
{
return Collections.emptySet();
}
/**
* Events do not have equivalent objects.
* @return Empty set
*/
@Override
public Collection<Node> getLowerEquivalent()
{
return Collections.emptySet();
}
}
| 20.868852 | 85 | 0.704242 |
41fb10d20fa04e2d85644eccf940f3e7531bd107 | 8,255 | package battleship;
import java.util.Scanner;
/* This file contains all the necessary methods & attributes for the battleship game
* Rules:
* Each player (Human & Computer) places 6 ships & 4 Grenades in each coordinate. Valid coordinates are character A-H or a-h followed by number 1 to 8.
Each position can only hold one type of element (Ship or Grenade)
The elements are hidden initially so ensure the players doesn't know each other's placements
The Human (User) launches rocket first in one of the valid coordinates.
If rocket falls in a coordinate where there is nothing, '*' is displayed
If rocket fall in a coordinate where there is a Ship -> if it human's ship then we display 's' or 'S' for computer's ship.
If rocket fall in a coordinate where there is a Grenade -> if it's human's grenade we display 'g' and 'G' for computer's ship and the player loses next turn (The other player hits twice)
If rocket falls in a coordinate which has been called before, nothing happens, and we display the previous coordinates.
The Computer launches rocket and the above rules are applied as well.
The game continues until all 6 ships are sunk (Rocket hits the coordinates where there is a ship) for one of the players.
The player who hit all 6 ships of the other player is declared the winner.
All the initial placements of Ships & Grenades for each player is displayed.
* Author: Mushfiqur Anik
* */
public class Battleship {
// Attributes
private Player[][] p = new Player[8][8];
private char[][] displayGrid = new char[8][8];
Scanner keyboard = new Scanner(System.in);
private String coord; // Get coordinates from Human
private int hShip = 0; // Number of ships sunk
private int cShip = 0;
private Type type = null;
private Owner owner = null;
private int numOfTurns = 0;
private boolean isHuman = true;
private int[] coordinates = new int[2]; // Coordinates
// Main game loop
public void play() {
// Repeat until all Ships of one of the players have been sunk
do {
if(numOfTurns == 0) { numOfTurns = 1; } // If one player's turn is finished - set it up for next player
outerloop:
// Launches rocket
while(numOfTurns > 0) {
if(isHuman) {
coordinates = getCoords(owner.HUMAN, type.ROCKET);
} else {
System.out.println("Computer's turn to launch the rocket: ");
coordinates = getCoords(owner.COMPUTER, type.ROCKET);
}
// Launch rocket
// If Grenade is hit, the other player plays twice
if(launchRocket() == 2) {
break outerloop;
}
}
System.out.println("");
isHuman = !isHuman; // Change player i.e From Human to Computer or vice versa
} while(cShip < 6 && hShip < 6);
winner(hShip, cShip); // Check and declare winner
displayInitialGrid(); // Display initial position of Ships & Grenades for both players
}
// Launch rocket
// Returns the number of turn for the next player
public int launchRocket() {
// If this coordinate has been called before then nothing happens
if(p[coordinates[0]][coordinates[1]].isCalled()) {
// Do nothing
System.out.println("This position has been called before, nothing happens!");
displayGrid();
numOfTurns--;
} else {
switch(p[coordinates[0]][coordinates[1]].getType()) {
case NOTHING:
p[coordinates[0]][coordinates[1]].setiSCalled(true);
System.out.println("Nothing was hit");
displayGrid[coordinates[0]][coordinates[1]] = '*';
displayGrid();
numOfTurns--;
return numOfTurns;
case SHIP:
if(p[coordinates[0]][coordinates[1]].getOwner() == owner.HUMAN) {
p[coordinates[0]][coordinates[1]].setiSCalled(true);
System.out.println("Your ship has been hit!");
displayGrid[coordinates[0]][coordinates[1]] = 's';
displayGrid();
hShip++;
} else {
p[coordinates[0]][coordinates[1]].setiSCalled(true);
System.out.println("Computer's ship has been hit!");
displayGrid[coordinates[0]][coordinates[1]] = 'S';
cShip++;
displayGrid();
}
numOfTurns--;
return numOfTurns;
case GRENADE:
p[coordinates[0]][coordinates[1]].setiSCalled(true);
if(p[coordinates[0]][coordinates[1]].getOwner() == owner.HUMAN) {
displayGrid[coordinates[0]][coordinates[1]] = 'g';
} else {
displayGrid[coordinates[0]][coordinates[1]] = 'G';
}
System.out.println("Grenade has been hit, next turn will be missed!");
displayGrid();
numOfTurns = 2;
return numOfTurns;
}
}
return -1;
}
// Places Ships & Grenades
public void placeShipsAndGren(Owner owner, Type type) {
int limit = 0;
//int[] coordinates = new int[2];
if(type == type.SHIP) { limit = 6;}
else limit = 4; // For Grenade
// Placing the Owner, Type of element (Ship or Grenade), and isCalled to false.
for(int i = 0; i < limit; i++) {
coordinates = getCoords(owner, type);
p[coordinates[0]][coordinates[1]].setPlayer(owner, type, false);
}
}
// Gets coordinates for Ships/Grenades/Rocket
public int[] getCoords(Owner owner, Type type) {
int[] coordinates = new int[2];
while(true) {
if(owner == owner.HUMAN) {
System.out.print("Enter the coordinates of your " + type + " (H): ");
coord = keyboard.nextLine();
if(coord.length() > 2) { continue; }
coordinates[0] = charToInt(coord.charAt(0)) - 1;
coordinates[1] = Character.getNumericValue(coord.charAt(1)) - 1;
} else {
coordinates[0] = (int)(Math.random() * 7) + 1;
coordinates[1] = (int)(Math.random() * 7) + 1;
System.out.println("Entering the coordinates for " + type + " (C): ");
}
if(!isValid(coordinates[0], coordinates[1])) {
System.out.println("Sorry, coordinates outside the grid. Try again!");
continue;
}
// Rockets can hit any position
if(type != type.ROCKET) {
if (!isAvailable(coordinates[0], coordinates[1])) {
System.out.println("Sorry, coordinates already used. Try again!");
continue;
}
}
return coordinates;
}
}
// Declares winner
public void winner(int human, int computer) {
// If human sinks computer's all 6 ships then Human is the winner
if(computer == 6) {
System.out.println("Congratulations you have won the battle");
} else {
System.out.println("Sorry you have lost the battle, better luck next game!");
}
}
// Converts characters to integers.
public int charToInt(char c) {
int converted;
c = Character.toUpperCase(c);
converted = (c - 'A' + 1);
return converted;
}
// Check if position is available
public boolean isAvailable(int i, int j) {
return (p[i][j].getType() == Type.NOTHING);
}
// Check if position is valid
public boolean isValid(int i, int j) {
return (0 <= i && i <= 7) && (0 <= j && j <= 7);
}
// Initializes the grids: Player as well the display grid
public void initializeGrid() {
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
p[i][j] = new Player();
displayGrid[i][j] = '-';
}
}
}
// Displays the grid after launching a rocket
public void displayGrid() {
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
System.out.print(displayGrid[i][j] + " ");
}
System.out.println("");
}
}
// Displays the positions of Ships & Grenades place by the Human & Computer.
public void displayInitialGrid() {
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
switch(p[i][j].getType()) {
case NOTHING:
System.out.print('-' + " ");
break;
case SHIP:
if(p[i][j].getOwner() == Owner.HUMAN) {
System.out.print('s' + " ");
} else {
System.out.print('S' + " ");
}
break;
case GRENADE:
if(p[i][j].getOwner() == Owner.HUMAN) {
System.out.print('g' + " ");
} else {
System.out.print('G' + " ");
}
break;
}
}
System.out.println("");
}
}
}
| 31.75 | 187 | 0.610781 |
64e83c1269b75ee6d5c9a87afd44719e3ea69eb9 | 1,876 | /*
* $Id: ParseExceptionTests.java,v 1.8 2007/03/16 10:30:41 agoubard Exp $
*
* Copyright 2003-2007 Orange Nederland Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.tests.common.text;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.xins.common.text.ParseException;
/**
* Tests for class <code>ParseException</code>.
*
* @version $Revision: 1.8 $ $Date: 2007/03/16 10:30:41 $
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
*/
public class ParseExceptionTests extends TestCase {
/**
* Constructs a new <code>ParseExceptionTests</code> test suite with
* the specified name. The name will be passed to the superconstructor.
*
* @param name
* the name for this test suite.
*/
public ParseExceptionTests(String name) {
super(name);
}
/**
* Returns a test suite with all test cases defined by this class.
*
* @return
* the test suite, never <code>null</code>.
*/
public static Test suite() {
return new TestSuite(ParseExceptionTests.class);
}
public void testParseException() throws Throwable {
ParseException p = new ParseException();
assertEquals(null, p.getMessage());
assertEquals(null, p.getDetail());
assertEquals(null, p.getCause());
p = new ParseException(null, null, null);
assertEquals(null, p.getMessage());
assertEquals(null, p.getDetail());
assertEquals(null, p.getCause());
Exception cause = new Exception();
String message = "'nough said.";
String detail = "Zoom zoom zoom";
p = new ParseException(message, cause, detail);
assertEquals(message, p.getMessage());
assertEquals(detail, p.getDetail());
assertEquals(cause, p.getCause());
}
}
| 29.3125 | 74 | 0.665245 |
edfbf6575c419656e78b08937cbe8742f65ced81 | 751 | package com.qxml.qxml_androidx.gen.lottie;
import android.graphics.ColorFilter;
import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieProperty;
import com.airbnb.lottie.SimpleColorFilter;
import com.airbnb.lottie.model.KeyPath;
import com.airbnb.lottie.value.LottieValueCallback;
public class LottieHelper {
public static void setLottieImageViewLottieColorFilter(LottieAnimationView lottieImageView, int color) {
SimpleColorFilter filter = new SimpleColorFilter(color);
KeyPath keyPath = new KeyPath("**");
LottieValueCallback<ColorFilter> callback = new LottieValueCallback<ColorFilter>(filter);
lottieImageView.addValueCallback(keyPath, LottieProperty.COLOR_FILTER, callback);
}
}
| 35.761905 | 108 | 0.793609 |
60cfcb787f2cb0476b3ac1aa92eef3678ace8a1b | 4,561 | /**
* Copyright 2019 The JoyQueue Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joyqueue.client.internal.consumer.support;
import org.apache.commons.collections.CollectionUtils;
import org.joyqueue.client.internal.consumer.BatchMessageListener;
import org.joyqueue.client.internal.consumer.config.ConsumerConfig;
import org.joyqueue.client.internal.consumer.converter.ConsumeMessageConverter;
import org.joyqueue.client.internal.consumer.domain.ConsumeMessage;
import org.joyqueue.client.internal.consumer.domain.ConsumeReply;
import org.joyqueue.client.internal.consumer.exception.IgnoreAckException;
import org.joyqueue.client.internal.consumer.interceptor.ConsumeContext;
import org.joyqueue.client.internal.consumer.interceptor.ConsumerInvoker;
import org.joyqueue.client.internal.metadata.domain.TopicMetadata;
import org.joyqueue.domain.ConsumerPolicy;
import org.joyqueue.network.command.RetryType;
import org.joyqueue.toolkit.time.SystemClock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* BatchConsumerInvoker
*
* author: gaohaoxiang
* date: 2019/1/11
*/
public class BatchConsumerInvoker implements ConsumerInvoker {
protected static final Logger logger = LoggerFactory.getLogger(BatchConsumerInvoker.class);
private ConsumerConfig config;
private TopicMetadata topicMetadata;
private ConsumerPolicy consumerPolicy;
private List<ConsumeMessage> messages;
private List<BatchMessageListener> listeners;
public BatchConsumerInvoker(ConsumerConfig config, TopicMetadata topicMetadata, ConsumerPolicy consumerPolicy,
List<ConsumeMessage> messages, List<BatchMessageListener> listeners) {
this.config = config;
this.topicMetadata = topicMetadata;
this.consumerPolicy = consumerPolicy;
this.messages = messages;
this.listeners = listeners;
}
@Override
public List<ConsumeReply> invoke(ConsumeContext context) {
final List<ConsumeMessage> filteredMessage = context.getFilteredMessages();
if (CollectionUtils.isEmpty(filteredMessage)) {
return ConsumeMessageConverter.convertToReply(messages, RetryType.NONE);
}
long ackTimeout = (config.getAckTimeout() != ConsumerConfig.NONE_ACK_TIMEOUT ? config.getAckTimeout() : consumerPolicy.getAckTimeout());
RetryType retryType = RetryType.NONE;
try {
long startTime = SystemClock.now();
for (BatchMessageListener listener : listeners) {
listener.onMessage(filteredMessage);
}
long endTime = SystemClock.now();
if (endTime - startTime > ackTimeout) {
logger.warn("execute batchMessageListener timeout, topic: {}, messages: {}, listeners: {}", topicMetadata.getTopic(), messages, listeners);
retryType = RetryType.NONE;
}
} catch (Exception e) {
if (e instanceof IgnoreAckException) {
if (logger.isDebugEnabled()) {
logger.debug("execute batchMessageListener, ignore ack, topic: {}, messages: {}, listeners: {}", topicMetadata.getTopic(), messages, listeners);
}
if (config.isForceAck()) {
retryType = RetryType.OTHER;
} else {
retryType = RetryType.NONE;
}
} else {
logger.error("execute batchMessageListener exception, topic: {}, messages: {}, listeners: {}", topicMetadata.getTopic(), messages, listeners, e);
retryType = RetryType.EXCEPTION;
}
}
return ConsumeMessageConverter.convertToReply(messages, retryType);
}
@Override
public List<ConsumeReply> reject(ConsumeContext context) {
logger.info("reject execute batchListener, topic: {}, messages: {}", topicMetadata.getTopic(), messages);
return ConsumeMessageConverter.convertToReply(messages, RetryType.NONE);
}
} | 43.855769 | 164 | 0.700724 |
b176cd1b61507d680d9e1e29ce0f9de2ab676539 | 2,072 | package com.elastisys.scale.cloudpool.commons.basepool;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import com.elastisys.scale.cloudpool.api.types.Machine;
import com.elastisys.scale.cloudpool.api.types.MachineState;
import com.elastisys.scale.cloudpool.api.types.MembershipStatus;
import com.elastisys.scale.commons.util.time.UtcTime;
public class BasePoolTestUtils {
public static Machine machine(String id) {
return Machine.builder().id(id).machineState(MachineState.RUNNING).machineSize("m1.small")
.cloudProvider("AWS-EC2").region("us-east-1").launchTime(UtcTime.now()).build();
}
public static Machine machine(String id, MachineState machineState) {
return Machine.builder().id(id).machineState(machineState).machineSize("m1.small").cloudProvider("AWS-EC2")
.region("us-east-1").launchTime(UtcTime.now()).build();
}
public static Machine machine(String id, MachineState machineState, DateTime launchTime) {
return Machine.builder().id(id).machineState(machineState).cloudProvider("AWS-EC2").region("us-east-1")
.machineSize("m1.small").launchTime(launchTime).build();
}
public static Machine machine(String id, MachineState machineState, MembershipStatus membershipStatus,
DateTime launchTime) {
return Machine.builder().id(id).machineState(machineState).cloudProvider("AWS-EC2").region("us-east-1")
.machineSize("m1.small").membershipStatus(membershipStatus).launchTime(launchTime).build();
}
public static Machine machine(String id, String publicIp) {
return Machine.builder().id(id).machineState(MachineState.RUNNING).cloudProvider("AWS-EC2").region("us-east-1")
.machineSize("m1.small").publicIp(publicIp).build();
}
public static List<Machine> machines(Machine... machines) {
List<Machine> list = new ArrayList<>();
for (Machine machine : machines) {
list.add(machine);
}
return list;
}
}
| 42.285714 | 119 | 0.697394 |
ffcdab3d9caed51707cdff817f3d5cf0049ee995 | 739 | package com.mercadopago.android.px.internal.viewmodel;
import androidx.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.widget.TextView;
import com.mercadopago.android.px.internal.util.TextUtil;
import com.mercadopago.android.px.internal.view.PaymentMethodDescriptorView;
public class EmptyInstallmentsDescriptorModel extends PaymentMethodDescriptorView.Model {
public static PaymentMethodDescriptorView.Model create() {
return new EmptyInstallmentsDescriptorModel();
}
@Override
public void updateLeftSpannable(@NonNull final SpannableStringBuilder spannableStringBuilder,
@NonNull final TextView textView) {
spannableStringBuilder.append(TextUtil.SPACE);
}
}
| 35.190476 | 97 | 0.806495 |
1e24cd966868d9c36a3d0c7571810c6d9918eb2d | 629 | class Solution {
public int uniqueMorseRepresentations(String[] words) {
String[] morse = new String[]{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
Set<String> res = new HashSet<>();
for(String a:words){
String wrd = "";
for(int i = 0;i<a.length();i++){
int val = (int) a.charAt(i) - 97;
wrd = wrd + morse[val];
}
res.add(wrd);
}
return res.size();
}
} | 37 | 200 | 0.313196 |
d0cd5346b6d99a03a0997cd8ff6bff5a174708bf | 4,083 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.toolkit.lib.applicationinsights;
import com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager;
import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponent;
import com.azure.resourcemanager.applicationinsights.models.ApplicationType;
import com.microsoft.azure.toolkit.lib.common.bundle.AzureString;
import com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException;
import com.microsoft.azure.toolkit.lib.common.messager.AzureMessager;
import com.microsoft.azure.toolkit.lib.common.messager.IAzureMessager;
import com.microsoft.azure.toolkit.lib.common.model.AzResource;
import com.microsoft.azure.toolkit.lib.common.model.Region;
import com.microsoft.azure.toolkit.lib.common.operation.AzureOperation;
import lombok.Getter;
import lombok.Setter;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Objects;
import java.util.Optional;
public class ApplicationInsightDraft extends ApplicationInsight implements AzResource.Draft<ApplicationInsight, ApplicationInsightsComponent> {
private static final String REGION_IS_REQUIRED = "'region' is required to create application insight.";
private static final String START_CREATING_APPLICATION_INSIGHT = "Start creating Application Insight ({0})...";
private static final String APPLICATION_INSIGHTS_CREATED = "Application Insight ({0}) is successfully created. " +
"You can visit {1} to view your Application Insights component.";
@Setter
@Nullable
private Region region;
@Getter
@Nullable
private final ApplicationInsight origin;
protected ApplicationInsightDraft(@Nonnull String name, @Nonnull String resourceGroupName, @Nonnull ApplicationInsightsModule module) {
super(name, resourceGroupName, module);
this.origin = null;
}
protected ApplicationInsightDraft(@Nonnull ApplicationInsight origin) {
super(origin);
this.origin = origin;
}
@Override
public void reset() {
this.region = null;
}
@Nonnull
@Override
@AzureOperation(
name = "resource.create_resource.resource|type",
params = {"this.getName()", "this.getResourceTypeName()"},
type = AzureOperation.Type.SERVICE
)
public ApplicationInsightsComponent createResourceInAzure() {
if (Objects.isNull(region)) {
throw new AzureToolkitRuntimeException(REGION_IS_REQUIRED);
}
final ApplicationInsightsManager applicationInsightsManager = Objects.requireNonNull(this.getParent().getRemote());
final IAzureMessager messager = AzureMessager.getMessager();
messager.info(AzureString.format(START_CREATING_APPLICATION_INSIGHT, getName()));
final ApplicationInsightsComponent result = applicationInsightsManager.components().define(getName())
.withRegion(region.getName())
.withExistingResourceGroup(getResourceGroupName())
.withKind("web")
.withApplicationType(ApplicationType.WEB).create();
messager.success(AzureString.format(APPLICATION_INSIGHTS_CREATED, getName(), getPortalUrl()));
return result;
}
@Nonnull
@Override
@AzureOperation(
name = "resource.update_resource.resource|type",
params = {"this.getName()", "this.getResourceTypeName()"},
type = AzureOperation.Type.SERVICE
)
public ApplicationInsightsComponent updateResourceInAzure(@Nonnull ApplicationInsightsComponent origin) {
throw new AzureToolkitRuntimeException("not supported");
}
@Nullable
@Override
public Region getRegion() {
return Optional.ofNullable(this.region).orElseGet(super::getRegion);
}
@Override
public boolean isModified() {
return this.region != null && !Objects.equals(this.region, this.origin.getRegion());
}
}
| 40.83 | 143 | 0.742591 |
a3848ec669f7d2de1c9e5ee73f358627a493853e | 491 | package com.yub.library.config;
/**
* Naver Open API에 접근하기 위한 정보를 포함하는 클래스
* Naver Open API 관한 정보를 변경한후
* naverAPI 변경하여 프로젝트를 빌드하시오
*/
public class NaverAPI_sample {
public static final String CLIENT_ID="your naver api id";
public static final String CLIENT_SECRET="your naver api secret";
public static final String NAVER_BOOK_URL="https://openapi.naver.com/v1/search/book.json";
public static final String NAVER_BASE_URL="https://openapi.naver.com/v1/search/book";
}
| 35.071429 | 94 | 0.745418 |
39b7cf206334fc81f56799e2d3754b7f4281aa4b | 4,547 | package com.lotaris.jee.validation;
import com.lotaris.jee.validation.JsonPointer;
import com.lotaris.rox.annotations.RoxableTest;
import com.lotaris.rox.annotations.RoxableTestClass;
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
/**
* @see JsonPointer
* @author Simon Oulevay (simon.oulevay@lotaris.com)
*/
@RoxableTestClass(tags = {"api", "jsonPointer"})
public class JsonPointerUnitTest {
private JsonPointer pointer;
@Before
public void setUp() {
pointer = new JsonPointer();
}
@Test
@RoxableTest(key = "73aa88204ef7")
public void jsonPointerShouldPointToDocumentRootByDefault() {
assertEquals("", pointer.toString());
}
@Test
@RoxableTest(key = "2d1f65119a63")
public void jsonPointerShouldIndicateRootByDefault() {
assertTrue(pointer.isRoot());
}
@Test
@RoxableTest(key = "14a693fbdaae")
public void jsonPointerShouldAddPathFragments() {
assertEquals("/one", pointer.path("one").toString());
assertEquals("/one/two", pointer.path("two").toString());
}
@Test
@RoxableTest(key = "6b1e4d1d75a2")
public void jsonPointerShouldAddIndexAsPathFragment() {
assertEquals("/4", pointer.path(4).toString());
assertEquals("/4/2", pointer.path(2).toString());
}
@Test
@RoxableTest(key = "4432c83334e6")
public void jsonPointerShouldEscapePathFragments() {
assertEquals("/one~1two", pointer.path("one/two").toString());
assertEquals("/one~1two/~1~0~1/three", pointer.path("/~/").path("three").toString());
}
@Test
@RoxableTest(key = "ac1a87258e22")
public void jsonPointerShouldPopPathFragments() {
pointer.path("one").path("two").path("three");
assertEquals("/one/two", pointer.pop().toString());
assertEquals("/one", pointer.pop().toString());
assertEquals("", pointer.pop().toString());
}
@Test
@RoxableTest(key = "442e317865cc")
public void jsonPointerShouldNotThrowWhenPoppingWhileEmpty() {
pointer.pop();
assertEquals("", pointer.toString());
}
@Test
@RoxableTest(key = "b731b9f53248")
public void jsonPointerShouldAddMultiplePathFragments() {
int n = pointer.add("/one/two");
assertEquals(2, n);
assertEquals("/one/two", pointer.toString());
n = pointer.add("/three/four/five");
assertEquals(3, n);
assertEquals("/one/two/three/four/five", pointer.toString());
}
@Test
@RoxableTest(key = "ee872ba43e50")
public void jsonPointerShouldAddNoPathFragmentsWithoutThrowing() {
assertEquals(0, pointer.add(null));
assertEquals("", pointer.toString());
}
@Test
@RoxableTest(key = "26dfbf351452")
public void jsonPointerShouldPopMultiplePathFragments() {
pointer.path("one").path("two").path("three").pop(2);
assertEquals("/one", pointer.toString());
}
@Test
@RoxableTest(key = "1a542fe66dbd")
public void jsonPointerShouldPopNoPathFragmentsWithoutThrowing() {
assertEquals("/one/two", pointer.path("one").path("two").pop(0).toString());
}
@Test
@RoxableTest(key = "b0691b10066a")
public void jsonPointerShouldNotThrowWhenPoppingMorePathFragmentsThanItContains() {
pointer.path("one").pop(42);
assertEquals("", pointer.toString());
}
@Test
@RoxableTest(key = "7f78f047c0e1")
public void jsonPointerShouldGoBackToDocumentRoot() {
final JsonPointer testPointer = pointer.path("one").path("two").root();
assertTrue(testPointer.isRoot());
assertEquals("", testPointer.toString());
}
@Test
@RoxableTest(key = "9df3a8d570f0")
public void jsonPointerShouldReturnIndividualPathFragments() {
pointer.path("one").path(2).path("three");
assertEquals("one", pointer.fragmentAt(0));
assertEquals("2", pointer.fragmentAt(1));
assertEquals("three", pointer.fragmentAt(2));
}
@Test
@RoxableTest(key = "472560432a90")
public void jsonPointerShouldThrowIndexOutOfBoundsExceptionForUnknownFramentIndices() {
pointer.path("one").path("two");
try {
pointer.fragmentAt(-1);
fail("IndexOutOfBoundsException should have been thrown trying to access path fragment at index -1");
} catch (IndexOutOfBoundsException ioobe) {
// success
}
try {
pointer.fragmentAt(2);
fail("IndexOutOfBoundsException should have been thrown trying to access path fragment at index 2 in a pointer with two fragments");
} catch (IndexOutOfBoundsException ioobe) {
// success
}
}
@Test
@RoxableTest(key = "39a430f615c9")
public void jsonPointerShouldBeAbleToRebuildItself() {
final String pointerString = pointer.path("one").path(2).path("three").toString();
assertEquals(3, pointer.root().add(pointerString));
assertEquals("/one/2/three", pointer.toString());
}
}
| 28.597484 | 135 | 0.724434 |
cc5bf216f59d7f7d5914e467b684396ec9d6aa98 | 1,744 | package cmpe.dos.dao;
import org.hibernate.criterion.Criterion;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
public interface HibernateDao<T> {
public T getById(Serializable id);
public void delete(T po);
public void deleteById(Serializable id);
public List<T> findAll();
public List<T> findByCriterion(final Criterion... criterion);
public void save(T po);
public T saveReturn(T po);
public void create(T po);
public void update(T po);
public T doQueryUnique(final String hql, final Object... values);
public T doQueryFirst(final String hql, final Object... values);
public void executeHsql(final String hql, final Object... values);
public List<T> doQueryList(final String hql, final boolean cacheable, final Object... values);
public String getFromHql();
public long doQueryCount(final String hql, final Object... values);
public List<T> doQueryLimitList(final String hql, final boolean cacheable, final int dataNum,
final Object... values);
public List<T> findByProperty(String propertyName, Object value);
public List<String> doQueryListString(final String hql, final boolean cacheable, final Object... values);
public List<Date> doQueryListDate(final String hql, final boolean cacheable, final Object... values);
public List<Date> doQueryLimitListDate(final String hql, final boolean cacheable, final int dataNum,
final Object... values);
public List<T> findByCombineProperties(final Map<String, Object> pairs);
public List doQueryListUntype(final String hql, final boolean cacheable, final Object... values);
public void batchCreate(final List<T> poList);
} | 29.559322 | 109 | 0.729931 |
6f1e7bf6b75fcfe8a7aea0033f0a5652d4f57b9b | 855 | package edu.kit.ibds.mowidi.shared.connection.asn;
public enum Oid {
/** {iso(1) member-body(2) us(840) x9-57(10040) x9algorithm(4) dsa-with-sha1(3)} */
DSA_WITH_SHA1(1, 2, 840, 10040, 4, 3),
/** {joint-iso-itu-t(2) ds(5) attributeType(4) commonName(3)} */
CN(2, 5, 4, 3),
/** {joint-iso-itu-t(2) ds(5) attributeType(4) countryName(6)} */
CO(2, 5, 4, 6),
/** {joint-iso-itu-t(2) ds(5) attributeType(4) localityName(7)} */
LN(2, 5, 4, 7),
/** {joint-iso-itu-t(2) ds(5) attributeType(4) stateOrProvinceName(8)} */
ST(2, 5, 4, 8),
/** {joint-iso-itu-t(2) ds(5) attributeType(4) organizationName(10)} */
ON(2, 5, 4, 10),
/** {joint-iso-itu-t(2) ds(5) attributeType(4) organizationUnitName(11)} */
OU(2, 5, 4, 11);
public final int[] val;
private Oid(int... v) {
this.val = v;
}
}
| 34.2 | 87 | 0.568421 |
652c242cc6b692108f39a85573110503685d6480 | 1,594 | package oysd.com.trade_app.modules.mycenter.presenter;
import oysd.com.trade_app.App;
import oysd.com.trade_app.http.BaseObserver;
import oysd.com.trade_app.http.RetrofitHelper;
import oysd.com.trade_app.http.RxSchedulers;
import oysd.com.trade_app.http.bean.ResponsePaging;
import oysd.com.trade_app.modules.mycenter.contract.OTCOrderContract;
import oysd.com.trade_app.modules.mycenter.http.MycenterApi;
import oysd.com.trade_app.modules.otc.bean.OtcOrderBean;
public class OTCOrderPresenter implements OTCOrderContract.Presenter {
private OTCOrderContract.View view;
public OTCOrderPresenter(OTCOrderContract.View view) {
this.view = view;
}
@Override
public void attachView(OTCOrderContract.View view) {
}
@Override
public void detachView() {
}
@Override
public void getOnlineOrderList(int page, int limit, String transactionType, String status) {
RetrofitHelper.createApi(MycenterApi.class)
.getOnlineOrderList(page, limit, transactionType, status)
.compose(RxSchedulers.ioMain())
.subscribe(new BaseObserver<ResponsePaging<OtcOrderBean>>(App.getContext()) {
@Override
public void onSuccess(ResponsePaging<OtcOrderBean> response) {
view.getOnlineOrderListSuccess(response);
}
@Override
public void onFailure(int code, String msg) {
view.getOnlineOrderListFailed(code, msg);
}
});
}
}
| 33.914894 | 96 | 0.665621 |
4b421a0297d460ce8f69f8eb4b6f2058f63027f8 | 851 | package tk.valoeghese.pibiomes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.world.biome.Biome;
class CategoricalBiomeAccessor {
private final Map<Biome.Category, List<Biome>> internal = new HashMap<>();
public void add(Biome biome) {
this.getListFor(biome.getCategory()).add(biome);
}
private List<Biome> getListFor(Biome.Category category) {
return this.internal.computeIfAbsent(category, e -> new ArrayList<>());
}
// pluck a biome from the list
public Biome pluck(Biome.Category category, IntRandom rand, Biome defaultBiome) {
List<Biome> biomes = this.getListFor(category);
if (biomes.isEmpty()) {
return defaultBiome;
}
int index = rand.next(biomes.size());
Biome result = biomes.get(index);
biomes.remove(index);
return result;
}
}
| 24.314286 | 82 | 0.733255 |
bc527049ccda2d98ffceea8aff43271e0afdab2e | 6,048 | package com.lawyer.project.repositories;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.lawyer.project.UserCredentials;
import com.lawyer.project.models.Cases;
import com.lawyer.project.models.Document;
@Repository
public class CaseRepository{
JdbcTemplate jdbctemplate;
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
public void setNameParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate)
{
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate ;
}
public void addCase(String username,String case_type, Long court_id, Long judge_id, String description, Date judgement_date, Date previous_hearing_date, Date next_hearing_date, String status) {
String sql="INSERT INTO cases(username, case_type, court_id, judge_id, description, judgement_date, previous_hearing_date, next_hearing_date, status) values (:username, :case_type, :court_id, :judge_id, :description, :judgement_date, :previous_hearing_date, :next_hearing_date, :status)";
namedParameterJdbcTemplate.update(sql,getSqlParameterByModel( username, case_type, court_id, judge_id, description, judgement_date, previous_hearing_date, next_hearing_date, status));
}
private SqlParameterSource getSqlParameterByModel(String username,String case_type, Long court_id, Long judge_id, String description, Date judgement_date, Date previous_hearing_date, Date next_hearing_date, String status)
{
MapSqlParameterSource paramSource =new MapSqlParameterSource();
paramSource.addValue("id", 0);
paramSource.addValue("username", username);
paramSource.addValue("case_type", case_type);
paramSource.addValue("court_id", court_id);
paramSource.addValue("judge_id", judge_id);
paramSource.addValue("description", description);
paramSource.addValue("judgement_date", judgement_date);
paramSource.addValue("next_hearing_date", next_hearing_date);
paramSource.addValue("previous_hearing_date", previous_hearing_date);
paramSource.addValue("status", status);
return paramSource;
}
public List <Cases> getAllCases() {
final String sql = "select * from cases";
final List<Cases> rows = (List < Cases >) namedParameterJdbcTemplate.query(sql, getSqlParameterByModel(null,null,null,null,null,null,null,null,null), new CaseMapper());
return rows;
}
public List <Cases> getCasesByUsername(String username) {
final String sql = "select * from cases where username=:username";
final List<Cases> rows = (List < Cases >) namedParameterJdbcTemplate.query(sql, getSqlParameterByModel(username,null,null,null,null,null,null,null,null), new CaseMapper());
return rows;
}
public List <Cases> getCaseById(Long id) {
final String sql = "select * from cases where id=:id";
final List<Cases> rows = (List < Cases >) namedParameterJdbcTemplate.query(sql, getSqlParameterByModel(id, null, null,null,null,null,null,null,null,null), new CaseMapper());
return rows;
}
public void UpdateCaseBy(Cases cas) {
final String sql = "update cases set username=:username, case_type=:case_type, court_id=:court_id, judge_id=:judge_id, description=:description, judgement_date=:judgement_date, previous_hearing_date=:previous_hearing_date, next_hearing_date=:next_hearing_date, status=:status where id=:id";
int rows = namedParameterJdbcTemplate.update(sql, getSqlParameterByModel(cas.getId(), cas.getUsername(), cas.getCaseType(), cas.getCourt_id(), cas.getJudge_id(), cas.getDescription(), cas.getJudgementDate(), cas.getPreviousHearingDate(), cas.getNextHearingDate(), cas.getStatus()));
System.out.println(rows);
}
private SqlParameterSource getSqlParameterByModel(Long id, String username,String case_type, Long court_id, Long judge_id, String description, Date judgement_date, Date previous_hearing_date, Date next_hearing_date, String status)
{
MapSqlParameterSource paramSource =new MapSqlParameterSource();
paramSource.addValue("id", id);
paramSource.addValue("username", username);
paramSource.addValue("case_type", case_type);
paramSource.addValue("court_id", court_id);
paramSource.addValue("judge_id", judge_id);
paramSource.addValue("description", description);
paramSource.addValue("judgement_date", judgement_date);
paramSource.addValue("next_hearing_date", next_hearing_date);
paramSource.addValue("previous_hearing_date", previous_hearing_date);
paramSource.addValue("status", status);
return paramSource;
}
private static final class CaseMapper implements RowMapper<Cases>
{
public Cases mapRow(ResultSet rs,int rowNum) throws SQLException
{
Cases user=new Cases();
user.setId(rs.getLong("id"));
user.setUsername(rs.getString("username"));
user.setCaseType(rs.getString("case_type"));
user.setDescription(rs.getString("description"));
user.setStatus(rs.getString("status"));
user.setJudge_id(rs.getLong("judge_id"));
user.setCourt_id(rs.getLong("court_id"));
user.setJudgementDate(rs.getDate("judgement_date"));
user.setPreviousHearingDate(rs.getDate("previous_hearing_date"));
user.setNextHearingDate(rs.getDate("next_hearing_date"));
return user;
}
}
}
| 50.823529 | 304 | 0.738426 |
1fa0383641a22adda468fe5322370a5cfc36abab | 847 | package com.exaroton.api.ws.data;
public class StreamData<Datatype> {
/**
* stream name
*/
private final String stream;
/**
* message type
*/
private final String type;
/**
* data
*/
private Datatype data;
public StreamData(String stream, String type) {
this.stream = stream;
this.type = type;
}
public StreamData(String stream, String type, Datatype data) {
this.stream = stream;
this.type = type;
this.data = data;
}
/**
* @return message type
*/
public String getType() {
return type;
}
/**
* @return stream name
*/
public String getStream() {
return stream;
}
/**
* @return stream data
*/
public Datatype getData() {
return data;
}
}
| 16.288462 | 66 | 0.524203 |
23761dcc17b05785abfa51755099fac63996976f | 26,969 | package com.example.android.inventory;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.inventory.data.ItemContract;
import com.example.android.inventory.data.ItemContract.ItemEntry;
import com.squareup.picasso.Picasso;
/**
* Allows user to create a new item or edit an existing one.
*/
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
/**
* Identifier for the image request
*/
public static final int PICK_IMAGE_REQUEST = 10;
private static final String LOG_TAG = EditorActivity.class.getSimpleName();
/**
* Identifier for the item data loader
*/
private static final int EXISTING_ITEM_LOADER = 0;
/**
* Content URI for the existing item (null if it's a new item)
*/
private Uri mCurrentItemUri;
/**
* variable to store if something on the edit screen has changed
*/
private boolean mItemHasChanged = false;
/**
* Create an OnTouchListener to monitor inputs
*/
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mItemHasChanged = true;
return false;
}
};
/**
* EditText field to enter the item's name
*/
private EditText mNameEditText;
/**
* EditText field to enter the item's supplier
*/
private EditText mSupplierEditText;
/**
* EditText field to enter the item's price
*/
private EditText mPriceEditText;
/**
* EditText field to enter the item's quantity
*/
private EditText mQuantityEditText;
/**
* Order button to order more items from the supplier
*/
private Button mOrderButton;
/**
* EditText field to enter the item's quantity
*/
private TextView mQuantityPlusButton;
/**
* EditText field to enter the item's quantity
*/
private TextView mQuantityMinusButton;
/**
* ImageView field for the item image
*/
private ImageView mItemImageView;
/**
* EditText field to enter the item's quantity
*/
private TextView mEmptyImageTextView;
/**
* Name of the item
*/
private String mItemName;
/**
* EditText field to enter the item's quantity
*/
private String mCurrentImageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Examine the intent that was used to launch this activity,
// in order to figure out if we're creating a new item or editing an existing one.
Intent intent = getIntent();
mCurrentItemUri = intent.getData();
// If the intent DOES NOT contain a item content URI, then we know that we are
// creating a new item.
if (mCurrentItemUri == null) {
// This is a new item, so change the app bar to say "Add a Item"
setTitle(getString(R.string.editor_activity_title_new_item));
// Invalidate the options menu, so the "Delete" menu option can be hidden.
// (It doesn't make sense to delete a item that hasn't been created yet.)
invalidateOptionsMenu();
} else {
// Otherwise this is an existing item, so change app bar to say "Edit Item"
setTitle(getString(R.string.editor_activity_title_edit_item));
// Initialize a loader to read the item data from the database
// and display the current values in the editor
getLoaderManager().initLoader(EXISTING_ITEM_LOADER, null, this);
}
// Find all relevant views that we will need to read user input from
mNameEditText = (EditText) findViewById(R.id.edit_name);
mSupplierEditText = (EditText) findViewById(R.id.edit_supplier);
mPriceEditText = (EditText) findViewById(R.id.edit_price);
mQuantityEditText = (EditText) findViewById(R.id.edit_quantity);
mOrderButton = (Button) findViewById(R.id.order_button);
mQuantityMinusButton = (TextView) findViewById(R.id.minus_quantity);
mQuantityPlusButton = (TextView) findViewById(R.id.plus_quantity);
mItemImageView = (ImageView) findViewById(R.id.image_view);
mEmptyImageTextView = (TextView) findViewById(R.id.empty_image);
// Set listeners on the input fields
mNameEditText.setOnTouchListener(mTouchListener);
mSupplierEditText.setOnTouchListener(mTouchListener);
mPriceEditText.setOnTouchListener(mTouchListener);
mQuantityEditText.setOnTouchListener(mTouchListener);
mItemImageView.setOnTouchListener(mTouchListener);
// Set click listener for order button
mOrderButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mItemName = String.valueOf(mNameEditText.getText());
// Send email for an order
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
// Can be used if email of supplier is saved in the database
// intent.putExtra(Intent.EXTRA_EMAIL, new String[]{getString(R.string.email_address)});
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_subject) + " " + mItemName);
intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.email_text));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
// Set Click Listener for add/subract quantity button clicks
mQuantityMinusButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Read out current value and only decrease if not null or 0
String previousValueString = mQuantityEditText.getText().toString();
int previousValue;
if (!previousValueString.isEmpty() && !previousValueString.equals("0")) {
try {
previousValue = Integer.parseInt(previousValueString);
mQuantityEditText.setText(String.valueOf(previousValue - 1));
} catch (NumberFormatException e) {
Toast.makeText(EditorActivity.this, R.string.message_wrong_number_format, Toast.LENGTH_SHORT).show();
return;
}
}
}
});
mQuantityPlusButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
// Read out current value and if null, set to zero. In any case, add 1 to the value
String previousValueString = mQuantityEditText.getText().toString();
int previousValue;
if (previousValueString.isEmpty()) {
previousValue = 0;
} else {
try {
previousValue = Integer.parseInt(previousValueString);
} catch (NumberFormatException e) {
Toast.makeText(EditorActivity.this, R.string.message_wrong_number_format, Toast.LENGTH_SHORT).show();
return;
}
}
mQuantityEditText.setText(String.valueOf(previousValue + 1));
}
});
// Set Click Listener on ImageView so the user can select an image
mItemImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
// Call method which starts the image selection
openImageSelector();
}
});
}
/**
* This method is called when the back button is pressed.
*/
@Override
public void onBackPressed() {
// If the item hasn't changed, continue with handling back button press
if (!mItemHasChanged) {
super.onBackPressed();
return;
}
// Otherwise if there are unsaved changes, setup a dialog to warn the user.
// Create a click listener to handle the user confirming that changes should be discarded.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, close the current activity.
finish();
}
};
// Show dialog that there are unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
}
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
// Create an AlertDialog.Builder and set the message, and click listeners
// for the positive and negative buttons on the dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.unsaved_changes_dialog_msg);
builder.setPositiveButton(R.string.discard, discardButtonClickListener);
builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Keep editing" button, so dismiss the dialog
// and continue editing the item.
if (dialog != null) {
dialog.dismiss();
}
}
});
// Create and show the AlertDialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Get user input from editor and save item into database.
*/
private void saveItem() {
// Read from input fields
// Use trim to eliminate leading or trailing white space
String nameString = mNameEditText.getText().toString().trim();
String supplierString = mSupplierEditText.getText().toString().trim();
String priceString = mPriceEditText.getText().toString().trim();
String quantityString = mQuantityEditText.getText().toString().trim();
if (TextUtils.isEmpty(nameString) ||
TextUtils.isEmpty(supplierString) ||
TextUtils.isEmpty(priceString) ||
TextUtils.isEmpty(quantityString) ||
mCurrentImageUri == null
) {
// Since fields may not be empty we return early and show a toast message
Toast.makeText(this, R.string.message_empty_input, Toast.LENGTH_SHORT).show();
return;
}
// If the price is not provided by the user, don't try to parse the string into an
// integer value. Use 0 by default.
double price;
int quantity;
// Try if the input format is correct, if not show a toast message and return early
try {
price = Double.parseDouble(priceString);
} catch (NumberFormatException e) {
Toast.makeText(this, R.string.message_wrong_input_format, Toast.LENGTH_SHORT).show();
return;
}
try {
quantity = Integer.parseInt(quantityString);
} catch (NumberFormatException e) {
Toast.makeText(this, R.string.message_wrong_input_format, Toast.LENGTH_SHORT).show();
return;
}
// Create a ContentValues object where column names are the keys,
// and item attributes from the editor are the values.
ContentValues values = new ContentValues();
// Insert values into ContentValues object
values.put(ItemEntry.COLUMN_ITEM_NAME, nameString);
values.put(ItemEntry.COLUMN_ITEM_SUPPLIER, supplierString);
values.put(ItemEntry.COLUMN_ITEM_IMAGE_URI, mCurrentImageUri);
values.put(ItemEntry.COLUMN_ITEM_PRICE, price);
values.put(ItemEntry.COLUMN_ITEM_QUANTITY, quantity);
// Determine if this is a new or existing item by checking if mCurrentItemUri is null or not
if (mCurrentItemUri == null) {
// This is a NEW item, so insert a new item into the provider,
// returning the content URI for the new item.
Uri newUri = getContentResolver().insert(ItemEntry.CONTENT_URI, values);
// Show a toast message depending on whether or not the insertion was successful.
if (newUri == null) {
// If the new content URI is null, then there was an error with insertion.
Toast.makeText(this, getString(R.string.editor_insert_item_failed),
Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the insertion was successful and we can display a toast.
Toast.makeText(this, getString(R.string.editor_insert_item_successful),
Toast.LENGTH_SHORT).show();
}
} else {
// Otherwise this is an EXISTING item, so update the item with content URI: mCurrentItemUri
// and pass in the new ContentValues. Pass in null for the selection and selection args
// because mCurrentItemUri will already identify the correct row in the database that
// we want to modify.
int rowsAffected = getContentResolver().update(mCurrentItemUri, values, null, null);
// Show a toast message depending on whether or not the update was successful.
if (rowsAffected == 0) {
// If no rows were affected, then there was an error with the update.
Toast.makeText(this, getString(R.string.editor_update_item_failed),
Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the update was successful and we can display a toast.
Toast.makeText(this, getString(R.string.editor_update_item_successful),
Toast.LENGTH_SHORT).show();
}
}
// Exit activity
finish();
}
private void showDeleteConfirmationDialog() {
// Create an AlertDialog.Builder and set the message, and click listeners
// for the postivie and negative buttons on the dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.delete_dialog_msg);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Delete" button, so delete the item.
deleteItem();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Cancel" button, so dismiss the dialog
// and continue editing the item.
if (dialog != null) {
dialog.dismiss();
}
}
});
// Create and show the AlertDialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Perform the deletion of the item in the database.
*/
private void deleteItem() {
// Only perform the delete if this is an existing item.
if (mCurrentItemUri != null) {
// Call the ContentResolver to delete the item at the given content URI.
// Pass in null for the selection and selection args because the mCurrentItemUri
// content URI already identifies the item that we want.
int rowsDeleted = getContentResolver().delete(
mCurrentItemUri,
null,
null
);
// Show a toast message depending on whether or not the delete was successful.
if (rowsDeleted == 0) {
// If no rows were deleted, then there was an error with the update.
Toast.makeText(this, getString(R.string.editor_delete_item_failed),
Toast.LENGTH_SHORT).show();
} else {
// Otherwise, the delete was successful and we can display a toast.
Toast.makeText(this, getString(R.string.editor_delete_item_successful),
Toast.LENGTH_SHORT).show();
}
}
// Exit activity
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_editor.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_editor, menu);
return true;
}
/**
* This method is called after invalidateOptionsMenu(), so that the
* menu can be updated (some menu items can be hidden or made visible).
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// If this is a new item, hide the "Delete" menu item.
if (mCurrentItemUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Save" menu option
case R.id.action_save:
// Save item to database
saveItem();
return true;
// Respond to a click on the "Delete" menu option
case R.id.action_delete:
// Call delete dialog
showDeleteConfirmationDialog();
return true;
// Respond to a click on the "Up" arrow button in the app bar
case android.R.id.home:
// If the item hasn't changed, continue with navigating up to parent activity
// which is the {@link CatalogActivity}.
if (!mItemHasChanged) {
NavUtils.navigateUpFromSameTask(EditorActivity.this);
return true;
}
// Otherwise if there are unsaved changes, setup a dialog to warn the user.
// Create a click listener to handle the user confirming that
// changes should be discarded.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, navigate to parent activity.
NavUtils.navigateUpFromSameTask(EditorActivity.this);
}
};
// Show a dialog that notifies the user they have unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
// Code sample from https://github.com/crlsndrsjmnz/MyShareImageExample
// Check SDK Version and set according intent action
public void openImageSelector() {
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
// Method that is called after image picker has been called and a result is given
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code READ_REQUEST_CODE.
// If the request code seen here doesn't match, it's the response to some other intent,
// and the below code shouldn't run at all.
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter. Pull that uri using "resultData.getData()"
if (resultData != null) {
Uri resultUri = resultData.getData();
mCurrentImageUri = resultUri.toString();
Log.i(LOG_TAG, "Uri: " + mCurrentImageUri);
// Load the image into the ImageView
if (mCurrentImageUri != null) {
Picasso.with(this)
.load(mCurrentImageUri)
.fit().centerCrop()
.into(mItemImageView);
// Hide the text to select an image
mEmptyImageTextView.setVisibility(View.GONE);
}
}
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// Since the editor shows all item attributes, define a projection that contains
// all columns from the item table
String[] projection = {
ItemContract.ItemEntry._ID,
ItemEntry.COLUMN_ITEM_NAME,
ItemEntry.COLUMN_ITEM_SUPPLIER,
ItemEntry.COLUMN_ITEM_QUANTITY,
ItemEntry.COLUMN_ITEM_PRICE,
ItemEntry.COLUMN_ITEM_IMAGE_URI};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
mCurrentItemUri, // Query the content URI for the current item
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Hide the text to select an image
mEmptyImageTextView.setVisibility(View.GONE);
// Bail early if the cursor is null or there is less than 1 row in the cursor
if (cursor == null || cursor.getCount() < 1) {
return;
}
// Proceed with moving to the first row of the cursor and reading data from it
// (This should be the only row in the cursor)
if (cursor.moveToFirst()) {
// Find the columns of item attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_NAME);
int supplierColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_SUPPLIER);
int quantityColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_QUANTITY);
int priceColumnIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_PRICE);
int imageUriIndex = cursor.getColumnIndex(ItemEntry.COLUMN_ITEM_IMAGE_URI);
// Extract out the value from the Cursor for the given column index
String name = cursor.getString(nameColumnIndex);
String supplier = cursor.getString(supplierColumnIndex);
int quantity = cursor.getInt(quantityColumnIndex);
double price = cursor.getDouble(priceColumnIndex);
mCurrentImageUri = cursor.getString(imageUriIndex);
// Update the views on the screen with the values from the database
mNameEditText.setText(name);
mSupplierEditText.setText(supplier);
mQuantityEditText.setText(Integer.toString(quantity));
mPriceEditText.setText(Double.toString(price));
// TODO: Check not working yet
/*
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor fileCursor = this.getContentResolver().query(Uri.parse(mCurrentImageUri), filePathColumn, null, null, null);
fileCursor.moveToFirst();
int columnIndex = fileCursor.getColumnIndex(filePathColumn[0]);
String filePath = fileCursor.getString(columnIndex);
fileCursor.close();
// Check if there is an image and load it into the ImageView
File imageFile = new File(filePath);
if (imageFile.exists()) {
*/
// Load image into image view. If the uri points to an empty path, set a placeholder imgae
if (mCurrentImageUri != null) {
Picasso.with(this)
.load(mCurrentImageUri)
.fit().centerCrop()
.placeholder(R.drawable.ic_empty_shelter)
.error(R.drawable.ic_empty_shelter)
.into(mItemImageView);
} else {
mEmptyImageTextView.setText("Image not found. Please select a new image");
mEmptyImageTextView.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// If the loader is invalidated, clear out all the data from the input fields.
mNameEditText.setText("");
mSupplierEditText.setText("");
mPriceEditText.setText("");
mQuantityEditText.setText("");
mItemImageView.setImageDrawable(null);
}
} | 40.677225 | 127 | 0.611369 |
74a5cd7fa88717c43256c396215c3febc23a88f4 | 159 | package org.jzy3d.painters;
public enum StencilFunc {
GL_NEVER,
GL_LESS,
GL_GEQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_EQUAL,
GL_ALWAYS
}
| 12.230769 | 27 | 0.72327 |
e020a7287757856c93b4e8dc8205120e2da9ed28 | 1,693 | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.spring;
import com.opengamma.engine.depgraph.ComputationTargetCollapser;
import com.opengamma.engine.depgraph.DefaultComputationTargetCollapser;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.temptarget.TempTargetRepository;
import com.opengamma.financial.view.ViewEvaluationTarget;
import com.opengamma.financial.view.ViewEvaluationTargetCollapser;
import com.opengamma.util.SingletonFactoryBean;
/**
* Creates {@link ComputationTargetCollapser} appropriate for the {@link DemoStandardFunctionConfiguration} functions.
*/
public class DemoComputationTargetCollapserBean extends SingletonFactoryBean<ComputationTargetCollapser> {
private FunctionCompilationContext _compilationContext;
public void setCompilationContext(final FunctionCompilationContext context) {
_compilationContext = context;
}
public FunctionCompilationContext getCompilationContext() {
return _compilationContext;
}
@Override
protected ComputationTargetCollapser createObject() {
final DefaultComputationTargetCollapser collapser = new DefaultComputationTargetCollapser();
if (getCompilationContext() != null) {
final TempTargetRepository tempTargets = OpenGammaCompilationContext.getTempTargets(getCompilationContext());
if (tempTargets != null) {
collapser.addCollapser(ViewEvaluationTarget.TYPE, new ViewEvaluationTargetCollapser(tempTargets));
}
}
return collapser;
}
}
| 37.622222 | 118 | 0.812758 |
f9feb44b9e62748a52072c6d8e80c8cd1089a1cf | 4,497 | package com.zlm.hello.spring.cloud.alibaba.nacos.provider.service.impl;
import com.zlm.hello.spring.cloud.alibaba.nacos.provider.dao.UserMapper;
import com.zlm.hello.spring.cloud.alibaba.nacos.provider.model.Order;
import com.zlm.hello.spring.cloud.alibaba.nacos.provider.model.User;
import com.zlm.hello.spring.cloud.alibaba.nacos.provider.service.OrderService;
import com.zlm.hello.spring.cloud.alibaba.nacos.provider.service.UserService;
import com.zlm.hello.spring.cloud.alibaba.nacos.provider.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private OrderService orderService;
@Autowired
private TransactionTemplate transactionTemplate;
@Autowired
private RedisUtil redisUtil;
private static final String HIGH_CURRENT_QUEUE ="HIGH:CURRENT:QUEUE";
private static final LinkedBlockingQueue<User> queue = new LinkedBlockingQueue();
@Override
public User selectUserOne(Integer id) {
//并发安全的阻塞队列,积攒请求。(每隔N毫秒批量处理一次)
CompletableFuture<User> future = new CompletableFuture<>();
User user = new User();
user.setId(id);
user.setFuture(future);
queue.add(user);
return future.join();
}
@PostConstruct
public void init() {
// 定时任务线程池
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(() -> {
int size = queue.size();
if (size == 0) {
return;
}
List<User> users = IntStream.range(0, size).boxed().map(i -> {
return queue.poll();
}).collect(Collectors.toList());
users.forEach(item -> {
User user = userMapper.selectUserOne(item.getId());
item.getFuture().complete(user);
});
}, 0, 10, TimeUnit.MILLISECONDS);
}
@Override
public int updateUserById(User user) {
int i = userMapper.updateUserById(user);
return i;
}
@Override
@Transactional
public int insertUser(User user) {
return userMapper.insertUser(user);
}
@Override
public void testTransactional(User user) {
int result = (int) transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus transactionStatus) {
int i = insertUser(user);
if (i == 1) {
int i1 = updateUserById(user);
}
int z = 1 / 0;
return i;
}
});
}
@Override
public void testTransactional2(User user) {
updateUserById(user);
insertUser(user);
int i = 1 / 0;
}
@Override
public int insertForeach() {
List<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
String string = UUID.randomUUID().toString();
User user = new User();
user.setName(string.substring(0, 5) + i);
user.setPassword(string);
users.add(user);
}
int i = userMapper.insertForeach(users);
users.forEach(System.err::println);
return i;
}
@Override
@Transactional
public void testTransactional() {
User user = new User();
user.setName("Transactional");
user.setPassword(UUID.randomUUID().toString());
insertUser(user);
try {
Order order = new Order();
order.setId(UUID.randomUUID().toString());
order.setName("Transactional");
orderService.insertOrder(order);
}catch (Exception e){
log.error("orderService :",e);
}
}
}
| 31.893617 | 96 | 0.63976 |
04c9ea90388eb9595c86b054825b4eb59b33d3aa | 1,714 | /*
* 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.createnet.raptor.common.authentication;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.createnet.raptor.models.auth.Permission;
import org.createnet.raptor.models.auth.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
*
* @author l
*/
public final class RaptorUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1L;
protected List<Permission> authorities = null;
public RaptorUserDetails(User user) {
super(user);
}
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if (authorities == null) {
authorities = new ArrayList();
this.getRoles().forEach((g) -> authorities.addAll(g.getPermissions()));
authorities.stream().distinct().collect(Collectors.toList());
}
return authorities;
}
@Override
public String getUsername() {
return super.getUsername();
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return isEnabled();
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return isEnabled();
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return isEnabled();
}
}
| 25.58209 | 83 | 0.690198 |
ee6a202f03cd4d13bb7fc3946ea9007466969d9d | 2,418 | package com.infilos.api;
import com.infilos.utils.Require;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Aka scala's Result<T>.
*/
public interface Result<T> {
boolean isSucced();
void ifSucced(final Consumer<T> consumer);
boolean isFailed();
void ifFailed(final Consumer<Throwable> consumer);
Result<T> switchIfFailed(final Function<Throwable, Result<T>> fallbackMethod);
<U> Result<U> map(final Function<? super T, ? extends U> mapper);
<U> Result<U> flatMap(final Function<? super T, Result<U>> mapper);
Result<T> mapFalied(final Function<Throwable, ? extends Throwable> mapper);
T get();
T getOrElse(final Supplier<T> supplier);
Throwable getFailure();
// below are factories
static <T> Result<T> succed(final T value) {
Require.checkNotNull(value, "The value of a Result cannot be null");
return new Succed<>(value);
}
static <T, E extends Throwable> Result<T> failed(final E throwable) {
Require.checkNotNull(throwable, "The error of a Result cannot be null");
return new Failed<>(throwable);
}
static <T> Result<T> of(final Supplier<T> supplier) {
Require.checkNotNull(supplier, "The value supplier cannot be null");
try {
return succed(supplier.get());
} catch (final Exception error) {
return failed(error);
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
static <T> Result<T> of(final Optional<T> optional) {
Require.checkNotNull(optional, "The optional value cannot be null");
return optional
.map(Result::succed)
.orElseGet(() -> failed(new NoSuchElementException("No value present when unwrapping the optional")));
}
static <T> Result<T> ofNullable(final T value) {
return ofNullable(value, () -> new NullPointerException("The result was initialized with a null value"));
}
static <T> Result<T> ofNullable(final T value, final Supplier<? extends Throwable> errorSupplier) {
Require.checkNotNull(errorSupplier, "The error supplier cannot be null");
return Objects.nonNull(value)
? succed(value)
: failed(errorSupplier.get());
}
}
| 29.487805 | 114 | 0.664599 |
60f7cdd261a145f9fed5af6f150d3c8fb375c38a | 5,170 | /**
* Copyright 2016 Sven Loesekann
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 ch.xxx.trader.controller;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import ch.xxx.trader.data.PrepareData;
import ch.xxx.trader.dtos.QuoteBf;
import ch.xxx.trader.dtos.QuotePdf;
import ch.xxx.trader.reports.ReportGenerator;
import ch.xxx.trader.utils.MongoUtils;
import ch.xxx.trader.utils.WebUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/bitfinex")
public class BitfinexController {
private static final String URLBF = "https://api.bitfinex.com";
@Autowired
private ReactiveMongoOperations operations;
@Autowired
private ReportGenerator reportGenerator;
@GetMapping("/{currpair}/orderbook")
public Mono<String> getOrderbook(@PathVariable String currpair, HttpServletRequest request) {
WebClient wc = WebUtils.buildWebClient(URLBF);
return wc.get().uri("/v1/book/" + currpair + "/").accept(MediaType.APPLICATION_JSON).exchange()
.flatMap(res -> res.bodyToMono(String.class));
}
@GetMapping("/{pair}/current")
public Mono<QuoteBf> currentQuote(@PathVariable String pair) {
Query query = MongoUtils.buildCurrentQuery(Optional.of(pair));
return this.operations.findOne(query, QuoteBf.class);
}
@GetMapping("/{pair}/{timeFrame}")
public Flux<QuoteBf> tfQuotes(@PathVariable String timeFrame, @PathVariable String pair) {
if (MongoUtils.TimeFrame.TODAY.getValue().equals(timeFrame)) {
Query query = MongoUtils.buildTodayQuery(Optional.of(pair));
return this.operations.find(query, QuoteBf.class).filter(q -> filterEvenMinutes(q));
} else if (MongoUtils.TimeFrame.SEVENDAYS.getValue().equals(timeFrame)) {
Query query = MongoUtils.build7DayQuery(Optional.of(pair));
return this.operations.find(query, QuoteBf.class, PrepareData.BF_HOUR_COL);
} else if (MongoUtils.TimeFrame.THIRTYDAYS.getValue().equals(timeFrame)) {
Query query = MongoUtils.build30DayQuery(Optional.of(pair));
return this.operations.find(query, QuoteBf.class, PrepareData.BF_DAY_COL);
} else if (MongoUtils.TimeFrame.NINTYDAYS.getValue().equals(timeFrame)) {
Query query = MongoUtils.build90DayQuery(Optional.of(pair));
return this.operations.find(query, QuoteBf.class, PrepareData.BF_DAY_COL);
}
return Flux.empty();
}
@GetMapping(path="/{pair}/{timeFrame}/pdf", produces=MediaType.APPLICATION_PDF_VALUE)
public Mono<byte[]> pdfReport(@PathVariable String timeFrame, @PathVariable String pair) {
if (MongoUtils.TimeFrame.TODAY.getValue().equals(timeFrame)) {
Query query = MongoUtils.buildTodayQuery(Optional.of(pair));
return this.reportGenerator.generateReport(this.operations.find(query, QuoteBf.class).filter(this::filter10Minutes).map(this::convert));
} else if (MongoUtils.TimeFrame.SEVENDAYS.getValue().equals(timeFrame)) {
Query query = MongoUtils.build7DayQuery(Optional.of(pair));
return this.reportGenerator.generateReport(this.operations.find(query, QuoteBf.class, PrepareData.BF_HOUR_COL).map(this::convert));
} else if (MongoUtils.TimeFrame.THIRTYDAYS.getValue().equals(timeFrame)) {
Query query = MongoUtils.build30DayQuery(Optional.of(pair));
return this.reportGenerator.generateReport(this.operations.find(query, QuoteBf.class, PrepareData.BF_DAY_COL).map(this::convert));
} else if (MongoUtils.TimeFrame.NINTYDAYS.getValue().equals(timeFrame)) {
Query query = MongoUtils.build90DayQuery(Optional.of(pair));
return this.reportGenerator.generateReport(this.operations.find(query, QuoteBf.class, PrepareData.BF_DAY_COL).map(this::convert));
}
return Mono.empty();
}
private QuotePdf convert(QuoteBf quote) {
QuotePdf quotePdf = new QuotePdf(quote.getLast_price(), quote.getPair(), quote.getVolume(), quote.getCreatedAt(), quote.getBid(), quote.getAsk());
return quotePdf;
}
private boolean filterEvenMinutes(QuoteBf quote) {
return MongoUtils.filterEvenMinutes(quote.getCreatedAt());
}
private boolean filter10Minutes(QuoteBf quote) {
return MongoUtils.filter10Minutes(quote.getCreatedAt());
}
}
| 44.188034 | 150 | 0.775629 |
cc5ffdd330bc1a2e2f808758e71a99e645f7b9cc | 4,360 | /*
* Copyright 2014 toxbee.se
*
* 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 se.toxbee.sleepfighter.utils.prefs;
import java.io.Serializable;
import java.util.Map;
/**
* {@link ForwardingPreferenceNode} is a guava-style forwarding {@link PreferenceNode}.
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Dec 14, 2013
*/
public abstract class ForwardingPreferenceNode implements PreferenceNode {
/**
* Returns the {@link PreferenceNode} delegated to.
*
* @return the node.
*/
protected abstract PreferenceNode delegate();
/**
* Returns the processed key, this is an opportunity to add namespace, etc.
*
* @param key the key.
* @return the processed key.
*/
protected String key( String key ) {
return key;
}
@Override
public PreferenceNode parent() {
return delegate().parent();
}
@Override
public Map<String, ?> getAll() {
return delegate().getAll();
}
@Override
public PreferenceNode clear() {
delegate().clear();
return this;
}
@Override
public PreferenceNode sub( String ns ) {
return delegate().sub( ns );
}
@Override
public boolean contains( String key ) {
return delegate().contains( key( key ) );
}
@Override
public PreferenceNode remove( String key ) {
delegate().remove( key( key ) );
return this;
}
@Override
public boolean applyForResult( PreferenceEditCallback cb ) {
return delegate().applyForResult( cb );
}
@Override
public PreferenceNode apply( PreferenceEditCallback cb ) {
delegate().apply( cb );
return this;
}
@Override
public boolean isApplying() {
return delegate().isApplying();
}
@Override
public boolean getBoolean( String key, boolean def ) {
return delegate().getBoolean( key( key ), def );
}
@Override
public char getChar( String key, char def ) {
return delegate().getChar( key( key ), def );
}
@Override
public short getShort( String key, short def ) {
return delegate().getShort( key( key ), def );
}
@Override
public int getInt( String key, int def ) {
return delegate().getInt( key( key ), def );
}
@Override
public long getLong( String key, long def ) {
return delegate().getLong( key( key ), def );
}
@Override
public float getFloat( String key, float def ) {
return delegate().getFloat( key( key ), def );
}
@Override
public double getDouble( String key, double def ) {
return delegate().getDouble( key( key ), def );
}
@Override
public String getString( String key, String def ) {
return delegate().getString( key( key ), def );
}
@Override
public <U extends Serializable> U get( String key, U def ) {
return delegate().get( key( key ), def );
}
@Override
public PreferenceNode setBoolean( String key, boolean val ) {
delegate().setBoolean( key( key ), val );
return this;
}
@Override
public PreferenceNode setChar( String key, char val ) {
delegate().setChar( key( key ), val );
return this;
}
@Override
public PreferenceNode setShort( String key, short val ) {
delegate().setShort( key( key ), val );
return this;
}
@Override
public PreferenceNode setInt( String key, int val ) {
delegate().setInt( key( key ), val );
return this;
}
@Override
public PreferenceNode setLong( String key, long val ) {
delegate().setLong( key( key ), val );
return this;
}
@Override
public PreferenceNode setFloat( String key, float val ) {
delegate().setFloat( key( key ), val );
return this;
}
@Override
public PreferenceNode setDouble( String key, double val ) {
delegate().setDouble( key( key ), val );
return this;
}
@Override
public PreferenceNode setString( String key, String val ) {
delegate().setString( key( key ), val );
return this;
}
@Override
public <U extends Serializable> U set( String key, U val ) {
return delegate().set( key( key ), val );
}
}
| 22.474227 | 87 | 0.683257 |
14b35961764b4a16a340f3e1f561efd178f2a840 | 2,471 | package com.adenki.smpp.util;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNotSame;
import static org.testng.Assert.assertSame;
import org.testng.annotations.Test;
@Test
public class APIConfigFactoryTest {
public void testPropertiesAPIConfigIsTheDefault() {
APIConfigFactory.reset();
APIConfig config = APIConfigFactory.getConfig();
assertNotNull(config);
assertEquals(config.getClass(), PropertiesAPIConfig.class);
}
public void testGetConfigReturnsACachedClass() {
APIConfigFactory.reset();
APIConfig config1 = APIConfigFactory.getConfig();
APIConfig config2 = APIConfigFactory.getConfig();
assertNotNull(config1);
assertNotNull(config2);
assertSame(config1, config2);
}
public void testNewInstanceIsInstantiatedWhenCachingIsDisabled() {
try {
System.setProperty(APIConfigFactory.CACHE_CONFIG_PROP, "false");
APIConfigFactory.reset();
APIConfig config1 = APIConfigFactory.getConfig();
APIConfig config2 = APIConfigFactory.getConfig();
assertNotNull(config1);
assertNotNull(config2);
assertNotSame(config1, config2);
} finally {
System.clearProperty(APIConfigFactory.CACHE_CONFIG_PROP);
}
}
public void testLoadConfigLoadsSpecifiedConfigClass() throws Exception {
try {
System.setProperty(
APIConfigFactory.CONFIG_CLASS_PROP,
"com.adenki.smpp.util.NullAPIConfig");
APIConfigFactory.reset();
APIConfig config = APIConfigFactory.loadConfig();
assertNotNull(config);
assertEquals(config.getClass(), NullAPIConfig.class);
} finally {
System.clearProperty(APIConfigFactory.CONFIG_CLASS_PROP);
}
}
@Test(expectedExceptions = {InvalidConfigurationException.class})
public void testLoadConfigThrowsExceptionWhenConfigClassDoesNotExist() {
try {
System.setProperty(
APIConfigFactory.CONFIG_CLASS_PROP,
"com.adenki.smpp.util.NonExistentAPIConfig");
APIConfigFactory.reset();
APIConfigFactory.loadConfig();
} finally {
System.clearProperty(APIConfigFactory.CONFIG_CLASS_PROP);
}
}
}
| 35.3 | 76 | 0.657628 |
1c3ffe28814ca1910ccf4e6d53c27a00c9d82034 | 617 | package com.shoppingmall.repository;
import com.shoppingmall.domain.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("select distinct o from Order o" +
" join fetch o.user u" +
" where u.identifier = :identifier")
List<Order> findAllByIdentifier(@Param("identifier") String identifier);
}
| 32.473684 | 76 | 0.766613 |
fa734956411360274d10201cd7c21a21150cbc44 | 636 |
package com.secs.framework.modules.sys.dao;
import com.secs.framework.modules.sys.entity.SysConfigEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* 系统配置信息
*
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2016年12月4日 下午6:46:16
*/
@Mapper
public interface SysConfigDao extends BaseMapper<SysConfigEntity> {
/**
* 根据key,查询value
*/
SysConfigEntity queryByKey(String paramKey);
/**
* 根据key,更新value
*/
int updateValueByKey(@Param("paramKey") String paramKey, @Param("paramValue") String paramValue);
}
| 19.875 | 98 | 0.75 |
cedd8d57276dd153591d8694a443c106ef3cb553 | 3,562 | package org.apache.maven.it;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.it.util.ResourceExtractor;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Benjamin Bentmann
* @version $Id$
*/
public class MavenIT0144LifecycleExecutionOrderTest
extends AbstractMavenIntegrationTestCase
{
public MavenIT0144LifecycleExecutionOrderTest()
{
super( ALL_MAVEN_VERSIONS );
}
/**
* Test that the lifecycle phases execute in proper order.
*/
public void testit0144()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/it0144" );
Verifier verifier = newVerifier( testDir.getAbsolutePath() );
verifier.deleteDirectory( "target" );
verifier.setAutoclean( false );
verifier.executeGoals( Arrays.asList( new String[]{ "post-clean", "deploy", "site-deploy" } ) );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
List<String> expected = new ArrayList<>();
expected.add( "pre-clean" );
expected.add( "clean" );
expected.add( "post-clean" );
expected.add( "validate" );
expected.add( "initialize" );
expected.add( "generate-sources" );
expected.add( "process-sources" );
expected.add( "generate-resources" );
expected.add( "process-resources" );
expected.add( "compile" );
expected.add( "process-classes" );
expected.add( "generate-test-sources" );
expected.add( "process-test-sources" );
expected.add( "generate-test-resources" );
expected.add( "process-test-resources" );
expected.add( "test-compile" );
if ( matchesVersionRange( "(2.0.4,)" ) )
{
// MNG-1508
expected.add( "process-test-classes" );
}
expected.add( "test" );
if ( matchesVersionRange( "(2.1.0-M1,)" ) )
{
// MNG-2097
expected.add( "prepare-package" );
}
expected.add( "package" );
if ( matchesVersionRange( "(2.0.1,)" ) )
{
expected.add( "pre-integration-test" );
}
expected.add( "integration-test" );
if ( matchesVersionRange( "(2.0.1,)" ) )
{
expected.add( "post-integration-test" );
}
expected.add( "verify" );
expected.add( "install" );
expected.add( "deploy" );
expected.add( "pre-site" );
expected.add( "site" );
expected.add( "post-site" );
expected.add( "site-deploy" );
List<String> phases = verifier.loadLines( "target/phases.log", "UTF-8" );
assertEquals( expected, phases );
}
}
| 32.09009 | 104 | 0.617911 |
aae9f814d1be97d2ed35e703814abd913dd601c4 | 3,992 | /*
* Copyright 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pgpainless.key.collection;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.pgpainless.PGPainless;
public class KeyRingCollection {
private static final Logger LOGGER = Logger.getLogger(KeyRingCollection.class.getName());
private PGPPublicKeyRingCollection publicKeys;
private PGPSecretKeyRingCollection secretKeys;
public KeyRingCollection(@Nonnull PGPPublicKeyRingCollection publicKeyRings, @Nonnull PGPSecretKeyRingCollection secretKeyRings) {
this.publicKeys = publicKeyRings;
this.secretKeys = secretKeyRings;
}
public KeyRingCollection(File pubRingFile, File secRingFile) throws IOException, PGPException {
if (pubRingFile == null && secRingFile == null) {
throw new NullPointerException("pubRingFile and secRingFile cannot BOTH be null.");
}
if (pubRingFile != null) {
InputStream pubRingIn = new FileInputStream(pubRingFile);
this.publicKeys = PGPainless.readKeyRing().publicKeyRingCollection(pubRingIn);
pubRingIn.close();
}
if (secRingFile != null) {
InputStream secRingIn = new FileInputStream(secRingFile);
this.secretKeys = PGPainless.readKeyRing().secretKeyRingCollection(secRingIn);
secRingIn.close();
}
}
public KeyRingCollection(@Nonnull PGPPublicKeyRingCollection publicKeyRings) {
this.publicKeys = publicKeyRings;
}
public KeyRingCollection(@Nonnull PGPSecretKeyRingCollection secretKeyRings) {
this.secretKeys = secretKeyRings;
}
public void importPublicKeys(@Nonnull PGPPublicKeyRingCollection publicKeyRings) {
if (this.publicKeys == null) {
this.publicKeys = publicKeyRings;
return;
}
for (PGPPublicKeyRing keyRing : publicKeyRings) {
try {
this.publicKeys = PGPPublicKeyRingCollection.addPublicKeyRing(this.publicKeys, keyRing);
} catch (IllegalArgumentException e) {
// TODO: merge key rings.
LOGGER.log(Level.FINE, "Keyring " + Long.toHexString(keyRing.getPublicKey().getKeyID()) +
" is already included in the collection. Skip!");
}
}
}
public void importSecretKeys(@Nonnull PGPSecretKeyRingCollection secretKeyRings) {
if (this.secretKeys == null) {
this.secretKeys = secretKeyRings;
return;
}
for (PGPSecretKeyRing keyRing : secretKeyRings) {
try {
this.secretKeys = PGPSecretKeyRingCollection.addSecretKeyRing(this.secretKeys, keyRing);
} catch (IllegalArgumentException e) {
// TODO: merge key rings.
LOGGER.log(Level.FINE, "Keyring " + Long.toHexString(keyRing.getPublicKey().getKeyID()) +
" is already included in the collection. Skip!");
}
}
}
}
| 37.660377 | 134 | 0.68512 |
ceae3a5d2c85fd0ba787513102ea86bc169b4e98 | 3,625 | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.hibernate3;
import java.util.Properties;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
/**
* Bean that encapsulates a Hibernate type definition.
*
* <p>Typically defined as inner bean within a LocalSessionFactoryBean
* definition, as list element for the "typeDefinitions" bean property.
* For example:
*
* <pre class="code">
* <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
* ...
* <property name="typeDefinitions">
* <list>
* <bean class="org.springframework.orm.hibernate3.TypeDefinitionBean">
* <property name="typeName" value="myType"/>
* <property name="typeClass" value="mypackage.MyTypeClass"/>
* </bean>
* </list>
* </property>
* ...
* </bean></pre>
*
* Alternatively, specify a bean id (or name) attribute for the inner bean,
* instead of the "typeName" property.
*
* @author Juergen Hoeller
* @since 1.2
* @see LocalSessionFactoryBean#setTypeDefinitions(TypeDefinitionBean[])
* @deprecated as of Spring 4.3, in favor of Hibernate 4.x/5.x
*/
@Deprecated
public class TypeDefinitionBean implements BeanNameAware, InitializingBean {
private String typeName;
private String typeClass;
private Properties parameters = new Properties();
/**
* Set the name of the type.
* @see org.hibernate.cfg.Mappings#addTypeDef(String, String, java.util.Properties)
*/
public void setTypeName(String typeName) {
this.typeName = typeName;
}
/**
* Return the name of the type.
*/
public String getTypeName() {
return typeName;
}
/**
* Set the type implementation class.
* @see org.hibernate.cfg.Mappings#addTypeDef(String, String, java.util.Properties)
*/
public void setTypeClass(String typeClass) {
this.typeClass = typeClass;
}
/**
* Return the type implementation class.
*/
public String getTypeClass() {
return typeClass;
}
/**
* Specify default parameters for the type.
* This only applies to parameterized types.
* @see org.hibernate.cfg.Mappings#addTypeDef(String, String, java.util.Properties)
* @see org.hibernate.usertype.ParameterizedType
*/
public void setParameters(Properties parameters) {
this.parameters = parameters;
}
/**
* Return the default parameters for the type.
*/
public Properties getParameters() {
return parameters;
}
/**
* If no explicit type name has been specified, the bean name of
* the TypeDefinitionBean will be used.
* @see #setTypeName
*/
@Override
public void setBeanName(String name) {
if (this.typeName == null) {
this.typeName = name;
}
}
@Override
public void afterPropertiesSet() {
if (this.typeName == null) {
throw new IllegalArgumentException("typeName is required");
}
if (this.typeClass == null) {
throw new IllegalArgumentException("typeClass is required");
}
}
}
| 27.052239 | 102 | 0.710897 |
f802e4b6a0584099923dd43bac81fd97519fa28a | 18,676 | /* Copyright IBM Corp. 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.watson.app.common.services.nlclassifier.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ibm.watson.app.common.services.nlclassifier.NLClassifier.Status;
import com.ibm.watson.app.common.services.nlclassifier.model.NLClassiferClassifyResponse;
import com.ibm.watson.app.common.services.nlclassifier.model.NLClassiferClassifyResponse.NLClassifiedClass;
@RunWith(MockitoJUnitRunner.class)
public class NLClassifierTest extends BaseNLClassifierTest {
@SuppressWarnings("unused")
private final NLClassifierTest GIVEN = this, WHEN = this, THEN = this, WITH = this, AND = this;
private NLClassifierImpl classifier;
private NLClassiferClassifyResponse expectedClassifyResponse, actualClassifyResponse;
private Status classifierStatus;
private boolean classifierDeleted;
private String classifierId;
@Test
public void test_classify_one_classified_class() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
GIVEN.a_new_classify_response();
AND.a_class_is_added_to_the_classify_response("class1", 0.175);
AND.response_handler_returns(expectedClassifyResponse);
WHEN.classifier_classify_is_invoked("Some text to classify");
THEN.verify_classified_items_is_not_null();
AND.verify_classified_items_size_is(1);
AND.verify_classified_items_item_is(0, "class1", 0.175);
AND.verify_http_client_execute_invoked("post", "application/json; charset=UTF-8", "/testId12345/classify");
AND.verify_entity_content_is_classify_data();
}
@Test
public void test_classify_multiple_classified_classes() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
GIVEN.a_new_classify_response();
AND.a_class_is_added_to_the_classify_response("class1", 0.975);
AND.a_class_is_added_to_the_classify_response("class2", 0.875);
AND.a_class_is_added_to_the_classify_response("class3", 0.775);
AND.a_class_is_added_to_the_classify_response("class4", 0.675);
AND.a_class_is_added_to_the_classify_response("class5", 0.575);
AND.response_handler_returns(expectedClassifyResponse);
WHEN.classifier_classify_is_invoked("Some text to classify");
THEN.verify_classified_items_is_not_null();
AND.verify_classified_items_size_is(5);
AND.verify_classified_items_item_is(0, "class1", 0.975);
AND.verify_classified_items_item_is(1, "class2", 0.875);
AND.verify_classified_items_item_is(2, "class3", 0.775);
AND.verify_classified_items_item_is(3, "class4", 0.675);
AND.verify_classified_items_item_is(4, "class5", 0.575);
AND.verify_http_client_execute_invoked("post", "application/json; charset=UTF-8", "/testId12345/classify");
AND.verify_entity_content_is_classify_data();
}
@Test
public void test_classify_gets_bad_response() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
GIVEN.a_new_classify_response();
AND.a_class_is_added_to_the_classify_response("class1", 0.975);
AND.response_handler_returns(expectedClassifyResponse);
AND.http_response_returns(400);
WHEN.classifier_classify_is_invoked("Some text to classify");
THEN.verify_classified_items_is_not_null();
AND.verify_classified_items_size_is(0);
AND.verify_http_client_execute_invoked("post", "application/json; charset=UTF-8", "/testId12345/classify");
AND.verify_entity_content_is_classify_data();
}
@Test
public void test_classify_gets_io_expection() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
GIVEN.a_new_classify_response();
AND.a_class_is_added_to_the_classify_response("class1", 0.975);
AND.response_handler_returns(expectedClassifyResponse);
AND.http_entity_input_stream_throws(new IOException("Cannot read"));
WHEN.classifier_classify_is_invoked("Some text to classify");
THEN.verify_classified_items_is_not_null();
AND.verify_classified_items_size_is(0);
AND.verify_http_client_execute_invoked("post", "application/json; charset=UTF-8", "/testId12345/classify");
AND.verify_entity_content_is_classify_data();
}
@Test
public void test_classify_gets_npe() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
GIVEN.a_new_classify_response();
AND.a_class_is_added_to_the_classify_response("class1", 0.975);
AND.response_handler_returns(expectedClassifyResponse);
AND.http_entity_input_stream_throws(new NullPointerException("Cannot read"));
WHEN.classifier_classify_is_invoked("Some text to classify");
THEN.verify_classified_items_is_not_null();
AND.verify_classified_items_size_is(0);
AND.verify_http_client_execute_invoked("post", "application/json; charset=UTF-8", "/testId12345/classify");
AND.verify_entity_content_is_classify_data();
}
@Test
public void test_classify_gets_non_json_response() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
GIVEN.a_new_classify_response();
AND.a_class_is_added_to_the_classify_response("class1", 0.975);
AND.response_handler_returns("this text is not json");
WHEN.classifier_classify_is_invoked("Some text to classify");
THEN.verify_classified_items_is_not_null();
AND.verify_classified_items_size_is(0);
AND.verify_http_client_execute_invoked("post", "application/json; charset=UTF-8", "/testId12345/classify");
AND.verify_entity_content_is_classify_data();
}
@Test
public void test_classify_gets_valid_json_response_but_invalid_schema() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
GIVEN.a_new_classify_response();
AND.a_class_is_added_to_the_classify_response("class1", 0.975);
AND.http_entity_content_is("{\"thisIsThe\":\"wrong format\",\"for\":\"the data\"}");
AND.http_response_returns(200);
WHEN.classifier_classify_is_invoked("Some text to classify");
THEN.verify_classified_items_is_not_null();
AND.verify_classified_items_size_is(0);
AND.verify_http_client_execute_invoked("post", "application/json; charset=UTF-8", "/testId12345/classify");
AND.verify_entity_content_is_classify_data();
}
@Test
public void test_get_status_training() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "Training", "the classifier is currently training");
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.TRAINING);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_non_existent() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "Non Existent", "the classifier does not exist");
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.NON_EXISTENT);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_failed() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "Failed", "the classifier failed");
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.FAILED);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_available() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "Available", "the classifier is available");
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.AVAILABLE);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_unavailable() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "Unavailable", "the classifier is unavailable");
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.UNAVAILABLE);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_unknown() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "¯\\(°_o)/¯", "i dunno what the classifier is up to");
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.UNKNOWN);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_valid_but_gets_500() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "training", "the classifier is training");
AND.http_response_returns(500);
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.UNKNOWN);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_valid_but_response_throws_npe() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "training", "the classifier is training");
AND.http_entity_input_stream_throws(new NullPointerException("Cannot read"));
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.UNKNOWN);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_valid_but_response_throws_io_exception() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.classifier_status_is("testId12345", "some_url", "training", "the classifier is training");
AND.http_entity_input_stream_throws(new IOException("Cannot read"));
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.UNKNOWN);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_response_is_not_json() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("this is not json");
AND.http_response_returns(200);
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.UNKNOWN);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_get_status_response_has_invalid_schema() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("{\"thisIsThe\":\"wrong format\",\"for\":\"the data\"}");
AND.http_response_returns(200);
WHEN.classifier_get_status_is_invoked();
THEN.verify_classifier_status_not_null();
AND.verify_classifier_state_is(Status.UNKNOWN);
AND.verify_http_client_execute_invoked("get", null, "/testId12345");
}
@Test
public void test_delete() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("");
AND.http_response_returns(200);
WHEN.classifier_delete_is_invoked();
THEN.verify_http_client_execute_invoked("delete", null, "/testId12345");
AND.classifier_was_deleted();
}
@Test
public void test_delete_json_response_should_be_ignored() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("{}");
AND.http_response_returns(200);
WHEN.classifier_delete_is_invoked();
THEN.verify_http_client_execute_invoked("delete", null, "/testId12345");
AND.classifier_was_deleted();
}
@Test
public void test_delete_non_json_response_should_be_ignored() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("this is not json");
AND.http_response_returns(200);
WHEN.classifier_delete_is_invoked();
THEN.verify_http_client_execute_invoked("delete", null, "/testId12345");
AND.classifier_was_deleted();
}
@Test
public void test_delete_gets_500() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("");
AND.http_response_returns(500);
WHEN.classifier_delete_is_invoked();
THEN.verify_http_client_execute_invoked("delete", null, "/testId12345");
AND.classifier_was_not_deleted();
}
@Test
public void test_delete_gets_response_throws_npe() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("");
AND.http_response_returns(200);
AND.http_entity_input_stream_throws(new NullPointerException("Cannot read"));
WHEN.classifier_delete_is_invoked();
THEN.verify_http_client_execute_invoked("delete", null, "/testId12345");
AND.classifier_was_deleted();
}
@Test
public void test_delete_gets_response_throws_io_exception() throws Exception {
GIVEN.classifier_is_created();
AND.mock_rest_client_is_created();
AND.rest_client_is_set_in_classifier();
AND.http_entity_content_is("");
AND.http_response_returns(200);
AND.http_entity_input_stream_throws(new IOException("Cannot read"));
WHEN.classifier_delete_is_invoked();
THEN.verify_http_client_execute_invoked("delete", null, "/testId12345");
AND.classifier_was_deleted();
}
@Test
public void test_get_id() throws Exception {
GIVEN.classifier_is_created();
WHEN.classifier_get_id_is_invoked();
THEN.verify_classifier_id_is_not_null();
}
private void verify_classifier_id_is_not_null() {
assertNotNull(classifierId);
}
private void classifier_was_not_deleted() {
assertFalse(classifierDeleted);
}
private void classifier_was_deleted() {
assertTrue(classifierDeleted);
}
private void verify_classifier_state_is(Status status) {
assertEquals(status, classifierStatus);
}
private void verify_classifier_status_not_null() {
assertNotNull(classifierStatus);
}
private void verify_entity_content_is_classify_data() {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(entityContent);
assertTrue(json.isJsonObject());
JsonObject jsonObject = json.getAsJsonObject();
assertTrue(jsonObject.has("text"));
String text = jsonObject.get("text").getAsString();
assertNotNull(text);
assertEquals(expectedClassifyResponse.getText(), text);
}
private void verify_classified_items_item_is(int index, String text, double conf) {
NLClassifiedClass classifiedClass = actualClassifyResponse.getClasses().get(index);
assertNotNull(classifiedClass);
assertEquals(text, classifiedClass.getClassName());
assertEquals(conf, classifiedClass.getConfidence(), 0);
}
private void verify_classified_items_size_is(int i) {
List<NLClassifiedClass> classes = actualClassifyResponse.getClasses();
assertNotNull(classes);
assertEquals(i, classes.size());
}
private void verify_classified_items_is_not_null() {
assertNotNull(actualClassifyResponse);
}
private void a_class_is_added_to_the_classify_response(String className, double confidence) {
List<NLClassifiedClass> classes = expectedClassifyResponse.getClasses();
if(classes.isEmpty()) {
expectedClassifyResponse.setTopClass(className);
}
classes.add(new NLClassifiedClass(className, confidence));
}
private void a_new_classify_response() {
expectedClassifyResponse = new NLClassiferClassifyResponse();
expectedClassifyResponse.setClasses(new ArrayList<NLClassifiedClass>());
}
private void classifier_get_status_is_invoked() {
classifierStatus = classifier.getStatus();
}
private void classifier_get_id_is_invoked() {
classifierId = classifier.getId();
}
private void classifier_classify_is_invoked(String text) {
expectedClassifyResponse.setText(text);
actualClassifyResponse = classifier.classify(text);
}
private void classifier_delete_is_invoked() {
classifierDeleted = classifier.delete();
}
private void rest_client_is_set_in_classifier() {
classifier.setRestClient(restClient);
}
private void classifier_is_created() {
classifier = new NLClassifierImpl("testId12345");
}
}
| 39.15304 | 110 | 0.78882 |
2f8963085a3616e16e7575ce0c41ef7193f2edca | 13,064 | package org.kie.remote.client.internal.command;
import static org.kie.remote.client.jaxb.ConversionUtil.convertMapToJaxbStringObjectPairArray;
import static org.kie.remote.client.jaxb.ConversionUtil.convertStringListToGenOrgEntList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.kie.remote.client.api.RemoteApiResponse;
import org.kie.remote.client.api.RemoteApiResponse.RemoteOperationStatus;
import org.kie.remote.client.api.RemoteTaskService;
import org.kie.remote.client.api.exception.RemoteApiException;
import org.kie.remote.client.api.exception.RemoteCommunicationException;
import org.kie.remote.client.api.exception.RemoteTaskException;
import org.kie.remote.jaxb.gen.AddContentFromUserCommand;
import org.kie.remote.jaxb.gen.GetContentMapForUserCommand;
import org.kie.remote.jaxb.gen.NominateTaskCommand;
public class RemoteTaskServiceClientImpl implements RemoteTaskService {
private final TaskServiceClientCommandObject delegate;
RemoteTaskServiceClientImpl(RemoteConfiguration config) {
this.delegate = new TaskServiceClientCommandObject(config);
}
private static <T> RemoteApiResponse<T> createRemoteApiResponse(RemoteClientException rce ) {
RemoteApiResponse<T> response;
String message = rce.getShortMessage();
if( message == null ) {
message = rce.getMessage();
}
Throwable exc = rce.getCause();
if( exc == null ) {
exc = rce;
}
if( rce instanceof RemoteTaskException ) {
response = new RemoteApiResponse<T>(RemoteOperationStatus.PERMISSIONS_FAILURE, message, exc);
} else if( rce instanceof RemoteCommunicationException ) {
response = new RemoteApiResponse<T>(RemoteOperationStatus.COMMUNICATION_FAILURE, message, exc);
} else if( rce instanceof RemoteApiException ) {
if( exc instanceof RemoteClientException ) {
response = new RemoteApiResponse<T>(RemoteOperationStatus.SERVER_FAILURE, message, exc);
} else {
response = new RemoteApiResponse<T>(RemoteOperationStatus.CLIENT_FAILURE, message, exc);
}
} else {
response = new RemoteApiResponse<T>(RemoteOperationStatus.UNKNOWN_FAILURE, message, exc);
}
return response;
}
// RemoteTaskService methods
@Override
public RemoteApiResponse activate( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.activate(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse claim( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.claim(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse claimNextAvailable() {
RemoteApiResponse<Void> response;
try {
delegate.claimNextAvailable(delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse complete( long taskId, Map<String, Object> data ) {
RemoteApiResponse<Void> response;
try {
delegate.complete(taskId, delegate.getConfig().getUserName(), data);
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse delegate( long taskId, String targetUserId ) {
RemoteApiResponse<Void> response;
try {
delegate.delegate(taskId, delegate.getConfig().getUserName(), targetUserId);
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse exit( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.exit(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse fail( long taskId ) {
return fail(taskId, null);
}
@Override
public RemoteApiResponse fail( long taskId, Map<String, Object> faultData ) {
RemoteApiResponse<Void> response;
try {
delegate.fail(taskId, delegate.getConfig().getUserName(), faultData);
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse forward( long taskId, String targetEntityId ) {
RemoteApiResponse<Void> response;
try {
delegate.forward(taskId, delegate.getConfig().getUserName(), targetEntityId);
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse release( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.release(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse resume( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.resume(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse skip( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.skip(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse start( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.start(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse stop( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.stop(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse suspend( long taskId ) {
RemoteApiResponse<Void> response;
try {
delegate.suspend(taskId, delegate.getConfig().getUserName());
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse nominate( long taskId, String... potentialOwnerUserIds ) {
RemoteApiResponse<Void> response;
if( potentialOwnerUserIds == null || potentialOwnerUserIds.length == 0 ) {
return new RemoteApiResponse<Void>(RemoteOperationStatus.CLIENT_FAILURE, "Null or empty list of potential owner user ids received as argument");
}
try {
NominateTaskCommand cmd = new NominateTaskCommand();
cmd.setTaskId(taskId);
cmd.setUserId(delegate.getConfig().getUserName());
List<org.kie.remote.jaxb.gen.OrganizationalEntity> genOrgEntList
= convertStringListToGenOrgEntList(Arrays.asList(potentialOwnerUserIds));
if( genOrgEntList != null ) {
cmd.getPotentialOwners().addAll(genOrgEntList);
}
delegate.executeCommand(cmd);
response = new RemoteApiResponse<Void>();
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Void>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
// CONTENT operations
@Override
public RemoteApiResponse<Long> addOutputContent( long taskId, Map<String, Object> params ) {
RemoteApiResponse<Long> response;
if( params == null ) {
return new RemoteApiResponse<Long>(RemoteOperationStatus.CLIENT_FAILURE, "Null Map<String, Object> received as argument");
}
try {
AddContentFromUserCommand cmd = new AddContentFromUserCommand();
cmd.setTaskId(taskId);
cmd.setUserId(delegate.getConfig().getUserName());
cmd.setOutputContentMap(convertMapToJaxbStringObjectPairArray(params));
Long contentId = delegate.executeCommand(cmd);
response = new RemoteApiResponse<Long>(contentId);
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Long>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
@Override
public RemoteApiResponse<Map<String, Object>> getOutputContentMap( long taskId ) {
RemoteApiResponse<Map<String, Object>> response;
try {
GetContentMapForUserCommand cmd = new GetContentMapForUserCommand();
cmd.setTaskId(taskId);
cmd.setUserId(delegate.getConfig().getUserName());
Map<String, Object> outputContentMap = delegate.executeCommand(cmd);
response = new RemoteApiResponse<Map<String, Object>>(outputContentMap);
} catch( RemoteClientException rce ) {
response = createRemoteApiResponse(rce);
} catch( Exception e ) {
response = new RemoteApiResponse<Map<String, Object>>(RemoteOperationStatus.UNKNOWN_FAILURE, e);
}
return response;
}
}
| 38.650888 | 155 | 0.641611 |
ac5baef81f4881c475837dc4c2e33e84e1d532d0 | 2,095 | package com.starquestminecraft.greeter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.concurrent.TimeUnit;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
public class CryoBounce extends Plugin implements Listener{
public static void callCryoMessage(final ProxiedPlayer plr, int iteration){
Server server = plr.getServer();
if(server != null){
ServerInfo info = server.getInfo();
sendMessage(plr.getName(), info);
} else if(iteration < 15){
final int itr2 = iteration + 1;
Greeter.getInstance().getProxy().getScheduler().schedule(Greeter.getInstance(), new Runnable(){
public void run(){
callCryoMessage(plr, itr2);
}
}, 1, TimeUnit.SECONDS);
} else {
plr.sendMessage(createMessage("Took more than 15 seconds to connect to server, active cryopod message failed!"));
return;
}
}
public static void fakeCryopodLogin(final ProxiedPlayer plr, ServerInfo target){
sendMessage(plr.getName(), target);
}
public static void sendMessage(String message, ServerInfo server) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(stream);
try{
out.writeUTF(message);
} catch (Exception e){
e.printStackTrace();
}
server.sendData("cryoBounce", stream.toByteArray());
// Alright quick note here guys : ProxiedPlayer.sendData() [b]WILL NOT WORK[/b]. It will send it to the client, and not to the server the client is connected. See the difference ? You need to send to Server or ServerInfo.
}
private static BaseComponent[] createMessage(String s){
return new ComponentBuilder(s).create();
}
}
| 36.12069 | 229 | 0.731265 |
6b05ccad2c9d950658d977e0249f411070613ecb | 3,683 | /*
* Copyright [2009-2014] EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ensembl.genomeloader.materializer.impl;
import java.util.ArrayList;
import java.util.List;
import org.ensembl.genomeloader.model.Gene;
import org.ensembl.genomeloader.model.ModelUtils;
import org.ensembl.genomeloader.model.Protein;
import org.ensembl.genomeloader.model.ProteinFeature;
import org.ensembl.genomeloader.model.ProteinFeatureSource;
import org.ensembl.genomeloader.model.ProteinFeatureType;
import org.ensembl.genomeloader.model.impl.DelegatingEntityLocation;
import org.ensembl.genomeloader.model.impl.GenomicComponentImpl;
import org.ensembl.genomeloader.model.impl.ProteinFeatureImpl;
import org.ensembl.genomeloader.util.biojava.FeatureLocationGapOverlapException;
import org.ensembl.genomeloader.util.biojava.LocationUtils;
import org.ensembl.genomeloader.util.biojava.TripletLocationException;
import org.ensembl.genomeloader.xrefregistry.DatabaseReferenceTypeRegistry;
import nu.xom.Element;
/**
* Parser for features of type sig_peptide, transit_peptide, mat_peptide. These
* are added as features to the proteins which enclose them
*
* @author dstaines
*/
public class PeptideFeatureParser extends XmlEnaFeatureParser {
public PeptideFeatureParser(DatabaseReferenceTypeRegistry registry) {
super(registry);
}
@Override
public void parseFeature(GenomicComponentImpl component, Element element) {
ProteinFeature ft = new ProteinFeatureImpl();
ft.setLocation(new DelegatingEntityLocation(parseLocation(element)));
ft.setType(ProteinFeatureType.forEmblString(element
.getAttributeValue("name")));
boolean found = false;
for (Gene gene : component.getGenes()) {
for (Protein protein : gene.getProteins()) {
if (protein.getLocation().contains(ft.getLocation())
&& LocationUtils.overlapsInFrame(ft.getLocation(),
protein.getLocation())) {
getLog().debug(
"Feature " + ft + " overlaps with CDS "
+ protein.getIdString() + ": assigning");
try {
ModelUtils.setFeatureCoordinates(ft,
protein.getLocation());
ModelUtils.assignLocationModifiers(
protein.getLocation(), ft.getLocation());
ft.setSource(ProteinFeatureSource.GENOMIC_ANNOTATION);
protein.addProteinFeature(ft);
found = true;
break;
} catch (TripletLocationException e) {
getLog().warn(
"Feature " + ft + " from location "
+ protein.getLocation()
+ " is not triplet based");
} catch (FeatureLocationGapOverlapException e) {
getLog().warn(
"Feature "
+ ft
+ " overlaps a gap in the genomic location "
+ protein.getLocation());
} finally {
}
}
}
}
if (!found) {
getLog().warn("Could not find protein for protein feature " + ft);
getDefaultParser().parseFeature(component, element);
}
}
@Override
public List<Class<? extends XmlEnaFeatureParser>> dependsOn() {
return new ArrayList<Class<? extends XmlEnaFeatureParser>>() {
{
add(CdsFeatureParser.class);
add(GeneFeatureParser.class);
}
};
}
}
| 33.481818 | 80 | 0.728482 |
fceb47948d7bec08ccc1268d216b1178462ff2c5 | 8,775 | package New;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class Uploader {
private JFrame form ;
private String sock = "";
private String Filename = "";
private String full_progress = "";
private String fname = "";
private JPanel Buttons;
//Program Owner : Saher Blue Eagle
public Uploader(String ip,String str1, String str2,String tr4) throws InterruptedException{
this.sock = ip;
this.Filename = str1;
this.full_progress = str2;
this.fname = tr4;
}
public void SetDownloader(String ip,String str1, String str2) throws InterruptedException{
this.sock = ip;
this.Filename = str1;
this.full_progress = str2;
prog.setMaximum(100);
message.setText("... Working");
message.repaint();
}
public void SetDownloader_W(String ip,String str1) throws InterruptedException{
this.sock = ip;
this.Filename = str1;
if (str1.contains("Error")){
filelocation.setText(str1);
filelocation.repaint();
message.setText("Cannot Upload File");
message.repaint();
}else{
message.setText("... Working");
message.repaint();
filelocation.setText(str1);
filelocation.repaint();
}
form.repaint();
}
public void Set_sock(String ip){
sock = ip;
}
public String Get_sock(){
return sock ;
}
public String Get_fname(){
return fname ;
}
private static ArrayList<String> SplitString(String s){
String Word = "";
String YY = "";
String xx = "|||";
YY = xx.charAt(0)+ "" +xx.charAt(1);
ArrayList<String>Words = new ArrayList<String>();
if(s.contains(YY)==false){
Words.add(s);
return Words;
}else{
for (int i = 0 ; i<s.length();i++){
if ((s.charAt(i) =='|')== false) {
Word += s.charAt(i);
}else{
if(Words.contains(Word)==false){
Words.add(Word);
}
Word = "";
}
}
return Words;
}
}
private ArrayList<String> SplitString_D(String s,String Delimeter){
String Word = "";
String YY = Delimeter;
ArrayList<String>Words = new ArrayList<String>();
if(s.contains(YY)==false){
Words.add(s);
return Words;
}else{
for (int i = 0 ; i<s.length();i++){
if ((s.charAt(i) =='|')== false) {
Word += s.charAt(i);
}else{
if(Words.contains(Word)==false){
Words.add(Word);
}
Word = "";
}
}
return Words;
}
}
private JProgressBar prog;
private JLabel id;
private JLabel message;
private JLabel filelocation;
private int counprog=0;
private int current_chunk=0;
public void On_Finish(String Filepath,String b){
counprog = 0;
message.setText("");
message.repaint();
form.repaint();
filelocation.setText("");
filelocation.repaint();
prog.setValue(0);
id.setText("Progress : ");
id.repaint();
prog.setMaximum(0);
prog.repaint();
form.repaint();
}
public void set_chunk_counter(int max,int curr){
double prec = (double) curr/max;
prec = prec * 100;
double rd = Math.round(prec);
form.setTitle( (int)rd +" % File Uploader For : " + sock);
form.setVisible(true);
form.repaint();
String YY = "";
String xx = "|||";
YY = xx.charAt(0)+ "" +xx.charAt(1);
current_chunk = curr ;
// counprog = (int) (x * 100.0 * prog.getMaximum());
prog.setMaximum(100);
counprog = (int)rd ;
prog.setValue(counprog);
//System.out.println("\n"+("Progress : " + (curr/prog.getMaximum())*100 ) + " %" + "\n" + prog.getMaximum() + "\n" +current_chunk );
id.setText("Progress : " + rd + " %");
id.repaint();
prog.repaint();
form.repaint();
form.repaint();
Buttons.repaint();
if(prog.getValue()==prog.getMaximum()){
for (File_Manager_VB opnx : Master.Get_Open_FM_VB()){
if(opnx.Get_sock().equals(sock)){
opnx.re_enable();
}
}
}
// counprog = x;
}
public void Do_frame(){
form = new JFrame();
form.setName("File Uploader For : " + sock);
form.setTitle("File Uploader For : " + sock);
form.setResizable(false);
int widthx = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int heightx = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
form.setLayout(null);
Font font = new Font("Microsoft Sans Serif", Font.PLAIN, 12);
form.setFont(font);
DefaultTableModel model = new DefaultTableModel(){
@Override
public boolean isCellEditable(int row, int column) {
//Only the third column
return false;
}
public Class<?> getColumnClass(int column) {
switch(column) {
case 0: return ImageIcon.class;
default: return Object.class;
}
}
};
ImageIcon icon=new ImageIcon("Drive.png");
Object[] columnNames = {"^.^","Drive / File / Folder", "Type / Ext.", "Size"};
model.setColumnIdentifiers(columnNames);
form.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
//on closing event
if (JOptionPane.showConfirmDialog(form,
"Are you sure you want to close File Uploader From : "+ sock +" window?", "Close Window?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
Master.Remove_Form_Open_Downloaders_uns(sock,fname);
String Word = "";
String YY = "";
String xx = "|||";
YY = xx.charAt(0)+ "" +xx.charAt(1);
Master.Send_Data("kill_uns_up" + YY , sock,false);
form.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} else{
form.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
});
FontUIResource fontx = new FontUIResource("Verdana", Font.BOLD, 13);
// form.add(btnNext);
// form.add(Dir);
// form.setBounds((widthx -300),(heightx -200), 300, 150);
form.setBounds((widthx -500)/2,( heightx -150)/2, 500, 150);
Buttons = new JPanel();
Buttons.setSize(form.getSize());
Buttons.setBackground(Color.DARK_GRAY);
Buttons.setLayout(null);
id = new JLabel("Progress : " );
id.setBounds(9,18, Buttons.getWidth(), 22);
id.setFont(fontx);
id.setForeground(Color.BLACK);
Buttons.add(id);
prog = new JProgressBar();
prog.setBounds(5,19, Buttons.getWidth() - 30, 22);
prog.setFont(fontx);
prog.setMaximum(Integer.parseInt(full_progress));
Buttons.add(prog);
message = new JLabel("Status : Uploading Commanded" );
message.setBounds(5,35, Buttons.getWidth(), 25);
message.setFont(fontx);
message.setForeground(Color.WHITE);
Buttons.add(message);
filelocation = new JLabel(Filename);
filelocation.setBounds(5,50, Buttons.getWidth(), 50);
filelocation.setFont(fontx);
filelocation.setForeground(Color.WHITE);
Buttons.add(filelocation);
form.validate();
form.add(Buttons);
form.setResizable(false);
form.setAlwaysOnTop(true);
form.setBackground(Color.DARK_GRAY);
form.repaint();
// form.add(sp);
form.validate();
// form.getContentPane().setBackground(Color.DARK_GRAY);
form.setVisible(true);
}
}
| 26.510574 | 137 | 0.564217 |
a5ee7d33094dbb546247a30b24bfc9dab244016c | 2,029 | package org.xh.cms.security;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.stream.Collectors;
/**
* Created by Administrator on 2019/6/15.
*/
public class MySecurityFilter extends FilterSecurityInterceptor{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
if(authentication instanceof AnonymousAuthenticationToken) {
super.doFilter(request, response, chain);
}
else{
String url=((HttpServletRequest)request).getRequestURI();
this.getAccessDecisionManager().decide(authentication,url,
this.getSecurityMetadataSource().getAttributes(url));
super.doFilter(request, response, chain);
}
}
catch (Exception ex){
return;
}
}
}
| 39.019231 | 132 | 0.763923 |
fb57a6d180c360c3f5900d172602d7757e57ddf3 | 19,456 | /*
* 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 io.prestosql.plugin.kinesis.util;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.ResponseMetadata;
import com.amazonaws.services.kinesis.AmazonKinesisClient;
import com.amazonaws.services.kinesis.model.CreateStreamRequest;
import com.amazonaws.services.kinesis.model.CreateStreamResult;
import com.amazonaws.services.kinesis.model.DescribeStreamRequest;
import com.amazonaws.services.kinesis.model.DescribeStreamResult;
import com.amazonaws.services.kinesis.model.GetRecordsRequest;
import com.amazonaws.services.kinesis.model.GetRecordsResult;
import com.amazonaws.services.kinesis.model.GetShardIteratorRequest;
import com.amazonaws.services.kinesis.model.GetShardIteratorResult;
import com.amazonaws.services.kinesis.model.ListStreamsRequest;
import com.amazonaws.services.kinesis.model.ListStreamsResult;
import com.amazonaws.services.kinesis.model.ListTagsForStreamRequest;
import com.amazonaws.services.kinesis.model.ListTagsForStreamResult;
import com.amazonaws.services.kinesis.model.PutRecordRequest;
import com.amazonaws.services.kinesis.model.PutRecordResult;
import com.amazonaws.services.kinesis.model.PutRecordsRequest;
import com.amazonaws.services.kinesis.model.PutRecordsRequestEntry;
import com.amazonaws.services.kinesis.model.PutRecordsResult;
import com.amazonaws.services.kinesis.model.PutRecordsResultEntry;
import com.amazonaws.services.kinesis.model.Record;
import com.amazonaws.services.kinesis.model.SequenceNumberRange;
import com.amazonaws.services.kinesis.model.Shard;
import com.amazonaws.services.kinesis.model.StreamDescription;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Mock kinesis client for testing that is primarily used for reading from the
* stream as we do here in Presto.
* <p>
* This is to help prove that the API is being used correctly and debug any
* issues that arise without incurring AWS load and charges. It is far from a complete
* implementation of Kinesis.
* <p>
*/
public class MockKinesisClient
extends AmazonKinesisClient
{
private List<InternalStream> streams = new ArrayList();
public static class InternalShard
extends Shard
{
private List<Record> recs = new ArrayList<>();
private String streamName = "";
private int index;
public InternalShard(String streamName, int index)
{
super();
this.streamName = streamName;
this.index = index;
this.setShardId(this.streamName + "_" + this.index);
}
public List<Record> getRecords()
{
return recs;
}
public List<Record> getRecordsFrom(ShardIterator iterator)
{
List<Record> returnRecords = new ArrayList();
for (Record record : this.recs) {
if (Integer.valueOf(record.getSequenceNumber()) >= iterator.recordIndex) {
returnRecords.add(record);
}
}
return returnRecords;
}
public String getStreamName()
{
return streamName;
}
public int getIndex()
{
return index;
}
public void addRecord(Record rec)
{
recs.add(rec);
}
public void clearRecords()
{
recs.clear();
}
}
public static class InternalStream
{
private String streamName = "";
private String streamAmazonResourceName = "";
private String streamStatus = "CREATING";
private int retentionPeriodHours = 24;
private List<InternalShard> shards = new ArrayList();
private int sequenceNo = 100;
private int nextShard;
public InternalStream(String streamName, int shardCount, boolean isActive)
{
this.streamName = streamName;
this.streamAmazonResourceName = "local:fake.stream:" + streamName;
if (isActive) {
this.streamStatus = "ACTIVE";
}
for (int i = 0; i < shardCount; i++) {
InternalShard newShard = new InternalShard(this.streamName, i);
newShard.setSequenceNumberRange((new SequenceNumberRange()).withStartingSequenceNumber("100").withEndingSequenceNumber("999"));
this.shards.add(newShard);
}
}
public String getStreamName()
{
return streamName;
}
public String getStreamAmazonResourceName()
{
return streamAmazonResourceName;
}
public String getStreamStatus()
{
return streamStatus;
}
public List<InternalShard> getShards()
{
return shards;
}
public List<InternalShard> getShardsFrom(String afterShardId)
{
String[] comps = afterShardId.split("_");
if (comps.length == 2) {
List<InternalShard> returnArray = new ArrayList();
int afterIndex = Integer.parseInt(comps[1]);
if (shards.size() > afterIndex + 1) {
for (InternalShard shard : shards) {
if (shard.getIndex() > afterIndex) {
returnArray.add(shard);
}
}
}
return returnArray;
}
else {
return new ArrayList();
}
}
public void activate()
{
this.streamStatus = "ACTIVE";
}
public PutRecordResult putRecord(ByteBuffer data, String partitionKey)
{
// Create record and insert into the shards. Initially just do it
// on a round robin basis.
long timestamp = System.currentTimeMillis() - 50000;
Record record = new Record();
record = record.withData(data).withPartitionKey(partitionKey).withSequenceNumber(String.valueOf(sequenceNo));
record.setApproximateArrivalTimestamp(new Date(timestamp));
if (nextShard == shards.size()) {
nextShard = 0;
}
InternalShard shard = shards.get(nextShard);
shard.addRecord(record);
PutRecordResult result = new PutRecordResult();
result.setSequenceNumber(String.valueOf(sequenceNo));
result.setShardId(shard.getShardId());
nextShard++;
sequenceNo++;
return result;
}
public void clearRecords()
{
for (InternalShard shard : this.shards) {
shard.clearRecords();
}
}
}
public static class ShardIterator
{
public String streamId = "";
public int shardIndex;
public int recordIndex;
public ShardIterator(String streamId, int shardIndex, int recordIndex)
{
this.streamId = streamId;
this.shardIndex = shardIndex;
this.recordIndex = recordIndex;
}
public String makeString()
{
return this.streamId + "_" + this.shardIndex + "_" + this.recordIndex;
}
public static ShardIterator fromStreamAndShard(String streamName, String shardId)
{
ShardIterator newInst = null;
String[] comps = shardId.split("_");
if (streamName.equals(comps[0]) && comps[1].matches("[0-9]+")) {
newInst = new ShardIterator(comps[0], Integer.parseInt(comps[1]), 0);
}
return newInst;
}
public static ShardIterator fromString(String input)
{
ShardIterator newInst = null;
String[] comps = input.split("_");
if (comps.length == 3) {
if (comps[1].matches("[0-9]+") && comps[2].matches("[0-9]+")) {
newInst = new ShardIterator(comps[0], Integer.parseInt(comps[1]), Integer.parseInt(comps[2]));
}
}
return newInst;
}
}
public MockKinesisClient()
{
super();
}
protected InternalStream getStream(String name)
{
InternalStream foundStream = null;
for (InternalStream stream : this.streams) {
if (stream.getStreamName().equals(name)) {
foundStream = stream;
break;
}
}
return foundStream;
}
protected List<Shard> getShards(InternalStream theStream)
{
List<Shard> externalList = new ArrayList();
for (InternalShard intshard : theStream.getShards()) {
externalList.add(intshard);
}
return externalList;
}
protected List<Shard> getShards(InternalStream theStream, String fromShardId)
{
List<Shard> externalList = new ArrayList();
for (InternalShard intshard : theStream.getShardsFrom(fromShardId)) {
externalList.add(intshard);
}
return externalList;
}
@Override
public PutRecordResult putRecord(PutRecordRequest putRecordRequest)
throws AmazonClientException
{
// Setup method to add a new record:
InternalStream theStream = this.getStream(putRecordRequest.getStreamName());
if (theStream != null) {
return theStream.putRecord(putRecordRequest.getData(), putRecordRequest.getPartitionKey());
}
else {
throw new AmazonClientException("This stream does not exist!");
}
}
@Override
public CreateStreamResult createStream(CreateStreamRequest createStreamRequest)
throws AmazonClientException
{
// Setup method to create a new stream:
InternalStream stream = new InternalStream(createStreamRequest.getStreamName(), createStreamRequest.getShardCount(), true);
this.streams.add(stream);
return new CreateStreamResult();
}
@Override
public CreateStreamResult createStream(String streamName, Integer integer)
throws AmazonClientException
{
return this.createStream((new CreateStreamRequest()).withStreamName(streamName).withShardCount(integer));
}
@Override
public PutRecordsResult putRecords(PutRecordsRequest putRecordsRequest)
throws AmazonClientException
{
// Setup method to add a batch of new records:
InternalStream theStream = this.getStream(putRecordsRequest.getStreamName());
if (theStream != null) {
PutRecordsResult result = new PutRecordsResult();
List<PutRecordsResultEntry> resultList = new ArrayList();
for (PutRecordsRequestEntry entry : putRecordsRequest.getRecords()) {
PutRecordResult putResult = theStream.putRecord(entry.getData(), entry.getPartitionKey());
resultList.add((new PutRecordsResultEntry()).withShardId(putResult.getShardId()).withSequenceNumber(putResult.getSequenceNumber()));
}
result.setRecords(resultList);
return result;
}
else {
throw new AmazonClientException("This stream does not exist!");
}
}
@Override
public DescribeStreamResult describeStream(DescribeStreamRequest describeStreamRequest)
throws AmazonClientException
{
InternalStream theStream = this.getStream(describeStreamRequest.getStreamName());
if (theStream != null) {
StreamDescription desc = new StreamDescription();
desc = desc.withStreamName(theStream.getStreamName()).withStreamStatus(theStream.getStreamStatus()).withStreamARN(theStream.getStreamAmazonResourceName());
if (describeStreamRequest.getExclusiveStartShardId() == null || describeStreamRequest.getExclusiveStartShardId().isEmpty()) {
desc.setShards(this.getShards(theStream));
desc.setHasMoreShards(false);
}
else {
// Filter from given shard Id, or may not have any more
String startId = describeStreamRequest.getExclusiveStartShardId();
desc.setShards(this.getShards(theStream, startId));
desc.setHasMoreShards(false);
}
DescribeStreamResult result = new DescribeStreamResult();
result = result.withStreamDescription(desc);
return result;
}
else {
throw new AmazonClientException("This stream does not exist!");
}
}
@Override
public GetShardIteratorResult getShardIterator(GetShardIteratorRequest getShardIteratorRequest)
throws AmazonClientException
{
ShardIterator iter = ShardIterator.fromStreamAndShard(getShardIteratorRequest.getStreamName(), getShardIteratorRequest.getShardId());
if (iter != null) {
InternalStream theStream = this.getStream(iter.streamId);
if (theStream != null) {
String seqAsString = getShardIteratorRequest.getStartingSequenceNumber();
if (seqAsString != null && !seqAsString.isEmpty() && getShardIteratorRequest.getShardIteratorType().equals("AFTER_SEQUENCE_NUMBER")) {
int sequence = Integer.parseInt(seqAsString);
iter.recordIndex = sequence + 1;
}
else {
iter.recordIndex = 100;
}
GetShardIteratorResult result = new GetShardIteratorResult();
return result.withShardIterator(iter.makeString());
}
else {
throw new AmazonClientException("Unknown stream or bad shard iterator!");
}
}
else {
throw new AmazonClientException("Bad stream or shard iterator!");
}
}
@Override
public GetRecordsResult getRecords(GetRecordsRequest getRecordsRequest)
throws AmazonClientException
{
ShardIterator iterator = ShardIterator.fromString(getRecordsRequest.getShardIterator());
if (iterator == null) {
throw new AmazonClientException("Bad shard iterator.");
}
// TODO: incorporate maximum batch size (getRecordsRequest.getLimit)
GetRecordsResult result = null;
InternalStream stream = this.getStream(iterator.streamId);
if (stream != null) {
InternalShard shard = stream.getShards().get(iterator.shardIndex);
if (iterator.recordIndex == 100) {
result = new GetRecordsResult();
List<Record> recs = shard.getRecords();
result.setRecords(recs); // NOTE: getting all for now
result.setNextShardIterator(getNextShardIterator(iterator, recs).makeString());
result.setMillisBehindLatest(100L);
}
else {
result = new GetRecordsResult();
List<Record> recs = shard.getRecordsFrom(iterator);
result.setRecords(recs); // may be empty
result.setNextShardIterator(getNextShardIterator(iterator, recs).makeString());
result.setMillisBehindLatest(100L);
}
}
else {
throw new AmazonClientException("Unknown stream or bad shard iterator.");
}
return result;
}
protected ShardIterator getNextShardIterator(ShardIterator previousIter, List<Record> records)
{
ShardIterator newIter = null;
if (records.size() == 0) {
newIter = previousIter;
}
else {
Record rec = records.get(records.size() - 1);
int lastSeq = Integer.valueOf(rec.getSequenceNumber());
newIter = new ShardIterator(previousIter.streamId, previousIter.shardIndex, lastSeq + 1);
}
return newIter;
}
//// Unsupported methods
@Override
public ListTagsForStreamResult listTagsForStream(ListTagsForStreamRequest listTagsForStreamRequest)
throws AmazonClientException
{
return null;
}
@Override
public ListStreamsResult listStreams(ListStreamsRequest listStreamsRequest)
throws AmazonClientException
{
return null;
}
@Override
public ListStreamsResult listStreams()
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public PutRecordResult putRecord(String s, ByteBuffer byteBuffer, String s1)
throws AmazonServiceException, AmazonClientException
{
throw new UnsupportedOperationException("MockKinesisClient doesn't support this.");
}
@Override
public PutRecordResult putRecord(String s, ByteBuffer byteBuffer, String s1, String s2)
throws AmazonServiceException, AmazonClientException
{
throw new UnsupportedOperationException("MockKinesisClient doesn't support this.");
}
@Override
public DescribeStreamResult describeStream(String streamName)
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public DescribeStreamResult describeStream(String streamName, String exclusiveStartShardId)
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public DescribeStreamResult describeStream(String streamName, Integer integer, String exclusiveStartShardId)
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public GetShardIteratorResult getShardIterator(String streamName, String shardId, String shardIteratorType)
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public GetShardIteratorResult getShardIterator(String streamName, String shardId, String shardIteratorType, String startingSequenceNumber)
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public ListStreamsResult listStreams(String exclusiveStartStreamName)
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public ListStreamsResult listStreams(Integer limit, String exclusiveStartStreamName)
throws AmazonServiceException, AmazonClientException
{
return null;
}
@Override
public void shutdown()
{
return; // Nothing to shutdown here
}
@Override
public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest amazonWebServiceRequest)
{
return null;
}
}
| 34.619217 | 167 | 0.63492 |
bf5d98e2235ec232fa032cc593ca91d9180ce88f | 1,029 | import java.util.Scanner;
public class Max {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
double[] list=new double[n];
for (int i = 0; i < list.length; i++) {
list[i]=in.nextDouble();
}
in.close();
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list.length-1; j++) {
if(list[j]<list[j+1]) {
double temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}
}
}
if(n>=4) {
int Max=(int)(list[0]*list[1]*list[2]*list[3]);
for (int i = 3; i >= 0; i--) {
if(i==0) {
System.out.println((int)list[i]);
}
else {
System.out.print((int)list[i]+" ");
}
}
System.out.print(Max);
}
else {
int Max=1;
for (int i = 0; i < list.length; i++) {
Max*=(int)list[i];
}
for (int i = 0; i < list.length; i++) {
if(i==list.length-1) {
System.out.println((int)list[i]);
}
else {
System.out.print((int)list[i]+" ");
}
}
System.out.print(Max);
}
}
}
| 19.788462 | 50 | 0.50243 |
a488c84d03f9bfab3fb2d44122629b9bde596699 | 918 | package org.matt1.utils;
import android.util.Log;
/**
* <p>
* Facade for standard logger with a given tag
* </p>
* @author Matt
*
*/
public class Logger {
/** Logger tag */
private static final String LOGGING_TAG = "matt1.http";
/**
* <p>
* Logs a debug message
* </p>
* @param pMessage
*/
public static void debug(String pMessage) {
Log.d(LOGGING_TAG, pMessage);
}
/**
* <p>
* Logs an info message
* </p>
* @param pMessage
*/
public static void info(String pMessage) {
Log.i(LOGGING_TAG, pMessage);
}
/**
* <p>
* Logs an error message
* </p>
* @param pMessage
*/
public static void error(String pMessage) {
Log.e(LOGGING_TAG, pMessage);
}
/**
* <p>
* Logs a warning message
* </p>
* @param pMessage
*/
public static void warn(String pMessage) {
Log.w(LOGGING_TAG, pMessage);
}
}
| 15.827586 | 57 | 0.565359 |
02ce0bd16e1ba6f4390ca6216077b171ce1a531f | 1,378 | package cn.wangyang.www.mygirlfriend;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import java.util.Random;
import tyrantgit.widget.HeartLayout;
public class MainActivity extends AppCompatActivity implements Handler.Callback{
private Random mRandom = new Random();
private Handler handler = new Handler(this);
private HeartLayout mHeartLayout;
private HeartLayout mHeartLayout2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHeartLayout = (HeartLayout) findViewById(R.id.heart_layout);
mHeartLayout2 = (HeartLayout) findViewById(R.id.heart_layout2);
handler.sendEmptyMessageDelayed(1, 500);
}
private int randomColor() {
return Color.rgb(mRandom.nextInt(255), mRandom.nextInt(255), mRandom.nextInt(255));
}
@Override
public boolean handleMessage(Message message) {
mHeartLayout.addHeart(randomColor());
mHeartLayout2.addHeart(randomColor());
handler.sendEmptyMessageDelayed(1, 200);
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
}
| 28.708333 | 91 | 0.719158 |
7c0c095b27655f14eabfd9203950b75b76bc940d | 983 | /*
* Automatically generated by jrpcgen 1.0.5 on 3/30/08 8:06 PM
* jrpcgen is part of the "Remote Tea" ONC/RPC package for Java
* See http://remotetea.sourceforge.net for details
*/
package info.ganglia.gmetric4j.xdr.v30x;
import org.acplt.oncrpc.*;
import java.io.IOException;
public class Ganglia_spoof_header implements XdrAble {
public String spoofName;
public String spoofIP;
public Ganglia_spoof_header() {
}
public Ganglia_spoof_header(XdrDecodingStream xdr)
throws OncRpcException, IOException {
xdrDecode(xdr);
}
public void xdrEncode(XdrEncodingStream xdr)
throws OncRpcException, IOException {
xdr.xdrEncodeString(spoofName);
xdr.xdrEncodeString(spoofIP);
}
public void xdrDecode(XdrDecodingStream xdr)
throws OncRpcException, IOException {
spoofName = xdr.xdrDecodeString();
spoofIP = xdr.xdrDecodeString();
}
}
// End of Ganglia_spoof_header.java
| 27.305556 | 63 | 0.700916 |
a836e910c3120b741efae92bc10b10aaa8e79b70 | 789 | package com.password.security.application.domain.rules;
import com.password.security.application.domain.interfaces.PasswordRulesInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.regex.Pattern;
@Slf4j
@Component
public class HaveNonRepeatingCharacters implements PasswordRulesInterface {
@Override
public boolean verify(String password) {
final String haveNonRepeatingCharactersRegex = "^(?!.*(.).*\\1).*$";
log.info("Checking if the password doesn't repeat characters");
Pattern haveNonRepeatingCharactersPattern = Pattern.compile(haveNonRepeatingCharactersRegex,
Pattern.CASE_INSENSITIVE);
return haveNonRepeatingCharactersPattern.matcher(password).find();
}
}
| 32.875 | 100 | 0.762991 |
f04a2ffff80a97d846e18f7481b4d7eb8b099b33 | 8,392 | package edu.cascadia.mobas.campusguidebook.data;
import android.util.Log;
import java.util.TimeZone;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import edu.cascadia.mobas.campusguidebook.application.AppExecutors;
import edu.cascadia.mobas.campusguidebook.data.database.AppDatabase;
import edu.cascadia.mobas.campusguidebook.data.model.Club;
import edu.cascadia.mobas.campusguidebook.data.model.Event;
import edu.cascadia.mobas.campusguidebook.data.model.Sustainability;
import edu.cascadia.mobas.campusguidebook.data.model.User;
public class SampleData {
private static final ZoneId zoneId = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
public static final Event[] events = {
new Event(
102,
"Events and Advocacy Board",
"Roll the dice at EAB and CEB's annual Casino Night!",
"https://padlet-uploads.storage.googleapis.com/621406566/f8a534f5b3cd80d89c87fcf7b2bc9392/Casino_Night_Final__11x17in_.png",
"{\"Date/Time\": \"2022-12-01T11:00:00-8:00[America/Los_Angeles]\",\"Location\": \"ARC Overlook\"}"
),
new Event(
106,
"Engineering Club - Symposium",
"The biggest Engineering event of the year",
"https://www.cascadia.edu/images_calendar/collegerelations/CCEngineersClub.png",
"{\"Date/Time\": \"2022-12-02T09:00:00-8:00[America/Los_Angeles]\",\"Location\": \"ARC Main\"}"
),
new Event(
112,
"Math Club - Weekly Meeting",
"Meets every other Tuesday at 3:30",
"engineers_mindset",
"{\"Date/Time\": \"2022-12-02T03:30:00-8:00[America/Los_Angeles]\",\"Location\": \"CC2-220\"}"
),
new Event(
114,
"Science Club - Weekly Meeting",
"Meets every other Tuesday at 3:30",
null,
"{\"Date/Time\": \"2022-12-04T03:30:00-8:00[America/Los_Angeles]\",\"Location\": \"CC2-220\"}"
),
new Event(
117,
"Art Club - Symposium",
"The biggest Art event of the year",
null,
"{\"Date/Time\": \"2022-12-05T10:00:00-8:00[America/Los_Angeles]\",\"Location\": \"CC2-220\"}"
),
new Event(119,
"Programming Club - Weekly Meeting",
"Meets every other Tuesday at 3:30",
null,
"{\"Date/Time\": \"2022-12-06T10:00:00-8:00[America/Los_Angeles]\",\"Location\": \"CC2-220\"}"
),
new Event(
120,
"Robotics Club - Symposium",
"The biggest Robotics event of the year",
"engineers_mindset",
"{\"Date/Time\": \"2022-12-07T14:00:00-8:00[America/Los_Angeles]\",\"Location\": \"CC2-220\"}"
)
};
public static final Club[] clubs = {
new Club(123,
"Japanese Culture Club",
"The purpose of this club is to provide a comfortable place for the students at Cascadia college to learn and experience Japanese culture together. In our club, we will share traditional Japanese culture such as Japanese calligraphy, origami, karate, etc. together.",
"https://www.cascadia.edu/images_calendar/collegerelations/JapaneseCultureClub.png",
ZonedDateTime.now(zoneId),
"{\"Contact\":\"jcc.cascadia@gmail.com\",\"Advisor\":\"Jane Doe\", \"Meetings\":\"Wednesdays 1:00 pm\",\"Location\":\"CC1-201\"}"
),
new Club(
456,
"CC Engineers Club",
"The engineering club is open to any student who is interested in science, technology, engineering, and math (STEM). Through hands on activities, members of all skill levels will have the opportunity to design, build, and share engineered projects with other creative problem solvers. Get ready to strengthen your skills, create a collection of projects related to your career, and connect with your peers! Some of the club projects we've undertaken include designing 3d printing models, making a video game with python, and electronic prototyping with Arduino.",
"https://www.cascadia.edu/images_calendar/collegerelations/CCEngineersClub.png",
ZonedDateTime.now(zoneId),
"{\"Contact\":\"ccengineers@gmail.com\", \"Meetings\":\"Mondays 5:00 pm\",\"Location\":\"CC2-261\"}"
),
new Club(
789,
"Math Club",
"A group for students who love math or who would like to learn more",
"engineers_mindset",
ZonedDateTime.now(zoneId),
"{\"Contact\":\"Mathy McMathface <mathy@mathface.com>\",\"Meetings\":\"Tuesdays 11:00 am\",\"Location\":\"CC2-301\"}"
),
new Club(
414,
"D&D Club",
"Roll20 until you reach the lands of 5e",
"dnd_club_logo",
ZonedDateTime.now(zoneId),
"{\"Contact\":\"Jasper of Cascadia <jasper@dnd.net>\",\"Meetings\":\"Mondays 7:00\",\"Location\":\"CC2-202\"}"
)
};
public static final Sustainability[] sustainabilities = {
new Sustainability(1L,"Wetlands", "We protect and continue to restore a 58-acre wetland that is one of the biggest floodplain restoration projects completed in the Pacific Northwest in conjunction with UW Bothell. Cascadia classes use the wetland as a living laboratory to study water quality, botany, ecology and wildlife biology. Cascadia students have done wetland stormwater sampling!","sustainability_wetlands", null),
new Sustainability(2L,"Green Buildings", "Our Global Learning and the Arts building (CC3) achieved Leadership in Energy and Environmental Design (LEED) Platinum standard for environmental sustainability and we produce clean, renewable energy via solar panels located on our parking garages and rooftops.","green_buildings", null),
new Sustainability(3L,"Campus Grounds", "Our campus, shared with University of Washington, Bothell, is Certified Salmon Safe and we produce herbs, flowers, fruits and vegetables in our campus Food Forest and Campus Farm using organic practices. We also provide habitat for native pollinators! ","campus_grounds", null),
new Sustainability(4L,"Stormwater Management", "Our Campus is a secondary permitee under the Western Washington Phase II Municipal Stormwater Plan. We manage stormwater with rain gardens, green stormwater infrastructure, signage and education, and working with our 58-acre restored wetland management! You can see many of our projects by visiting the campus, or photos on our social media!","stormwater_management", null),
};
public static final User[] users = new User[]{
new User("John Q. Public", "Math Club, Engineering Club", "OpenSecret"),
};
public static void addAll(AppDatabase appDatabase, AppExecutors appExecutors) {
// clear existing data from all tables and add all the sample data above
appExecutors.diskIO().execute(() -> {
appDatabase.clearAllTables();
// use a transaction to insert all the sample data in one pass
appDatabase.runInTransaction(() -> {
for (Event event : SampleData.events) {
appDatabase.EventDao().insert(event);
}
for (Club club : SampleData.clubs) {
appDatabase.ClubDao().insert(club);
}
for (Sustainability sustainability : SampleData.sustainabilities) {
appDatabase.SustainabilityDao().insert(sustainability);
}
for (User user : SampleData.users)
appDatabase.UserDao().insert(user);
Log.d("AppDatabase", "Adding sample data FINISHED");
});
});
}
} | 61.255474 | 583 | 0.595091 |
5cf2d12cfa20efed56d47c614ce35299d63996f1 | 3,097 | package de.mpii.trinitreloaded.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import de.mpii.trinitreloaded.utils.Config.LoggingLevel;
/**
* A class for debugging and logging purpose.
* Set the value of {@code debugmode} in {@link Config} to <code>true</code>
* to print the debug statements.
*
* Usage:
* Call the static methods, {@code print()} or {@code println()}, to print the debug statements.
* Call the static methods, {@code startLog()} and {@code stopLog()}, to start and stop logging.
*
* @author Madhulika Mohanty (madhulikam@cse.iitd.ac.in)
*
*/
public class Logger {
public static String logFile;
public static boolean logging = false;
static BufferedWriter bw;
public static void startLog(){
String db = "";
if(Config.isRDFDB)
db = "Virtuoso";
else
db = "PostgreSQL";
logFile = Config.queryFile.replace(".txt", "") + "-db-" + db + "-histtype-" +
Config.histType + "-numbuckets-" + Config.numBuckets + "-result-k-" + Config.k + ".log";
System.out.println("Starting to log------>");
System.out.println("***************************************************");
System.out.println("Check the " + logFile + " file for logs.");
System.out.println("***************************************************");
logging = true;
try {
// Rename if already exists.
File f = new File(logFile);
char fileNum = '1';
String newLogFile = "";
boolean changed = false;
while(f.exists()){
newLogFile = logFile + "(" + fileNum + ")";
fileNum++;
f = new File(newLogFile);
changed = true;
}
if(changed)
logFile = newLogFile;
bw = new BufferedWriter(new FileWriter(logFile));
println(Config.getVal(), LoggingLevel.EXPERIMENTS);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void stopLog(){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
logging = false;
System.out.println("Log over!!");
}
public static void print(Object printString, LoggingLevel dlvl) {
if (Config.debugmode == true && dlvl.getNumVal()<=Config.loggingLevel.getNumVal()) {
System.out.println(printString.toString());
}
if(dlvl==LoggingLevel.EXPERIMENTS && logging){
try {
bw.write(printString.toString());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void println(Object printString, LoggingLevel dlvl) {
if (Config.debugmode == true && dlvl.getNumVal()<=Config.loggingLevel.getNumVal()) {
System.out.println(printString.toString() + "\n");
}
if(dlvl==LoggingLevel.EXPERIMENTS && logging){
try {
bw.write(printString.toString());
bw.newLine();
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 29.216981 | 96 | 0.596061 |
4455d2f9f22c8cbdbb3fe917d85f53114847d488 | 2,330 | /*
* © Crown Copyright 2013
*
* 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 uk.nhs.hdn.common.reflection.toString.delegates;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import uk.nhs.hdn.common.exceptions.ShouldNeverHappenException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static uk.nhs.hdn.common.reflection.MethodModifiers.methodModifiers;
public final class EnumMethodDelegate<E extends Enum<E>, V> implements Delegate<V>
{
@SuppressWarnings("MethodNamesDifferingOnlyByCase")
@NotNull
public static <E extends Enum<E>, V> Delegate<V> enumMethodDelegate(@NotNull final E enumValue, @NotNull final String methodName, @NotNull final Class<?>... parameterTypes)
{
final Method method;
try
{
method = enumValue.getClass().getMethod(methodName, parameterTypes);
}
catch (NoSuchMethodException e)
{
throw new IllegalStateException(e);
}
return new EnumMethodDelegate<>(enumValue, method);
}
@NotNull private final E enumValue;
@NotNull private final Method constructor;
public EnumMethodDelegate(@NotNull final E enumValue, @NotNull final Method constructor)
{
this.enumValue = enumValue;
if (!methodModifiers(constructor).isInstance())
{
throw new IllegalArgumentException("constructor is not instance");
}
this.constructor = constructor;
}
@SuppressWarnings({"unchecked", "ThrowInsideCatchBlockWhichIgnoresCaughtException"})
@Nullable
@Override
public V invoke(@NotNull final Object... arguments)
{
try
{
return (V) constructor.invoke(enumValue, arguments);
}
catch (IllegalAccessException e)
{
throw new ShouldNeverHappenException(e);
}
catch (InvocationTargetException e)
{
throw new IllegalStateException(e.getCause());
}
}
}
| 29.493671 | 173 | 0.758369 |
6e37d77e858420af2a0f3b314467dd2738fb6a65 | 855 | package com.przemyslawlusnia.vocabularycreator.core.utils;
import com.przemyslawlusnia.vocabularycreator.BuildConfig;
import java.util.Map;
public class CommonUtils {
public static boolean isEmptyText(String text) {
return text == null || text.isEmpty() || text.equalsIgnoreCase("null");
}
public static void putNonNullObjectToMap(String key, Object value, Map<String, Object> requestBody) {
if (value != null && !isEmptyText(key)) {
requestBody.put(key, value);
}
}
public static boolean isDebug() {
return BuildConfig.DEBUG && BuildConfig.BUILD_TYPE.equals("debug");
}
public static boolean isDevDebug() {
return BuildConfig.DEBUG && BuildConfig.FLAVOR.equals("develop") && BuildConfig.BUILD_TYPE.equals("debug");
}
public static boolean isProd() {
return BuildConfig.FLAVOR.equals("prod");
}
}
| 27.580645 | 111 | 0.718129 |
33af8fdb843ca457e8b03b45b3fdcda235e3e91e | 8,340 | /* ProtectionDomain.java -- A security domain
Copyright (C) 1998, 2003, 2004 Free Software Foundation, Inc.
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
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
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 java.security;
import gnu.classpath.SystemProperties;
/**
* This class represents a group of classes, along with their granted
* permissions. The classes are identified by a {@link CodeSource}. Thus, any
* class loaded from the specified {@link CodeSource} is treated as part of
* this domain. The set of permissions is represented by an instance of
* {@link PermissionCollection}.
*
* <p>Every class in the system will belong to one and only one
* <code>ProtectionDomain</code>.</p>
*
* @author Aaron M. Renn (arenn@urbanophile.com)
* @version 0.0
*/
public class ProtectionDomain
{
/** This is the <code>CodeSource</code> for this protection domain. */
private CodeSource code_source;
/** This is the set of permissions granted to this domain. */
private PermissionCollection perms;
/** The {@link ClassLoader} associated with this domain. */
private ClassLoader classloader;
/** The array of Principals associated with this domain.. */
private Principal[] principals;
/** Post 1.4 the policy may be refreshed! use false for pre 1.4. */
private boolean staticBinding;
/**
* Initializes a new instance of <code>ProtectionDomain</code> representing
* the specified {@link CodeSource} and set of permissions. No permissions
* can be added later to the {@link PermissionCollection} and this contructor
* will call the <code>setReadOnly</code> method on the specified set of
* permissions.
*
* @param codesource
* The {@link CodeSource} for this domain.
* @param permissions
* The set of permissions for this domain.
* @see PermissionCollection#setReadOnly()
*/
public ProtectionDomain(CodeSource codesource, PermissionCollection permissions)
{
this(codesource, permissions, null, null, true);
}
/**
* This method initializes a new instance of <code>ProtectionDomain</code>
* given its {@link CodeSource}, granted permissions, associated
* {@link ClassLoader} and {@link Principal}s.
*
* <p>Similar to the previous constructor, if the designated set of
* permissions is not <code>null</code>, the <code>setReadOnly</code> method
* is called on that set.</p>
*
* @param codesource
* The {@link CodeSource} for this domain.
* @param permissions
* The permission set for this domain.
* @param classloader
* the ClassLoader associated with this domain.
* @param principals
* the array of {@link Principal}s associated with this domain.
* @since 1.4
* @see PermissionCollection#setReadOnly()
*/
public ProtectionDomain(CodeSource codesource,
PermissionCollection permissions,
ClassLoader classloader, Principal[] principals)
{
this(codesource, permissions, classloader, principals, false);
}
private ProtectionDomain(CodeSource codesource,
PermissionCollection permissions,
ClassLoader classloader, Principal[] principals,
boolean staticBinding)
{
super();
code_source = codesource;
if (permissions != null)
{
perms = permissions;
perms.setReadOnly();
}
this.classloader = classloader;
this.principals =
(principals != null ? (Principal[]) principals.clone() : new Principal[0]);
this.staticBinding = staticBinding;
}
/**
* Returns the {@link CodeSource} of this domain.
*
* @return the {@link CodeSource} of this domain.
* @since 1.2
*/
public final CodeSource getCodeSource()
{
return code_source;
}
/**
* Returns the {@link ClassLoader} of this domain.
*
* @return the {@link ClassLoader} of this domain.
* @since 1.4
*/
public final ClassLoader getClassLoader()
{
return this.classloader;
}
/**
* Returns a clone of the {@link Principal}s of this domain.
*
* @return a clone of the {@link Principal}s of this domain.
* @since 1.4
*/
public final Principal[] getPrincipals()
{
return (Principal[]) principals.clone();
}
/**
* Returns the {@link PermissionCollection} of this domain.
*
* @return The {@link PermissionCollection} of this domain.
*/
public final PermissionCollection getPermissions()
{
return perms;
}
/**
* Tests whether or not the specified {@link Permission} is implied by the
* set of permissions granted to this domain.
*
* @param permission
* the {@link Permission} to test.
* @return <code>true</code> if the specified {@link Permission} is implied
* for this domain, <code>false</code> otherwise.
*/
public boolean implies(Permission permission)
{
if (staticBinding)
return (perms == null ? false : perms.implies(permission));
// Else dynamically bound. Do we have it?
// NOTE: this will force loading of Policy.currentPolicy
return Policy.getCurrentPolicy().implies(this, permission);
}
/**
* Returns a string representation of this object. It will include the
* {@link CodeSource} and set of permissions associated with this domain.
*
* @return A string representation of this object.
*/
public String toString()
{
String linesep = SystemProperties.getProperty("line.separator");
StringBuffer sb = new StringBuffer("ProtectionDomain (").append(linesep);
if (code_source == null)
sb.append("CodeSource:null");
else
sb.append(code_source);
sb.append(linesep);
if (classloader == null)
sb.append("ClassLoader:null");
else
sb.append(classloader);
sb.append(linesep);
sb.append("Principals:");
if (principals != null && principals.length > 0)
{
sb.append("[");
Principal pal;
for (int i = 0; i < principals.length; i++)
{
pal = principals[i];
sb.append("'").append(pal.getName())
.append("' of type ").append(pal.getClass().getName());
if (i < principals.length-1)
sb.append(", ");
}
sb.append("]");
}
else
sb.append("none");
sb.append(linesep);
if (!staticBinding) // include all but dont force loading Policy.currentPolicy
if (Policy.isLoaded())
sb.append(Policy.getCurrentPolicy().getPermissions(this));
else // fallback on this one's permissions
sb.append(perms);
else
sb.append(perms);
return sb.append(linesep).append(")").append(linesep).toString();
}
}
| 33.227092 | 83 | 0.676499 |
62b629fec4ff4ecc0cbe411fd589e9417aacff26 | 2,729 | package com.wrc.tutor.business.auth.controller;
import com.tuyang.beanutils.BeanCopyUtils;
import com.wrc.tutor.business.auth.entity.bo.CashoutBO1;
import com.wrc.tutor.business.auth.entity.bo.TeacherBO1;
import com.wrc.tutor.business.auth.entity.vo.TeacherVO;
import com.wrc.tutor.business.auth.service.AuthTeacherService;
import com.wrc.tutor.business.common.exception.ResourceNotFondException;
import com.wrc.tutor.common.entity.dto.TeacherDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/business/auth/teachers/me")
@Api("老师接口")
public class AuthTeacherController {
@Autowired
AuthTeacherService authTeacherService;
@ApiOperation(value="获取我的信息")
@ApiResponses({
@ApiResponse(code=200,message="成功"),
})
@GetMapping
public TeacherVO getById( ) throws ResourceNotFondException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Long id = Long.valueOf((String)authentication.getPrincipal());
TeacherDTO teacherDTO = authTeacherService.getDTOById(id);
return BeanCopyUtils.copyBean(teacherDTO,TeacherVO.class);
}
@ApiOperation(value="部分字段更新我的信息")
@ApiResponses({
@ApiResponse(code=200,message="成功"),
})
@PatchMapping
public TeacherVO patchById(@RequestBody TeacherBO1 teacherBO) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Long id = Long.valueOf((String)authentication.getPrincipal());
TeacherDTO teacherDTO = authTeacherService.patchById(id,teacherBO);
return BeanCopyUtils.copyBean(teacherDTO,TeacherVO.class);
}
@ApiOperation(value="提现")
@ApiResponses({
@ApiResponse(code=200,message="成功"),
})
@PatchMapping("cashout")
public void cashout(@RequestBody CashoutBO1 cashoutBO1) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Long id = Long.valueOf((String)authentication.getPrincipal());
authTeacherService.cashout(id,cashoutBO1);
}
}
| 37.902778 | 95 | 0.766215 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.