repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
helospark/FakeSsh | src/main/java/com/helospark/FakeSsh/SshDebugMessageHandler.java | 977 | package com.helospark.FakeSsh;
import com.helospark.lightdi.annotation.Autowired;
import com.helospark.lightdi.annotation.Component;
import com.helospark.FakeSsh.domain.DebugMessage;
import com.helospark.FakeSsh.util.LoggerSupport;
@Component
public class SshDebugMessageHandler implements SshCommonState {
private LoggerSupport loggerSupport;
@Autowired
public SshDebugMessageHandler(LoggerSupport loggerSupport) {
this.loggerSupport = loggerSupport;
}
@Override
public StateMachineResult enterState(SshConnection connection, byte[] previousPackage) {
try {
DebugMessage debugMessage = new DebugMessage(previousPackage);
loggerSupport.logDebugString(debugMessage.toString());
return StateMachineResult.CLOSED;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean canHandle(byte[] previousPackage) {
PacketType type = PacketType.fromValue(previousPackage[0]);
return type == PacketType.SSH_MSG_DEBUG;
}
}
| mit |
Dacaspex/Fractal | org/jcodec/codecs/mjpeg/tools/Asserts.java | 1716 | package org.jcodec.codecs.mjpeg.tools;
/**
* This class is part of JCodec ( www.jcodec.org )
* This software is distributed under FreeBSD License
*
* @author The JCodec project
*
*/
public class Asserts {
public static void assertEquals(int expected, int actual) {
if (expected != actual) {
throw new AssertionException("assert failed: " + expected
+ " != " + actual);
}
}
public static void assertInRange(String message, int low, int up, int val) {
if (val < low || val > up) {
throw new AssertionException(message);
}
}
public static void assertEpsilonEqualsInt(int[] expected, int[] actual, int eps) {
if (expected.length != actual.length)
throw new AssertionException("arrays of different size");
for (int i = 0; i < expected.length; i++) {
int e = expected[i];
int a = actual[i];
if (Math.abs(e - a) > eps) {
throw new AssertionException(
"array element out of expected diff range");
}
}
}
public static void assertEpsilonEquals(byte[] expected, byte[] actual,
int eps) {
if (expected.length != actual.length)
throw new AssertionException("arrays of different size");
for (int i = 0; i < expected.length; i++) {
int e = expected[i] & 0xff;
int a = actual[i] & 0xff;
if (Math.abs(e - a) > eps) {
throw new AssertionException(
"array element out of expected diff range: "
+ (Math.abs(e - a)));
}
}
}
}
| mit |
HerrB92/obp | OpenBeaconPackage/src/obp/persistence/joda/DatabaseZoneConfigured.java | 237 | package obp.persistence.joda;
/**
* @author Chris
* @param <T> Type representing the database zone
*/
public interface DatabaseZoneConfigured<T> {
void setDatabaseZone(T databaseZone);
T parseZone(String zoneString);
} | mit |
Haehnchen/idea-php-symfony2-plugin | src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/form/FormOptionGotoCompletionRegistrarTest.java | 3323 | package fr.adrienbrault.idea.symfony2plugin.tests.form;
import com.intellij.patterns.PlatformPatterns;
import com.jetbrains.php.lang.PhpFileType;
import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*
* @see fr.adrienbrault.idea.symfony2plugin.form.FormOptionGotoCompletionRegistrar
*/
public class FormOptionGotoCompletionRegistrarTest extends SymfonyLightCodeInsightFixtureTestCase {
public void setUp() throws Exception {
super.setUp();
myFixture.copyFileToProject("classes.php");
myFixture.copyFileToProject("FormOptionGotoCompletionRegistrar.php");
}
protected String getTestDataPath() {
return "src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/form/fixtures";
}
public void testFormReferenceCompletionProvider() {
String[] types = {
"'\\Foo\\Form\\Bar'",
"\\Foo\\Form\\Bar::class",
"new \\Foo\\Form\\Bar()"
};
for (String s : types) {
assertCompletionContains(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $builder \\Symfony\\Component\\Form\\FormBuilderInterface */\n" +
String.format("$builder->add('foo', %s, [\n", s) +
"'<caret>'\n" +
"])",
"configure_options", "class_const_option", "global_const_option", "global_const_define"
);
assertCompletionContains(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $builder \\Symfony\\Component\\Form\\FormBuilderInterface */\n" +
String.format("$builder->add('foo', %s, [\n", s) +
"'<caret>' => ''\n" +
"])",
"configure_options", "class_const_option", "global_const_option", "global_const_define"
);
assertNavigationMatch(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $builder \\Symfony\\Component\\Form\\FormBuilderInterface */\n" +
String.format("$builder->add('foo', %s, [\n", s) +
"'configure_options<caret>'\n" +
"])",
PlatformPatterns.psiElement()
);
assertNavigationMatch(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $builder \\Symfony\\Component\\Form\\FormBuilderInterface */\n" +
String.format("$builder->add('foo', %s, [\n", s) +
"'configure_options<caret>' => null\n" +
"])",
PlatformPatterns.psiElement()
);
}
}
public void testFormReferenceCompletionProviderForDefaultOptionsParameter() {
assertCompletionContains(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $resolver \\Symfony\\Component\\OptionsResolver\\OptionsResolver */\n" +
"$resolver->setDefault('<caret>')",
"configure_options"
);
assertNavigationMatch(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $resolver \\Symfony\\Component\\OptionsResolver\\OptionsResolver */\n" +
"$resolver->setDefault('configure_<caret>options')",
PlatformPatterns.psiElement()
);
}
}
| mit |
OuZhencong/logback | logback-core/src/test/java/ch/qos/logback/core/util/StringCollectionUtilTest.java | 2377 | /**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2013, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.core.util;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
/**
* Unit tests for {@link StringCollectionUtil}.
*
* @author Carl Harris
*/
public class StringCollectionUtilTest {
@Test
public void testRetainMatchingWithNoPatterns() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.retainMatching(values);
assertTrue(values.contains("A"));
}
@Test
public void testRetainMatchingWithMatchingPattern() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.retainMatching(values, "A");
assertTrue(values.contains("A"));
}
@Test
public void testRetainMatchingWithNoMatchingPattern() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.retainMatching(values, "B");
assertTrue(values.isEmpty());
}
@Test
public void testRemoveMatchingWithNoPatterns() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.removeMatching(values);
assertTrue(values.contains("A"));
}
@Test
public void testRemoveMatchingWithMatchingPattern() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.removeMatching(values, "A");
assertTrue(values.isEmpty());
}
@Test
public void testRemoveMatchingWithNoMatchingPattern() throws Exception {
Collection<String> values = stringToList("A");
StringCollectionUtil.removeMatching(values, "B");
assertTrue(values.contains("A"));
}
@SuppressWarnings("unchecked")
private List<String> stringToList(String... values) {
List<String> result = new ArrayList<String>(values.length);
result.addAll(Arrays.asList(values));
return result;
}
}
| mit |
felixhamel/ift287_tp4 | src/main/java/ligueBaseball/models/MatchModel.java | 3053 | package ligueBaseball.models;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import ligueBaseball.entities.DatabaseEntity;
import ligueBaseball.entities.Match;
import ligueBaseball.entities.Official;
import ligueBaseball.exceptions.FailedToRetrieveMatchException;
import ligueBaseball.exceptions.FailedToRetrievePlayersOfTeamException;
import ligueBaseball.exceptions.NotInstanceOfClassException;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
@XmlRootElement
@JsonSerialize(include = Inclusion.NON_NULL)
public class MatchModel
{
private int id = 0;
private String date;
private String time;
private int localTeamScore = 0;
private int visitorTeamScore = 0;
private FieldModel field;
private TeamModel localTeam;
private TeamModel visitorTeam;
private List<OfficialModel> officials = new ArrayList<>();
public MatchModel() {
}
public MatchModel(Match match) throws FailedToRetrieveMatchException, FailedToRetrievePlayersOfTeamException {
this.createFromEntity(match);
}
public int getId()
{
return id;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public String getTime()
{
return time;
}
public void setTime(String t)
{
this.time = t;
}
public int getLocalTeamScore()
{
return localTeamScore;
}
public void setLocalTeamScore(int score)
{
this.localTeamScore = score;
}
public int getVisitorTeamScore()
{
return visitorTeamScore;
}
public void setVisitorTeamScore(int score)
{
this.visitorTeamScore = score;
}
public TeamModel getLocalTeam()
{
return localTeam;
}
public TeamModel getVisitorTeam()
{
return visitorTeam;
}
public FieldModel getField()
{
return field;
}
public List<OfficialModel> getOfficials()
{
return officials;
}
public void createFromEntity(DatabaseEntity entity) throws FailedToRetrieveMatchException, FailedToRetrievePlayersOfTeamException
{
if (!(entity instanceof Match)) {
throw new NotInstanceOfClassException(Match.class);
}
Match match = (Match) entity;
this.id = match.getId();
this.setTime(match.getTime().toString());
this.setDate(match.getDate().toString());
this.setLocalTeamScore(match.getLocalTeamScore());
this.setVisitorTeamScore(match.getVisitorTeamScore());
this.localTeam = new TeamModel(match.getLocalTeam());
this.visitorTeam = new TeamModel(match.getVisitorTeam());
this.field = new FieldModel(match.getField());
// Add officials
for (Official official : match.getOfficials()) {
this.officials.add(new OfficialModel(official));
}
}
}
| mit |
williambai/beyond-webapp | unicom/libs/cbss_order/src/java/com/hoyotech/utils/FileHelper.java | 4486 | package com.hoyotech.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class FileHelper {
private static final String DEFAULT_ENCODING = "utf-8";
public static void write(String fileName, String text){
write(fileName, text, false);
}
public static void write(String fileName, String text, boolean tag) {
write(fileName, text, DEFAULT_ENCODING, tag);
}
public static void write(String fileName, String text, String encoding, boolean tag) {
OutputStreamWriter out = null;
try {
File f = new File(fileName);
if (!f.exists()) {
f.createNewFile();
}
out = new OutputStreamWriter(new FileOutputStream(f, tag), DEFAULT_ENCODING);
out.write(text);
out.flush();
} catch (IOException e) {
} finally {
try {
if(out != null){
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected static String lineSeparator = System.getProperty("line.separator");
public static void writeBinary(String fileName, byte[] text) {
FileOutputStream out = null;
try {
out=new FileOutputStream(fileName);
out.write(text);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static String readFile(String filename) {
return readFile(filename, DEFAULT_ENCODING);
}
public static String readFile(String path, String encoding) {
FileInputStream inStream = null;
String content = "";
try {
inStream = load(path);
byte[] byteBuf = new byte[inStream.available()];
inStream.read(byteBuf);
content = new String(byteBuf, encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inStream != null)
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
public static FileInputStream load(String filename)
throws FileNotFoundException {
return new FileInputStream(filename);
}
public static String[] readLine(String filename, String encoding) {
FileInputStream is = null;
InputStreamReader inReader = null;
BufferedReader reader = null;
List<String> texts = new ArrayList<String>();
try {
is = load(filename);
inReader = new InputStreamReader(is, encoding);
reader = new BufferedReader(inReader);
String line = null;
while ((line = reader.readLine()) != null)
texts.add(line);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
if (inReader != null)
inReader.close();
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return texts.toArray(new String[0]);
}
public static String[] readLines(String filename) {
return readLine(filename, DEFAULT_ENCODING);
}
public static String getClasspath() {
URL url = Thread.currentThread().getContextClassLoader().getResource("/");
String classpath;
if(url== null) {
classpath = FileHelper.class.getResource("/").toString();
} else {
classpath = Thread.currentThread().getContextClassLoader().getResource("/").toString();
}
String path = classpath.substring(6);
// eclipse、bat加载路径不一致
if(path != null && !path.endsWith("/bin/")){
path = path + "/bin/";
}
return (isLinux()) ? "/" + path : path;
}
private static boolean isLinux(){
boolean isLinux = false;
try {
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
if("linux".equalsIgnoreCase(os)){
isLinux = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return isLinux;
}
}
| mit |
kiddingbaby/learn | InvertedIndex/src/main/java/com/test/InvertedIndex/InvertedIndex.java | 4682 | package com.test.InvertedIndex;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import java.io.IOException;
import java.util.StringTokenizer;
public class InvertedIndex {
/**
* Mapper类
* @author hadoop
*
*/
public static class InvertedIndexMapper extends
Mapper<Object,Text,Object,Text>{
private Text keyInfo = new Text();//存储单词和URI的组合
private Text valueInfo = new Text();//存储词频
private FileSplit split;//存储Split对象
@Override
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
//输入3个文件:1.txt("MapReduce is Simple")
//2.txt("MapReduce is powerful is Simple")
//3.txt("Hello MapReduce bye MapReduce")
//获取<key,value>对所属的FileSplit对象
split = (FileSplit)context.getInputSplit();
//map方法中的value值存储的是文本文件中的一行信息(以回车符为行结束标记)。
//map方法中的key值为该行的首字符相对与文本文件的首地址的偏移量。
//StringTokenizer类将每一行拆分成一个个的单词,并将<word,1>作为map方法的结果输出。
StringTokenizer itr = new StringTokenizer(value.toString());
while(itr.hasMoreTokens()){
//key值由单词和URI组成
keyInfo.set(itr.nextToken()+":"+split.getPath().toString());
valueInfo.set("1");
context.write(keyInfo, valueInfo);//输出:<key,value>---<"MapReduce:1.txt",1>
}
}
}
/**
* Combiner类
* @author hadoop
*
*/
public static class InvertedIndexCombiner
extends Reducer<Text, Text, Text, Text>{
private Text info = new Text();
@Override
protected void reduce(Text key, Iterable<Text> values,Context context)
throws IOException, InterruptedException {
//输入:<key,value>---<"MapReduce:1.txt",list(1,1,1,1)>
//key="MapReduce:1.txt",value=list(1,1,1,1);
int sum = 0;
for(Text value : values){
sum += Integer.parseInt(value.toString());
}
int splitIndex = key.toString().indexOf(":");
info.set(key.toString().substring(splitIndex+1)+":"+sum);
key.set(key.toString().substring(0,splitIndex));
context.write(key, info);//输出:<key,value>----<"Mapreduce","0.txt:2">
}
}
/**
* Reducer类
* @author hadoop
*
*/
public static class InvertedIndexReducer
extends Reducer<Text, Text, Text, Text>{
private Text result = new Text();
@Override
protected void reduce(Text key, Iterable<Text> values,Context context)
throws IOException, InterruptedException {
//输入:<"MapReduce",list("0.txt:1","1.txt:1","2.txt:1")>
//输出:<"MapReduce","0.txt:1,1.txt:1,2.txt:1">
String fileList = new String();
for(Text value : values){//value="0.txt:1"
fileList += value.toString()+";";
}
result.set(fileList);
context.write(key, result);//输出:<"MapReduce","0.txt:1,1.txt:1,2.txt:1">
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: InvertedIndex <in> <out>");
System.exit(2);
}
Job job = new Job(conf, "InvertedIndex");
job.setJarByClass(InvertedIndex.class);
//使用InvertedIndexMapper类完成Map过程;
job.setMapperClass(InvertedIndexMapper.class);
//使用InvertedIndexCombiner类完成Combiner过程;
job.setCombinerClass(InvertedIndexCombiner.class);
//使用InvertedIndexReducer类完成Reducer过程;
job.setReducerClass(InvertedIndexReducer.class);
//设置了Map过程和Reduce过程的输出类型,其中设置key的输出类型为Text;
job.setOutputKeyClass(Text.class);
//设置了Map过程和Reduce过程的输出类型,其中设置value的输出类型为Text;
job.setOutputValueClass(Text.class);
//设置任务数据的输入路径;
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
//设置任务输出数据的保存路径;
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
//调用job.waitForCompletion(true) 执行任务,执行成功后退出;
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| mit |
RockyNiu/RockMPG | app/src/main/java/com/rockyniu/calculatempg/listener/SwipeDismissTouchListener.java | 11060 | package com.rockyniu.calculatempg.listener;
/*
* Copyright 2013 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.
*/
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.ListActivity;
import android.app.ListFragment;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
/**
* A {@link android.view.View.OnTouchListener} that makes any {@link android.view.View} dismissable when the
* user swipes (drags her finger) horizontally across the view.
*
* <p><em>For {@link android.widget.ListView} list items that don't manage their own touch events
* (i.e. you're using
* {@link android.widget.ListView#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)}
* or an equivalent listener on {@link android.app.ListActivity} or
* {@link android.app.ListFragment}, use {@link SwipeDismissListViewTouchListener} instead.</em></p>
*
* <p>Example usage:</p>
*
* <pre>
* view.setOnTouchListener(new SwipeDismissTouchListener(
* view,
* null, // Optional token/cookie object
* new SwipeDismissTouchListener.OnDismissCallback() {
* public void onDismiss(View view, Object token) {
* parent.removeView(view);
* }
* }));
* </pre>
*
* <p>This class Requires API level 12 or later due to use of {@link
* android.view.ViewPropertyAnimator}.</p>
*
* @see SwipeDismissListViewTouchListener
*/
public class SwipeDismissTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private View mView;
private DismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private float mDownX;
private float mDownY;
private boolean mSwiping;
private int mSwipingSlop;
private Object mToken;
private VelocityTracker mVelocityTracker;
private float mTranslationX;
/**
* The callback interface used by {@link com.rockyniu.calculatempg.listener.SwipeDismissTouchListener} to inform its client
* about a successful dismissal of the view for which it was created.
*/
public interface DismissCallbacks {
/**
* Called to determine whether the view can be dismissed.
*/
boolean canDismiss(Object token);
/**
* Called when the user has indicated they she would like to dismiss the view.
*
* @param view The originating {@link android.view.View} to be dismissed.
* @param token The optional token passed to this object's constructor.
*/
void onDismiss(View view, Object token);
}
/**
* Constructs a new swipe-to-dismiss touch listener for the given view.
*
* @param view The view to make dismissable.
* @param token An optional token/cookie object to be passed through to the callback.
* @param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss this view.
*/
public SwipeDismissTouchListener(View view, Object token, DismissCallbacks callbacks) {
ViewConfiguration vc = ViewConfiguration.get(view.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = view.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mView = view;
mToken = token;
mCallbacks = callbacks;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// offset because the view is translated during swipe
motionEvent.offsetLocation(mTranslationX, 0);
if (mViewWidth < 2) {
mViewWidth = mView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
// TODO: ensure this is a finger, and set a flag
mDownX = motionEvent.getRawX();
mDownY = motionEvent.getRawY();
if (mCallbacks.canDismiss(mToken)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
}
return false;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX
&& absVelocityY < absVelocityX && mSwiping) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
mView.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
performDismiss();
}
});
} else if (mSwiping) {
// cancel
mView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
mView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
mVelocityTracker.recycle();
mVelocityTracker = null;
mTranslationX = 0;
mDownX = 0;
mDownY = 0;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
float deltaY = motionEvent.getRawY() - mDownY;
if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
mSwiping = true;
mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
mView.getParent().requestDisallowInterceptTouchEvent(true);
// Cancel listview's touch
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex() <<
MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mTranslationX = deltaX;
mView.setTranslationX(deltaX - mSwipingSlop);
// TODO: use an ease-out interpolator or such
mView.setAlpha(Math.max(0f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
private void performDismiss() {
// Animate the dismissed view to zero-height and then fire the dismiss callback.
// This triggers layout on each animation frame; in the future we may want to do something
// smarter and more performant.
final ViewGroup.LayoutParams lp = mView.getLayoutParams();
final int originalHeight = mView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCallbacks.onDismiss(mView, mToken);
// Reset view presentation
mView.setAlpha(1f);
mView.setTranslationX(0);
lp.height = originalHeight;
mView.setLayoutParams(lp);
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
mView.setLayoutParams(lp);
}
});
animator.start();
}
}
| mit |
authy/authy-java | src/test/java/com/authy/api/TokensTest.java | 7500 | package com.authy.api;
import static com.authy.api.Error.Code.TOKEN_INVALID;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.fail;
import com.authy.AuthyApiClient;
import com.authy.AuthyException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class TokensTest extends TestApiBase {
private Tokens tokens;
private int testUserId = 123456;
private String testToken = "123456";
private final String invalidTokenResponse = "{"
+ " \"message\": \"Token is invalid\","
+ " \"token\": \"is invalid\","
+ " \"success\": false,"
+ " \"errors\": {"
+ " \"message\": \"Token is invalid\""
+ " },\n"
+ " \"error_code\": \"60020\""
+ "}";
private final String validTokenResponse = "{"
+ " \"message\": \"Token is valid.\","
+ " \"token\": \"is valid\","
+ " \"success\": \"true\","
+ " \"device\": {"
+ " \"id\": null,"
+ " \"os_type\": \"sms\","
+ " \"registration_date\": 1500648405,"
+ " \"registration_method\": null,"
+ " \"registration_country\": null,"
+ " \"registration_region\": null,"
+ " \"registration_city\": null,"
+ " \"country\": null,"
+ " \"region\": null,"
+ " \"city\": null,"
+ " \"ip\": null,"
+ " \"last_account_recovery_at\": 1494631010,"
+ " \"last_sync_date\": null"
+ " }"
+ "}";
private final String invalidErrorFormatResponse = ""
+ " \"message\": \"Token is invalid\","
+ " \"token\": \"is invalid\","
+ " \"success\": false,"
+ " \"errors\": {"
+ " \"message\": \"Token is invalid\""
+ " },"
+ " \"error_code\": \"60019\""
+ "}";
@Before
public void setUp() {
tokens = new AuthyApiClient(testApiKey, testHost, true).getTokens();
}
@Test
public void tokenFormatValidation() {
String alphaToken = "abcde";
try {
tokens.verify(0, alphaToken);
fail("Tokens must be numeric");
} catch (Exception e) {
Assert.assertTrue("Proper exception must be thrown", e instanceof AuthyException);
}
}
@Test
public void tokenLengthValidation() {
String shortToken = "123";
try {
tokens.verify(0, shortToken);
fail("Tokens must be between 6 and 10 digits");
} catch (Exception e) {
Assert.assertTrue("Proper exception must be thrown", e instanceof AuthyException);
}
String longToken = "12345678901";
try {
tokens.verify(0, longToken);
fail("Tokens must be between 6 and 10 digits");
} catch (Exception e) {
Assert.assertTrue("Proper exception must be thrown", e instanceof AuthyException);
}
}
@Test
public void testInvalidTokenResponse() {
stubFor(get(urlPathMatching("/protected/json/verify/.*"))
.willReturn(aResponse()
.withStatus(401)
.withHeader("Content-Type", "application/json")
.withBody(invalidTokenResponse)));
try {
Token token = tokens.verify(testUserId, testToken);
final Error error = token.getError();
Assert.assertNotNull("Token must have an error", error);
assertEquals(TOKEN_INVALID, error.getCode());
} catch (AuthyException e) {
fail("Token should have an error object");
}
}
@Test
public void testValidTokenResponse() {
stubFor(get(urlPathMatching("/protected/json/verify/.*"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(validTokenResponse)));
try {
Token token = tokens.verify(testUserId, testToken);
Assert.assertNull("Token must not have an error", token.getError());
Assert.assertTrue("Token verification must be successful", token.isOk());
} catch (AuthyException e) {
fail("Verification should be successful");
}
}
@Test
public void testVerificationOptions() {
stubFor(get(urlPathMatching("/protected/json/verify/.*"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(validTokenResponse)));
try {
Map<String, String> options = new HashMap<>();
options.put("force", "false");
Token token = tokens.verify(testUserId, testToken, options);
Assert.assertNull("Token must not have an error", token.getError());
Assert.assertTrue("Token verification must be successful", token.isOk());
} catch (AuthyException e) {
fail("Verification should be successful");
}
}
@Test
public void testInvalidErrorFormatResponse() {
stubFor(get(urlPathMatching("/protected/json/verify/.*"))
.willReturn(aResponse()
.withStatus(401)
.withHeader("Content-Type", "application/json")
.withBody(invalidErrorFormatResponse)));
try {
tokens.verify(testUserId, testToken);
fail("Exception must be thrown");
} catch (AuthyException e) {
return;
}
fail("Proper exception must be thrown");
}
@Test
public void testRequestParameters() {
stubFor(get(urlPathMatching("/protected/json/verify/.*"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(validTokenResponse)));
try {
Token token = tokens.verify(testUserId, testToken);
verify(getRequestedFor(urlPathEqualTo("/protected/json/verify/" + testToken + "/" + testUserId))
.withHeader("X-Authy-API-Key", equalTo(testApiKey)));
Assert.assertNull("Token must not have an error", token.getError());
Assert.assertTrue("Token verification must be successful", token.isOk());
} catch (AuthyException e) {
fail("Verification should be successful");
}
}
} | mit |
psigen/robotutils | src/main/java/robotutils/data/CoordUtils.java | 2769 | /*
* The MIT License
*
* Copyright 2010 Prasanna Velagapudi <psigen@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package robotutils.data;
/**
* Contains helper methods for operations on coordinates.
* @author Prasanna Velagapudi <psigen@gmail.com>
*/
public class CoordUtils {
/**
* Returns Manhattan distance from this point to another.
*
* @param a the first point
* @param b the second point
* @return the Manhattan distance between the two points
*/
public static final double mdist(Coordinate a, Coordinate b) {
if (a == null || b == null) {
throw new IllegalArgumentException("No distance to null array.");
} else if (a.dims() != a.dims()) {
throw new IllegalArgumentException("Coordinate lengths don't match.");
}
int dist = 0;
for (int i = 0; i < a.dims(); i++) {
dist += Math.abs(a.get(i) - b.get(i));
}
return dist;
}
/**
* Returns Euclidean distance from this point to another.
*
* @param a the first point
* @param b the second point
* @return the Euclidean distance between the two points
*/
public static final double edist(Coordinate a, Coordinate b) {
if (a == null || b == null) {
throw new IllegalArgumentException("No distance to null array.");
} else if (a.dims() != a.dims()) {
throw new IllegalArgumentException("Coordinate lengths don't match.");
}
double dist = 0;
for (int i = 0; i < a.dims(); i++) {
dist += (a.get(i) - b.get(i))*(a.get(i) - b.get(i));
}
return Math.sqrt(dist);
}
}
| mit |
girinoboy/lojacasamento | pagseguro-api/src/main/java/br/com/uol/pagseguro/api/installment/InstallmentListingResponseXML.java | 2002 | /*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.installment;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import br.com.uol.pagseguro.api.common.domain.DataList;
/**
* Implementation of {@code DataList<InstallmentDetailXML>}
*
* @author PagSeguro Internet Ltda.
*/
@XmlRootElement(name = "installments")
public class InstallmentListingResponseXML implements DataList<InstallmentDetailXML> {
@XmlElement(name = "installment")
private List<InstallmentDetailXML> installments;
InstallmentListingResponseXML() {
}
@Override
public List<InstallmentDetailXML> getData() {
return installments != null ? installments : Collections.<InstallmentDetailXML>emptyList();
}
@Override
public Integer getTotalPages() {
return 1;
}
@Override
public Integer size() {
return getData().size();
}
@Override
public Boolean isEmpty() {
return getData().isEmpty();
}
@Override
public Iterator<InstallmentDetailXML> iterator() {
return getData().iterator();
}
@Override
public String toString() {
return "InstallmentListingResponseXML{" +
"installments=" + installments +
'}';
}
}
| mit |
lz1asl/CaveSurvey | src/main/java/com/astoev/cave/survey/util/PointUtil.java | 7409 | package com.astoev.cave.survey.util;
import com.astoev.cave.survey.Constants;
import com.astoev.cave.survey.model.Leg;
import com.astoev.cave.survey.model.Point;
import com.astoev.cave.survey.service.Workspace;
import java.sql.SQLException;
import static com.astoev.cave.survey.util.GalleryUtil.generateNextGalleryName;
/**
* Created by IntelliJ IDEA.
* User: astoev
* Date: 3/30/12
* Time: 1:14 AM
* To change this template use File | Settings | File Templates.
* 1-2-3-4-5
* 1-A1-a2-a3
* 2-b1-b2
*
*/
public class PointUtil {
private static final int START_INDEX = 0;
private static final char DELIMITER = '.';
public static Point createFirstPoint() {
Point p = new Point();
p.setName("" + START_INDEX);
return p;
}
public static Point generateNextPoint(Integer aGalleryId) throws SQLException {
Point lastGalleryPoint = Workspace.getCurrentInstance().getLastGalleryPoint(aGalleryId);
Point newPoint = new Point();
String pointName = lastGalleryPoint.getName();
// TODO no middle point support
if (pointName.indexOf(DELIMITER) != -1) {
int delimiterIndex = pointName.indexOf(DELIMITER);
String pointBaseName = pointName.substring(0, delimiterIndex);
if (Character.isLetter(pointName.charAt(pointName.length() - 1))) {
// skip the middle point 2.3A -> 2.4
String index = pointName.substring(delimiterIndex + 1, pointName.length() - 1);
String newName = pointBaseName + DELIMITER + (Integer.parseInt(index) + 1);
newPoint.setName(newName);
} else {
// increase after the delimiter 2.3 -> 2.4
String index = pointName.substring(delimiterIndex + 1);
String newName = pointBaseName + DELIMITER + (Integer.parseInt(index) + 1);
newPoint.setName(newName);
}
} else {
if (Character.isLetter(pointName.charAt(pointName.length() - 1))) {
// increase letter index 2A -> 2B
char letter = pointName.charAt(pointName.length() - 1);
String newName = pointName.substring(pointName.length() - 1) + (char) (letter + 1);
newPoint.setName(newName.toUpperCase(Constants.DEFAULT_LOCALE));
} else {
// increase the index 2 -> 3
newPoint.setName(String.valueOf(Long.parseLong(lastGalleryPoint.getName()) + 1));
}
}
return newPoint;
}
public static Point generateDeviationPoint(Point aPoint) {
Point point = new Point();
point.setName(aPoint.getName() + DELIMITER + START_INDEX);
return point;
}
public static Point createSecondPoint() {
Point p = new Point();
p.setName("" + (START_INDEX + 1));
return p;
}
/**
* Helper method to give the gallery name as string for particular from point
*
* @param pointArg - from point
* @param galleryId - gallery id
* @return gallery's name
* @throws SQLException
*/
public static String getGalleryNameForFromPoint(Point pointArg, Integer galleryId) throws SQLException{
Leg prevLeg = DaoUtil.getLegByToPoint(pointArg);
if (galleryId != null) {
if (prevLeg != null && !prevLeg.getGalleryId().equals(galleryId)) {
return DaoUtil.getGallery(prevLeg.getGalleryId()).getName();
} else {
return DaoUtil.getGallery(galleryId).getName();
}
} else {
// fresh leg for new gallery
return DaoUtil.getGallery(prevLeg.getGalleryId()).getName();
}
}
/**
* Helper method to give the gallery name as string for particular to point
*
* @param galleryId - to point
* @return gallery's name
* @throws SQLException
*/
public static String getGalleryNameForToPoint(Integer galleryId) throws SQLException {
if (galleryId != null) {
return DaoUtil.getGallery(galleryId).getName();
} else {
// fresh leg for new gallery
return generateNextGalleryName();
}
}
public static String getPointGalleryName(String pointName) {
if (StringUtils.isNotEmpty(pointName)) {
StringBuilder gallery = new StringBuilder();
int startIndex = 0;
if (pointName.contains(Constants.FROM_TO_POINT_DELIMITER)) {
startIndex = pointName.indexOf(Constants.FROM_TO_POINT_DELIMITER) + 1;
}
for (int i=startIndex; i< pointName.length(); i++) {
char c = pointName.charAt(i);
if (Character.isLetter(c)) {
gallery.append(c);
} else {
break;
}
}
return gallery.toString();
}
return null;
}
public static String getPointName(String pointName) {
if (StringUtils.isNotEmpty(pointName)) {
StringBuilder point = new StringBuilder();
for (int i=0; i< pointName.length(); i++) {
char c = pointName.charAt(i);
if (Character.isLetter(c)) {
continue;
// } else if (Constants.FROM_TO_POINT_DELIMITER.equals(c)) {
// continue;
} else {
point.append(c);
}
}
return point.toString();
}
return null;
}
public static boolean isMiddlePoint(String fromPointName, String toPointName) {
return !isVector(toPointName)
&& (fromPointName.indexOf(Constants.MIDDLE_POINT_DELIMITER_EXPORT) > 0 || toPointName.indexOf(Constants.MIDDLE_POINT_DELIMITER_EXPORT) > 0
|| fromPointName.indexOf(Constants.FROM_TO_POINT_DELIMITER) > 0 || toPointName.indexOf(Constants.FROM_TO_POINT_DELIMITER) > 0);
}
public static boolean isVector(String toPointName) {
return StringUtils.isEmpty(toPointName);
}
public static String getMiddleFromName(String aMiddlePointName) {
if (aMiddlePointName.contains(Constants.FROM_TO_POINT_DELIMITER)) {
return aMiddlePointName.substring(0, aMiddlePointName.indexOf(Constants.FROM_TO_POINT_DELIMITER));
} else {
return aMiddlePointName;
}
}
public static String getMiddleToName(String aToPointName) {
if (aToPointName.contains(Constants.FROM_TO_POINT_DELIMITER)) {
return aToPointName.substring(aToPointName.indexOf(Constants.FROM_TO_POINT_DELIMITER) + 1,
Math.max(aToPointName.indexOf(Constants.MIDDLE_POINT_DELIMITER_EXPORT),
aToPointName.indexOf(Constants.MIDDLE_POINT_DELIMITER)));
} else {
return aToPointName;
}
}
public static float getMiddleLength(String aPointName) {
int lengthDelimiterIndex = Math.max(aPointName.indexOf(Constants.MIDDLE_POINT_DELIMITER_EXPORT), aPointName.indexOf(Constants.MIDDLE_POINT_DELIMITER));
if (lengthDelimiterIndex > 0) {
String length = aPointName.substring(lengthDelimiterIndex + 1);
return Float.parseFloat(length);
} else {
return 0;
}
}
}
| mit |
kbase/user_and_job_state | src/us/kbase/common/schemamanager/exceptions/IncompatibleSchemaException.java | 679 | package us.kbase.common.schemamanager.exceptions;
/**
* Thrown when there is no way to upgrade from one schema version to another,
* or the schema version of the database is higher than the schema version
* of the the codebase.
* @author gaprice@lbl.gov
*
*/
public class IncompatibleSchemaException extends SchemaException {
private static final long serialVersionUID = 1L;
public IncompatibleSchemaException() { super(); }
public IncompatibleSchemaException(String message) { super(message); }
public IncompatibleSchemaException(String message, Throwable cause) { super(message, cause); }
public IncompatibleSchemaException(Throwable cause) { super(cause); }
}
| mit |
kamiya-tips/Aquarius | server/s6team_aquarius/src/main/java/net/s6team/aquarius/maajan/MaajanTable.java | 979 | package net.s6team.aquarius.maajan;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author kamiya<kamiya.tips@gmail.com>
*/
public class MaajanTable {
private final int MAAJAN_START = 1;
private final int MAAJAN_END = 9;
private final int MAAJAN_JI_END = 7;
private final int MAAJAN_SIZE = 4;
private List<PlayerMaajan> playerMaajanList = new ArrayList<>();
private List<Maajan> maajanList = new ArrayList<Maajan>();
public void init() {
for (MaaianEnum maajanEnum : MaaianEnum.values()) {
int maxSize = MAAJAN_END;
if (maajanEnum == MaaianEnum.JI) {
maxSize = MAAJAN_JI_END;
}
for (int i = MAAJAN_START; i <= maxSize; i++) {
for (int j = 0; j < MAAJAN_SIZE; j++) {
Maajan maajan = new Maajan(maajanEnum, i);
maajanList.add(maajan);
}
}
}
}
public void restart() {
for (PlayerMaajan playerMaajan : playerMaajanList) {
maajanList.addAll(playerMaajan.clearMaajan());
}
}
public void start() {
}
}
| mit |
ZenMaster91/uniovi.ri | cws_model_to_java_skel/src/main/java/uo/ri/model/Factura.java | 6259 | package uo.ri.model;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import alb.util.date.DateUtil;
import alb.util.math.Round;
import uo.ri.model.exception.BusinessException;
import uo.ri.model.types.AveriaStatus;
import uo.ri.model.types.FacturaStatus;
@Entity public class Factura {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
private Long numero;
private Calendar fecha = Calendar.getInstance();
private double importe;
private FacturaStatus facturaStatus = FacturaStatus.SIN_ABONAR;
@OneToMany(mappedBy = "factura") private Set<Averia> averias = new HashSet<>();
@OneToMany(mappedBy = "factura") private Set<Cargo> cargos = new HashSet<>();
/**
* Allocates a invoice object and initializes it so that it represents an
* invoice from the real world.
*/
Factura() {}
/**
* Allocates a invoice object and initializes it so that it represents an
* invoice from the real world.
*
* @param numero is the number of the invoice.
*/
public Factura( Long numero ) {
super();
this.numero = numero;
}
/**
* Allocates a invoice object and initializes it so that it represents an
* invoice from the real world.
*
* @param numero is the number of the invoice.
* @param fecha is the date where the invoice takes place.
*/
public Factura( Long numero, Date fecha ) {
this( numero );
this.fecha.setTime( fecha );
}
/**
* Allocates a invoice object and initializes it so that it represents an
* invoice from the real world.
*
* @param numero is the number of the invoice.
* @param averias the list of faults that are billed in this invoice.
* @throws BusinessException if there's any fault that has not been fixed
* yet.
*/
public Factura( long numero, List<Averia> averias ) throws BusinessException {
this( numero );
for (Averia a : averias) {
if (a.getStatus() != AveriaStatus.TERMINADA) {
throw new BusinessException( "Avería no terminada" );
} else {
addAveria( a );
}
}
}
/**
* Allocates a invoice object and initializes it so that it represents an
* invoice from the real world.
*
* @param numero is the number of the invoice.
* @param fecha is the date where the invoice takes place.
* @param averias the list of faults that are billed in this invoice.
* @throws BusinessException if there's any fault that has not been fixed
* yet.
*/
public Factura( long numero, Date fecha, List<Averia> averias ) throws BusinessException {
this( numero, fecha );
for (Averia a : averias) {
if (a.getStatus() != AveriaStatus.TERMINADA) {
throw new BusinessException( "Avería no terminada" );
} else {
addAveria( a );
}
}
}
/**
* @return the id unique if of the object. JPA.
*/
public long getId() {
return this.id;
}
/**
* @return the number of the invoice.
*/
public Long getNumero() {
return numero;
}
/**
* @return the date of the invoice.
*/
public Date getFecha() {
return new Date( fecha.getTimeInMillis() );
}
/**
* Changes the date of the invoice.
*
* @param fecha is the new date.
*/
public void setFecha( Date fecha ) {
this.fecha.setTime( fecha );
}
/**
* @return the tax percentage corresponding to the period of the invoice.
*/
public double getIva() {
Date limit = DateUtil.fromString( "01/07/2012" );
if (this.fecha != null) {
Date actual = DateUtil.fromString(
"" + this.fecha.get( Calendar.DAY_OF_MONTH ) + "/"
+ this.fecha.get( Calendar.MONTH ) + "/"
+ this.fecha.get( Calendar.YEAR ) + "" );
if (actual.before( limit )) {
return 0.18;
}
}
return 0.21;
}
/**
* @return the status of the invoice.
*/
public FacturaStatus getStatus() {
return facturaStatus;
}
/**
* Changes the status of the invoice.
*
* @param newStatus is the new Status of the invoice.
*/
public void setStatus( FacturaStatus newStatus ) {
this.facturaStatus = newStatus;
}
/**
* @return the amount of the invoice.
*/
public double getImporte() {
return importe;
}
/**
* @return a copy of the original set of faults that will be charged in the
* invoice.
*/
public Set<Averia> getAverias() {
return new HashSet<>( averias );
}
/**
* @return a copy of the original set of payments done to this invoice.
*/
public Set<Cargo> getCargos() {
return new HashSet<>( cargos );
}
/**
* Adds a given fault to the invoice.
*
* @param averia to add to the invoice.
*/
public void addAveria( Averia averia ) {
if (this.getStatus().equals( FacturaStatus.SIN_ABONAR )) {
if (averia.getStatus().equals( AveriaStatus.TERMINADA )) {
Association.Facturar.link( this, averia );
averia.markAsInvoiced();
calcularImporte();
}
}
}
/**
* Deletes the fault from the invoice. Only if the invoice has not been
* payed.
*
* @param averia to remove from the invoice.
*/
public void removeAveria( Averia averia ) {
if (this.getStatus().equals( FacturaStatus.SIN_ABONAR )) {
Association.Facturar.unlink( this, averia );
averia.markBackToFinished();
importe = 0;
}
}
/**
* @return original set of faults that will be charged in the invoice.
*/
Set<Averia> _getAverias() {
return averias;
}
/**
* @return the original set of payments done to this invoice.
*/
Set<Cargo> _getCargos() {
return cargos;
}
/**
* Calculates the import of the invoice.
*
* @throws ParseException if any error while calculating the amount of the
* invoice.
*/
void calcularImporte() {
double acum = 0;
for (Averia averia : averias) {
acum += averia.getImporte();
}
this.importe = Round.twoCents( ( acum * getIva() ) + acum );
}
}
| mit |
menshele/smcplugin | src/com/smcplugin/psi/SmcTokenType.java | 517 | package com.smcplugin.psi;
import com.intellij.psi.tree.IElementType;
import com.smcplugin.SmcLanguage;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
* scmplugin
* Created by lemen on 30.01.2016.
*/
public class SmcTokenType extends IElementType {
public SmcTokenType(@NotNull @NonNls String debugName) {
super(debugName, SmcLanguage.INSTANCE);
}
@Override
public String toString() {
return /*"SmcTokenType." + */super.toString();
}
} | mit |
nico01f/z-pec | ZimbraAdminVersionCheck/src/java/com/zimbra/qa/unittest/TestVersionCheck.java | 12268 | package com.zimbra.qa.unittest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.XMLWriter;
import com.zimbra.common.localconfig.LC;
import com.zimbra.common.soap.AdminConstants;
import com.zimbra.common.soap.Element;
import com.zimbra.common.util.Version;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.client.LmcSession;
import com.zimbra.cs.client.soap.LmcVersionCheckRequest;
import com.zimbra.cs.client.soap.LmcVersionCheckResponse;
import com.zimbra.cs.service.versioncheck.VersionCheck;
import com.zimbra.cs.util.BuildInfo;
import com.zimbra.cs.versioncheck.VersionUpdate;
/**
* @author Greg Solovyev
*/
public class TestVersionCheck extends TestCase {
private String versionCheckURL;
private String lastResponse;
private boolean httpEnabled = true;
@Override
public void setUp() throws Exception {
Provisioning prov = Provisioning.getInstance();
Config config;
config = prov.getConfig();
this.versionCheckURL = config.getAttr(Provisioning.A_zimbraVersionCheckURL);
this.lastResponse = config.getAttr(Provisioning.A_zimbraVersionCheckLastResponse);
Map<String, String> attrs = new HashMap<String, String>();
Server server = prov.getLocalServer();
attrs.put(Provisioning.A_zimbraVersionCheckURL, "http://localhost:"+server.getAttr(Provisioning.A_zimbraMailPort, "80")+"/zimbra/testversion.xml");
prov.modifyAttrs(config, attrs, true);
generateTestVersionXML();
String mode = server.getAttr(Provisioning.A_zimbraMailMode, "");
if ("http".equals(mode) || "both".equals(mode)) {
httpEnabled = true;
} else {
httpEnabled = false;
}
}
private void generateTestVersionXML() {
try {
FileWriter fileWriter = new FileWriter(LC.mailboxd_directory.value()+"/webapps/zimbra/testversion.xml");
XMLWriter xw = new XMLWriter(fileWriter, org.dom4j.io.OutputFormat.createPrettyPrint());
Document doc = DocumentHelper.createDocument();
org.dom4j.Element rootEl = DocumentHelper.createElement("versionCheck");
rootEl.addAttribute("status", "1");
org.dom4j.Element updatesEl = DocumentHelper.createElement("updates");
doc.add(rootEl);
rootEl.add(updatesEl);
org.dom4j.Element updateEl = DocumentHelper.createElement("update");
updateEl.addAttribute("type", "major");
updateEl.addAttribute("shortversion", Integer.toString(Integer.parseInt(BuildInfo.MAJORVERSION)+1)+".0.0");
updateEl.addAttribute("version", Integer.toString(Integer.parseInt(BuildInfo.MAJORVERSION)+1)+".0.0_GA");
updateEl.addAttribute("platform", BuildInfo.PLATFORM);
updateEl.addAttribute("buildtype", BuildInfo.TYPE);
updateEl.addAttribute("release", Integer.toString(Integer.parseInt(BuildInfo.BUILDNUM)+10));
updateEl.addAttribute("critical", "0");
updateEl.addAttribute("updateURL", "http://www.zimbra.com/community/downloads.html");
updateEl.addAttribute("description", "description");
updatesEl.add(updateEl);
updateEl = DocumentHelper.createElement("update");
updateEl.addAttribute("type", "minor");
updateEl.addAttribute("shortversion",String.format("%s.%d.0", BuildInfo.MAJORVERSION,Integer.parseInt(BuildInfo.MINORVERSION)+1));
updateEl.addAttribute("version", String.format("%s.%d.0_GA_%d", BuildInfo.MAJORVERSION,Integer.parseInt(BuildInfo.MINORVERSION)+1,Integer.parseInt(BuildInfo.BUILDNUM)+5));
updateEl.addAttribute("platform", BuildInfo.PLATFORM);
updateEl.addAttribute("buildtype", BuildInfo.TYPE);
updateEl.addAttribute("release", Integer.toString(Integer.parseInt(BuildInfo.BUILDNUM)+5));
updateEl.addAttribute("critical", "0");
updateEl.addAttribute("updateURL", "http://www.zimbra.com/community/downloads.html");
updateEl.addAttribute("description", "description");
updatesEl.add(updateEl);
updateEl = DocumentHelper.createElement("update");
updateEl.addAttribute("type", "micro");
updateEl.addAttribute("shortversion",String.format("%s.%s.%d", BuildInfo.MAJORVERSION,BuildInfo.MINORVERSION,Integer.parseInt(BuildInfo.MICROVERSION)+1));
updateEl.addAttribute("version", String.format("%s.%s.%d_GA_%d", BuildInfo.MAJORVERSION,BuildInfo.MINORVERSION,Integer.parseInt(BuildInfo.MICROVERSION)+1,Integer.parseInt(BuildInfo.BUILDNUM)+2));
updateEl.addAttribute("platform", BuildInfo.PLATFORM);
updateEl.addAttribute("buildtype", BuildInfo.TYPE);
updateEl.addAttribute("release", Integer.toString(Integer.parseInt(BuildInfo.BUILDNUM)+2));
updateEl.addAttribute("critical", "1");
updateEl.addAttribute("updateURL", "http://www.zimbra.com/community/downloads.html");
updateEl.addAttribute("description", "description");
updatesEl.add(updateEl);
updateEl = DocumentHelper.createElement("update");
updateEl.addAttribute("type", "build");
updateEl.addAttribute("shortversion",String.format("%s.%s.%s", BuildInfo.MAJORVERSION,BuildInfo.MINORVERSION,Integer.toString(Integer.parseInt(BuildInfo.MICROVERSION)+1)));
updateEl.addAttribute("version", String.format("%s.%s.%s_GA_%d", BuildInfo.MAJORVERSION,BuildInfo.MINORVERSION,BuildInfo.MICROVERSION,Integer.parseInt(BuildInfo.BUILDNUM)+1));
updateEl.addAttribute("platform", BuildInfo.PLATFORM);
updateEl.addAttribute("buildtype", BuildInfo.TYPE);
updateEl.addAttribute("release", Integer.toString(Integer.parseInt(BuildInfo.BUILDNUM)+1));
updateEl.addAttribute("critical", "1");
updateEl.addAttribute("updateURL", "http://www.zimbra.com/community/downloads.html");
updateEl.addAttribute("description", "description");
updatesEl.add(updateEl);
xw.write(doc);
xw.flush();
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
private void cleanup() throws Exception {
Provisioning prov = Provisioning.getInstance();
Config config;
config = prov.getConfig();
Map<String, String> attrs = new HashMap<String, String>();
attrs.put(Provisioning.A_zimbraVersionCheckURL, this.versionCheckURL);
attrs.put(Provisioning.A_zimbraVersionCheckLastResponse, this.lastResponse);
prov.modifyAttrs(config, attrs, true);
File testxmlfile = new File(LC.mailboxd_directory.value()+"/webapps/zimbra/testversion.xml");
testxmlfile.delete();
}
@Override
public void tearDown() throws Exception {
cleanup();
}
public void testSOAP() throws Exception {
if (!httpEnabled) {
ZimbraLog.test.warn("http is not enabled on this server, skipping version test");
return;
}
LmcSession session = TestUtil.getAdminSoapSession();
LmcVersionCheckRequest checkRequest = new LmcVersionCheckRequest();
checkRequest.setAction(AdminConstants.VERSION_CHECK_CHECK);//this should retreive the new version from http://localhost/zimbra/test/testversion.xml
checkRequest.setSession(session);
String url = TestUtil.getAdminSoapUrl();
LmcVersionCheckResponse resp = (LmcVersionCheckResponse) checkRequest.invoke(url);
//this response is empty - nothing to check except that we got it
assertNotNull(resp);
//check the response in LDAP
Provisioning prov = Provisioning.getInstance();
Config config;
config = prov.getConfig();
String savedResp = config.getAttr(Provisioning.A_zimbraVersionCheckLastResponse);
assertNotNull(savedResp);
//check response from admin service
LmcVersionCheckRequest versionRequest = new LmcVersionCheckRequest();
versionRequest.setAction(AdminConstants.VERSION_CHECK_STATUS);
versionRequest.setSession(session);
LmcVersionCheckResponse versionResp = (LmcVersionCheckResponse)versionRequest.invoke(url);
//the test xml should contain one major update, one minor update and two micro updates (critical and non-critical)
List <VersionUpdate> updates = versionResp.getUpdates();
int counter=0;
int majorCounter=0;
int minorCounter=0;
int microCounter=0;
int buildCounter=0;
for(Iterator <VersionUpdate> iter = updates.iterator();iter.hasNext();){
counter++;
VersionUpdate update = iter.next();
assertNotNull(update);
assertTrue("Update is older than current version",Version.compare(BuildInfo.VERSION, update.getShortversion()) < 0);
assertNotNull(update.getUpdateURL());
assertNotNull(update.getType());
assertNotNull(update.getShortversion());
String updateType = update.getType();
if(updateType.equalsIgnoreCase("major")) {
majorCounter++;
} else if (updateType.equalsIgnoreCase("minor")) {
minorCounter++;
} else if(updateType.equalsIgnoreCase("micro")) {
microCounter++;
} else if(updateType.equalsIgnoreCase("build")) {
buildCounter++;
}
}
assertEquals("Wrong number of updates in SOAP response",4,counter);
assertEquals("Wring number of major updates parsed",majorCounter,1);
assertEquals("Wring number of minor updates parsed",minorCounter,1);
assertEquals("Wring number of micro updates parsed",microCounter,1);
assertEquals("Wring number of build updates parsed",buildCounter,1);
}
public void testCheckVersion() throws Exception {
if (!httpEnabled) {
ZimbraLog.test.warn("http is not enabled on this server, skipping version test");
return;
}
//the idea is to test retreiving an XML and putting it into LDAP
VersionCheck.checkVersion(); //this should retreive the new version from http://localhost/zimbra/test/testversion.xml
Provisioning prov = Provisioning.getInstance();
Config config;
config = prov.getConfig();
String resp = config.getAttr(Provisioning.A_zimbraVersionCheckLastResponse);
assertNotNull(resp);
Element respDoc = Element.parseXML(resp);
assertNotNull(respDoc);
boolean hasUpdates = respDoc.getAttributeBool(AdminConstants.A_VERSION_CHECK_STATUS, false);
assertTrue("Update XML document status is not 1 or true",hasUpdates);
Element eUpdates = respDoc.getElement(AdminConstants.E_UPDATES);
assertNotNull(eUpdates);
int counter=0;
int majorCounter=0;
int minorCounter=0;
int microCounter=0;
int buildCounter=0;
for (Element e : eUpdates.listElements()) {
counter++;
String updateType = e.getAttribute(AdminConstants.A_UPDATE_TYPE);
if(updateType.equalsIgnoreCase("major")) {
majorCounter++;
} else if (updateType.equalsIgnoreCase("minor")) {
minorCounter++;
} else if(updateType.equalsIgnoreCase("micro")) {
microCounter++;
} else if(updateType.equalsIgnoreCase("build")) {
buildCounter++;
}
}
assertEquals("Wring number of updates parsed",counter,4);
assertEquals("Wring number of major updates parsed",majorCounter,1);
assertEquals("Wring number of minor updates parsed",minorCounter,1);
assertEquals("Wring number of micro updates parsed",microCounter,1);
assertEquals("Wring number of build updates parsed",buildCounter,1);
}
}
| mit |
Chormon/UltimateLib | src/main/java/pl/chormon/ultimatelib/utils/MsgUtils.java | 3686 | /*
* The MIT License
*
* Copyright 2014 Chormon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package pl.chormon.ultimatelib.utils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
/**
*
* @author Chormon
*/
public class MsgUtils {
private static ConsoleCommandSender console;
private String prefix = "&e[UltimateLib]&r";
private final static String info = "&a[INFO]&r ";
private final static String warning = "&e[WARNING]&r ";
private final static String error = "&c[ERROR]&r ";
public MsgUtils() {
}
public MsgUtils(String prefix) {
this.prefix = prefix;
}
public void setConsole(ConsoleCommandSender console) {
MsgUtils.console = console;
}
private void log(String msg, String prefix, Object... vars) {
String[] split = fixMsg(msg, vars).split("\n");
String pre = fixMsg(this.prefix + prefix);
for(String str : split) {
console.sendMessage(pre + str);
}
}
public void info(String msg) {
log(msg, info, (Object) null);
}
public void info(String msg, Object... vars) {
log(msg, info, vars);
}
public void warning(String msg) {
log(msg, warning, (Object) null);
}
public void warning(String msg, Object... vars) {
log(msg, warning, vars);
}
public void error(String msg) {
log(msg, error, (Object) null);
}
public void error(String msg, Object... vars) {
log(msg, error, vars);
}
public static void msg(CommandSender cs, String msg) {
msg(cs, msg, (Object) null);
}
public static void msg(CommandSender cs, String msg, Object... vars) {
String[] split = fixMsg(msg, vars).split("\n");
for(String str : split) {
cs.sendMessage(str);
}
}
public static void broadcast(String msg) {
broadcast(msg, (Object) null);
}
public static void broadcast(String msg, Object... vars) {
String[] split = fixMsg(msg, vars).split("\n");
for(String str : split) {
Bukkit.getServer().broadcastMessage(str);
}
}
private static String fixMsg(String msg, Object... vars) {
if (vars != null) {
for (int i = 0; i < vars.length; i++) {
if (vars[i] == null) {
break;
}
msg = msg.replace(vars[i].toString(), vars[++i].toString());
}
}
return ChatColor.translateAlternateColorCodes('&', msg);
}
}
| mit |
Bernardo-MG/jpa-example | src/test/java/com/bernardomg/example/jpa/test/integration/enumeration/ITEnumerationEntityQueryJpql.java | 4265 | /**
* The MIT License (MIT)
* <p>
* Copyright (c) 2016-2021 the the original author or authors.
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.bernardomg.example.jpa.test.integration.enumeration;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.bernardomg.example.jpa.model.enumeration.NumbersEnum;
import com.bernardomg.example.jpa.test.config.annotation.PersistenceIntegrationTest;
/**
* Integration tests for a {@code EnumerationEntity} testing it loads values
* correctly by using JPQL queries.
*
* @author Bernardo Martínez Garrido
*/
@PersistenceIntegrationTest
public class ITEnumerationEntityQueryJpql
extends AbstractJUnit4SpringContextTests {
/**
* The persistence entity manager.
*/
@Autowired
private EntityManager entityManager;
/**
* The query to acquire all the entities by the ordinal value.
*/
@Value("${query.findAllByEnumOrdinal}")
private String findAllByOrdinal;
/**
* The query to acquire all the entities by the string value.
*/
@Value("${query.findAllByEnumString}")
private String findAllByString;
/**
* Default constructor.
*/
public ITEnumerationEntityQueryJpql() {
super();
}
/**
* Tests that retrieving all the entities with a specific enum, through the
* ordinal value, gives the correct number of them.
*/
@Test
public final void testGetEntity_Ordinal() {
final Integer readCount;
readCount = getOrdinalQuery().getResultList().size();
// Reads the expected number of entities
Assertions.assertEquals(2, readCount);
}
/**
* Tests that retrieving all the entities with a specific enum, through the
* string value, gives the correct number of them.
*/
@Test
public final void testGetEntity_String() {
final Integer readCount;
readCount = getStringQuery().getResultList().size();
// Reads the expected number of entities
Assertions.assertEquals(2, readCount);
}
/**
* Returns the query for the test.
*
* @return the query for the test
*/
private final Query getOrdinalQuery() {
final NumbersEnum value; // Value to find
final Query query;
// Queried value
value = NumbersEnum.TWO;
query = entityManager.createQuery(findAllByOrdinal);
query.setParameter("enum", value);
return query;
}
/**
* Returns the query for the test.
*
* @return the query for the test
*/
private final Query getStringQuery() {
final NumbersEnum value; // Value to find
final Query query;
// Queried value
value = NumbersEnum.TWO;
query = entityManager.createQuery(findAllByString);
query.setParameter("enum", value);
return query;
}
}
| mit |
Redcley/iot-insider-lab | platforms/android/HelloIoT/iothub-java-client/src/main/java/com/microsoft/azure/iothub/transport/https/HttpsBatchMessage.java | 7272 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package com.microsoft.azure.iothub.transport.https;
import com.microsoft.azure.iothub.Message;
import com.microsoft.azure.iothub.MessageProperty;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
//import javax.naming.SizeLimitExceededException;
/**
* Builds a batched IoT Hub request body as a JSON array. The batched message
* has a maximum size of 256 kb.
*/
public final class HttpsBatchMessage implements HttpsMessage
{
// Note: this limit is defined by the IoT Hub.
public static final int SERVICEBOUND_MESSAGE_MAX_SIZE_BYTES = 255 * 1024 - 1;
/**
* The value for the "content-type" header field in a batched HTTPS
* request.
*/
public static String HTTPS_BATCH_CONTENT_TYPE = "application/vnd.microsoft.iothub.json";
/**
* The charset used to encode IoT Hub messages. The server will interpret
* the JSON array using UTF-8 by default according to RFC4627.
*/
public static Charset BATCH_CHARSET = StandardCharsets.UTF_8;
/** The current batched message body. */
protected String batchBody;
/** The current number of messages in the batch. */
protected int numMsgs;
/** Constructor. Initializes the batch body as an empty JSON array. */
public HttpsBatchMessage()
{
// Codes_SRS_HTTPSBATCHMESSAGE_11_001: [The constructor shall initialize the batch message with the body as an empty JSON array.]
this.batchBody = "[]";
this.numMsgs = 0;
}
/**
* Adds a message to the batch.
*
* @param msg the message to be added.
*
* @throws Exception if adding the message causes the
* batched message to exceed 256 kb in size. The batched message will remain
* as if the message was never added.
*/
public void addMessage(HttpsSingleMessage msg)
throws Exception
{
String jsonMsg = msgToJson(msg);
// Codes_SRS_HTTPSBATCHMESSAGE_11_002: [The function shall add the message as a JSON object appended to the current JSON array.]
String newBatchBody = addJsonObjToArray(jsonMsg, this.batchBody);
// Codes_SRS_HTTPSBATCHMESSAGE_11_008: [If adding the message causes the batched message to exceed 256 kb in size, the function shall throw a SizeLimitExceededException.]
// Codes_SRS_HTTPSBATCHMESSAGE_11_009: [If the function throws a SizeLimitExceedException, the batched message shall remain as if the message was never added.]
byte[] newBatchBodyBytes = newBatchBody.getBytes(BATCH_CHARSET);
if (newBatchBodyBytes.length > SERVICEBOUND_MESSAGE_MAX_SIZE_BYTES) {
String errMsg = String.format("Service-bound message size (%d bytes) cannot exceed %d bytes.\n",
newBatchBodyBytes.length, SERVICEBOUND_MESSAGE_MAX_SIZE_BYTES);
throw new Exception(errMsg);
}
this.batchBody = newBatchBody;
this.numMsgs++;
}
/**
* Returns the current batch body as a UTF-8 encoded byte array.
*
* @return the current batch body as a UTF-8 encoded byte array.
*/
public byte[] getBody()
{
// Codes_SRS_HTTPSBATCHMESSAGE_11_006: [The function shall return the current batch message body.]
// Codes_SRS_HTTPSBATCHMESSAGE_11_007: [The batch message body shall be encoded using UTF-8.]
return this.batchBody.getBytes(BATCH_CHARSET);
}
/**
* Returns the message content-type as 'application/vnd.microsoft.iothub.json'.
*
* @return the message content-type as 'application/vnd.microsoft.iothub.json'.
*/
public String getContentType()
{
// Codes_SRS_HTTPSBATCHMESSAGE_11_011: [The function shall return 'application/vnd.microsoft.iothub.json'.]
return HTTPS_BATCH_CONTENT_TYPE;
}
/**
* Returns an empty list of properties for the batched message.
*
* @return an empty list of properties for the batched message.
*/
public MessageProperty[] getProperties()
{
// Codes_SRS_HTTPSBATCHMESSAGE_11_012: [The function shall return an empty array.]
return new MessageProperty[0];
}
/**
* Returns the number of messages currently in the batch.
*
* @return the number of messages currently in the batch.
*/
public int numMessages()
{
// Codes_SRS_HTTPSBATCHMESSAGE_11_010: [The function shall return the number of messages currently in the batch.]
return this.numMsgs;
}
/**
* Converts a service-bound message to a JSON object with the correct
* format.
*
* @param msg the message to be converted to a corresponding JSON object.
*
* @return the JSON string representation of the message.
*/
protected static String msgToJson(HttpsSingleMessage msg)
{
StringBuilder jsonMsg = new StringBuilder("{");
// Codes_SRS_HTTPSBATCHMESSAGE_11_003: [The JSON object shall have the field "body" set to the raw message.]
jsonMsg.append("\"body\":");
jsonMsg.append("\"" + msg.getBodyAsString() + "\",");
// Codes_SRS_HTTPSBATCHMESSAGE_11_004: [The JSON object shall have the field "base64Encoded" set to whether the raw message was Base64-encoded.]
jsonMsg.append("\"base64Encoded\":");
jsonMsg.append(Boolean.toString(msg.isBase64Encoded()));
// Codes_SRS_HTTPSBATCHMESSAGE_11_005: [The JSON object shall have the field "properties" set to a JSON object which has the field "content-type" set to the content type of the raw message.]
MessageProperty[] properties = msg.getProperties();
int numProperties = properties.length;
if (numProperties > 0)
{
jsonMsg.append(",");
jsonMsg.append("\"properties\":");
jsonMsg.append("{");
for (int i = 0; i < numProperties - 1; ++i)
{
MessageProperty property = properties[i];
jsonMsg.append("\"" + property.getName() + "\":");
jsonMsg.append("\"" + property.getValue() + "\",");
}
if (numProperties > 0)
{
MessageProperty property = properties[numProperties - 1];
jsonMsg.append("\"" + property.getName() + "\":");
jsonMsg.append("\"" + property.getValue() + "\"");
}
jsonMsg.append("}");
}
jsonMsg.append("}");
return jsonMsg.toString();
}
/**
* Adds a JSON object to a JSON array.
*
* @param jsonObj the object to be added to the JSON array.
* @param jsonArray the JSON array.
*
* @return the JSON string representation of the JSON array with the object
* added.
*/
protected static String addJsonObjToArray(String jsonObj, String jsonArray)
{
if (jsonArray.equals("[]"))
{
return "[" + jsonObj + "]";
}
// removes the closing brace of the JSON array.
String openJsonArray = jsonArray.substring(0, jsonArray.length() - 1);
return openJsonArray + "," + jsonObj + "]";
}
}
| mit |
Azure/azure-sdk-for-java | sdk/hybridkubernetes/azure-resourcemanager-hybridkubernetes/src/main/java/com/azure/resourcemanager/hybridkubernetes/fluent/package-info.java | 326 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
/** Package containing the service clients for HybridKubernetesManagementClient. Hybrid Kubernetes Client. */
package com.azure.resourcemanager.hybridkubernetes.fluent;
| mit |
nithinvnath/PAVProject | com.ibm.wala.util/src/com/ibm/wala/util/intset/BitVector.java | 10138 | /*******************************************************************************
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wala.util.intset;
import java.io.Serializable;
/**
*/
public class BitVector extends BitVectorBase<BitVector> implements Serializable {
private static final long serialVersionUID = 9087259335807761617L;
private final static int MAX_BITS = Integer.MAX_VALUE / 4;
public BitVector() {
this(1);
}
/**
* Creates an empty string with the specified size.
*
* @param nbits the size of the string
*/
public BitVector(int nbits) {
if (nbits > MAX_BITS || nbits < 0) {
throw new IllegalArgumentException("invalid nbits: " + nbits);
}
bits = new int[subscript(nbits) + 1];
}
/**
* Expand this bit vector to size newCapacity.
*/
void expand(int newCapacity) {
int[] oldbits = bits;
bits = new int[subscript(newCapacity) + 1];
for (int i = 0; i < oldbits.length; i++) {
bits[i] = oldbits[i];
}
}
/**
* Creates a copy of a Bit String
*
* @param s the string to copy
* @throws IllegalArgumentException if s is null
*/
public BitVector(BitVector s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
bits = new int[s.bits.length];
copyBits(s);
}
/**
* Sets a bit.
*
* @param bit the bit to be set
*/
@Override
public final void set(int bit) {
int shiftBits = bit & LOW_MASK;
int subscript = subscript(bit);
if (subscript >= bits.length) {
expand(bit);
}
try {
bits[subscript] |= (1 << shiftBits);
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Clears a bit.
*
* @param bit the bit to be cleared
*/
@Override
public final void clear(int bit) {
if (bit < 0) {
throw new IllegalArgumentException("invalid bit: " + bit);
}
int ss = subscript(bit);
if (ss >= bits.length) {
return;
}
int shiftBits = bit & LOW_MASK;
bits[ss] &= ~(1 << shiftBits);
}
/**
* Gets a bit.
*
* @param bit the bit to be gotten
*/
@Override
public final boolean get(int bit) {
if (bit < 0) {
throw new IllegalArgumentException("illegal bit: " + bit);
}
int ss = subscript(bit);
if (ss >= bits.length) {
return false;
}
int shiftBits = bit & LOW_MASK;
return ((bits[ss] & (1 << shiftBits)) != 0);
}
/**
* Return the NOT of a bit string
*/
public static BitVector not(BitVector s) {
BitVector b = new BitVector(s);
b.not();
return b;
}
/**
* Logically ANDs this bit set with the specified set of bits.
*
* @param set the bit set to be ANDed with
*/
@Override
public final void and(BitVector set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
if (this == set) {
return;
}
int n = Math.min(bits.length, set.bits.length);
for (int i = n - 1; i >= 0;) {
bits[i] &= set.bits[i];
i--;
}
for (int i = n; i < bits.length; i++) {
bits[i] = 0;
}
}
/**
* Return a new bit string as the AND of two others.
*/
public static BitVector and(BitVector b1, BitVector b2) {
if (b1 == null) {
throw new IllegalArgumentException("null b1");
}
if (b2 == null) {
throw new IllegalArgumentException("null b2");
}
BitVector b = new BitVector(b1);
b.and(b2);
return b;
}
/**
* Logically ORs this bit set with the specified set of bits.
*
* @param set the bit set to be ORed with
*/
@Override
public final void or(BitVector set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
if (this == set) { // should help alias analysis
return;
}
ensureCapacity(set);
int n = Math.min(bits.length, set.bits.length);
for (int i = n - 1; i >= 0;) {
bits[i] |= set.bits[i];
i--;
}
}
private void ensureCapacity(BitVector set) {
if (set.bits.length > bits.length) {
expand(BITS_PER_UNIT * set.bits.length - 1);
}
}
/**
* Logically ORs this bit set with the specified set of bits. This is performance-critical, and so, a little ugly in an attempt to
* help out the compiler.
*
* @param set
* @return the number of bits added to this.
* @throws IllegalArgumentException if set is null
*/
public final int orWithDelta(BitVector set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
int delta = 0;
ensureCapacity(set);
int[] otherBits = set.bits;
int n = Math.min(bits.length, otherBits.length);
for (int i = n - 1; i >= 0;) {
int v1 = bits[i];
int v2 = otherBits[i];
if (v1 != v2) {
delta -= Bits.populationCount(v1);
int v3 = v1 | v2;
delta += Bits.populationCount(v3);
bits[i] = v3;
}
i--;
}
return delta;
}
/**
* Return a new FixedSizeBitVector as the OR of two others
*/
public static BitVector or(BitVector b1, BitVector b2) {
if (b1 == null) {
throw new IllegalArgumentException("null b1");
}
if (b2 == null) {
throw new IllegalArgumentException("null b2");
}
BitVector b = new BitVector(b1);
b.or(b2);
return b;
}
/**
* Return a new FixedSizeBitVector as the XOR of two others
*/
public static BitVector xor(BitVector b1, BitVector b2) {
if (b1 == null) {
throw new IllegalArgumentException("null b1");
}
if (b2 == null) {
throw new IllegalArgumentException("null b2");
}
BitVector b = new BitVector(b1);
b.xor(b2);
return b;
}
/**
* Logically XORs this bit set with the specified set of bits.
*
* @param set the bit set to be XORed with
* @throws IllegalArgumentException if set is null
*/
@Override
public final void xor(BitVector set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
ensureCapacity(set);
int n = Math.min(bits.length, set.bits.length);
for (int i = n - 1; i >= 0;) {
bits[i] ^= set.bits[i];
i--;
}
}
/**
* Check if the intersection of the two sets is empty
*
* @param other the set to check intersection with
* @throws IllegalArgumentException if other is null
*/
@Override
public final boolean intersectionEmpty(BitVector other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
int n = Math.min(bits.length, other.bits.length);
for (int i = n - 1; i >= 0;) {
if ((bits[i] & other.bits[i]) != 0) {
return false;
}
i--;
}
return true;
}
/**
* Calculates and returns the set's size in bits. The maximum element in the set is the size - 1st element.
*/
@Override
public final int length() {
return bits.length << LOG_BITS_PER_UNIT;
}
/**
* Compares this object against the specified object.
*
* @param B the object to compare with
* @return true if the objects are the same; false otherwise.
*/
@Override
public final boolean sameBits(BitVector B) {
if (B == null) {
throw new IllegalArgumentException("null B");
}
if (this == B) { // should help alias analysis
return true;
}
int n = Math.min(bits.length, B.bits.length);
if (bits.length > B.bits.length) {
for (int i = n; i < bits.length; i++) {
if (bits[i] != 0)
return false;
}
} else if (B.bits.length > bits.length) {
for (int i = n; i < B.bits.length; i++) {
if (B.bits[i] != 0)
return false;
}
}
for (int i = n - 1; i >= 0;) {
if (bits[i] != B.bits[i]) {
return false;
}
i--;
}
return true;
}
/**
* @return true iff this is a subset of other
*/
@Override
public boolean isSubset(BitVector other) {
if (other == null) {
throw new IllegalArgumentException("null other");
}
if (this == other) { // should help alias analysis
return true;
}
for (int i = 0; i < bits.length; i++) {
if (i >= other.bits.length) {
if (bits[i] != 0) {
return false;
}
} else {
if ((bits[i] & ~other.bits[i]) != 0) {
return false;
}
}
}
return true;
}
@Override
public void andNot(BitVector vector) {
if (vector == null) {
throw new IllegalArgumentException("null vector");
}
int ai = 0;
int bi = 0;
for (ai = 0, bi = 0; ai < bits.length && bi < vector.bits.length; ai++, bi++) {
bits[ai] = bits[ai] & (~vector.bits[bi]);
}
}
/**
* Compares this object against the specified object.
*
* @param obj the object to compare with
* @return true if the objects are the same; false otherwise.
*/
@Override
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof BitVector)) {
if (this == obj) { // should help alias analysis
return true;
}
BitVector set = (BitVector) obj;
return sameBits(set);
}
return false;
}
/**
* Sets all bits.
*/
public final void setAll() {
for (int i = 0; i < bits.length; i++) {
bits[i] = MASK;
}
}
/**
* Logically NOT this bit string
*/
public final void not() {
for (int i = 0; i < bits.length; i++) {
bits[i] ^= MASK;
}
}
/**
* Return a new bit string as the AND of two others.
*/
public static BitVector andNot(BitVector b1, BitVector b2) {
BitVector b = new BitVector(b1);
b.andNot(b2);
return b;
}
}
| mit |
suchasplus/jconcurrent | src/com/suchasplus/jconcurrent/demo/nio/Buffer.java | 1175 | package com.suchasplus.jconcurrent.demo.nio;
import java.nio.ByteBuffer;
import java.util.stream.IntStream;
/**
* Powered by suchasplus@gmail.com on 2017/4/16.
*
* position capacity limit
*/
public class Buffer {
private static void eg() {
ByteBuffer b = ByteBuffer.allocate(15);
System.out.println("limit: " + b.limit() + " capacity: " + b.capacity() + " position: " + b.position());
IntStream.range(0, 10).forEach((i) -> {
b.put((byte)i);
});
System.out.println("limit: " + b.limit() + " capacity: " + b.capacity() + " position: " + b.position());
b.flip();
System.out.println("limit: " + b.limit() + " capacity: " + b.capacity() + " position: " + b.position());
IntStream.range(0,5).forEach((i)-> System.out.println(b.get()));
System.out.println();
System.out.println("limit: " + b.limit() + " capacity: " + b.capacity() + " position: " + b.position());
b.flip();
System.out.println("limit: " + b.limit() + " capacity: " + b.capacity() + " position: " + b.position());
}
public static void main(String[] args) {
eg();
}
}
| mit |
dahotre/NoDatabaseBlog | src/main/java/org/dahotre/web/controller/HomeController.java | 4845 | package org.dahotre.web.controller;
import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.notestore.NoteFilter;
import com.evernote.edam.notestore.NoteList;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.NoteSortOrder;
import com.evernote.edam.type.Notebook;
import com.evernote.thrift.TException;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.dahotre.web.common.EvernoteData;
import org.dahotre.web.common.ViewNames;
import org.dahotre.web.helper.EvernoteSyncClient;
import org.dahotre.web.helper.S3Helper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Controls home page as well as other one-off endpoints that won't need CRUD actions
*/
@Controller
@RequestMapping("/")
public class HomeController {
public static final int PAGE_SIZE = 20;
private static final Logger LOG = LoggerFactory.getLogger(HomeController.class);
@Autowired
EvernoteSyncClient evernoteSyncClient;
@Autowired
S3Helper s3Helper;
@RequestMapping("")
public ModelAndView getHome(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page
, @RequestParam(name = "search", required = false) String query
, @RequestParam(name = "tagId", required = false) String tagId
, @RequestParam(name = "tag", required = false) String tag) throws Exception {
boolean isHomePage = true; //This is used to decide if the request is for the home page.
// The results will be cached in a static variable if this remains true.
if (page != 1) {
isHomePage = false;
}
final Notebook defaultNotebook = evernoteSyncClient.getDefaultNotebook();
NoteFilter noteFilter = new NoteFilter();
noteFilter.setNotebookGuid(defaultNotebook.getGuid());
noteFilter.setOrder(NoteSortOrder.CREATED.getValue());
noteFilter.setAscending(false);
if (StringUtils.isNotBlank(query)) {
noteFilter.setWords(query);
isHomePage = false;
}
if (StringUtils.isNotBlank(tagId)) {
noteFilter.setTagGuids(Lists.newArrayList(tagId));
isHomePage = false;
}
final Integer noteCount = evernoteSyncClient.findNoteCounts(noteFilter, false)
.getNotebookCounts().values().stream()
.findFirst().get();
NoteList noteList;
if (isHomePage) {
final int liveUpdateCount = evernoteSyncClient.getSyncState().getUpdateCount();
if (liveUpdateCount > EvernoteData.updateCount || EvernoteData.homePageNoteList == null) {
EvernoteData.updateCount = liveUpdateCount;
EvernoteData.homePageNoteList = findNotes(page, noteFilter);
}
noteList = EvernoteData.homePageNoteList;
}
else {
noteList = findNotes(page, noteFilter);
}
final List<Note> notes = noteList.getNotes();
notes.stream()
.filter(eachNote -> eachNote.getResourcesSize() > 0)
.forEach(
note -> note.getResources().forEach(
resource -> {
try {
s3Helper.checkAndPut(resource);
} catch (EDAMUserException | EDAMSystemException | EDAMNotFoundException | TException e) {
LOG.error("Problem in checkAndPut resource " + resource.getGuid(), e);
}
}
)
);
final Map<String, String> noteToImgUrlMap = notes.parallelStream()
.filter(note -> note != null && note.getResources() != null && note.getResourcesIterator().hasNext())
.collect(Collectors.toMap(Note::getGuid
, note -> s3Helper.generateS3ImageUrl(note.getResourcesIterator().next().getGuid()))
);
return new ModelAndView(ViewNames.HOME)
.addObject("hello", "Hello world!")
.addObject("noteCount", noteCount)
.addObject("notes", notes)
.addObject("noteToImgUrlMap", noteToImgUrlMap)
.addObject("page", page)
.addObject("totalPages", (noteCount/(PAGE_SIZE + 1)) + 1)
.addObject("search", query)
.addObject("tag", tag);
}
private NoteList findNotes(@RequestParam(name = "page", required = false, defaultValue = "1") Integer page, NoteFilter noteFilter) throws EDAMUserException, EDAMSystemException, EDAMNotFoundException, TException {
return evernoteSyncClient.findNotes(noteFilter, (page - 1) * PAGE_SIZE, PAGE_SIZE);
}
}
| mit |
lightstorm/lightstorm-server | src/org/hyperion/rs2/model/region/Tile.java | 129 | package org.hyperion.rs2.model.region;
/**
* Represents a tile.
*
* @author Graham Edgecombe
*
*/
public class Tile {
}
| mit |
skn9x/Anubis | src/anubis/runtime/ObjectType.java | 1255 | package anubis.runtime;
import anubis.TypeName;
/**
* @author SiroKuro
*/
public class ObjectType {
public static final String OBJECT = "object";
public static final String FUNCTION = "function";
public static final String BOOL = "bool";
public static final String NULL = "null";
public static final String NUMBER = "number";
public static final String STRING = "string";
public static final String REGEX = "regex";
public static final String JPACKAGE = "jpackage";
public static final String JCLASS = "jclass";
public static final String JFUNCTION = "jfunction";
public static final String LIST = "list";
public static final String MAP = "map";
public static final String SET = "set";
public static final String CONTEXT = "context";
public static final String LOBBY = "lobby";
public static final String NOP = "nop";
public static String get(Class<?> cls) {
TypeName type = cls.getAnnotation(TypeName.class);
if (type != null) {
String result = type.value();
if (result != null) {
return result;
}
}
return cls.getSimpleName();
}
public static String get(Object obj) {
if (obj == null) {
return OBJECT;
}
else {
return get(obj.getClass());
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/compute/generated/VirtualMachineRunCommandsCreateOrUpdateSamples.java | 2102 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.generated;
import com.azure.core.util.Context;
import com.azure.resourcemanager.compute.fluent.models.VirtualMachineRunCommandInner;
import com.azure.resourcemanager.compute.models.RunCommandInputParameter;
import com.azure.resourcemanager.compute.models.VirtualMachineRunCommandScriptSource;
import java.util.Arrays;
/** Samples for VirtualMachineRunCommands CreateOrUpdate. */
public final class VirtualMachineRunCommandsCreateOrUpdateSamples {
/*
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-11-01/examples/runCommands/CreateOrUpdateRunCommand.json
*/
/**
* Sample code: Create or update a run command.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void createOrUpdateARunCommand(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.virtualMachines()
.manager()
.serviceClient()
.getVirtualMachineRunCommands()
.createOrUpdate(
"myResourceGroup",
"myVM",
"myRunCommand",
new VirtualMachineRunCommandInner()
.withLocation("West US")
.withSource(new VirtualMachineRunCommandScriptSource().withScript("Write-Host Hello World!"))
.withParameters(
Arrays
.asList(
new RunCommandInputParameter().withName("param1").withValue("value1"),
new RunCommandInputParameter().withName("param2").withValue("value2")))
.withAsyncExecution(false)
.withRunAsUser("user1")
.withRunAsPassword("<runAsPassword>")
.withTimeoutInSeconds(3600),
Context.NONE);
}
}
| mit |
karim/adila | database/src/main/java/adila/db/v1_lg2de411f.java | 210 | // This file is automatically generated.
package adila.db;
/*
* LG Optimus L1II
*
* DEVICE: v1
* MODEL: LG-E411f
*/
final class v1_lg2de411f {
public static final String DATA = "LG|Optimus L1II|";
}
| mit |
urazovm/opacclient | src/de/geeksfactory/opacclient/OpacClient.java | 9522 | /**
* Copyright (C) 2013 by Raphael Michel under the MIT license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package de.geeksfactory.opacclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import org.acra.ACRA;
import org.acra.ACRAConfiguration;
import org.acra.annotation.ReportsCrashes;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.preference.PreferenceManager;
import de.geeksfactory.opacclient.apis.BiBer1992;
import de.geeksfactory.opacclient.apis.Bibliotheca;
import de.geeksfactory.opacclient.apis.IOpac;
import de.geeksfactory.opacclient.apis.OpacApi;
import de.geeksfactory.opacclient.apis.Pica;
import de.geeksfactory.opacclient.apis.SISIS;
import de.geeksfactory.opacclient.apis.Zones22;
import de.geeksfactory.opacclient.frontend.MainPreferenceActivity;
import de.geeksfactory.opacclient.frontend.NavigationFragment;
import de.geeksfactory.opacclient.frontend.SearchResultsActivity;
import de.geeksfactory.opacclient.frontend.WelcomeActivity;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.storage.AccountDataSource;
import de.geeksfactory.opacclient.storage.SQLMetaDataSource;
import de.geeksfactory.opacclient.storage.StarContentProvider;
@ReportsCrashes(formKey = "", mailTo = "info@opacapp.de", mode = org.acra.ReportingInteractionMode.DIALOG)
public class OpacClient extends Application {
public Exception last_exception;
public static int NOTIF_ID = 1;
public static int BROADCAST_REMINDER = 2;
public static final String PREF_SELECTED_ACCOUNT = "selectedAccount";
public static final String PREF_HOME_BRANCH_PREFIX = "homeBranch_";
public final String LIMIT_TO_LIBRARY = null;
public final boolean SLIDING_MENU = true;
private SharedPreferences sp;
private Account account;
private OpacApi api;
private Library library;
public static Context context;
public static String versionName = "unknown";
private final Uri STAR_PROVIDER_STAR_URI = StarContentProvider.STAR_URI;
public Uri getStarProviderStarUri() {
return STAR_PROVIDER_STAR_URI;
}
public void addFirstAccount(Activity activity) {
Intent intent = new Intent(activity, WelcomeActivity.class);
activity.startActivity(intent);
activity.finish();
}
public NavigationFragment newNavigationFragment() {
return new NavigationFragment();
}
public Class getSearchResultsActivityClass() {
return SearchResultsActivity.class;
}
public void startSearch(Activity caller, Bundle query) {
Intent myIntent = new Intent(caller, SearchResultsActivity.class);
myIntent.putExtra("query", query);
caller.startActivity(myIntent);
}
public boolean isOnline() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public OpacApi getNewApi(Library lib) throws ClientProtocolException,
SocketException, IOException, NotReachableException {
OpacApi newApiInstance = null;
if (lib.getApi().equals("bond26") || lib.getApi().equals("bibliotheca"))
// Backwardscompatibility
newApiInstance = new Bibliotheca();
else if (lib.getApi().equals("oclc2011")
|| lib.getApi().equals("sisis"))
// Backwards compatibility
newApiInstance = new SISIS();
else if (lib.getApi().equals("zones22"))
newApiInstance = new Zones22();
else if (lib.getApi().equals("biber1992"))
newApiInstance = new BiBer1992();
else if (lib.getApi().equals("pica"))
newApiInstance = new Pica();
else if (lib.getApi().equals("iopac"))
newApiInstance = new IOpac();
else
return null;
newApiInstance.init(new SQLMetaDataSource(this), lib);
return newApiInstance;
}
private OpacApi initApi(Library lib) throws ClientProtocolException,
SocketException, IOException, NotReachableException {
api = getNewApi(lib);
return api;
}
public void resetCache() {
account = null;
api = null;
library = null;
}
public OpacApi getApi() {
if (account != null && api != null) {
if (sp.getLong(PREF_SELECTED_ACCOUNT, 0) == account.getId()) {
return api;
}
}
try {
api = initApi(getLibrary());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return api;
}
public Account getAccount() {
if (account != null) {
if (sp.getLong(PREF_SELECTED_ACCOUNT, 0) == account.getId()) {
return account;
}
}
AccountDataSource data = new AccountDataSource(this);
data.open();
account = data.getAccount(sp.getLong(PREF_SELECTED_ACCOUNT, 0));
data.close();
return account;
}
public void setAccount(long id) {
sp.edit().putLong(OpacClient.PREF_SELECTED_ACCOUNT, id).commit();
resetCache();
if (getLibrary() != null) {
ACRA.getErrorReporter().putCustomData("library",
getLibrary().getIdent());
}
}
public Library getLibrary(String ident) throws IOException, JSONException {
String line;
StringBuilder builder = new StringBuilder();
InputStream fis = getAssets().open(
ASSETS_BIBSDIR + "/" + ident + ".json");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis,
"utf-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
fis.close();
String json = builder.toString();
return Library.fromJSON(ident, new JSONObject(json));
}
public Library getLibrary() {
if (getAccount() == null)
return null;
if (account != null && library != null) {
if (sp.getLong(PREF_SELECTED_ACCOUNT, 0) == account.getId()) {
return library;
}
}
try {
library = getLibrary(getAccount().getLibrary());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
ACRA.getErrorReporter().handleException(e);
}
return library;
}
public static final String ASSETS_BIBSDIR = "bibs";
public List<Library> getLibraries() throws IOException {
AssetManager assets = getAssets();
String[] files = assets.list(ASSETS_BIBSDIR);
int num = files.length;
List<Library> libs = new ArrayList<Library>();
StringBuilder builder = null;
BufferedReader reader = null;
InputStream fis = null;
String line = null;
String json = null;
for (int i = 0; i < num; i++) {
builder = new StringBuilder();
fis = assets.open(ASSETS_BIBSDIR + "/" + files[i]);
reader = new BufferedReader(new InputStreamReader(fis, "utf-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
fis.close();
json = builder.toString();
try {
Library lib = Library.fromJSON(files[i].replace(".json", ""),
new JSONObject(json));
libs.add(lib);
} catch (JSONException e) {
Log.w("JSON library files", "Failed parsing library "
+ files[i]);
e.printStackTrace();
}
}
return libs;
}
public void toPrefs(Activity activity) {
Intent intent = new Intent(activity, MainPreferenceActivity.class);
activity.startActivity(intent);
}
@Override
public void onCreate() {
super.onCreate();
sp = PreferenceManager.getDefaultSharedPreferences(this);
ACRAConfiguration config = ACRA.getNewDefaultConfig(this);
config.setResToastText(R.string.crash_toast_text);
config.setResDialogText(R.string.crash_dialog_text);
ACRA.setConfig(config);
ACRA.init(this);
if (getLibrary() != null) {
ACRA.getErrorReporter().putCustomData("library",
getLibrary().getIdent());
}
OpacClient.context = getApplicationContext();
try {
OpacClient.versionName = getPackageManager().getPackageInfo(
getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
public boolean getSlidingMenuEnabled() {
return SLIDING_MENU;
}
}
| mit |
petergeneric/stdlib | guice/common/src/main/java/com/peterphi/std/guice/apploader/GuiceApplication.java | 805 | package com.peterphi.std.guice.apploader;
/**
* A service that is registered with a {@link com.peterphi.std.guice.apploader.impl.GuiceRegistry} for configuration and lifecycle
* event injection.
*/
public interface GuiceApplication
{
/**
* Called when a new Injector has been created, after Guice injection has been applied to this instance.
* <p/>
* No guarantees are made about the order in which GuiceApplication instances will be called
*/
public void configured();
/**
* Called when an Injector is stopping and before the ShutdownManager for the GuiceRegistry is signalled<br />
* The GuiceRegistry will wait for this method to return before proceeding. No guarantees are made about the order in which
* GuiceApplication instances will be called
*/
public void stopping();
}
| mit |
gmurray/protorabbit | src/org/protorabbit/servlet/BufferedServletOutputStream.java | 994 | /*
* Protorabbit
*
* Copyright (c) 2009 Greg Murray (protorabbit.org)
*
* Licensed under the MIT License:
*
* http://www.opensource.org/licenses/mit-license.php
*
*/
package org.protorabbit.servlet;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import javax.servlet.ServletOutputStream;
public class BufferedServletOutputStream extends ServletOutputStream {
ByteArrayOutputStream buffer = null;
BufferedServletOutputStream(ByteArrayOutputStream buffer) {
this.buffer = buffer;
}
public void write(int b) throws IOException {
this.buffer.write(b);
}
public void write(byte[] b) throws IOException {
new Throwable().printStackTrace();
this.buffer.write(b);
}
public void write(byte[] b, int off, int len) throws IOException {
new Throwable().printStackTrace();
this.buffer.write(b, off, len);
}
public void flush() throws IOException {
this.buffer.flush();
}
public void close() throws IOException {
this.buffer.close();
}
}
| mit |
alternet/alternet.ml | parsing/src/main/java/ml/alternet/parser/visit/Dump.java | 9032 | package ml.alternet.parser.visit;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import ml.alternet.parser.Grammar;
import ml.alternet.parser.Grammar.Rule;
import ml.alternet.parser.visit.TraversableRule.CombinedRule;
import ml.alternet.parser.visit.TraversableRule.StandaloneRule;
import ml.alternet.parser.visit.TraversableRule.SimpleRule;
/**
* Dump a rule.
*
* @author Philippe Poulard
*/
public class Dump extends Traverse implements Visitor, Supplier<StringBuffer> {
/**
* Convenient method for dumping a rule with details
* (rules class names and hash codes).
*
* @param rule The rule to dump.
*
* @return The tree-string representation of the internals
* of the rule.
*/
public static String detailed(Rule rule) {
Dump dumper = new Dump();
rule.accept(dumper);
return dumper.toString();
}
/**
* Convenient method for dumping a grammar with details
* (rules class names and hash codes).
*
* @param grammar The grammar to dump.
*
* @return The tree-string representation of the internals
* of the main rule if it exists, or "".
*/
public static String detailed(Grammar grammar) {
return grammar.mainRule()
.map(Dump::detailed)
.orElse("");
}
/**
* Convenient method for dumping a rule with details
* (rules class names and hash codes).
*
* This method use the grammar owner, typically when
* a grammar extends another one, its rule can be
* considered as the original rule (which is the case
* without the grammar argument) or as an imported
* rule in the extended grammar.
*
* @param grammar The owner grammar.
* @param rule The rule to dump.
*
* @return The tree-string representation of the internals
* of the rule.
*/
public static String detailed(Grammar grammar, Rule rule) {
Dump dumper = new Dump();
rule = grammar.adopt(rule);
rule.accept(dumper);
return dumper.toString();
}
/**
* Convenient method for dumping a rule.
*
* This method use the grammar owner, typically when
* a grammar extends another one, its rule can be
* considered as the original rule (which is the case
* without the grammar argument) or as an imported
* rule in the extended grammar.
*
* @param grammar The grammar that owns the rule to dump.
* @param rule The rule to dump.
*
* @return The tree-string representation of the internals
* of the rule.
*/
public static String tree(Grammar grammar, Rule rule) {
Dump dumper = new Dump().withoutClass().withoutHash();
rule = grammar.adopt(rule);
rule.accept(dumper);
return dumper.toString();
}
/**
* Convenient method for dumping a grammar.
*
* @param grammar The grammar to dump.
*
* @return The tree-string representation of the internals
* of the main rule if it exists, or "".
*/
public static String tree(Grammar grammar) {
return grammar.mainRule()
.map(Dump::tree)
.orElse("");
}
/**
* Convenient method for dumping a rule.
*
* @param rule The rule to dump.
*
* @return The tree-string representation of the internals
* of the rule.
*/
public static String tree(Rule rule) {
Dump dumper = new Dump().withoutClass().withoutHash();
rule.accept(dumper);
return dumper.toString();
}
boolean withHash = true;
boolean withClass = true;
StringBuffer buf = new StringBuffer();
// state
String prefix = "";
boolean isTail = true;
boolean isTop = true; // allow to process the top element
int size = 0; // state for list of rules
int index = 0; // state for list of rules
/**
* Create a dump visitor.
*/
public Dump() {
this.depth = true;
}
/**
* Return tree-string representation of the internals
* of the rule.
*
* @return The dump of a rule.
*/
@Override
public StringBuffer get() {
return this.buf;
}
/**
* Return tree-string representation of the internals
* of the rule.
*
* @return The dump of a rule.
*/
@Override
public String toString() {
return this.buf.toString();
}
/**
* Configure this dump :
* by default, a hash is displayed in the dump ;
* calling this method removes it.
*
* @return {@code this}, for chaining
*/
public Dump withoutHash() {
this.withHash = false;
return this;
}
/**
* Configure this dump :
* by default, a class name is displayed in the dump ;
* calling this method removes it.
*
* @return {@code this}, for chaining
*/
public Dump withoutClass() {
this.withClass = false;
return this;
}
/**
* Configure this dump by setting a set of rules
* considered to be already visited.
*
* @param visited The already visited rules.
*
* @return {@code this}, for chaining
*/
public Dump setVisited(Set<Rule> visited) {
this.traversed.addAll(visited);
return this;
}
/**
* Configure this dump by setting a rule
* considered to be already visited.
*
* @param visited The already visited rule.
*
* @return {@code this}, for chaining
*/
public Dump setVisited(Rule visited) {
this.traversed.add(visited);
return this;
}
@Override
public void visit(StandaloneRule selfRule) {
dumpTop((Rule) selfRule);
if (selfRule.isGrammarField()) {
buf.append(" ━━━ ")
.append(((Rule) selfRule).toPrettyString().toString());
}
buf.append('\n');
}
@Override
public void visit(SimpleRule simpleRule) {
boolean wasTop = dumpTop((Rule) simpleRule);
buf.append('\n');
// save state
int prevSize = size;
String prevPrefix = prefix;
boolean prevTail = isTail;
// set current state
size = 1;
prefix += wasTop ? "" : (isTail ? " " : "┃ ");
super.visit(simpleRule);
// restore state
prefix = prevPrefix;
isTail = prevTail;
size = prevSize;
}
@Override
public void visit(CombinedRule combinedRule) {
boolean wasTop = dumpTop((Rule) combinedRule);
List<Rule> rules = combinedRule.getComponent();
if (! rules.isEmpty()) {
buf.append('\n');
}
// save state
int prevSize = size;
int prevIndex = index;
String prevPrefix = prefix;
boolean prevTail = isTail;
// set current state
size = rules.size();
index = 0;
prefix += wasTop ? "" : (isTail ? " " : "┃ ");
super.visit(combinedRule);
// restore state
prefix = prevPrefix;
isTail = prevTail;
index = prevIndex;
size = prevSize;
}
boolean dumpTop(Rule rule) {
if (isTop) {
accept(rule);
isTop = false;
return true;
} else {
return false;
}
}
@Override
public void accept(Rule rule) {
index++;
isTail = index >= size;
if (this.withHash) {
appendHash(buf, rule).append(' ');
}
if (this.withClass) {
String cl = rule.getClass().getName();
if (cl.contains("Grammar$")) {
cl = cl.substring(cl.indexOf("Grammar$") + 8);
} else {
cl = rule.getClass().getSimpleName();
}
int size = 18;
if (cl.length() > size) {
cl = cl.substring(0, size);
}
if (cl.length() < size) {
cl = cl + new String(new char[size - cl.length()]).replace("\0", " ");
}
buf.append(cl).append(" ┊ ");
}
buf.append(prefix)
.append(isTop ? "" : isTail ? "┗━━ " : "┣━━ ")
.append(rule.isGrammarField() ? rule.getName() : rule.toPrettyString().toString());
}
static StringBuffer appendHash(StringBuffer buf, Rule rule) {
buf.append('<');
String id = Integer.toHexString(Objects.hashCode(rule));
for (int i = id.length(); i < 8 ; i++) {
buf.append('0');
}
buf.append(id).append('>');
return buf;
}
/**
* Convenient method for displaying the hash of a Rule.
*
* @param rule The actual rule
* @return A hash, in hexa.
*/
public static String getHash(Rule rule) {
return appendHash(new StringBuffer(), rule).toString();
}
}
| mit |
dgautier/PlatformJavaClient | src/main/java/com/docuware/dev/schema/_public/services/annotations/LinkInvoke.java | 1025 |
package com.docuware.dev.schema._public.services.annotations;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LinkInvoke", propOrder = {
"accepts",
"produces"
})
public class LinkInvoke {
@XmlElement(name = "Accepts")
protected ContentTypeList accepts;
@XmlElement(name = "Produces")
protected ContentTypeList produces;
@XmlAttribute(name = "Verb")
protected HttpMethod verb;
public ContentTypeList getAccepts() {
return accepts;
}
public void setAccepts(ContentTypeList value) {
this.accepts = value;
}
public ContentTypeList getProduces() {
return produces;
}
public void setProduces(ContentTypeList value) {
this.produces = value;
}
public HttpMethod getVerb() {
if (verb == null) {
return HttpMethod.GET;
} else {
return verb;
}
}
public void setVerb(HttpMethod value) {
this.verb = value;
}
}
| mit |
tyster04/Kindrid | features/02-call-an-api/KindridProject/src/JsonReader.java | 4193 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.text.*;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader
{
public static void main(String[] args) throws JSONException, IOException
{
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(CallAPI(args[0]));
//System.out.println(CallAPI("http://api.fixer.io/2016-05-03"));
//System.out.println("5.65 USD = $" + df.format(ConvertToUSD("USD", 5.65)) + " USD");
//System.out.println("76.91 Canadian dollars = $" + df.format(ConvertToUSD("CAD", 76.91)) + " USD");
}
public static double ConvertToUSD(String fromCurrency, double amount) throws JSONException, IOException
{
String ratesString;
String[] tuples; // List of all country/rate pairs.
String[] tuple; // Single country/rate pair.
double rate; // Set to the exchange rate for the specified country.
ratesString = CallAPI("http://api.fixer.io/2016-05-03");
ratesString = ratesString.replace('{', '\0');
ratesString = ratesString.replace('}', '\0');
tuples = ratesString.split(",");
for(int i=0; i<tuples.length; i++)
{
tuple = tuples[i].split(":");
if(tuple[0].equals(fromCurrency))
{
/*Could bypass creating and using the 'rate' variable altogether, but this makes
the process more clear in the code and the compiler will condense automatically.*/
rate = Double.valueOf(tuple[1]);
return (rate * amount);
}
}
return -1; // Execution reaches this only if the currency rate was not found.
}
public static String CallAPI(String address) throws IOException, JSONException
{
String ratesString; // List of all rates for all countries.
String[] ratesTuple; // Single tuple in ratesString, separated by commas.
LinkedList<Double> rates = new LinkedList<Double>(); // List of all rates.
// To make this more robust, could create new object type to force indexing between country label and rate.
LinkedList<String> countries = new LinkedList<String>(); // List of all countries.
String[] temp;
double normalizer = 1; // Will be set to USD rate to normalize all values to USD.
String outputString = "{";
JSONObject json = readJsonFromUrl(address);
ratesString = json.get("rates").toString();
// Remove curly braces.
ratesString = ratesString.replace('{', '\0');
ratesString = ratesString.replace('}', '\0');
ratesString = ratesString.replace(' ', '\0');
//Split string containing all rates into individual tuples.
ratesTuple = ratesString.split(",");
for(int i=0; i<ratesTuple.length; i++)
{
temp = ratesTuple[i].split(":");
countries.add(temp[0].replace("\"", ""));
rates.add(Double.valueOf(temp[1]));
// Since USD=1, all other rates must be normalized according to USD rate.
if(countries.get(i).toString().equals("USD"))
{
normalizer = Double.parseDouble(rates.get(i).toString());
}
}
for(int i=0; i<countries.size(); i++)
{
if(countries.get(i).toString().equals("USD") || countries.get(i).toString().equals("CAD") || countries.get(i).toString().equals("EUR") || countries.get(i).toString().equals("GBP"))
outputString = outputString + (countries.get(i) + ":" + rates.get(i)/normalizer + ",");
}
outputString = outputString + "EUR:" + 1.0/normalizer + "}";
return outputString;
}
private static String readAll(Reader rd) throws IOException
{
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1)
{
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try
{
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
finally
{
is.close();
}
}
} | mit |
pholser/property-binder | com.pholser.util.properties.propertybinder.it/src/test/java/com/pholser/util/properties/it/InvokingObjectMethodsOnBoundInterfaceTest.java | 2495 | /*
The MIT License
Copyright (c) 2009-2021 Paul R. Holser, Jr.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.pholser.util.properties.it;
import com.pholser.util.properties.BoundProperty;
import org.junit.jupiter.api.Test;
import java.io.FileReader;
import static java.lang.System.identityHashCode;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class InvokingObjectMethodsOnBoundInterfaceTest
extends TypedStringBindingTestSupport<InvokingObjectMethodsOnBoundInterfaceTest.PropertyFacade> {
InvokingObjectMethodsOnBoundInterfaceTest() {
super("/test.properties", "test", "properties");
}
@Test void answeringEquals() throws Exception {
PropertyFacade second =
binder.bind(new FileReader(propertiesFile, UTF_8));
assertEquals(bound, bound);
assertNotEquals(bound, second);
assertEquals(second, second);
assertNotEquals(second, bound);
}
@Test void answeringHashCode() {
assertEquals(identityHashCode(bound), bound.hashCode());
}
@Test void answeringToString() {
assertThat(bound.toString()).contains("wrapped.integer");
}
@Override protected Class<PropertyFacade> boundType() {
return PropertyFacade.class;
}
interface PropertyFacade {
@BoundProperty(value = "string.property") String stringProperty();
}
}
| mit |
Tektor/tallDoors | tektor/minecraft/talldoors/packet/PacketPipeline.java | 7780 | package tektor.minecraft.talldoors.packet;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.*;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.*;
import io.netty.buffer.*;
import io.netty.channel.*;
import io.netty.handler.codec.MessageToMessageCodec;
import java.util.*;
import tektor.minecraft.talldoors.doorworkshop.network.DirectionPacket;
import tektor.minecraft.talldoors.doorworkshop.network.DoorModuleWorkbenchPacket;
import tektor.minecraft.talldoors.doorworkshop.network.ModuleAssemblerPacket;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.*;
import net.minecraft.network.*;
@ChannelHandler.Sharable
public class PacketPipeline extends
MessageToMessageCodec<FMLProxyPacket, AbstractPacket> {
private EnumMap<Side, FMLEmbeddedChannel> channels;
private LinkedList<Class<? extends AbstractPacket>> packets = new LinkedList<Class<? extends AbstractPacket>>();
private boolean isPostInitialised = false;
/**
* Register your packet with the pipeline. Discriminators are automatically
* set.
*
* @param clazz
* the class to register
*
* @return whether registration was successful. Failure may occur if 256
* packets have been registered or if the registry already contains
* this packet
*/
public boolean registerPacket(Class<? extends AbstractPacket> clazz) {
if (this.packets.size() > 256) {
// You should log here!!
return false;
}
if (this.packets.contains(clazz)) {
// You should log here!!
return false;
}
if (this.isPostInitialised) {
// You should log here!!
return false;
}
this.packets.add(clazz);
return true;
}
// In line encoding of the packet, including discriminator setting
@Override
protected void encode(ChannelHandlerContext ctx, AbstractPacket msg,
List<Object> out) throws Exception {
ByteBuf buffer = Unpooled.buffer();
Class<? extends AbstractPacket> clazz = msg.getClass();
if (!this.packets.contains(msg.getClass())) {
throw new NullPointerException("No Packet Registered for: "
+ msg.getClass().getCanonicalName());
}
byte discriminator = (byte) this.packets.indexOf(clazz);
buffer.writeByte(discriminator);
msg.encodeInto(ctx, buffer);
FMLProxyPacket proxyPacket = new FMLProxyPacket(buffer.copy(), ctx
.channel().attr(NetworkRegistry.FML_CHANNEL).get());
out.add(proxyPacket);
}
// In line decoding and handling of the packet
@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg,
List<Object> out) throws Exception {
ByteBuf payload = msg.payload();
byte discriminator = payload.readByte();
Class<? extends AbstractPacket> clazz = this.packets.get(discriminator);
if (clazz == null) {
throw new NullPointerException(
"No packet registered for discriminator: " + discriminator);
}
AbstractPacket pkt = clazz.newInstance();
pkt.decodeInto(ctx, payload.slice());
EntityPlayer player;
switch (FMLCommonHandler.instance().getEffectiveSide()) {
case CLIENT:
player = this.getClientPlayer();
pkt.handleClientSide(player);
break;
case SERVER:
INetHandler netHandler = ctx.channel()
.attr(NetworkRegistry.NET_HANDLER).get();
player = ((NetHandlerPlayServer) netHandler).playerEntity;
pkt.handleServerSide(player);
break;
default:
}
out.add(pkt);
}
// Method to call from FMLInitializationEvent
public void initalise() {
this.channels = NetworkRegistry.INSTANCE.newChannel("TallDoors", this);
registerPackets();
}
public void registerPackets() {
registerPacket(KeyPacket.class);
registerPacket(MosaicPacket.class);
registerPacket(DrawBridgeWorkbenchPacket.class);
registerPacket(DoorModuleWorkbenchPacket.class);
registerPacket(DirectionPacket.class);
registerPacket(ModuleAssemblerPacket.class);
}
// Method to call from FMLPostInitializationEvent
// Ensures that packet discriminators are common between server and client
// by using logical sorting
public void postInitialise() {
if (this.isPostInitialised) {
return;
}
this.isPostInitialised = true;
Collections.sort(this.packets,
new Comparator<Class<? extends AbstractPacket>>() {
@Override
public int compare(Class<? extends AbstractPacket> clazz1,
Class<? extends AbstractPacket> clazz2) {
int com = String.CASE_INSENSITIVE_ORDER.compare(
clazz1.getCanonicalName(),
clazz2.getCanonicalName());
if (com == 0) {
com = clazz1.getCanonicalName().compareTo(
clazz2.getCanonicalName());
}
return com;
}
});
}
@SideOnly(Side.CLIENT)
private EntityPlayer getClientPlayer() {
return Minecraft.getMinecraft().thePlayer;
}
/**
* Send this message to everyone.
* <p/>
* Adapted from CPW's code in
* cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
*
* @param message
* The message to send
*/
public void sendToAll(AbstractPacket message) {
this.channels.get(Side.SERVER)
.attr(FMLOutboundHandler.FML_MESSAGETARGET)
.set(FMLOutboundHandler.OutboundTarget.ALL);
this.channels.get(Side.SERVER).writeAndFlush(message);
}
/**
* Send this message to the specified player.
* <p/>
* Adapted from CPW's code in
* cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
*
* @param message
* The message to send
* @param player
* The player to send it to
*/
public void sendTo(AbstractPacket message, EntityPlayerMP player) {
this.channels.get(Side.SERVER)
.attr(FMLOutboundHandler.FML_MESSAGETARGET)
.set(FMLOutboundHandler.OutboundTarget.PLAYER);
this.channels.get(Side.SERVER)
.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);
this.channels.get(Side.SERVER).writeAndFlush(message);
}
/**
* Send this message to everyone within a certain range of a point.
* <p/>
* Adapted from CPW's code in
* cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
*
* @param message
* The message to send
* @param point
* The
* {@link cpw.mods.fml.common.network.NetworkRegistry.TargetPoint}
* around which to send
*/
public void sendToAllAround(AbstractPacket message,
NetworkRegistry.TargetPoint point) {
this.channels.get(Side.SERVER)
.attr(FMLOutboundHandler.FML_MESSAGETARGET)
.set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
this.channels.get(Side.SERVER)
.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);
this.channels.get(Side.SERVER).writeAndFlush(message);
}
/**
* Send this message to everyone within the supplied dimension.
* <p/>
* Adapted from CPW's code in
* cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
*
* @param message
* The message to send
* @param dimensionId
* The dimension id to target
*/
public void sendToDimension(AbstractPacket message, int dimensionId) {
this.channels.get(Side.SERVER)
.attr(FMLOutboundHandler.FML_MESSAGETARGET)
.set(FMLOutboundHandler.OutboundTarget.DIMENSION);
this.channels.get(Side.SERVER)
.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS)
.set(dimensionId);
this.channels.get(Side.SERVER).writeAndFlush(message);
}
/**
* Send this message to the server.
* <p/>
* Adapted from CPW's code in
* cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper
*
* @param message
* The message to send
*/
public void sendToServer(AbstractPacket message) {
this.channels.get(Side.CLIENT)
.attr(FMLOutboundHandler.FML_MESSAGETARGET)
.set(FMLOutboundHandler.OutboundTarget.TOSERVER);
this.channels.get(Side.CLIENT).writeAndFlush(message);
}
}
| mit |
SpongePowered/Sponge | src/main/java/org/spongepowered/common/event/inventory/UpdateAnvilEventCost.java | 2597 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.event.inventory;
import org.spongepowered.api.data.persistence.DataContainer;
import org.spongepowered.api.data.persistence.Queries;
import org.spongepowered.api.item.inventory.AnvilCost;
import org.spongepowered.common.util.Constants;
public class UpdateAnvilEventCost implements AnvilCost {
private final int levelCost;
private final int materialCost;
public UpdateAnvilEventCost(int levelCost, int materialCost) {
this.levelCost = levelCost;
this.materialCost = materialCost;
}
public int levelCost() {
return this.levelCost;
}
public int materialCost() {
return this.materialCost;
}
public AnvilCost withLevelCost(int levelCost) {
return new UpdateAnvilEventCost(levelCost, this.materialCost);
}
public AnvilCost withMaterialCost(int materialCost) {
return new UpdateAnvilEventCost(this.levelCost, materialCost);
}
@Override
public int contentVersion() {
return 1;
}
@Override
public DataContainer toContainer() {
return DataContainer.createNew().set(Queries.CONTENT_VERSION, this.contentVersion())
.set(Constants.TileEntity.Anvils.MATERIALCOST, this.materialCost())
.set(Constants.TileEntity.Anvils.LEVELCOST, this.levelCost());
}
}
| mit |
asavonic/DotsBoxes | src/dotsboxes/rmi/EventTransmitter.java | 252 | /**
*
*/
package dotsboxes.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
import dotsboxes.events.Event;
/**
*
*
*/
public interface EventTransmitter extends Remote {
public void transmit(Event event) throws RemoteException;
}
| mit |
rogerthealien/hookly | src/uk/gla/hookly/social/HooklyTwitterUtils.java | 13550 | package uk.gla.hookly.social;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import uk.gla.hookly.storage.HooklyParseUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseTwitterUtils;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class HooklyTwitterUtils {
private static final String TAG = "TWT";
private static final String TWITTER_RETWEET_ENDPOINT = "https://api.twitter.com/1.1/statuses/retweet/";
private static final String TWITTER_FOLLOW_CREATE_ENDPOINT = "https://api.twitter.com/1.1/friendships/create.json";
private static final String TWITTER_SHOW_ENDPOINT = "https://api.twitter.com/1.1/users/show.json";
// private static final String TWITTER_FOLLOW_LOOKUP_ENDPOINT =
// "https://api.twitter.com/1.1/friendships/show.json";
public static void logIn(Activity activity,
final TwitterAuthenticationListener authListener) {
if (ParseUser.getCurrentUser() == null) {
ParseTwitterUtils.logIn(activity, new LogInCallback() {
@Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d(TAG, "Uh oh. The user cancelled the Twitter login.");
authListener.onTwitterAuthenticationFailure();
} else if (user.isNew()) {
authListener.onTwitterAuthenticationSuccess();
HooklyParseUtils.updateInstallationOwner();
HooklyTwitterUtils.updateImageUrl();
Log.d(TAG, "User signed up and logged in through Twitter!");
} else {
authListener.onTwitterAuthenticationSuccess();
Log.d(TAG, "User logged in through Twitter!");
HooklyParseUtils.updateInstallationOwner();
HooklyTwitterUtils.updateImageUrl();
}
}
});
}
}
public static void logOut(final TwitterUnauthenticationListener listener) {
ParseUser.logOut();
if (listener != null) {
listener.onTwitterLogoutSuccess();
}
}
public static void initiateFollow(final String followHandle,
final TwitterFollowListener listener) {
Thread twitterThread = new Thread() {
@Override
public void run() {
follow(followHandle, listener);
}
};
twitterThread.start();
}
public static void initiateRetweet(final String tweetId,
final TwitterRetweetListener listener) {
Thread twitterThread = new Thread() {
@Override
public void run() {
retweet(tweetId, listener);
}
};
twitterThread.start();
}
public static void initiateFollowAndRetweet(final String followHandle,
final String tweetId, final TwitterFollowListener followListener,
final TwitterRetweetListener retweetListener) {
Thread twitterThread = new Thread() {
@Override
public void run() {
followAndRetweet(followHandle, tweetId, retweetListener,
followListener);
}
};
twitterThread.start();
}
public static void follow(String userHandle, TwitterFollowListener listener) {
HttpClient followClient = new DefaultHttpClient();
HttpPost followPost = new HttpPost(TWITTER_FOLLOW_CREATE_ENDPOINT);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs
.add(new BasicNameValuePair("screen_name", userHandle));
nameValuePairs.add(new BasicNameValuePair("follow", "true"));
followPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ParseTwitterUtils.getTwitter().signRequest(followPost);
HttpResponse followResponse = followClient.execute(followPost);
switch (followResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
// Log.e("TWT",
// EntityUtils.toString(followResponse.getEntity()));
listener.onTwitterFollowSuccess();
break;
case HttpStatus.SC_FORBIDDEN:
// follow exists
listener.onTwitterFollowFailure();
break;
default:
listener.onTwitterFollowFailure();
break;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
listener.onTwitterFollowFailure();
} catch (IOException e) {
e.printStackTrace();
listener.onTwitterFollowFailure();
} finally {
followClient.getConnectionManager().shutdown();
}
}
public static void retweet(String tweetId, TwitterRetweetListener listener) {
HttpClient retweetClient = new DefaultHttpClient();
HttpPost retweetPost = new HttpPost(formatRetweetUrl(tweetId));
try {
ParseTwitterUtils.getTwitter().signRequest(retweetPost);
HttpResponse retweetResponse = retweetClient.execute(retweetPost);
switch (retweetResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
listener.onTwitterRetweetSuccess();
break;
case HttpStatus.SC_FORBIDDEN:
// Retweet exists here
listener.onTwitterRetweetFailure();
break;
default:
listener.onTwitterRetweetFailure();
break;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
listener.onTwitterRetweetFailure();
} catch (IOException e) {
e.printStackTrace();
listener.onTwitterRetweetFailure();
} finally {
retweetClient.getConnectionManager().shutdown();
}
}
public static void followAndRetweet(String followHandle, String tweetId,
TwitterRetweetListener retweetListener,
TwitterFollowListener followListener) {
HttpClient followClient = new DefaultHttpClient();
HttpPost followPost = new HttpPost(TWITTER_FOLLOW_CREATE_ENDPOINT);
HttpClient retweetClient = new DefaultHttpClient();
HttpPost retweetPost = new HttpPost(formatRetweetUrl(tweetId));
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("screen_name",
followHandle));
nameValuePairs.add(new BasicNameValuePair("follow", "true"));
followPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ParseTwitterUtils.getTwitter().signRequest(followPost);
HttpResponse followResponse = followClient.execute(followPost);
switch (followResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
followListener.onTwitterFollowSuccess();
break;
case HttpStatus.SC_FORBIDDEN:
// follow exists
followListener.onTwitterFollowFailure();
break;
default:
followListener.onTwitterFollowFailure();
break;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
followListener.onTwitterFollowFailure();
} catch (IOException e) {
e.printStackTrace();
followListener.onTwitterFollowFailure();
} finally {
followClient.getConnectionManager().shutdown();
}
try {
ParseTwitterUtils.getTwitter().signRequest(retweetPost);
HttpResponse retweetResponse = retweetClient.execute(retweetPost);
switch (retweetResponse.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
retweetListener.onTwitterRetweetSuccess();
break;
case HttpStatus.SC_FORBIDDEN:
// Retweet exists here
retweetListener.onTwitterRetweetFailure();
break;
default:
retweetListener.onTwitterRetweetFailure();
break;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
retweetListener.onTwitterRetweetFailure();
} catch (IOException e) {
e.printStackTrace();
retweetListener.onTwitterRetweetFailure();
} finally {
retweetClient.getConnectionManager().shutdown();
}
}
// private static String formatFollowLookupUrl(String source, String target)
// {
// return TWITTER_FOLLOW_LOOKUP_ENDPOINT + "?source_screen_name=" + source
// + "&target_screen_name=" + target;
// }
// private static void runFollowQuery(String sourceHandle,
// String targetHandle, TwitterCheckFollowListener listener) {
//
// HttpClient client = new DefaultHttpClient();
// HttpGet checkGet = new HttpGet(formatFollowLookupUrl(sourceHandle,
// targetHandle));
//
// try {
// ParseTwitterUtils.getTwitter().signRequest(checkGet);
// HttpResponse response = client.execute(checkGet);
//
// switch (response.getStatusLine().getStatusCode()) {
// case HttpStatus.SC_OK:
// // Log.d("TWT", EntityUtils.toString(response.getEntity()));
//
// BufferedReader streamReader = new BufferedReader(
// new InputStreamReader(
// response.getEntity().getContent(), "UTF-8"));
// StringBuilder responseStrBuilder = new StringBuilder();
//
// String inputStr;
// while ((inputStr = streamReader.readLine()) != null)
// responseStrBuilder.append(inputStr);
// try {
// JSONObject object = new JSONObject(
// responseStrBuilder.toString());
// JSONObject source = object.getJSONObject("relationship")
// .getJSONObject("source");
// String sourceName = source.getString("screen_name");
// boolean isFollowing = source.getBoolean("following");
//
// if (sourceName.equalsIgnoreCase(sourceHandle)
// && isFollowing) {
// listener.onTwitterFollowCheckUpdate(true);
// } else {
// listener.onTwitterFollowCheckUpdate(false);
// }
// } catch (JSONException e) {
// Log.d(TAG, "JSONException");
// listener.onTwitterFollowCheckUpdate(false);
// }
// break;
// case HttpStatus.SC_FORBIDDEN:
// listener.onTwitterFollowCheckUpdate(false);
// break;
// default:
// listener.onTwitterFollowCheckUpdate(false);
// break;
// }
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// listener.onTwitterFollowCheckUpdate(false);
// } catch (IOException e) {
// e.printStackTrace();
// listener.onTwitterFollowCheckUpdate(false);
// }
// }
// public static void checkFollow(final String handle,
// final TwitterCheckFollowListener listener) {
// ParseUser user = ParseUser.getCurrentUser();
// final String userHandle = ParseTwitterUtils.getTwitter()
// .getScreenName();
// if (user == null || userHandle == null) {
// Log.d(TAG, "checkFollow: user or twitter is null, not following "
// + handle);
// listener.onTwitterFollowCheckUpdate(false);
// } else {
// Thread twitterThread = new Thread() {
// @Override
// public void run() {
// runFollowQuery(userHandle, handle, listener);
// }
// };
// twitterThread.start();
// }
// }
public static void updateImageUrl() {
if (ParseUser.getCurrentUser() != null)
if (ParseUser.getCurrentUser().get("imageUrl") == null) {
new ImageTask().execute(ParseTwitterUtils.getTwitter().getScreenName());
}
}
private static class ImageTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String handle = params[0];
findImageUrl(handle);
return null;
}
@Override
protected void onPostExecute(Void voids) {
ParseUser.getCurrentUser().saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
Log.d(TAG, "On TW image fetch: saved user");
}
});
}
}
private static void findImageUrl(String twitterHandle) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(TWITTER_SHOW_ENDPOINT + "?screen_name="
+ twitterHandle.trim());
try {
ParseTwitterUtils.getTwitter().signRequest(request);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
BufferedReader streamReader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
try {
JSONObject object = new JSONObject(
responseStrBuilder.toString());
String imageUrl = object.getString("profile_image_url");
if (imageUrl != null) {
ParseUser.getCurrentUser().put("imageUrl", imageUrl);
}
} catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
}
} catch (UnsupportedEncodingException e) {
Log.d(TAG, "UnsupportedEncodingException: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "IOException: " + e.getMessage());
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
}
private static String formatRetweetUrl(String tweetId) {
return TWITTER_RETWEET_ENDPOINT + tweetId + ".json";
}
public static boolean userHasTwitterAccess() {
return ParseUser.getCurrentUser() != null
&& ParseTwitterUtils.isLinked(ParseUser.getCurrentUser());
}
public interface TwitterAuthenticationListener {
public void onTwitterAuthenticationSuccess();
public void onTwitterAuthenticationFailure();
}
public interface TwitterUnauthenticationListener {
public void onTwitterLogoutSuccess();
}
public interface TwitterRetweetListener {
public void onTwitterRetweetSuccess();
public void onTwitterRetweetFailure();
}
public interface TwitterFollowListener {
public void onTwitterFollowSuccess();
public void onTwitterFollowFailure();
}
public interface TwitterCheckFollowListener {
public void onTwitterFollowCheckUpdate(boolean isFollowing);
}
} | mit |
CCI-MIT/XCoLab | microservices/clients/comment-client/src/main/java/org/xcolab/client/comment/ThreadClientMockImpl.java | 1254 | package org.xcolab.client.comment;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.xcolab.client.comment.exceptions.ThreadNotFoundException;
import org.xcolab.client.comment.pojo.IThread;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Component
@Profile("test")
public class ThreadClientMockImpl implements IThreadClient {
@Override
public List<IThread> listThreads(Integer startRecord, Integer limitRecord, String sort,
Long authorUserId, Long categoryId, Long groupId) {
return Collections.emptyList();
}
@Override
public IThread getThread(Long threadId) throws ThreadNotFoundException {
return null;
}
@Override
public boolean updateThread(Long threadId , IThread thread ) {
return false;
}
@Override
public IThread createThread(IThread thread) {
return null;
}
@Override
public boolean deleteThread(Long threadId) {
return false;
}
@Override
public Date getLastActivityDate(Long threadId) {
return null;
}
@Override
public Long getLastActivityAuthorUserId(Long threadId) {
return null;
}
}
| mit |
pluvia/jdb | jms-priority/src/main/java/jdb/jms/priority/consumer/Consumer.java | 1872 | package jdb.jms.priority.consumer;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Consumer {
private static final Logger logger = LoggerFactory
.getLogger(Consumer.class);
private Connection connection;
private Session session;
private MessageConsumer consumer;
public void openConnection() throws JMSException {
// Create a new connection factory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_BROKER_URL);
connection = connectionFactory.createConnection();
}
public void closeConnection() throws JMSException {
// Always close the connection
connection.close();
}
public void createConsumer(String queue) throws JMSException {
// Create a session for receiving messages
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create the destination from which messages will be received
Destination destination = session.createQueue(queue);
// Create a MessageConsumer for receiving messages
consumer = session.createConsumer(destination);
// Start the connection in order to be able to receive messages
connection.start();
}
public String receive(int timeout) throws JMSException {
// Read a message from the destination
Message message = consumer.receive(timeout);
// Cast the message to the correct type
TextMessage input = (TextMessage) message;
// Retrieve the message content
String text = input.getText();
logger.info(text + " received");
return (text);
}
} | mit |
winny-/cs-251 | hwk7/Homework7/Building.java | 980 | // Name: Winston Weinert
// Class: COMPSCI 251
// Assignment: Homework7
// Date: 31-Oct-2016
//
// -- Comments --
//
// I changed the package name to Homework7.
//
// All unit tests pass.
package Homework7;
public class Building {
Apartment[] apartments;
public Building(Apartment[] units) {
this.apartments = units;
}
// Return the total order all apartments in this building
TotalOrder order() {
TotalOrder order = new TotalOrder();
for (Apartment apt : this.apartments) {
order.add(apt.totalOrder());
}
return order;
}
public String toString() {
String strings[] = new String[this.apartments.length+1];
for (int i = 0; i < this.apartments.length; i++) {
strings[i] = this.apartments[i].toString();
}
strings[this.apartments.length] = "";
return String.join("\n", strings);
}
}
| mit |
CCI-MIT/XCoLab | view/src/main/java/org/xcolab/view/pages/contestmanagement/utils/ActivityCsvWriter.java | 3480 | package org.xcolab.view.pages.contestmanagement.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xcolab.client.activity.pojo.IActivityEntry;
import org.xcolab.client.user.StaticUserContext;
import org.xcolab.client.user.exceptions.MemberNotFoundException;
import org.xcolab.client.user.pojo.wrapper.UserWrapper;
import org.xcolab.commons.CsvResponseWriter;
import org.xcolab.util.activities.enums.ActivityType;
import org.xcolab.view.activityentry.ActivityEntryHelper;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
public class ActivityCsvWriter extends CsvResponseWriter {
private static final Logger _log = LoggerFactory.getLogger(ActivityCsvWriter.class);
private static final String MEMBER_NOT_FOUND_MESSAGE = "Member not found";
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final String FILE_NAME = "activityReport";
private static final List<String> COLUMN_NAMES = Arrays.asList(
"User Id",
"screenName",
"firstName",
"lastName",
"activityCategory",
"activityType",
"activityCreatedAt",
"activityBody"
);
private final ActivityEntryHelper activityEntryHelper;
public ActivityCsvWriter(HttpServletResponse response,
ActivityEntryHelper activityEntryHelper) throws IOException {
super(FILE_NAME, COLUMN_NAMES, response);
this.activityEntryHelper = activityEntryHelper;
}
public void writeActivities(Collection<IActivityEntry> activityEntries) {
activityEntries.forEach(this::writeActivity);
}
public void writeActivity(IActivityEntry activityEntry) {
final ActivityType activityType = activityEntry.getActivityTypeEnum();
if (activityType != null) {
UserWrapper member = getMemberOrNull(activityEntry);
List<String> row = new ArrayList<>();
addValue(row, member != null ? member.getId() : MEMBER_NOT_FOUND_MESSAGE);
addValue(row, member != null ? member.getScreenName() : MEMBER_NOT_FOUND_MESSAGE);
addValue(row, member != null ? member.getFirstName() : MEMBER_NOT_FOUND_MESSAGE);
addValue(row, member != null ? member.getLastName() : MEMBER_NOT_FOUND_MESSAGE);
addValue(row, activityType.getCategory().name());
addValue(row, activityType.name());
addValue(row, DATE_FORMAT.format(activityEntry.getCreatedAt()));
addValue(row, activityEntryHelper.getActivityBody(activityEntry));
writeRow(row);
} else {
_log.warn("Unknown ActivityCategory {} found when generating report",
activityEntry.getActivityCategory());
}
}
private UserWrapper getMemberOrNull(IActivityEntry activityEntry) {
try {
return StaticUserContext.getUserClient().getMember(activityEntry.getUserId());
} catch (MemberNotFoundException e) {
_log.warn("Member {} not found when generating report", activityEntry.getUserId());
return null;
}
}
private void addValue(List<String> list, Object value) {
list.add(String.valueOf(value));
}
}
| mit |
RecursiveMode/jrpg | cliente/src/main/java/frame/PuntosHabilidadInsuficientes.java | 1966 | package frame;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PuntosHabilidadInsuficientes extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
PuntosHabilidadInsuficientes dialog = new PuntosHabilidadInsuficientes();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public PuntosHabilidadInsuficientes() {
setLocationRelativeTo(null);
setBounds(100, 100, 311, 182);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblNoTienesPuntos = new JLabel("No tienes puntos de habilidad disponibles");
lblNoTienesPuntos.setHorizontalAlignment(SwingConstants.CENTER);
lblNoTienesPuntos.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblNoTienesPuntos.setBounds(10, 11, 275, 88);
contentPanel.add(lblNoTienesPuntos);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
}
}
}
| mit |
emboss/krypt-core-java | src/impl/krypt/asn1/ParsedHeader.java | 1605 | /*
* krypt-core API - Java version
*
* Copyright (c) 2011-2013
* Hiroshi Nakamura <nahi@ruby-lang.org>
* Martin Bosslet <martin.bosslet@gmail.com>
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package impl.krypt.asn1;
import java.io.InputStream;
/**
*
* @author <a href="mailto:Martin.Bosslet@gmail.com">Martin Bosslet</a>
*/
public interface ParsedHeader extends Header {
public void skipValue();
public byte[] getValue();
public InputStream getValueStream(boolean valuesOnly);
public Asn1Object getObject();
}
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/ConnectedOrganizationReferenceRequest.java | 2487 | // Template Source: BaseEntityReferenceRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.ConnectedOrganization;
import com.microsoft.graph.requests.DirectoryObjectCollectionRequestBuilder;
import com.microsoft.graph.requests.DirectoryObjectRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.options.QueryOption;
import com.microsoft.graph.http.BaseReferenceRequest;
import com.microsoft.graph.http.HttpMethod;
import com.microsoft.graph.core.IBaseClient;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonObject;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Connected Organization Reference Request.
*/
public class ConnectedOrganizationReferenceRequest extends BaseReferenceRequest<ConnectedOrganization> {
/**
* The request for the ConnectedOrganization
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public ConnectedOrganizationReferenceRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, ConnectedOrganization.class);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public ConnectedOrganizationReferenceRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public ConnectedOrganizationReferenceRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
}
| mit |
aelroby/Sapphire | src/sapphire/test/SimilarityFunctionTest.java | 582 | package sapphire.test;
import info.debatty.java.stringsimilarity.JaroWinkler;
import me.xdrop.fuzzywuzzy.FuzzySearch;
public class SimilarityFunctionTest {
public static void main(String[] args) {
JaroWinkler jw = new JaroWinkler();
String s1 = "Viking Press";
String s2 = "The Viking Press";
System.out.println("FuzzyWuzzy Similarity between \"" + s1 + "\" and \"" + s2 + "\": " +
1.0 * FuzzySearch.ratio(s1, s2)/100);
System.out.println("Jaro-Winkler Similarity between \"" + s1 + "\" and \"" + s2 + "\": " +
jw.similarity(s1, s2));
}
}
| mit |
deonwu/Goku | unittest/org/goku/TestDemo.java | 263 | package org.goku;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestDemo {
@Test
public void unittest_demo() {
//assertEquals(R(0, 8), "BB2B");
assertEquals(260, 260);
}
}
| mit |
AgeOfWar/Telejam | src/main/java/io/github/ageofwar/telejam/users/UserProfilePhotos.java | 1783 | package io.github.ageofwar.telejam.users;
import com.google.gson.annotations.SerializedName;
import io.github.ageofwar.telejam.TelegramObject;
import io.github.ageofwar.telejam.media.PhotoSize;
import java.util.Arrays;
import java.util.Objects;
/**
* This object represent a user's profile pictures.
*
* @author Michi Palazzo
*/
public class UserProfilePhotos implements TelegramObject {
static final String TOTAL_COUNT_FIELD = "total_count";
static final String PHOTOS_FIELD = "photos";
/**
* Total number of profile pictures the target user has.
*/
@SerializedName(TOTAL_COUNT_FIELD)
private final int totalCount;
/**
* Requested profile pictures (in up to 4 sizes each).
*/
@SerializedName(PHOTOS_FIELD)
private final PhotoSize[][] photos;
public UserProfilePhotos(int totalCount, PhotoSize[][] photos) {
this.totalCount = totalCount;
this.photos = Objects.requireNonNull(photos);
}
/**
* Getter for property {@link #totalCount}.
*
* @return value for property {@link #totalCount}
*/
public int getTotalCount() {
return totalCount;
}
/**
* Getter for property {@link #photos}.
*
* @return value for property {@link #photos}
*/
public PhotoSize[][] getPhotos() {
return photos;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof UserProfilePhotos)) {
return false;
}
UserProfilePhotos userProfilePhotos = (UserProfilePhotos) obj;
return totalCount == userProfilePhotos.totalCount &&
Arrays.deepEquals(photos, userProfilePhotos.getPhotos());
}
@Override
public int hashCode() {
return 31 * totalCount + Arrays.deepHashCode(photos);
}
}
| mit |
Gnail-nehc/testclient | src/com/testclient/enums/LabFolderName.java | 88 | package com.testclient.enums;
public interface LabFolderName {
String folder="LAB";
}
| mit |
MihawkHu/SimPl | src/simpl/parser/ast/UnaryExpr.java | 154 | package simpl.parser.ast;
public abstract class UnaryExpr extends Expr {
public Expr e;
public UnaryExpr(Expr e) {
this.e = e;
}
}
| mit |
Nexmo/nexmo-java-sdk | src/main/java/com/vonage/client/incoming/SpeechResults.java | 2118 | /*
* Copyright (c) 2020 Vonage
*
* 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.vonage.client.incoming;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Collection;
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class SpeechResults {
@JsonProperty("timeout_reason")
private TimeoutReason timeoutReason;
private Collection<Result> results;
private String error;
public String getError() {
return error;
}
public TimeoutReason getTimeoutReason() {
return timeoutReason;
}
/**
* @param timeoutReason Indicates whether the input ended when the user stopped speaking, by the max duration
* timeout, or if the user didn't say anything
*/
public void setTimeoutReason(TimeoutReason timeoutReason) {
this.timeoutReason = timeoutReason;
}
public Collection<Result> getResults() {
return results;
}
/**
* @param results list of speech recognition results that displays the words(s) that the user spoke and the
* likelihood that the recognized word(s) in the list where the actual word(s) that the user spoke.
*/
public void setResults(Collection<Result> results) {
this.results = results;
}
public enum TimeoutReason {
@JsonProperty("end_on_silence_timeout")
END_ON_SILENCE_TIMEOUT,
@JsonProperty("max_duration")
MAX_DURATION,
@JsonProperty("start_timeout")
START_TIMEOUT
}
}
| mit |
good2000mo/OpenClassicAPI | src/main/java/ch/spacebase/openclassic/api/event/entity/EntityMoveEvent.java | 1442 | package ch.spacebase.openclassic.api.event.entity;
import ch.spacebase.openclassic.api.Position;
import ch.spacebase.openclassic.api.entity.BlockEntity;
import ch.spacebase.openclassic.api.event.Cancellable;
/**
* Called when an entity moves.
*/
public class EntityMoveEvent extends EntityEvent implements Cancellable {
private boolean cancelled = false;
private Position from;
private Position to;
public EntityMoveEvent(BlockEntity entity, Position from, Position to) {
super(EventType.ENTITY_MOVE, entity);
this.from = from;
this.to = to;
}
/**
* Gets the location this move is from.
* @return The location the move is from.
*/
public Position getFrom() {
return this.from;
}
/**
* Sets the location this move is from.
* @param from The location the move is from.
*/
public void setFrom(Position from) {
this.from = from;
}
/**
* Gets the location this move is to.
* @return The location the move is to.
*/
public Position getTo() {
return this.to;
}
/**
* Sets the location this move is to.
* @param to The location the move is to.
*/
public void setTo(Position to) {
this.to = to;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
}
| mit |
Blaubot/Blaubot | blaubot/src/main/java/eu/hgross/blaubot/mock/BlaubotDeviceMock.java | 1194 | package eu.hgross.blaubot.mock;
import eu.hgross.blaubot.core.IBlaubotDevice;
/**
* Mocks a blaubot device
*
* @author Henning Gross {@literal (mail.to@henning-gross.de)}
*
*/
public class BlaubotDeviceMock implements IBlaubotDevice {
private String uniqueId;
public BlaubotDeviceMock(String uniqueId) {
this.uniqueId = uniqueId;
}
@Override
public String getUniqueDeviceID() {
return uniqueId;
}
@Override
public int compareTo(IBlaubotDevice o) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getReadableName() {
// TODO Auto-generated method stub
return null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof BlaubotDeviceMock))
return false;
BlaubotDeviceMock other = (BlaubotDeviceMock) obj;
if (uniqueId == null) {
if (other.uniqueId != null)
return false;
} else if (!uniqueId.equals(other.uniqueId))
return false;
return true;
}
}
| mit |
arthurportas/academia-rumos-java15_16 | labs/soln/les09/FilmTest.java | 632 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class FilmTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Actor actor1 = new Actor(),
actor2 = new Actor(),
actor3 = new Actor();
Film film = new Film();
int actorsCount = 0;
film.addActor(actor1);
film.addActor(actor2);
actorsCount = film.addActor(actor3);
System.out.println("Total number of actors is " + actorsCount);
}
}
| mit |
TheBear01/App | FishGame/core/src/com/matt/game/states/playState.java | 1953 | package com.matt.game.states;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.matt.game.FishGame;
import com.matt.game.sprites.Fisherman;
/**
* Created by User on 16/04/2017.
*/
public class PlayState extends State {
private Fisherman fisher;
private Texture bg;
public PlayState(GameStateManager gsm) {
super(gsm);
fisher = new Fisherman(50,100);
cam.setToOrtho(false, FishGame.WIDTH / 2, FishGame.HEIGHT / 2); // drawing in
bg = new Texture("bg.png");
}
protected void handleInput() {
if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
fisher.left();
}
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
fisher.right();
}
}
public void update(float dt) {
handleInput();
fisher.update(dt);
}
public void render(SpriteBatch sb) { // REMEMBER !!! only drawing when the player can't see!
sb.setProjectionMatrix(cam.combined); // <Fish> ! <fish> ! //
sb.begin();
// ! ! <fish> //
sb.draw(bg, cam.position.x - (cam.viewportHeight /2), 0); // <Fish> ! fisher ! //
sb.draw(fisher.getTexture(), fisher.getPosition().x, fisher.getPosition().y); // <Fish> ! fisher ! //
sb.end(); // ! ! <fish> //
}
public void dispose() {
}
}
| mit |
dachengxi/spring1.1.1_source | test/org/springframework/beans/factory/xml/OverrideOneMethodSubclass.java | 993 | /*
* Copyright 2002-2004 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.beans.factory.xml;
/**
* Subclass of OverrideOneMethod, to check that overriding is
* supported for inherited methods.
* @author Rod Johnson
*/
public abstract class OverrideOneMethodSubclass extends OverrideOneMethod {
protected void doSomething(String arg) {
// This implementation does nothing!
// It's not overloaded
}
}
| mit |
sugandhi/CMPE273 | CMPE-273-Project/src/beans/InvoiceInfo.java | 1121 | package beans;
/**
* InvoiceInfo class
*
* @author Team 7
*/
public class InvoiceInfo {
private int invoiceId;
private String invoiceDate;
private float invoiceAmount;
public InvoiceInfo() {
// DO NOTHING
}
/**
* @return the invoiceId
*/
public final int getInvoiceId() {
return invoiceId;
}
/**
* @param invoiceId the invoiceId to set
*/
public final void setInvoiceId(int invoiceId) {
this.invoiceId = invoiceId;
}
/**
* @return the invoiceDate
*/
public final String getInvoiceDate() {
return invoiceDate;
}
/**
* @param invoiceDate the invoiceDate to set
*/
public final void setInvoiceDate(String invoiceDate) {
this.invoiceDate = invoiceDate;
}
/**
* @return the invoiceAmount
*/
public final float getInvoiceAmount() {
return invoiceAmount;
}
/**
* @param invoiceAmount the invoiceAmount to set
*/
public final void setInvoiceAmount(float invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
}
| mit |
IzzelAliz/LCL | src/main/java/me/kevinwalker/ui/controller/PopupController.java | 716 | package me.kevinwalker.ui.controller;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import me.kevinwalker.main.ImageResourc;
import java.net.URL;
import java.util.ResourceBundle;
public class PopupController implements Initializable {
public static PopupController instance;
public Label message;
public Button cancel;
public ImageView error;
@Override
public void initialize(URL location, ResourceBundle resources) {
instance = this;
if (ImageResourc.error != null)
error.setImage(ImageResourc.error);
else error.setImage(ImageResourc.loading);
}
}
| mit |
AlnaSoftware/eSaskaita | src/JAVA SRC/lt/registrucentras/esaskaita/service/invoice/ubl/cbc/TaxLevelCodeType.java | 4560 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.07.24 at 05:36:05 PM EEST
//
package lt.registrucentras.esaskaita.service.invoice.ubl.cbc;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.google.common.base.Objects;
import lt.registrucentras.esaskaita.service.invoice.ubl.udt.CodeType;
/**
* <p>Java class for TaxLevelCodeType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TaxLevelCodeType">
* <simpleContent>
* <extension base="<urn:oasis:names:specification:ubl:schema:xsd:UnqualifiedDataTypes-2>CodeType">
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TaxLevelCodeType")
public class TaxLevelCodeType
extends CodeType
implements Serializable
{
private final static long serialVersionUID = 1L;
/**
* Default no-arg constructor
*
*/
public TaxLevelCodeType() {
super();
}
/**
* Fully-initialising value constructor
*
*/
public TaxLevelCodeType(final String value, final String listID, final String listAgencyID, final String listAgencyName, final String listName, final String listVersionID, final String name, final String languageID, final String listURI, final String listSchemeURI) {
super(value, listID, listAgencyID, listAgencyName, listName, listVersionID, name, languageID, listURI, listSchemeURI);
}
@Override
public TaxLevelCodeType withValue(String value) {
setValue(value);
return this;
}
@Override
public TaxLevelCodeType withListID(String value) {
setListID(value);
return this;
}
@Override
public TaxLevelCodeType withListAgencyID(String value) {
setListAgencyID(value);
return this;
}
@Override
public TaxLevelCodeType withListAgencyName(String value) {
setListAgencyName(value);
return this;
}
@Override
public TaxLevelCodeType withListName(String value) {
setListName(value);
return this;
}
@Override
public TaxLevelCodeType withListVersionID(String value) {
setListVersionID(value);
return this;
}
@Override
public TaxLevelCodeType withName(String value) {
setName(value);
return this;
}
@Override
public TaxLevelCodeType withLanguageID(String value) {
setLanguageID(value);
return this;
}
@Override
public TaxLevelCodeType withListURI(String value) {
setListURI(value);
return this;
}
@Override
public TaxLevelCodeType withListSchemeURI(String value) {
setListSchemeURI(value);
return this;
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("value", value).add("listID", listID).add("listAgencyID", listAgencyID).add("listAgencyName", listAgencyName).add("listName", listName).add("listVersionID", listVersionID).add("name", name).add("languageID", languageID).add("listURI", listURI).add("listSchemeURI", listSchemeURI).toString();
}
@Override
public int hashCode() {
return Objects.hashCode(value, listID, listAgencyID, listAgencyName, listName, listVersionID, name, languageID, listURI, listSchemeURI);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (getClass()!= other.getClass()) {
return false;
}
final TaxLevelCodeType o = ((TaxLevelCodeType) other);
return (((((((((Objects.equal(value, o.value)&&Objects.equal(listID, o.listID))&&Objects.equal(listAgencyID, o.listAgencyID))&&Objects.equal(listAgencyName, o.listAgencyName))&&Objects.equal(listName, o.listName))&&Objects.equal(listVersionID, o.listVersionID))&&Objects.equal(name, o.name))&&Objects.equal(languageID, o.languageID))&&Objects.equal(listURI, o.listURI))&&Objects.equal(listSchemeURI, o.listSchemeURI));
}
}
| mit |
evdubs/XChange | xchange-bittrex/src/main/java/org/knowm/xchange/bittrex/dto/marketdata/BittrexTradesResponse.java | 942 | package org.knowm.xchange.bittrex.dto.marketdata;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonProperty;
public class BittrexTradesResponse {
private final boolean success;
private final String message;
private final BittrexTrade[] trades;
public BittrexTradesResponse(@JsonProperty("success") boolean success, @JsonProperty("message") String message,
@JsonProperty("result") BittrexTrade[] trades) {
super();
this.success = success;
this.message = message;
this.trades = trades;
}
public boolean getSuccess() {
return success;
}
public String getMessage() {
return message;
}
public BittrexTrade[] getTrades() {
return trades;
}
@Override
public String toString() {
return "BittrexTradesResponse [success=" + success + ", message=" + message + ", trades=" + Arrays.toString(trades) + "]";
}
}
| mit |
ejl888/spring-hateoas-extended | src/main/java/nl/my888/springframework/hateoas/links/ExtendedLink.java | 3407 | package nl.my888.springframework.hateoas.links;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.UriTemplate;
import org.springframework.hateoas.hal.Jackson2HalModule;
import org.springframework.http.HttpMethod;
/**
* A link extended with allowed HTTP methods.
*
* @author ejl
*
*/
@JsonIgnoreProperties(value = { "rel" })
public final class ExtendedLink extends Link {
private static final long serialVersionUID = 465184861038994286L;
@XmlAttribute
private final List<String> allow = new ArrayList<>(5);
/**
* Bouw link op met href, zonder methodes.
* @param link HAL link
*/
public ExtendedLink(Link link) {
this(link.getHref(), link.getRel(), null);
}
/**
* Bouw link op met href.
* @param href http referentiee
* @param rel Ilent relatie type
* @param methods methodes
*/
ExtendedLink(String href, String rel, Collection<String> methods) {
super(href, rel);
if (methods != null) {
this.allow.addAll(methods);
}
}
/**
* Bouw link op met href met UriTemplate.
* @param uriTemplate template voor gebruik van templated variabelen.
* @param rel Ilent relatie type
* @param methods methodes
*/
ExtendedLink(UriTemplate uriTemplate, String rel, Collection<String> methods) {
super(uriTemplate, rel);
if (methods != null) {
this.allow.addAll(methods);
}
}
@Override
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonSerialize(using = Jackson2HalModule.TrueOnlyBooleanSerializer.class)
public boolean isTemplated() {
return super.isTemplated();
}
public List<String> getAllow() {
return allow;
}
/**
* Voeg DELETE toe aan toegestaane methodes.
*
* @return kopie van link met toegevoegde methode.
*/
public ExtendedLink allowDelete() {
return allowMethod(HttpMethod.DELETE.name());
}
/**
* Voeg POST toe aan toegestaane methodes.
*
* @return kopie van link met toegevoegde methode.
*/
public ExtendedLink allowPost() {
return allowMethod(HttpMethod.POST.name());
}
/**
* Voeg PATCH toe aan toegestaane methodes.
*
* @return kopie van link met toegevoegde methode.
*/
public ExtendedLink allowPatch() {
return allowMethod(HttpMethod.PATCH.name());
}
/**
* Voeg GET toe aan toegestaane methodes.
*
* @return kopie van link met toegevoegde methode.
*/
public ExtendedLink allowGet() {
return allowMethod(HttpMethod.GET.name());
}
/**
* Voeg PUT toe aan toegestaane methodes.
*
* @return kopie van link met toegevoegde methode.
*/
public ExtendedLink allowPut() {
return allowMethod(HttpMethod.PUT.name());
}
private ExtendedLink allowMethod(String name) {
final Collection<String> methods = new ArrayList<>(allow);
methods.add(name);
return new ExtendedLink(getHref(), getRel(), methods);
}
}
| mit |
dansimpson/chronos | chronos-jackson/src/test/java/org/ds/chronos/timeline/json/JsonTest.java | 1679 | package org.ds.chronos.timeline.json;
import java.util.ArrayList;
import java.util.List;
import org.ds.chronos.api.ChronosException;
import org.ds.chronos.api.chronicle.MemoryChronicle;
import org.ds.chronos.timeline.SimpleTimeline;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.core.type.TypeReference;
public class JsonTest {
SimpleTimeline<JsonTestObject> timeline;
@Before
public void setup() throws ChronosException {
timeline = new JsonTimeline<JsonTestObject>(new MemoryChronicle(), new TypeReference<JsonTestObject>() {
});
}
public JsonTestObject buildObject(long time) {
JsonTestObject object = new JsonTestObject();
object.setId(4);
object.setName("Dan");
object.setAge(28);
object.setWeight(171.0);
object.setTimestamp(time);
return object;
}
@Test
public void testCodec() {
JsonTestObject object = buildObject(1000);
timeline.add(buildObject(1000));
JsonTestObject other = timeline.query(0, 1000).first().get();
Assert.assertNotNull(other);
Assert.assertEquals(object.getId(), other.getId());
Assert.assertEquals(object.getName(), other.getName());
Assert.assertEquals(object.getAge(), other.getAge());
Assert.assertEquals(object.getWeight(), other.getWeight(), 0.1);
Assert.assertEquals(object.getTimestamp(), other.getTimestamp());
}
@Test
public void testBatch() {
List<JsonTestObject> list = new ArrayList<JsonTestObject>();
for (int i = 0; i < 100; i++) {
list.add(buildObject(i * 1000));
}
timeline.add(list);
List<JsonTestObject> other = timeline.query(0, 1000 * 100).toList();
Assert.assertEquals(list.size(), other.size());
}
}
| mit |
adrobotics/BlackBoxGaming-Engine | src/main/java/com/blackboxgaming/engine/systems/ObstacleSpawnerSystem.java | 1742 | package com.blackboxgaming.engine.systems;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Disposable;
import com.blackboxgaming.engine.Entity;
import com.blackboxgaming.engine.util.Global;
import com.blackboxgaming.engine.util.OldButNotThatOldWorldSetup;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Adrian
*/
public class ObstacleSpawnerSystem implements ISystem, Disposable {
private final List<Entity> entities = new ArrayList();
private final List<Entity> bricks = new ArrayList();
public int maxObstacles;
public ObstacleSpawnerSystem(int maxObstacles) {
this.maxObstacles = maxObstacles;
}
@Override
public void add(Entity entity) {
if (!entities.contains(entity)) {
entities.add(entity);
}
}
@Override
public void remove(Entity entity) {
entities.remove(entity);
}
@Override
public void update(float delta) {
while (entities.size() < maxObstacles) {
if (MathUtils.randomBoolean()) {
bricks.addAll(OldButNotThatOldWorldSetup.createWall(Global.boxWidth - Global.boxWidth / 6f, Global.boxLength / 4f, 8, 1));
} else {
bricks.addAll(OldButNotThatOldWorldSetup.createWallAroundPoint(2, 6, Global.boxLength / 4f, 0, 0));
bricks.addAll(OldButNotThatOldWorldSetup.createWallAroundPoint(4, 4, Global.boxLength / 4f, 0, 0));
}
for (Entity brick : bricks) {
entities.add(brick);
}
bricks.clear();
}
}
@Override
public void dispose() {
System.out.println("Disposing " + this.getClass());
entities.clear();
}
}
| mit |
dentmaged/Cardinal-Dev | src/main/java/in/twizmwaz/cardinal/module/modules/wools/WoolObjective.java | 15266 | package in.twizmwaz.cardinal.module.modules.wools;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.chat.ChatConstant;
import in.twizmwaz.cardinal.chat.LocalizedChatMessage;
import in.twizmwaz.cardinal.chat.UnlocalizedChatMessage;
import in.twizmwaz.cardinal.event.CardinalDeathEvent;
import in.twizmwaz.cardinal.event.SnowflakeChangeEvent;
import in.twizmwaz.cardinal.event.objective.ObjectiveCompleteEvent;
import in.twizmwaz.cardinal.event.objective.ObjectiveProximityEvent;
import in.twizmwaz.cardinal.event.objective.ObjectiveTouchEvent;
import in.twizmwaz.cardinal.module.GameObjective;
import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion;
import in.twizmwaz.cardinal.module.modules.scoreboard.GameObjectiveScoreboardHandler;
import in.twizmwaz.cardinal.module.modules.snowflakes.Snowflakes;
import in.twizmwaz.cardinal.module.modules.timeLimit.TimeLimit;
import in.twizmwaz.cardinal.teams.Team;
import in.twizmwaz.cardinal.util.ChatUtils;
import in.twizmwaz.cardinal.util.FireworkUtil;
import in.twizmwaz.cardinal.util.MiscUtils;
import in.twizmwaz.cardinal.util.TeamUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Wool;
import org.bukkit.util.Vector;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class WoolObjective implements GameObjective {
private final Team team;
private final String name;
private final String id;
private final DyeColor color;
private final BlockRegion place;
private final boolean craftable;
private final boolean show;
private Vector location;
private double proximity;
private Set<UUID> playersTouched;
private boolean touched;
private boolean complete;
private GameObjectiveScoreboardHandler scoreboardHandler;
protected WoolObjective(final Team team, final String name, final String id, final DyeColor color, final BlockRegion place, final boolean craftable, final boolean show, final Vector location) {
this.team = team;
this.name = name;
this.id = id;
this.color = color;
this.place = place;
this.craftable = craftable;
this.show = show;
this.location = location;
this.proximity = Double.POSITIVE_INFINITY;
this.playersTouched = new HashSet<>();
this.scoreboardHandler = new GameObjectiveScoreboardHandler(this);
}
@Override
public void unload() {
HandlerList.unregisterAll(this);
}
@Override
public Team getTeam() {
return team;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getId() {
return id;
}
@Override
public boolean isTouched() {
return touched;
}
@Override
public boolean isComplete() {
return complete;
}
@Override
public boolean showOnScoreboard() {
return show;
}
public DyeColor getColor() {
return color;
}
@Override
public GameObjectiveScoreboardHandler getScoreboardHandler() {
return scoreboardHandler;
}
@EventHandler
public void onWoolPickup(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
if (!this.complete && GameHandler.getGameHandler().getMatch().isRunning()) {
try {
if (event.getCurrentItem().getType() == Material.WOOL && event.getCurrentItem().getData().getData() == color.getData()) {
if (TeamUtils.getTeamByPlayer(player) == team) {
boolean touchMessage = false;
if (!this.playersTouched.contains(player.getUniqueId())) {
this.playersTouched.add(player.getUniqueId());
if (this.show && !this.complete) {
TeamUtils.getTeamChannel(team).sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.GRAY + "{0}", new LocalizedChatMessage(ChatConstant.UI_OBJECTIVE_PICKED, player.getDisplayName() + ChatColor.GRAY, MiscUtils.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.GRAY)));
for (Player player1 : Bukkit.getOnlinePlayers()) {
if (TeamUtils.getTeamByPlayer(player1) != null && TeamUtils.getTeamByPlayer(player1).isObserver()) {
player1.sendMessage(new UnlocalizedChatMessage(ChatColor.GRAY + "{0}", new LocalizedChatMessage(ChatConstant.UI_OBJECTIVE_PICKED_FOR, player.getDisplayName() + ChatColor.GRAY, MiscUtils.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.GRAY, team.getCompleteName() + ChatColor.GRAY)).getMessage(player1.getLocale()));
}
}
touchMessage = true;
}
}
boolean oldState = this.touched;
this.touched = true;
if (touchMessage) {
double newProx;
if (location != null) {
newProx = location.distance(place.getVector());
} else {
newProx = player.getLocation().toVector().distance(place.getVector());
}
if (!oldState || newProx < proximity) {
proximity = newProx;
}
}
ObjectiveTouchEvent touchEvent = new ObjectiveTouchEvent(this, player, !oldState, touchMessage);
Bukkit.getServer().getPluginManager().callEvent(touchEvent);
}
}
} catch (NullPointerException e) {
}
}
}
@EventHandler
public void onWoolPickup(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
if (!this.complete && GameHandler.getGameHandler().getMatch().isRunning()) {
try {
if (event.getItem().getItemStack().getType() == Material.WOOL && event.getItem().getItemStack().getData().getData() == color.getData()) {
if (TeamUtils.getTeamByPlayer(player) == team) {
boolean touchMessage = false;
if (!this.playersTouched.contains(player.getUniqueId())) {
this.playersTouched.add(player.getUniqueId());
if (this.show && !this.complete) {
TeamUtils.getTeamChannel(team).sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.GRAY + "{0}", new LocalizedChatMessage(ChatConstant.UI_OBJECTIVE_PICKED, player.getDisplayName() + ChatColor.GRAY, MiscUtils.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.GRAY)));
for (Player player1 : Bukkit.getOnlinePlayers()) {
if (TeamUtils.getTeamByPlayer(player1) != null && TeamUtils.getTeamByPlayer(player1).isObserver()) {
player1.sendMessage(new UnlocalizedChatMessage(ChatColor.GRAY + "{0}", new LocalizedChatMessage(ChatConstant.UI_OBJECTIVE_PICKED_FOR, player.getDisplayName() + ChatColor.GRAY, MiscUtils.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.GRAY, team.getCompleteName() + ChatColor.GRAY)).getMessage(player1.getLocale()));
}
}
touchMessage = true;
}
}
boolean oldState = this.touched;
this.touched = true;
if (touchMessage) {
double newProx;
if (location != null) {
newProx = location.distance(place.getVector());
} else {
newProx = player.getLocation().toVector().distance(place.getVector());
}
if (!oldState || newProx < proximity) {
proximity = newProx;
}
}
ObjectiveTouchEvent touchEvent = new ObjectiveTouchEvent(this, player, !oldState, touchMessage);
Bukkit.getServer().getPluginManager().callEvent(touchEvent);
}
}
} catch (NullPointerException e) {
}
}
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
while (playersTouched.contains(event.getEntity().getUniqueId())) {
playersTouched.remove(event.getEntity().getUniqueId());
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event) {
if (event.getBlock().equals(place.getBlock())) {
if (event.getBlock().getType().equals(Material.WOOL)) {
if (((Wool) event.getBlock().getState().getData()).getColor().equals(color)) {
if (TeamUtils.getTeamByPlayer(event.getPlayer()) == team) {
this.complete = true;
if (this.show)
ChatUtils.getGlobalChannel().sendLocalizedMessage(new UnlocalizedChatMessage(ChatColor.WHITE + "{0}", new LocalizedChatMessage(ChatConstant.UI_OBJECTIVE_PLACED, event.getPlayer().getDisplayName() + ChatColor.WHITE, team.getCompleteName() + ChatColor.WHITE, MiscUtils.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.WHITE)));
FireworkUtil.spawnFirework(event.getPlayer().getLocation(), event.getPlayer().getWorld(), MiscUtils.convertChatColorToColor(MiscUtils.convertDyeColorToChatColor(color)));
ObjectiveCompleteEvent compEvent = new ObjectiveCompleteEvent(this, event.getPlayer());
Bukkit.getServer().getPluginManager().callEvent(compEvent);
event.setCancelled(false);
} else {
event.setCancelled(true);
if (this.show)
ChatUtils.sendWarningMessage(event.getPlayer(), "You may not complete the other team's objective.");
}
} else {
event.setCancelled(true);
if (this.show)
ChatUtils.sendWarningMessage(event.getPlayer(), new LocalizedChatMessage(ChatConstant.ERROR_BLOCK_PLACE, MiscUtils.convertDyeColorToChatColor(color) + color.name().toUpperCase().replaceAll("_", " ") + " WOOL" + ChatColor.RED));
}
} else {
event.setCancelled(true);
if (this.show)
ChatUtils.sendWarningMessage(event.getPlayer(), new LocalizedChatMessage(ChatConstant.ERROR_BLOCK_PLACE, MiscUtils.convertDyeColorToChatColor(color) + color.name().toUpperCase().replaceAll("_", " ") + " WOOL" + ChatColor.RED));
}
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
if (event.getBlock().equals(place.getBlock())) {
event.setCancelled(true);
}
}
@EventHandler
public void onCraftWool(CraftItemEvent event) {
if (event.getRecipe().getResult().equals(new ItemStack(Material.WOOL, 1, color.getData())) && !this.craftable) {
event.setCancelled(true);
}
}
@EventHandler
public void onCardinalDeath(CardinalDeathEvent event) {
if (event.getKiller() != null && location != null && GameHandler.getGameHandler().getMatch().isRunning() && !this.touched && TeamUtils.getTeamByPlayer(event.getKiller()) != null && TeamUtils.getTeamByPlayer(event.getKiller()) == this.team) {
if (event.getKiller().getLocation().toVector().distance(location) < proximity) {
double old = proximity;
proximity = event.getKiller().getLocation().toVector().distance(location);
Bukkit.getServer().getPluginManager().callEvent(new ObjectiveProximityEvent(this, event.getKiller(), old, proximity));
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onSafetyPlace(BlockPlaceEvent event) {
if (!event.isCancelled() && this.touched) {
if (event.getBlock().getType().equals(Material.WOOL)) {
if (((Wool) event.getBlock().getState().getData()).getColor().equals(color)) {
if (TeamUtils.getTeamByPlayer(event.getPlayer()) == team) {
if (event.getBlockPlaced().getLocation().distance(place.getLocation()) < proximity) {
double old = proximity;
proximity = event.getBlockPlaced().getLocation().distance(place.getLocation());
Bukkit.getServer().getPluginManager().callEvent(new ObjectiveProximityEvent(this, event.getPlayer(), old, proximity));
}
}
}
}
}
}
public double getProximity() {
return proximity;
}
public boolean showProximity() {
return GameHandler.getGameHandler().getMatch().getModules().getModule(TimeLimit.class).getTimeLimit() != 0 && GameHandler.getGameHandler().getMatch().getModules().getModule(TimeLimit.class).getResult().equals(TimeLimit.Result.MOST_OBJECTIVES);
}
@EventHandler
public void onWoolTouch(ObjectiveTouchEvent event) {
if (event.getObjective().equals(this) && event.displayTouchMessage()) {
Bukkit.getServer().getPluginManager().callEvent(new SnowflakeChangeEvent(event.getPlayer(), Snowflakes.ChangeReason.WOOL_TOUCH, 8, MiscUtils.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.GRAY));
}
}
@EventHandler
public void onWoolPlace(ObjectiveCompleteEvent event) {
if (event.getObjective().equals(this) && event.getObjective().showOnScoreboard()) {
Bukkit.getServer().getPluginManager().callEvent(new SnowflakeChangeEvent(event.getPlayer(), Snowflakes.ChangeReason.WOOL_PLACE, 15, MiscUtils.convertDyeColorToChatColor(color) + name.toUpperCase().replaceAll("_", " ") + ChatColor.GRAY));
}
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/chain/web/SearchSfEuOrderController.java | 886 | package com.swfarm.biz.chain.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.swfarm.biz.chain.srv.SfShippingService;
public class SearchSfEuOrderController extends AbstractController {
private SfShippingService sfShippingService;
public void setSfShippingService(SfShippingService sfShippingService) {
this.sfShippingService = sfShippingService;
}
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse res) throws Exception {
String orderid = req.getParameter("orderid");
String shippingOrderNo = this.sfShippingService.searchEuOrder(orderid);
logger.warn("shipping order no [" + shippingOrderNo + "]");
return null;
}
}
| mit |
LetsCoders/MassiveTanks | src/main/java/pl/letscode/tanks/map/terrain/solid/SolidBlockFactory.java | 910 | package pl.letscode.tanks.map.terrain.solid;
import org.dyn4j.dynamics.Body;
import org.dyn4j.dynamics.BodyFixture;
import org.dyn4j.geometry.Mass.Type;
import org.dyn4j.geometry.Rectangle;
import pl.letscode.tanks.map.terrain.TerrainObject;
public final class SolidBlockFactory {
private SolidBlockFactory() {
// private
}
public static SolidBlock getBlock(final long id) {
Body solidBody = buildBody();
SolidBlock solidBlock = new SolidBlock(solidBody, id);
solidBody.setUserData(solidBlock);
return solidBlock;
}
private static Body buildBody() {
Body body = new Body();
Rectangle rectangle = new Rectangle(TerrainObject.DEFAULT_TERRAIN_SIZE,
TerrainObject.DEFAULT_TERRAIN_SIZE);
BodyFixture bodyFixture = new BodyFixture(rectangle);
bodyFixture.setRestitution(0.01);
body.addFixture(bodyFixture);
body.setMass();
body.setMassType(Type.INFINITE);
return body;
}
}
| mit |
settipalli/Algorithms | src/ch2/test/QuickSortTest.java | 7954 | /*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ****************************************************************************
*/
package ch2.test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import ch2.QuickSort;
import edu.princeton.cs.introcs.In;
import edu.princeton.cs.introcs.StdOut;
public class QuickSortTest {
String[] inputChars;
String[] inputWords;
Integer[] inputNumber1k;
Integer[] inputNumber2k;
Integer[] inputNumber4k;
Integer[] inputNumber8k;
public QuickSortTest() {
String filePathPrefix = "/home/ssettipalli/workspace/projects/github/Algorithms/src/ch2/test/data/Sort";
inputChars = In.readStrings(filePathPrefix + "/tiny.txt");
inputWords = In.readStrings(filePathPrefix + "/words3.txt");
int[] int1kvalues = In.readInts(filePathPrefix + "/1Kints.txt");
inputNumber1k = new Integer[int1kvalues.length];
for (int i = 0; i < int1kvalues.length; i++)
inputNumber1k[i] = int1kvalues[i];
int[] int2kvalues = In.readInts(filePathPrefix + "/2Kints.txt");
inputNumber2k = new Integer[int2kvalues.length];
for (int i = 0; i < int2kvalues.length; i++)
inputNumber2k[i] = int2kvalues[i];
int[] int4kvalues = In.readInts(filePathPrefix + "/4Kints.txt");
inputNumber4k = new Integer[int4kvalues.length];
for (int i = 0; i < int4kvalues.length; i++)
inputNumber4k[i] = int4kvalues[i];
int[] int8kvalues = In.readInts(filePathPrefix + "/8Kints.txt");
inputNumber8k = new Integer[int8kvalues.length];
for (int i = 0; i < int8kvalues.length; i++)
inputNumber8k[i] = int8kvalues[i];
}
@Test
public void testSort() {
// Ascending order sort - Characters
QuickSort.sort(inputChars, true);
boolean isSorted = QuickSort.isSorted(inputChars, 0,
inputChars.length - 1, true);
assertEquals(true, isSorted);
for (String c : inputChars)
StdOut.print("\"" + c + "\", ");
// Descending order sort - Characters
StdOut.println();
QuickSort.sort(inputChars, false);
isSorted = QuickSort.isSorted(inputChars, 0, inputChars.length - 1,
false);
assertEquals(true, isSorted);
for (String c : inputChars)
StdOut.print("\"" + c + "\", ");
// Ascending order sort - words
StdOut.println();
QuickSort.sort(inputWords, true);
isSorted = QuickSort.isSorted(inputWords, 0, inputWords.length - 1,
true);
assertEquals(true, isSorted);
for (String c : inputWords)
StdOut.print("\"" + c + "\", ");
// Descending order sort - words
StdOut.println();
QuickSort.sort(inputWords, false);
isSorted = QuickSort.isSorted(inputWords, 0, inputWords.length - 1,
false);
assertEquals(true, isSorted);
for (String c : inputWords)
StdOut.print("\"" + c + "\", ");
// Ascending order sort - 1000 numbers
StdOut.println();
QuickSort.sort(inputNumber1k, true);
isSorted = QuickSort.isSorted(inputNumber1k, 0,
inputNumber1k.length - 1, true);
assertEquals(true, isSorted);
// Descending order sort - 1000 numbers
StdOut.println();
QuickSort.sort(inputNumber1k, false);
isSorted = QuickSort.isSorted(inputNumber1k, 0,
inputNumber1k.length - 1, false);
assertEquals(true, isSorted);
// Ascending order sort - 2000 numbers
StdOut.println();
QuickSort.sort(inputNumber2k, true);
isSorted = QuickSort.isSorted(inputNumber2k, 0,
inputNumber2k.length - 1, true);
assertEquals(true, isSorted);
// Descending order sort - 2000 numbers
StdOut.println();
QuickSort.sort(inputNumber2k, false);
isSorted = QuickSort.isSorted(inputNumber2k, 0,
inputNumber2k.length - 1, false);
assertEquals(true, isSorted);
// Ascending order sort - 4000 numbers
StdOut.println();
QuickSort.sort(inputNumber4k, true);
isSorted = QuickSort.isSorted(inputNumber4k, 0,
inputNumber4k.length - 1, true);
assertEquals(true, isSorted);
// Descending order sort - 4000 numbers
StdOut.println();
QuickSort.sort(inputNumber4k, false);
isSorted = QuickSort.isSorted(inputNumber4k, 0,
inputNumber4k.length - 1, false);
assertEquals(true, isSorted);
// Ascending order sort - 8000 numbers
StdOut.println();
QuickSort.sort(inputNumber8k, true);
isSorted = QuickSort.isSorted(inputNumber8k, 0,
inputNumber8k.length - 1, true);
assertEquals(true, isSorted);
// Descending order sort - 8000 numbers
StdOut.println();
QuickSort.sort(inputNumber8k, false);
isSorted = QuickSort.isSorted(inputNumber8k, 0,
inputNumber8k.length - 1, false);
assertEquals(true, isSorted);
}
@Test
public void testIsSorted() {
// Check for ascending order sort - characters.
String[] inputSet1 = { "A", "E", "E", "L", "M", "O", "P", "R", "S",
"T", "X" };
boolean isSorted = QuickSort.isSorted(inputSet1, 0,
inputSet1.length - 1, true);
assertEquals(true, isSorted);
// Check for descending order sort - characters.
String[] inputSet2 = { "X", "T", "S", "R", "P", "O", "M", "L", "E",
"E", "A" };
isSorted = QuickSort
.isSorted(inputSet2, 0, inputSet2.length - 1, false);
assertEquals(true, isSorted);
// Check for ascending order sort - words.
String[] inputSet3 = { "all", "bad", "bed", "bug", "dad", "dim", "dug",
"egg", "fee", "few", "for", "gig", "hut", "ilk", "jam", "jay",
"jot", "joy", "men", "nob", "now", "owl", "rap", "sky", "sob",
"tag", "tap", "tar", "tip", "wad", "was", "wee", "yes", "yet",
"zoo" };
isSorted = QuickSort.isSorted(inputSet3, 0, inputSet3.length - 1, true);
assertEquals(true, isSorted);
// Check for descending order sort - words.
String[] inputSet4 = { "zoo", "yet", "yes", "wee", "was", "wad", "tip",
"tar", "tap", "tag", "sob", "sky", "rap", "owl", "now", "nob",
"men", "joy", "jot", "jay", "jam", "ilk", "hut", "gig", "for",
"few", "fee", "egg", "dug", "dim", "dad", "bug", "bed", "bad",
"all", };
isSorted = QuickSort
.isSorted(inputSet4, 0, inputSet4.length - 1, false);
assertEquals(true, isSorted);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/metricsadvisor/azure-ai-metricsadvisor/src/main/java/com/azure/ai/metricsadvisor/administration/MetricsAdvisorAdministrationClientBuilder.java | 16597 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.metricsadvisor.administration;
import com.azure.ai.metricsadvisor.implementation.AzureCognitiveServiceMetricsAdvisorRestAPIOpenAPIV2Impl;
import com.azure.ai.metricsadvisor.implementation.AzureCognitiveServiceMetricsAdvisorRestAPIOpenAPIV2ImplBuilder;
import com.azure.ai.metricsadvisor.models.MetricsAdvisorKeyCredential;
import com.azure.ai.metricsadvisor.models.MetricsAdvisorServiceVersion;
import com.azure.core.annotation.ServiceClientBuilder;
import com.azure.core.http.ContentType;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.policy.AddDatePolicy;
import com.azure.core.http.policy.AddHeadersPolicy;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.policy.HttpPolicyProviders;
import com.azure.core.http.policy.RequestIdPolicy;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.Configuration;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* This class provides a fluent builder API to help instantiation of
* {@link MetricsAdvisorAdministrationClient MetricsAdvisorAdministrationClients}
* and {@link MetricsAdvisorAdministrationAsyncClient MetricsAdvisorAdministrationAsyncClient},
* call {@link #buildClient()} buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively to
* construct an instance of the desired client.
*
* <p>
* The client needs the service endpoint of the Azure Metrics Advisor to access the resource service.
* {@link #credential(MetricsAdvisorKeyCredential)} gives the builder access to credential.
* </p>
*
* <p><strong>Instantiating an asynchronous Metrics Advisor Client</strong></p>
*
* {@codesnippet com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationAsyncClient.instantiation}
*
* <p><strong>Instantiating a synchronous Metrics Advisor Client</strong></p>
*
* {@codesnippet com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationClient.instantiation}
*
* <p>
* Another way to construct the client is using a {@link HttpPipeline}. The pipeline gives the client an
* authenticated way to communicate with the service. Set the pipeline with {@link #pipeline(HttpPipeline) this} and
* set the service endpoint with {@link #endpoint(String) this}. Using a
* pipeline requires additional setup but allows for finer control on how the {@link MetricsAdvisorAdministrationClient}
* and {@link MetricsAdvisorAdministrationAsyncClient} is built.
* </p>
*
* {@codesnippet com.azure.ai.metricsadvisor.administration.MetricsAdvisorAdministrationClient.pipeline.instantiation}
*
* @see MetricsAdvisorAdministrationAsyncClient
* @see MetricsAdvisorAdministrationClient
*/
@ServiceClientBuilder(serviceClients = {MetricsAdvisorAdministrationAsyncClient.class,
MetricsAdvisorAdministrationClient.class})
public final class MetricsAdvisorAdministrationClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON;
private static final String ACCEPT_HEADER = "Accept";
private static final String METRICSADVISOR_PROPERTIES = "azure-ai-metricsadvisor.properties";
private static final String NAME = "name";
private static final String VERSION = "version";
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms",
ChronoUnit.MILLIS);
private static final String DEFAULT_SCOPE = "https://cognitiveservices.azure.com/.default";
private final ClientLogger logger = new ClientLogger(MetricsAdvisorAdministrationClientBuilder.class);
private final List<HttpPipelinePolicy> policies;
private final HttpHeaders headers;
private final String clientName;
private final String clientVersion;
private String endpoint;
private MetricsAdvisorKeyCredential credential;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private MetricsAdvisorServiceVersion version;
static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key";
static final String API_KEY = "x-api-key";
/**
* The constructor with defaults.
*/
public MetricsAdvisorAdministrationClientBuilder() {
policies = new ArrayList<>();
httpLogOptions = new HttpLogOptions();
Map<String, String> properties = CoreUtils.getProperties(METRICSADVISOR_PROPERTIES);
clientName = properties.getOrDefault(NAME, "UnknownName");
clientVersion = properties.getOrDefault(VERSION, "UnknownVersion");
headers = new HttpHeaders()
.put(ECHO_REQUEST_ID_HEADER, "true")
.put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE);
}
/**
* Creates a {@link MetricsAdvisorAdministrationClient} based on options set in the builder. Every time
* {@code buildClient()} is called a new instance of {@link MetricsAdvisorAdministrationClient} is created.
*
* <p>
* If {@link #pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and
* {@link #endpoint(String) endpoint} are used to create the {@link MetricsAdvisorAdministrationClient client}.
* All other builder settings are ignored.
* </p>
*
* @return A MetricsAdvisorAdministrationClient with the options set from the builder.
* @throws NullPointerException if {@link #endpoint(String) endpoint} or
* {@link #credential(MetricsAdvisorKeyCredential)} has not been set.
* @throws IllegalArgumentException if {@link #endpoint(String) endpoint} cannot be parsed into a valid URL.
*/
public MetricsAdvisorAdministrationClient buildClient() {
return new MetricsAdvisorAdministrationClient(buildAsyncClient());
}
/**
* Creates a {@link MetricsAdvisorAdministrationAsyncClient} based on options set in the builder. Every time
* {@code buildAsyncClient()} is called a new instance of {@link MetricsAdvisorAdministrationAsyncClient} is
* created.
*
* <p>
* If {@link #pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and
* {@link #endpoint(String) endpoint} are used to create the {@link MetricsAdvisorAdministrationClient client}.
* All other builder settings are ignored.
* </p>
*
* @return A MetricsAdvisorAdministrationAsyncClient with the options set from the builder.
* @throws NullPointerException if {@link #endpoint(String) endpoint} or
* {@link #credential(MetricsAdvisorKeyCredential)} has not been set.
* @throws IllegalArgumentException if {@link #endpoint(String) endpoint} cannot be parsed into a valid URL.
*/
public MetricsAdvisorAdministrationAsyncClient buildAsyncClient() {
// Endpoint cannot be null, which is required in request authentication
Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null.");
// Global Env configuration store
final Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration().clone() : configuration;
// Service Version
final MetricsAdvisorServiceVersion serviceVersion =
version != null ? version : MetricsAdvisorServiceVersion.getLatest();
HttpPipeline pipeline = httpPipeline;
// Create a default Pipeline if it is not given
if (pipeline == null) {
pipeline = getDefaultHttpPipeline(buildConfiguration);
}
final AzureCognitiveServiceMetricsAdvisorRestAPIOpenAPIV2Impl advisorRestAPIOpenAPIV2 =
new AzureCognitiveServiceMetricsAdvisorRestAPIOpenAPIV2ImplBuilder()
.endpoint(endpoint)
.pipeline(pipeline)
.buildClient();
return new MetricsAdvisorAdministrationAsyncClient(advisorRestAPIOpenAPIV2, serviceVersion);
}
private HttpPipeline getDefaultHttpPipeline(Configuration buildConfiguration) {
// Closest to API goes first, closest to wire goes last.
final List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion,
buildConfiguration));
policies.add(new RequestIdPolicy());
policies.add(new AddHeadersPolicy(headers));
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy);
policies.add(new AddDatePolicy());
// Authentications
if (credential.getSubscriptionKey() != null || credential.getApiKey() != null) {
headers.put(OCP_APIM_SUBSCRIPTION_KEY, credential.getSubscriptionKey());
headers.put(API_KEY, credential.getApiKey());
} else {
// Throw exception that credential cannot be null
throw logger.logExceptionAsError(
new IllegalArgumentException("Missing credential information while building a client."));
}
policies.addAll(this.policies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Sets the service endpoint for the Azure Metrics Advisor instance.
*
* @param endpoint The URL of the Azure Metrics Advisor instance service requests to and receive responses from.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
* @throws NullPointerException if {@code endpoint} is null
* @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL.
*/
public MetricsAdvisorAdministrationClientBuilder endpoint(String endpoint) {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL.", ex));
}
if (endpoint.endsWith("/")) {
this.endpoint = endpoint.substring(0, endpoint.length() - 1);
} else {
this.endpoint = endpoint;
}
return this;
}
/**
* Sets the {@link MetricsAdvisorKeyCredential} to use when authenticating HTTP requests for this
* MetricsAdvisorAdministrationClientBuilder.
*
* @param metricsAdvisorKeyCredential {@link MetricsAdvisorKeyCredential} API key credential
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
* @throws NullPointerException If {@code metricsAdvisorKeyCredential} is null.
*/
public MetricsAdvisorAdministrationClientBuilder credential(
MetricsAdvisorKeyCredential metricsAdvisorKeyCredential) {
this.credential = Objects.requireNonNull(metricsAdvisorKeyCredential,
"'metricsAdvisorKeyCredential' cannot be null.");
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p>If {@code logOptions} isn't provided, the default options will use {@link HttpLogDetailLevel#NONE}
* which will prevent logging.</p>
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
*/
public MetricsAdvisorAdministrationClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a policy to the set of existing policies that are executed after required policies.
*
* @param policy The retry policy for service requests.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
public MetricsAdvisorAdministrationClientBuilder addPolicy(HttpPipelinePolicy policy) {
policies.add(Objects.requireNonNull(policy, "'policy' cannot be null."));
return this;
}
/**
* Sets the HTTP client to use for sending and receiving requests to and from the service.
*
* @param client The HTTP client to use for requests.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
*/
public MetricsAdvisorAdministrationClientBuilder httpClient(HttpClient client) {
if (this.httpClient != null && client == null) {
logger.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = client;
return this;
}
/**
* Sets the HTTP pipeline to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from
* {@link MetricsAdvisorAdministrationClientBuilder#endpoint(String) endpoint} to build
* {@link MetricsAdvisorAdministrationAsyncClient} or {@link MetricsAdvisorAdministrationClient}.
*
* @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
*/
public MetricsAdvisorAdministrationClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
* <p>
* The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global
* configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction.
*
* @param configuration The configuration store used to.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
*/
public MetricsAdvisorAdministrationClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy#RetryPolicy()} that is used when each request is sent.
* <p>
* The default retry policy will be used if not provided
* {@link MetricsAdvisorAdministrationClientBuilder#buildAsyncClient()}
* to build {@link MetricsAdvisorAdministrationAsyncClient} or {@link MetricsAdvisorAdministrationClient}.
*
* @param retryPolicy user's retry policy applied to each request.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
*/
public MetricsAdvisorAdministrationClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link MetricsAdvisorServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link MetricsAdvisorServiceVersion} of the service to be used when making requests.
*
* @return The updated MetricsAdvisorAdministrationClientBuilder object.
*/
public MetricsAdvisorAdministrationClientBuilder serviceVersion(MetricsAdvisorServiceVersion version) {
this.version = version;
return this;
}
}
| mit |
sharathprabhal/NBS3Sync | src/test/java/com/example/utils/TestingUtils.java | 2153 | package com.example.utils;
import com.example.config.Config;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
public class TestingUtils {
public static Config getMockConfig() {
Path path = getConfigFile("key", "secret", "/foo/bar", "foo", "testQueue");
return new Config(path);
}
public static Path getConfigFile(String awsKey, String secretKey, String baseDir, String bucketName, String queueName) {
Path path = null;
try {
String prefix = "temp";
String suffix = ".properties";
File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
PrintWriter printWriter = new PrintWriter(tempFile);
String sampleProperties = "awsAccessKey=" + awsKey +
"\nawsSecretKey=" + secretKey +
"\nbaseDirectory=" + baseDir +
"\nbucket=" + bucketName +
"\nqueueName=" + queueName;
printWriter.write(sampleProperties);
printWriter.close();
path = tempFile.toPath();
} catch (IOException e) {
//TODO: Log it..
}
return path;
}
public static Path createTempFile(Path baseDir, String prefix, String suffix) throws IOException {
Path tmp = Files.createTempFile(baseDir, prefix, suffix);
tmp.toFile().deleteOnExit();
return tmp;
}
public static Path createTempFile(String prefix, String suffix) throws IOException {
Path tmp = Files.createTempFile(prefix, suffix);
tmp.toFile().deleteOnExit();
return tmp;
}
public static Path createTempDirectory(String prefix) throws IOException {
Path dir = Files.createTempDirectory(prefix);
dir.toFile().deleteOnExit();
return dir;
}
public static Path createTempDirectory(Path baseDir, String prefix) throws IOException {
Path dir = Files.createTempDirectory(baseDir, prefix);
dir.toFile().deleteOnExit();
return dir;
}
}
| mit |
matgr1/ai-playground | neat/src/main/java/matgr/ai/neat/NeatGenome.java | 8939 | package matgr.ai.neat;
import matgr.ai.genetic.Genome;
import matgr.ai.neuralnet.cyclic.NeuronParameters;
import matgr.ai.neuralnet.cyclic.*;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
// TODO: look here: http://nn.cs.utexas.edu/downloads/papers/stanley.gecco02_1.pdf and
// here: http://nn.cs.utexas.edu/downloads/papers/stanley.ec02.pdf
public class NeatGenome implements Genome {
protected UUID genomeId;
// TODO: don't expose this?
public final NeatNeuralNet neuralNet;
public NeatGenome(int inputCount,
Iterable<NeuronParameters> outputNodesParameters) {
this(
new NeatNeuralNet(inputCount, outputNodesParameters),
UUID.randomUUID());
}
public NeatGenome(NeatGenome other) {
this(CyclicNeuralNet.deepClone(other.neuralNet), other.genomeId);
}
private NeatGenome(NeatNeuralNet neuralNet, UUID genomeId) {
this.neuralNet = neuralNet;
this.genomeId = genomeId;
}
@Override
public NeatGenome deepClone(UUID genomeId) {
NeatGenome clone = deepClone();
clone.genomeId = genomeId;
return clone;
}
public NeatGenome deepClone() {
return new NeatGenome(this);
}
@Override
public UUID genomeId() {
return genomeId;
}
public static double computeDistance(NeatGenome a,
NeatGenome b,
double excessFactor,
double disjointFactor,
double weightFactor,
int baseGenomeSize,
int minGenomeNormalizationSize) {
// TODO: maybe find a better way of computing the distance? this might start getting a bit low when the
// number of connections increases... (or maybe not as long as there are lots of different connections?)
// TODO: might not matter when pruning is implemented... ? ...can something be detected somehow?
// TODO: maybe normalizationSize should always be 1?
// TODO: compare neurons as well? (activation functions/parameters?) ...does this make sense since they aren't
// correlated for crossover? (might still be useful for speciation...)
int sizeA = a.neuralNet.connectionMap().size() - baseGenomeSize;
int sizeB = b.neuralNet.connectionMap().size() - baseGenomeSize;
int normalizationSize = Math.max(1, Math.max(sizeA, sizeB) - minGenomeNormalizationSize);
return computeDistance(a, b, excessFactor, disjointFactor, weightFactor, normalizationSize);
}
public static double computeDistance(NeatGenome a,
NeatGenome b,
double excessFactor,
double disjointFactor,
double weightFactor) {
return computeDistance(a, b, excessFactor, disjointFactor, weightFactor, 1);
}
public static void correlate(
NeatGenome a,
NeatGenome b,
Consumer<NeatConnection> onExcess,
Consumer<NeatConnection> onDisjoint,
BiConsumer<NeatConnection, NeatConnection> onMatch) {
correlate(a, b, onExcess, onDisjoint, onExcess, onDisjoint, onMatch);
}
public static void correlate(
NeatGenome a,
NeatGenome b,
Consumer<NeatConnection> onAExcess,
Consumer<NeatConnection> onADisjoint,
Consumer<NeatConnection> onBExcess,
Consumer<NeatConnection> onBDisjoint,
BiConsumer<NeatConnection, NeatConnection> onMatch) {
SortedConnectionGeneIterator aEnum = new SortedConnectionGeneIterator(a.neuralNet.connectionMap());
SortedConnectionGeneIterator bEnum = new SortedConnectionGeneIterator(b.neuralNet.connectionMap());
if (aEnum.isPastEnd()) {
while (!bEnum.isPastEnd()) {
onAExcess.accept(bEnum.getCurrent());
bEnum.increment();
}
} else if (bEnum.isPastEnd()) {
while (!aEnum.isPastEnd()) {
onAExcess.accept(aEnum.getCurrent());
aEnum.increment();
}
} else {
while (!aEnum.isPastEnd() || !bEnum.isPastEnd()) {
if (aEnum.isPastEnd()) {
if (null != aEnum.getPrevious()) {
long aEndInnovationId = aEnum.getPrevious().innovationNumber;
long bInnovationId = bEnum.getCurrent().innovationNumber;
if (bInnovationId > aEndInnovationId) {
// b excess
onBExcess.accept(bEnum.getCurrent());
} else {
// b disjoint
onBDisjoint.accept(bEnum.getCurrent());
}
} else {
// b excess
onBExcess.accept(bEnum.getCurrent());
}
bEnum.increment();
} else if (bEnum.isPastEnd()) {
if (null != bEnum.getPrevious()) {
long bEndInnovationId = bEnum.getPrevious().innovationNumber;
long aInnovationId = aEnum.getCurrent().innovationNumber;
if (aInnovationId > bEndInnovationId) {
// a excess
onAExcess.accept(aEnum.getCurrent());
} else {
// a disjoint
onADisjoint.accept(aEnum.getCurrent());
}
} else {
// a excess
onAExcess.accept(aEnum.getCurrent());
}
aEnum.increment();
} else {
long aInnovationId = aEnum.getCurrent().innovationNumber;
long bInnovationId = bEnum.getCurrent().innovationNumber;
if (aInnovationId < bInnovationId) {
if (bEnum.isAtStart()) {
// a excess
onAExcess.accept(aEnum.getCurrent());
} else {
// a disjoint
onADisjoint.accept(aEnum.getCurrent());
}
aEnum.increment();
} else if (bInnovationId < aInnovationId) {
if (aEnum.isAtStart()) {
// b excess
onBExcess.accept(bEnum.getCurrent());
} else {
// b disjoint
onBDisjoint.accept(bEnum.getCurrent());
}
bEnum.increment();
} else {
// match
onMatch.accept(aEnum.getCurrent(), bEnum.getCurrent());
aEnum.increment();
bEnum.increment();
}
}
}
}
}
private static double computeDistance(NeatGenome a,
NeatGenome b,
double excessFactor,
double disjointFactor,
double weightFactor,
int normalizationSize) {
final int[] disjointCount = {0};
final int[] excessCount = {0};
final double[] weightDifferenceSum = {0.0};
final int[] weightDifferenceCount = {0};
correlate(
a,
b,
c -> excessCount[0]++,
c -> disjointCount[0]++,
(cA, cB) -> {
double difference = Math.abs(cA.weight - cB.weight);
weightDifferenceSum[0] += difference;
weightDifferenceCount[0]++;
});
double averageWeightDifference = 0.0;
if (weightDifferenceCount[0] > 0) {
averageWeightDifference = weightDifferenceSum[0] / (double) weightDifferenceCount[0];
}
double excessDistance = excessFactor * (double) excessCount[0] / (double) normalizationSize;
double disjointDistance = disjointFactor * (double) disjointCount[0] / (double) normalizationSize;
double weightDistance = weightFactor * averageWeightDifference;
return excessDistance + disjointDistance + weightDistance;
}
}
| mit |
tyagihas/awsbigdata | kinesisapp/src/com/amazonaws/services/kinesis/app/Processor.java | 3040 | package com.amazonaws.services.kinesis.app;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import com.amazonaws.services.dynamodb.loader.Loader;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessor;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorCheckpointer;
import com.amazonaws.services.kinesis.clientlibrary.types.ShutdownReason;
import com.amazonaws.services.kinesis.model.Record;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
/**
* Processor
*
* Message format : <user id>,<latitude>,<longitude>
* eg.
* 10290,35.40.100,139.45.205
* 20135,35.38.200,139.35.208
* ...
*
**/
public class Processor implements IRecordProcessor {
private long counter;
private int target;
private HashSet<String> users;
private CoordinateListener coordsListener;
private LogAnalyzer logAnalyzer;
private Loader loader;
private byte[] bytearray;
public Processor() {
counter = 0;
target = 50;
bytearray = new byte[128];
}
@Override
public void initialize(String arg0) {
coordsListener = new CoordinateListener();
try {
logAnalyzer = new LogAnalyzer();
loader = new Loader();
users = logAnalyzer.getUsers();
} catch (SQLException e) {
e.printStackTrace();
System.exit(1);
}
}
@Override
public void processRecords(List<Record> arg0, IRecordProcessorCheckpointer arg1) {
counter += arg0.size();
if (counter > target) {
System.out.println("Received : " + counter + " records");
target += target;
}
Record rec;
for(int i = 0; i < arg0.size(); i++) {
rec = arg0.get(i);
try {
verifyRecord(rec.getData());
}
catch (JSONException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
private boolean verifyRecord(ByteBuffer buffer) throws JSONException, UnsupportedEncodingException {
buffer.get(bytearray, 0, buffer.remaining());
JSONObject json = new JSONObject(new String(bytearray, "UTF-8"));
String user = json.getString("user");
if (users.contains(user)) {
MessageProxy proxy = MessageProxy.getInstance();
double x = json.getDouble("latitude");
double y = json.getDouble("longitude");
proxy.sendMesg(user + "," + json.getDouble("latitude") + "," + json.getDouble("longitude"));
System.out.println(x + "," + y);
if (coordsListener.verifyCoordinates(x, y)) {
System.out.println("Matched! '" + user + "' is at (" + x + ", " + y + ")");
loader.put(user, System.currentTimeMillis(), x, y);
return true;
}
}
return false;
}
@Override
public void shutdown(IRecordProcessorCheckpointer arg0, ShutdownReason arg1) {
}
public void test() throws JSONException, UnsupportedEncodingException {
String str = "00001,35.65,139.65";
initialize("test");
ByteBuffer buffer = ByteBuffer.allocateDirect(128);
buffer.put(str.getBytes());
buffer.flip();
verifyRecord(buffer);
}
}
| mit |
andrewoma/restless | example/api/src/main/java/com/github/andrewoma/restless/example/api/Permissions.java | 1300 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.restless.example.api;
public class Permissions {
static final String BLOG_EDIT = "blog:edit";
static final String BLOG_VIEW = "blog:view";
}
| mit |
EternalDeiwos/ru_mobile_dev_project | BioMAPapp/app/src/main/java/com/github/eternaldeiwos/biomapapp/helper/HashHelper.java | 1417 | package com.github.eternaldeiwos.biomapapp.helper;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* Created by glinklater on 2016/05/27.
*/
public final class HashHelper {
private HashHelper() {} // static class
private static HashMap<String, String> hashes; // replace with thread-safe persistence later
public static String hashMD5(String plain_text) {
HashCode hc = Hashing.md5().hashString(plain_text, Charset.defaultCharset());
String hashed = hc.toString();
System.err.println(hashed);
return hashed;
}
public static String hashSHA1(String plain_text) {
HashCode hc = Hashing.sha1().hashString(plain_text, Charset.defaultCharset());
return hc.toString();
}
private static Map<String, String> getHashes() {
if (hashes == null) hashes = new HashMap<>();
return hashes;
}
public static boolean isDataChanged(String key, String data) {
if (getHashes().containsKey(key))
if (getHashes().get(key).equals(hashSHA1(data))) return false;
return true;
}
public static void updateHash (String key, String data) {
getHashes().put(key, hashSHA1(data));
}
public static String getHash (String key) {
return getHashes().get(key);
}
}
| mit |
lanen/mint4j | game-net-netty/demo/main/java/evanq/net1/DemoHandler.java | 876 | package evanq.net1;
import java.io.IOException;
import java.net.Socket;
/**
*
* 这是最典型的处理网络数据方式
*
* @author Evan cppmain@gmail.com
*
*/
public class DemoHandler implements Runnable {
//客户端
final Socket socket;
static final int MAX_INPUT = 2048;
public DemoHandler(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try{
//step 1. read
//缓存区,动态扩展。
byte[] input = new byte[MAX_INPUT] ;
socket.getInputStream().read(input);
//step 2. decode
//step 3. process
//step 4. encode
//事件多路分离
byte[] output = process(input);
//step 5. write
//写数据
socket.getOutputStream().write(output);
}catch(IOException ioe){
ioe.printStackTrace();
}
}
private byte[] process(byte[] input){
return new byte[1];
}
}
| mit |
Mooophy/dragon-book-2nd | ch02/2.6/java/lexer/Token.java | 154 | package lexer; //File Token.java
public class Token
{
public final int tag;
public Token(int t)
{
tag = t;
}
}
| mit |
bioelectromecha/CryptoBox | app/src/main/java/cryptobox/dataobjects/KeyWrapper.java | 272 | package cryptobox.dataobjects;
/**
* Created by avishai on 08/10/2016.
*/
public class KeyWrapper {
public Long keyId;
public String decryptedKey;
public String encryptedKey;
public String keyToEncryptWith;
public String encryptedKeyToEncrypt;
}
| mit |
zsavely/PatternedTextWatcher | patternedtextwatcher/src/test/java/com/szagurskii/patternedtextwatcher/deletion/BaseCustomizedDeletionTests.java | 2668 | package com.szagurskii.patternedtextwatcher.deletion;
import android.widget.EditText;
import com.szagurskii.patternedtextwatcher.PatternedTextWatcher;
import org.junit.Test;
import static com.szagurskii.patternedtextwatcher.utils.EditTextUtils.clearTextChangeListener;
public abstract class BaseCustomizedDeletionTests extends BaseDeletionTests {
@Test
public void deletion1() {
appendClearOneSymbolAndCheck(STRING_TO_BE_TYPED_LENGTH_NINE, "12345", PATTERN_1);
}
@Test
public void deletion2() {
appendClearOneSymbolAndCheck(STRING_TO_BE_TYPED_LENGTH_NINE, "(123456", PATTERN_2);
}
@Test
public void deletion3() {
appendClearOneSymbolAndCheck(STRING_TO_BE_TYPED_LENGTH_NINE, "(123456))))", PATTERN_3);
}
@Test
public void multipleDeletion1() {
PatternedTextWatcher patternedTextWatcher = init(editText, PATTERN_4);
addText(editText, STRING_TO_BE_TYPED_LENGTH_NINE);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))456))))", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))456)))", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))456))", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))456)", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))456", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))45", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))4", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)))", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123))", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123)", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(123", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(12", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(1", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "(", PATTERN_4);
backspace(STRING_TO_BE_TYPED_LENGTH_NINE, "", PATTERN_4);
clearTextChangeListener(editText, patternedTextWatcher);
}
@Override
protected PatternedTextWatcher init(EditText editText, String pattern) {
PatternedTextWatcher patternedTextWatcher = new PatternedTextWatcher.Builder(pattern)
.deleteExtraCharactersAutomatically(false)
.build();
editText.addTextChangedListener(patternedTextWatcher);
return patternedTextWatcher;
}
/**
* Add text to the EditText via
* {@link EditText#setText(char[], int, int)} or {@link EditText#append(CharSequence)}.
*
* @param editText EditText to which the text will be appended.
* @param value the value th append.
*/
abstract void addText(EditText editText, String value);
}
| mit |
renesansz/VogellaExercises | DataBinding/app/src/androidTest/java/com/example/renesansz/databinding/ApplicationTest.java | 364 | package com.example.renesansz.databinding;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
m-wrona/gwt-medicapital | client/com/medicapital/client/core/entities/EditableEntitiesPresenter.java | 4535 | package com.medicapital.client.core.entities;
import static com.medicapital.client.log.Tracer.tracer;
import java.util.HashSet;
import java.util.Set;
import com.google.gwt.event.shared.EventBus;
import com.medicapital.client.core.commands.EditCommandFactory;
import com.medicapital.client.dao.ServiceResponse;
import com.medicapital.common.commands.CommandResp;
import com.medicapital.common.commands.entity.DeleteCommand;
import com.medicapital.common.commands.entity.DeleteCommandResp;
import com.medicapital.common.dao.ResponseHandler;
import com.medicapital.common.entities.SerializableEntity;
/**
* Presenter allows to display list of elements and update them (delete and edit
* actions are supported)
*
* @author michal
*
* @param <E>
*/
abstract public class EditableEntitiesPresenter<E extends SerializableEntity> extends EntitiesPresenter<E> {
private final EditableEntitiesView<E> display;
private EditCommandFactory<E> editCommandFactory;
private final Set<Integer> selectedElements = new HashSet<Integer>();
public EditableEntitiesPresenter(final Class<E> entityClass, final EditableEntitiesView<E> display, final EventBus eventBus) {
super(entityClass, display, eventBus);
this.display = display;
}
public void setEntitySelected(final int entityId, final boolean selected) {
tracer(this).debug("Set entity selected - elementId: " + entityId + ", selected: " + selected);
if (selected) {
selectedElements.add(entityId);
} else {
selectedElements.remove(entityId);
}
display.setDeleteSelectedHandlerEnabled(!selectedElements.isEmpty());
}
/**
* Delete selected elements
*
* @param elementsIds
*/
final public void deleteSelectedEntities() {
tracer(this).debug("Deleting entities - size: " + selectedElements.size());
validatePresenter();
// TODO: optimize that
final int elementsIds[] = new int[selectedElements.size()];
int index = 0;
for (final int selectedElementId : selectedElements) {
elementsIds[index++] = selectedElementId;
}
final DeleteCommand<E> deleteCommand = editCommandFactory.createDeleteCommand(elementsIds);
getServiceAccess().execute(deleteCommand, new ResponseHandler<E>() {
/**
* @param response
*/
@Override
public void handle(final CommandResp<E> response) {
if (response instanceof DeleteCommandResp<?>) {
final DeleteCommandResp<E> deleteResp = (DeleteCommandResp<E>) response;
tracer(this).debug("Response from service, elements deleted: " + deleteResp.getCount() + "/" + selectedElements.size());
if (deleteResp.getCount() == selectedElements.size()) {
final Set<Integer> deletedEntitiesIds = new HashSet<Integer>();
final int elementsOnPage = getDisplayedElements().size();
for (final int deletedEntityId : selectedElements) {
deletedEntitiesIds.add(deletedEntityId);
getDisplayedElements().remove(deletedEntityId);
}
// broadcast message
deleteResp.setDeletedElements(deletedEntitiesIds);
getEventBus().fireEvent(new ServiceResponse<E>(this, deleteResp));
tracer(this).debug("Elements deleted: " + deletedEntitiesIds.size() + ", elements on page: " + elementsOnPage);
if (deletedEntitiesIds.size() == elementsOnPage) {
/*
* if all elements from current page were deleted
* then new page must be loaded
*/
tracer(this).debug("All elements from page were deleted - going to previous page...");
goToPage(getCurrentPageNumber() - 1);
} else {
refreshDisplay(false);
}
}
}
}
@Override
public void handleException(final Throwable throwable) {
// ignore
}
});
}
@Override
final public void refreshDisplay(final boolean redownloadData) throws IllegalArgumentException {
super.refreshDisplay(redownloadData);
selectedElements.clear();
display.setSelectAllEntities(false);
display.setDeleteSelectedHandlerEnabled(false);
}
@Override
protected void validatePresenter() throws IllegalArgumentException {
super.validatePresenter();
if (editCommandFactory == null) {
throw new IllegalArgumentException("Edit command factory not set");
}
}
final public void setEditCommandFactory(final EditCommandFactory<E> editCommandFactory) {
this.editCommandFactory = editCommandFactory;
}
final public EditCommandFactory<E> getEditCommandFactory() {
return editCommandFactory;
}
}
| mit |
VDuda/SyncRunner-Pub | src/API/amazon/mws/feeds/model/ManageReportScheduleRequest.java | 10011 |
package API.amazon.mws.feeds.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Marketplace" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="Merchant" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ReportType" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="Schedule" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ScheduledDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
* Generated by AWS Code Generator
* <p/>
* Wed Feb 18 13:28:59 PST 2009
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"marketplace",
"merchant",
"reportType",
"schedule",
"scheduledDate"
})
@XmlRootElement(name = "ManageReportScheduleRequest")
public class ManageReportScheduleRequest {
@XmlElement(name = "Marketplace")
protected String marketplace;
@XmlElement(name = "Merchant", required = true)
protected String merchant;
@XmlElement(name = "ReportType", required = true)
protected String reportType;
@XmlElement(name = "Schedule", required = true)
protected String schedule;
@XmlElement(name = "ScheduledDate")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar scheduledDate;
/**
* Default constructor
*
*/
public ManageReportScheduleRequest() {
super();
}
/**
* Value constructor
*
*/
public ManageReportScheduleRequest(final String marketplace, final String merchant, final String reportType, final String schedule, final XMLGregorianCalendar scheduledDate) {
this.marketplace = marketplace;
this.merchant = merchant;
this.reportType = reportType;
this.schedule = schedule;
this.scheduledDate = scheduledDate;
}
/**
* Gets the value of the marketplace property.
*
* @deprecated See {@link #setMarketplace(String)}
* @return
* possible object is
* {@link String }
*
*/
public String getMarketplace() {
return marketplace;
}
/**
* Sets the value of the marketplace property.
*
* @deprecated Not used anymore. MWS ignores this parameter, but it is left
* in here for backwards compatibility.
* @param value
* allowed object is
* {@link String }
*
*/
public void setMarketplace(String value) {
this.marketplace = value;
}
/**
* @deprecated See {@link #setMarketplace(String)}
*/
public boolean isSetMarketplace() {
return (this.marketplace!= null);
}
/**
* Gets the value of the merchant property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMerchant() {
return merchant;
}
/**
* Sets the value of the merchant property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMerchant(String value) {
this.merchant = value;
}
public boolean isSetMerchant() {
return (this.merchant!= null);
}
/**
* Gets the value of the reportType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReportType() {
return reportType;
}
/**
* Sets the value of the reportType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReportType(String value) {
this.reportType = value;
}
public boolean isSetReportType() {
return (this.reportType!= null);
}
/**
* Gets the value of the schedule property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSchedule() {
return schedule;
}
/**
* Sets the value of the schedule property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSchedule(String value) {
this.schedule = value;
}
public boolean isSetSchedule() {
return (this.schedule!= null);
}
/**
* Gets the value of the scheduledDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getScheduledDate() {
return scheduledDate;
}
/**
* Sets the value of the scheduledDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setScheduledDate(XMLGregorianCalendar value) {
this.scheduledDate = value;
}
public boolean isSetScheduledDate() {
return (this.scheduledDate!= null);
}
/**
* Sets the value of the Marketplace property.
*
* @deprecated See {@link #setMarketplace(String)}
* @param value
* @return
* this instance
*/
public ManageReportScheduleRequest withMarketplace(String value) {
setMarketplace(value);
return this;
}
/**
* Sets the value of the Merchant property.
*
* @param value
* @return
* this instance
*/
public ManageReportScheduleRequest withMerchant(String value) {
setMerchant(value);
return this;
}
/**
* Sets the value of the ReportType property.
*
* @param value
* @return
* this instance
*/
public ManageReportScheduleRequest withReportType(String value) {
setReportType(value);
return this;
}
/**
* Sets the value of the Schedule property.
*
* @param value
* @return
* this instance
*/
public ManageReportScheduleRequest withSchedule(String value) {
setSchedule(value);
return this;
}
/**
* Sets the value of the ScheduledDate property.
*
* @param value
* @return
* this instance
*/
public ManageReportScheduleRequest withScheduledDate(XMLGregorianCalendar value) {
setScheduledDate(value);
return this;
}
/**
*
* JSON fragment representation of this object
*
* @return JSON fragment for this object. Name for outer
* object expected to be set by calling method. This fragment
* returns inner properties representation only
*
*/
protected String toJSONFragment() {
StringBuffer json = new StringBuffer();
boolean first = true;
if (isSetMarketplace()) {
if (!first) json.append(", ");
json.append(quoteJSON("Marketplace"));
json.append(" : ");
json.append(quoteJSON(getMarketplace()));
first = false;
}
if (isSetMerchant()) {
if (!first) json.append(", ");
json.append(quoteJSON("Merchant"));
json.append(" : ");
json.append(quoteJSON(getMerchant()));
first = false;
}
if (isSetReportType()) {
if (!first) json.append(", ");
json.append(quoteJSON("ReportType"));
json.append(" : ");
json.append(quoteJSON(getReportType()));
first = false;
}
if (isSetSchedule()) {
if (!first) json.append(", ");
json.append(quoteJSON("Schedule"));
json.append(" : ");
json.append(quoteJSON(getSchedule()));
first = false;
}
if (isSetScheduledDate()) {
if (!first) json.append(", ");
json.append(quoteJSON("ScheduledDate"));
json.append(" : ");
json.append(quoteJSON(getScheduledDate() + ""));
first = false;
}
return json.toString();
}
/**
*
* Quote JSON string
*/
private String quoteJSON(String string) {
StringBuffer sb = new StringBuffer();
sb.append("\"");
int length = string.length();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '/':
sb.append("\\/");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (c < ' ') {
sb.append("\\u" + String.format("%03x", Integer.valueOf(c)));
} else {
sb.append(c);
}
}
}
sb.append("\"");
return sb.toString();
}
}
| mit |
llun/thorfun-android | src/th/in/llun/thorfun/PostActivity.java | 7415 | package th.in.llun.thorfun;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.ocpsoft.prettytime.PrettyTime;
import th.in.llun.thorfun.api.Thorfun;
import th.in.llun.thorfun.api.model.Post;
import th.in.llun.thorfun.api.model.RemoteCollection;
import th.in.llun.thorfun.api.model.Reply;
import th.in.llun.thorfun.api.model.ThorfunResult;
import th.in.llun.thorfun.utils.ImageLoader;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;
public class PostActivity extends SherlockActivity {
public static final String KEY_POST = "post";
private Thorfun mThorfun;
private Post mPost;
private List<Reply> mReplies;
private ReplyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_view);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setTitle(getString(R.string.board_post_title));
String rawPost = getIntent().getStringExtra(KEY_POST);
try {
mPost = new Post(new JSONObject(rawPost));
ImageView icon = (ImageView) findViewById(R.id.board_post_avatar);
ViewGroup loading = (ViewGroup) findViewById(R.id.board_post_loading);
loading.setVisibility(View.VISIBLE);
new ImageLoader(icon, loading).execute(mPost.getNeightbour()
.getImageURL());
TextView title = (TextView) findViewById(R.id.board_post_title);
title.setText(Html.fromHtml(mPost.getTitle()));
TextView username = (TextView) findViewById(R.id.board_post_username_text);
username.setText(mPost.getNeightbour().getName());
PrettyTime prettyTime = new PrettyTime();
TextView time = (TextView) findViewById(R.id.board_post_timestamp);
time.setText(prettyTime.format(mPost.getTime()));
mThorfun = Thorfun.getInstance(this);
mReplies = new ArrayList<Reply>();
mAdapter = new ReplyAdapter(this, getLayoutInflater(), mPost, mReplies);
ListView repliesView = (ListView) findViewById(R.id.board_post_replies);
repliesView.setAdapter(mAdapter);
mThorfun.loadPostReplies(mPost, null,
new ThorfunResult<RemoteCollection<Reply>>() {
@Override
public void onResponse(RemoteCollection<Reply> response) {
mReplies.addAll(response.collection());
mAdapter.notifyDataSetChanged();
}
});
View inputView = findViewById(R.id.board_post_reply_field);
if (mThorfun.isLoggedIn()) {
inputView.setVisibility(View.VISIBLE);
} else {
inputView.setVisibility(View.GONE);
}
final EditText inputField = (EditText) findViewById(R.id.board_post_reply_input);
final Button inputButton = (Button) findViewById(R.id.board_post_reply_submit);
inputButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String text = inputField.getText().toString().trim();
if (text.length() > 0) {
inputField.setText("");
inputButton.setEnabled(false);
mThorfun.commentPost(mPost, text, new ThorfunResult<Reply>() {
@Override
public void onResponse(Reply response) {
inputButton.setEnabled(true);
mReplies.add(response);
mAdapter.notifyDataSetChanged();
}
});
}
}
});
} catch (JSONException e) {
Log.e(Thorfun.LOG_TAG, "Can't parse post json", e);
finish();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static class ReplyAdapter extends BaseAdapter {
private Activity mActivity;
private LayoutInflater mInflater;
private Post mPost;
private List<Reply> mReplies;
private boolean mIsLoading = false;
private boolean mIsLastPage = false;
public ReplyAdapter(Activity activity, LayoutInflater inflater, Post post,
List<Reply> replies) {
mActivity = activity;
mInflater = inflater;
mPost = post;
mReplies = replies;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == getCount() - 1) {
RelativeLayout row = (RelativeLayout) convertView;
if (row == null) {
row = (RelativeLayout) mInflater.inflate(
R.layout.fragment_loading_row, parent, false);
}
if (mReplies.size() < Thorfun.DEFAULT_PAGE_LIMIT) {
mIsLastPage = true;
}
final BaseAdapter self = this;
if (!mIsLoading && !mIsLastPage) {
mIsLoading = true;
Thorfun.getInstance(mActivity).loadPostReplies(mPost,
mReplies.get(mReplies.size() - 1),
new ThorfunResult<RemoteCollection<Reply>>() {
@Override
public void onResponse(RemoteCollection<Reply> response) {
mIsLoading = false;
List<Reply> next = response.collection();
if (next.size() > 0) {
mReplies.addAll(next);
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
self.notifyDataSetChanged();
}
});
} else {
mIsLastPage = true;
}
}
});
}
if (mIsLastPage) {
row.setVisibility(View.GONE);
}
return row;
} else {
View row = convertView;
if (row == null) {
row = mInflater.inflate(R.layout.story_comment_reply_row, parent,
false);
}
Reply reply = mReplies.get(position);
ImageView icon = (ImageView) row
.findViewById(R.id.story_comment_avatar);
ViewGroup loading = (ViewGroup) row
.findViewById(R.id.story_comment_progress_box);
loading.setVisibility(View.VISIBLE);
new ImageLoader(icon, loading).execute(reply.getNeightbour()
.getImageURL());
TextView usernameText = (TextView) row
.findViewById(R.id.story_comment_user);
usernameText.setText(reply.getNeightbour().getName());
TextView commentText = (TextView) row
.findViewById(R.id.story_comment_text);
commentText.setText(Html.fromHtml(reply.getText()));
TextView timeText = (TextView) row
.findViewById(R.id.story_comment_time);
timeText.setText(new PrettyTime().format(reply.getTime()));
return row;
}
}
@Override
public long getItemId(int position) {
return mReplies.get(position).getID();
}
@Override
public Object getItem(int position) {
return mReplies.get(position);
}
@Override
public int getCount() {
if (mReplies.size() > 0) {
return mReplies.size() + 1;
}
return 0;
}
public int getViewTypeCount() {
return 2;
}
public int getItemViewType(int position) {
if (position == getCount() - 1) {
return 0;
}
return 1;
}
}
}
| mit |
OblivionNW/Nucleus | src/main/java/io/github/nucleuspowered/nucleus/modules/world/commands/lists/AvailableBaseCommand.java | 1901 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.world.commands.lists;
import io.github.nucleuspowered.nucleus.Nucleus;
import io.github.nucleuspowered.nucleus.Util;
import io.github.nucleuspowered.nucleus.internal.command.AbstractCommand;
import io.github.nucleuspowered.nucleus.internal.messages.MessageProvider;
import org.spongepowered.api.CatalogType;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import java.util.List;
import java.util.stream.Collectors;
@NonnullByDefault
public abstract class AvailableBaseCommand extends AbstractCommand<CommandSource> {
private final Class<? extends CatalogType> catalogType;
private final String titleKey;
AvailableBaseCommand(Class<? extends CatalogType> catalogType, String titleKey) {
this.catalogType = catalogType;
this.titleKey = titleKey;
}
@Override
protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) {
MessageProvider mp = Nucleus.getNucleus().getMessageProvider();
List<Text> types = Sponge.getRegistry().getAllOf(this.catalogType).stream()
.map(x -> mp.getTextMessageWithFormat("command.world.presets.item", x.getId(), x.getName()))
.collect(Collectors.toList());
Util.getPaginationBuilder(src).title(mp.getTextMessageWithTextFormat(this.titleKey))
.contents(types).sendTo(src);
return CommandResult.success();
}
}
| mit |
OpenSIRF/opensirf-core | src/main/java/org/opensirf/catalog/SIRFCatalog.java | 4805 | /*
* OpenSIRF Core
*
* Copyright IBM Corporation 2015.
* All Rights Reserved.
*
* MIT License:
*
* 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.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization of the
* copyright holder.
*/
package org.opensirf.catalog;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.opensirf.container.ContainerIdentifier;
import org.opensirf.container.ContainerInformation;
import org.opensirf.container.ContainerProvenanceReference;
import org.opensirf.container.SIRFContainer;
import org.opensirf.container.State;
import org.opensirf.obj.PreservationObjectIdentifier;
import org.opensirf.obj.PreservationObjectInformation;
import org.opensirf.obj.PreservationObjectLogicalIdentifier;
import org.opensirf.obj.PreservationObjectName;
import org.opensirf.obj.PreservationObjectParentIdentifier;
import org.opensirf.obj.PreservationObjectVersionIdentifier;
import org.opensirf.obj.Retention;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class SIRFCatalog {
public SIRFCatalog() {
objectInformation = new IndexedObjectInformationSet();
}
public SIRFCatalog(String catalogId, String containerName) {
this.catalogId = catalogId;
objectInformation = new IndexedObjectInformationSet();
// Creating the provenance PO and adding it to the catalog
PreservationObjectInformation provenanceInfo = new PreservationObjectInformation("none");
PreservationObjectIdentifier provenanceId = new PreservationObjectIdentifier();
String provenanceLogicalIdentifier = SIRFContainer.SIRF_DEFAULT_PROVENANCE_MANIFEST_FILE;
String provenanceVersionIdentifier = provenanceLogicalIdentifier;
provenanceId.setObjectLogicalIdentifier(new PreservationObjectLogicalIdentifier("logicalIdentifier", "en", provenanceLogicalIdentifier));
provenanceId.setObjectParentIdentifier(new PreservationObjectParentIdentifier("parentIdentifier", "en", "null"));
provenanceId.setObjectVersionIdentifier(new PreservationObjectVersionIdentifier("versionIdentifier", "en", provenanceVersionIdentifier));
provenanceId.putObjectName(new PreservationObjectName("name", "en", SIRFContainer.SIRF_DEFAULT_PROVENANCE_MANIFEST_FILE));
provenanceInfo.addObjectIdentifier(provenanceId);
Retention r = new Retention("time_period", "forever");
provenanceInfo.setObjectRetention(r);
objectInformation.put(provenanceInfo);
// Creating the container information
containerInformation = new ContainerInformation();
containerInformation.setContainerIdentifier(new ContainerIdentifier("containerIdentifier", "en", containerName));
containerInformation.setContainerState(new State(State.STATE_TYPE_CONTAINER_READY, State.TRUE));
containerInformation.setContainerProvenanceReference(new ContainerProvenanceReference("internal", "Provenance", provenanceVersionIdentifier));
}
public String getCatalogId() {
return catalogId;
}
public ContainerInformation getContainerInformation() {
return containerInformation;
}
public IndexedObjectInformationSet getSirfObjects() {
return objectInformation;
}
public void setCatalogId(String catalogId) {
this.catalogId = catalogId;
}
public void setContainerInformation(ContainerInformation containerInformation) {
this.containerInformation = containerInformation;
}
private String catalogId;
private ContainerInformation containerInformation;
@XmlElementWrapper(name="objectsSet")
private IndexedObjectInformationSet objectInformation;
}
| mit |
juniormesquitadandao/report4all | lib/src/net/sf/jasperreports/engine/xml/JRGenericPrintElementParameterFactory.java | 3624 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.xml;
import net.sf.jasperreports.engine.JRGenericPrintElement;
import net.sf.jasperreports.engine.util.JRValueStringUtils;
import org.apache.commons.digester.Rule;
import org.xml.sax.Attributes;
/**
* Helper factory class used to parse generic print element parameters.
*
* @author Lucian Chirita (lucianc@users.sourceforge.net)
* @version $Id: JRGenericPrintElementParameterFactory.java 7199 2014-08-27 13:58:10Z teodord $
* @see JRGenericPrintElement#setParameterValue(String, Object)
*/
public class JRGenericPrintElementParameterFactory extends JRBaseFactory
{
public Object createObject(Attributes attributes) throws Exception
{
JRGenericPrintElement element = (JRGenericPrintElement) digester.peek();
String name = attributes.getValue(JRXmlConstants.ATTRIBUTE_name);
return new Parameter(element, name);
}
public static class Parameter
{
protected JRGenericPrintElement element;
protected String name;
protected Object value;
public Parameter(JRGenericPrintElement element, String name)
{
this.element = element;
this.name = name;
}
protected void setValue(Object value)
{
this.value = value;
}
public void addParameter()
{
element.setParameterValue(name, value);
}
}
public static class ParameterValue
{
protected String valueClass;
protected Object value;
public ParameterValue(String valueClass)
{
this.valueClass = valueClass;
}
public void setData(String data)
{
if (data != null)
{
value = JRValueStringUtils.deserialize(valueClass, data);
}
}
}
public static class ParameterValueFactory extends JRBaseFactory
{
public Object createObject(Attributes attributes) throws Exception
{
String valueClass = attributes.getValue(JRXmlConstants.ATTRIBUTE_class);
return new ParameterValue(valueClass);
}
}
public static class ArbitraryValueSetter extends Rule
{
@Override
public void begin(String namespace, String name, Attributes attributes) throws Exception
{
((JRXmlDigester) digester).clearLastPopped();
}
@Override
public void end(String namespace, String name) throws Exception
{
Parameter parameter = (Parameter) digester.peek();
Object lastPopped = ((JRXmlDigester) digester).lastPopped();
if (lastPopped != null)
{
Object value;
if (lastPopped instanceof ParameterValue)
{
// this is for genericElementParameterValue elements
value = ((ParameterValue) lastPopped).value;
}
else
{
// arbitrary elements
value = lastPopped;
}
parameter.setValue(value);
}
}
}
}
| mit |
Unymicle/Geek-Coder-News-Server | src/main/java/com/geekcoder/server/model/Category.java | 560 | package com.geekcoder.server.model;
/**
* @author Cheng Liufeng
* ÐÂÎÅÀà±ð
*/
public class Category {
private int cid; //ÐÂÎÅÀà±ðid
private int pid; //¸¸Àà±ðpid(pidΪ0´ú±í¸ú½Úµã)
private String name; //Àà±ðÃû³Æ
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| mit |
HPFOD/FoDBugTrackerUtility | bugtracker-ssc-common/src/main/java/com/fortify/bugtracker/common/ssc/json/preprocessor/filter/SSCJSONMapFilterHasBugURL.java | 1895 | /*******************************************************************************
* (c) Copyright 2020 Micro Focus or one of its affiliates, a Micro Focus company
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
******************************************************************************/
package com.fortify.bugtracker.common.ssc.json.preprocessor.filter;
import java.util.regex.Pattern;
import com.fortify.util.rest.json.preprocessor.filter.JSONMapFilterRegEx;
/**
* This class allows for including or excluding SSC vulnerabilities based on whether
* the vulnerability bugURL field contains any value or not.
*
* @author Ruud Senden
*
*/
public class SSCJSONMapFilterHasBugURL extends JSONMapFilterRegEx {
public SSCJSONMapFilterHasBugURL(MatchMode matchMode) {
super(matchMode, "bugURL", Pattern.compile("^\\S+$"));
}
}
| mit |
argonium/beetle-cli | src/io/miti/beetle/model/Config.java | 4483 | /*
* Java class for the CONFIG database table.
* Generated on 01 Apr 2015 11:59:30 by DB2Java.
*/
package io.miti.beetle.model;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import io.miti.beetle.prefs.*;
import io.miti.beetle.dbutil.*;
/**
* Java class to encapsulate the CONFIG table.
*
* @version 1.0
*/
public final class Config implements FetchDatabaseRecords, IInsertable,
IUpdateable
{
/**
* The table column DB_VERSION.
*/
private int dbVersion;
/**
* Default constructor.
*/
public Config() {
super();
}
/**
* Implement the FetchDatabaseRecords interface.
*
* @param rs the result set to get the data from
* @param listRecords the list of data to add to
* @return the success of the operation
*/
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean getFields(final ResultSet rs, final List listRecords) {
// Default return value
boolean bResult = false;
// Set up our try/catch block
try {
// Iterate over the result set
while (rs.next()) {
// Instantiate a new object
Config obj = new Config();
// Save the data in our object
obj.dbVersion = rs.getInt(1);
// Add to our list
listRecords.add(obj);
}
// There was no error
bResult = true;
} catch (java.sql.SQLException sqle) {
// Add the exception to the master list and save the
// result as the error code
System.err.println(sqle.getMessage());
}
// Return the result of the operation
return bResult;
}
/**
* Get all objects from the database.
*
* @return a list of all objects in the database
*/
public static List<Config> getList() {
return getList(null);
}
/**
* Get all objects from the database.
*
* @param whereClause the where clause for the select statement
* @return a list of all objects in the database
*/
public static List<Config> getList(final String whereClause) {
// This will hold the list that gets returned
List<Config> listData = new ArrayList<Config>(100);
// Build our query
StringBuffer buf = new StringBuffer(100);
buf.append("SELECT DB_VERSION");
buf.append(" from CONFIG");
// Check if there's a where clause to append
if (whereClause != null) {
buf.append(" ").append(whereClause);
}
// Get all of the objects from the database
boolean bResult = PrefsDatabase.executeSelect(buf.toString(), listData,
new Config());
if (!bResult) {
// An error occurred
listData.clear();
listData = null;
}
// Return the list
return listData;
}
/**
* Insert a record into the database.
*/
public void insert() {
StringBuilder sb = new StringBuilder(200);
sb.append("INSERT into CONFIG (");
sb.append("DB_VERSION");
sb.append(") values (");
sb.append("?");
sb.append(")");
// There should only be one row in this table, so delete before inserting
PrefsDatabase.delete("delete from CONFIG");
PrefsDatabase.insert(sb.toString(), this);
}
/**
* Set the parameter values in the INSERT statement.
*
* @param ps the prepared statement
* @throws java.sql.SQLException a database exception
*/
@Override
public void setInsertFields(final PreparedStatement ps) throws SQLException {
ps.setInt(1, dbVersion);
}
/**
* Update a record in the database.
*/
public void update() {
StringBuilder sb = new StringBuilder(200);
sb.append("UPDATE CONFIG set ");
sb.append("DB_VERSION = ?");
PrefsDatabase.update(sb.toString(), this);
}
/**
* Set the parameter values in the INSERT statement.
*
* @param ps the prepared statement
* @throws java.sql.SQLException a database exception
*/
@Override
public void setUpdateFields(final PreparedStatement ps) throws SQLException {
ps.setInt(1, dbVersion);
}
/**
* Get the value for dbVersion.
*
* @return the dbVersion
*/
public int getDbVersion() {
return dbVersion;
}
/**
* Update the value for dbVersion.
*
* @param pDbVersion the new value for dbVersion
*/
public void setDbVersion(final int pDbVersion) {
dbVersion = pDbVersion;
}
@Override
public String toString() {
return "Config [dbVersion=" + dbVersion + "]";
}
}
| mit |
haihaio/AmenEye | app/src/main/java/cn/aaronyi/ameneye/adapter/ZhihuDailyAdapter.java | 3358 | package cn.aaronyi.ameneye.adapter;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.Calendar;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.aaronyi.ameneye.R;
import cn.aaronyi.ameneye.magicrecyclerView.BaseItem;
import cn.aaronyi.ameneye.magicrecyclerView.BaseRecyclerAdapter;
import cn.aaronyi.ameneye.model.zhihu.ZhiHuStory;
import cn.aaronyi.ameneye.utils.DateUtil;
/**
* Created by yihaimen on 17/4/26.
*/
public class ZhihuDailyAdapter extends BaseRecyclerAdapter {
private Context mContext;
private int image_width;
private int image_height;
public ZhihuDailyAdapter(Fragment fragment) {
mContext = fragment.getContext();
float width = fragment.getResources().getDimension(R.dimen.news_image_width);
image_width = (int) width;
image_height = image_width * 3 / 4;
}
@Override
public RecyclerView.ViewHolder onCreate(ViewGroup parent, int viewType) {
View view;
if (viewType == RecyclerItemType.TYPE_TAGS.getiNum()) {
view = LayoutInflater.from(mContext).inflate(R.layout.zhihu_story_date_tag, parent, false);
return new TitleHolder(view);
} else {
view = LayoutInflater.from(mContext).inflate(R.layout.zhihu_story_item, parent, false);
return new ViewHolder(view);
}
}
@Override
public void onBind(RecyclerView.ViewHolder viewHolder, int RealPosition, BaseItem data) {
if (data.getItemType() == RecyclerItemType.TYPE_NORMAL) { //普通内容
ZhiHuStory story = (ZhiHuStory) data.getData();
ViewHolder holder = (ViewHolder) viewHolder;
holder.mNewsTitle.setText(story.getTitle());
Glide.with(mContext)
.load(story.getImages().get(0)) //加载第一张图
.centerCrop()
.override(image_width, image_height)
.into(holder.mNewsImage);
} else if (data.getItemType() == RecyclerItemType.TYPE_TAGS) { //日期标签
String title = (String) data.getData();
int year = Integer.parseInt(title.substring(0, 4));
int mon = Integer.parseInt(title.substring(4, 6));
int day = Integer.parseInt(title.substring(6, 8));
Calendar calendar = Calendar.getInstance();
calendar.set(year, mon-1, day);
TitleHolder holder = (TitleHolder) viewHolder;
holder.mItemTitle.setText(DateUtil.formatDate(calendar) + " | " + DateUtil.getWeek(calendar));
}
}
class TitleHolder extends Holder {
@BindView(R.id.item_title)
TextView mItemTitle;
TitleHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
class ViewHolder extends Holder {
@BindView(R.id.news_image)
ImageView mNewsImage;
@BindView(R.id.news_title)
TextView mNewsTitle;
ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
| mit |
martinodutto/todolist-bot | src/main/java/com/martinodutto/App.java | 1362 | package com.martinodutto;
import com.martinodutto.components.TodoListBot;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.generics.BotSession;
/**
* Main class.
*/
@SpringBootApplication
public class App implements CommandLineRunner {
static {
ApiContextInitializer.init();
}
private final Logger logger = LogManager.getLogger(this.getClass());
private final TodoListBot todoListBot;
@Autowired
public App(TodoListBot todoListBot) {
this.todoListBot = todoListBot;
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Override
public void run(String... strings) throws Exception {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
BotSession session = telegramBotsApi.registerBot(todoListBot);
if (!session.isRunning()) {
session.start();
}
logger.info("Session started!");
}
}
| mit |
ZiryLee/FileUpload2Spring | FileUpload2Spring/src/util/image/EasyImage.java | 20930 | package util.image;
import java.awt.Color;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
*
EasyImage允许你做所有的基本操作,形象 <br>
*转换,裁剪,调整大小,旋转,翻转…<br>
* +让你做一些很酷的影响。<br>
*所有完成超级容易。<br>
*结合操作可以产生一些非常酷的结果。<br>
*
*操作:<br>
*开放的形象。<br>
*保存图像<br>
*转换图像<br>
*用户形象<br>
*作物图像<br>
*转换为黑白图像<br>
*旋转图像<br>
*翻转图像<br>
*添加颜色图像<br>
*与原有的多个实例创建图像<br>
*2图像结合在一起<br>
*强调的部分图像<br>
*
*更多文档参考:http://www.aviyehuda.com/downloads/easyimage/easyimage_javadoc/index
*/
public class EasyImage {
private BufferedImage bufferedImage;
private String fileName;
/**
* Constructor - loads from an image file.
* @param imageFile
*/
public EasyImage(File imageFile) {
try {
bufferedImage = ImageIO.read(imageFile);
fileName = imageFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
bufferedImage = null;
imageFile = null;
}
}
/**
* Constructor - loads from an image file.
* @param imageFilePath
*/
public EasyImage(String imageFilePath) {
this(new File(imageFilePath));
}
/**
* Return image as java.awt.image.BufferedImage
* @return image as java.awt.image.BufferedImage
*/
public BufferedImage getAsBufferedImage(){
return bufferedImage;
}
/**
* Save the image as a new image file.
* Can also convert the image according to file type.
* @param fileName
*/
public void saveAs(String fileName){
saveImage(new File(fileName));
this.fileName = fileName;
}
/**
* Saves the image to the original file.
*/
public void save(){
saveImage(new File(fileName));
}
/**
* Resizing the image by percentage of the original.
* @param percentOfOriginal
*/
public void resize( int percentOfOriginal){
int newWidth = bufferedImage.getWidth() * percentOfOriginal / 100;
int newHeight = bufferedImage.getHeight() * percentOfOriginal / 100;
resize(newWidth, newHeight);
}
/**
* Resizing the image by width and height.
* @param newWidth
* @param newHeight
*/
public void resize( int newWidth, int newHeight){
int oldWidth = bufferedImage.getWidth();
int oldHeight = bufferedImage.getHeight();
if(newWidth == -1 || newHeight == -1){
if(newWidth == -1){
if(newHeight == -1){
return;
}
newWidth = newHeight * oldWidth/ oldHeight;
}
else {
newHeight = newWidth * oldHeight / oldWidth;
}
}
BufferedImage result =
new BufferedImage(newWidth , newHeight, BufferedImage.TYPE_INT_BGR);
double widthSkip = new Double(oldWidth-newWidth) / new Double(newWidth);
double heightSkip = new Double(oldHeight-newHeight) / new Double(newHeight);
double widthCounter = 0;
double heightCounter = 0;
int newY = 0;
boolean isNewImageWidthSmaller = widthSkip >0;
boolean isNewImageHeightSmaller = heightSkip >0;
for (int y = 0; y < oldHeight && newY < newHeight; y++) {
if(isNewImageHeightSmaller && heightCounter > 1){ //new image suppose to be smaller - skip row
heightCounter -= 1;
}
else if (heightCounter < -1){ //new image suppose to be bigger - duplicate row
heightCounter += 1;
if(y > 1)
y = y - 2;
else
y = y - 1;
}
else{
heightCounter += heightSkip;
int newX = 0;
for (int x = 0; x < oldWidth && newX < newWidth; x++) {
if(isNewImageWidthSmaller && widthCounter > 1){ //new image suppose to be smaller - skip column
widthCounter -= 1;
}
else if (widthCounter < -1){ //new image suppose to be bigger - duplicate pixel
widthCounter += 1;
if(x >1)
x = x - 2;
else
x = x - 1;
}
else{
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(newX, newY, rgb);
newX++;
widthCounter += widthSkip;
}
}
newY++;
}
}
bufferedImage = result;
}
/**
* Add color to the RGB of the pixel
* @param numToAdd
*/
public void addPixelColor(int numToAdd){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
for (int x = 0; x < width; x ++) {
for (int y = 0; y < height; y ++) {
int rgb = bufferedImage.getRGB(x, y);
bufferedImage.setRGB(x, y, rgb+numToAdd);
}
}
}
/**
* Covert image to black and white.
*/
public void convertToBlackAndWhite() {
ColorSpace gray_space = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp convert_to_gray_op = new ColorConvertOp(gray_space, null);
convert_to_gray_op.filter(bufferedImage, bufferedImage);
}
/**
* Rotates image 90 degrees to the left.
*/
public void rotateLeft(){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage result = new BufferedImage(height,
width, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < width; x ++) {
for (int y = 0; y < height; y ++) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(y, x, rgb);
}
}
bufferedImage = result;
}
/**
* Rotates image 90 degrees to the right.
*/
public void rotateRight(){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage result = new BufferedImage(height,
width, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < width; x ++) {
for (int y = 0; y < height; y ++) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(height-y-1, x, rgb);
}
}
bufferedImage = result;
}
/**
* Rotates image 180 degrees.
*/
public void rotate180(){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage result = new BufferedImage(width,
height, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < width; x ++) {
for (int y = 0; y < height; y ++) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(width-x-1, height-y-1, rgb);
}
}
bufferedImage = result;
}
/**
* Flips the image horizontally
*/
public void flipHorizontally(){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage result = new BufferedImage(width,
height, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < width; x ++) {
for (int y = 0; y < height; y ++) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(width-x-1, y, rgb);
}
}
bufferedImage = result;
}
/**
* Flips the image vertically.
*/
public void flipVertically(){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage result = new BufferedImage(width,
height, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < width; x ++) {
for (int y = 0; y < height; y ++) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(x, height-y-1, rgb);
}
}
bufferedImage = result;
}
/**
* Multiply the image.
* @param timesToMultiplyVertically
* @param timesToMultiplyHorizantelly
*/
public void multiply(int timesToMultiplyVertically,
int timesToMultiplyHorizantelly){
multiply(timesToMultiplyVertically,timesToMultiplyHorizantelly,0);
}
/**
* Multiply the image and also add color each of the multiplied images.
* @param timesToMultiplyVertically
* @param timesToMultiplyHorizantelly
*/
public void multiply(int timesToMultiplyVertically,
int timesToMultiplyHorizantelly, int colorToHenhancePerPixel){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage result = new BufferedImage(width*timesToMultiplyVertically,
height*timesToMultiplyHorizantelly, BufferedImage.TYPE_INT_BGR);
for (int xx = 0; xx < timesToMultiplyVertically; xx ++) {
for (int yy = 0; yy < timesToMultiplyHorizantelly; yy ++) {
for (int x = 0; x < width; x ++) {
for (int y = 0; y < height; y ++) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(width*xx+x, height*yy+y, rgb+colorToHenhancePerPixel*(yy+xx));
}
}
}
}
bufferedImage = result;
}
/**
* Combines the image with another image in an equal presence to both;
* @param newImagePath - image to combine with
*/
public void combineWithPicture(String newImagePath){
combineWithPicture(newImagePath, 2);
}
/**
* Combines the image with another image.
* jump = 2 means that every two pixels the new image is replaced.
* This makes the 2 images equal in presence. If jump=3 than every 3rd
* pixel is replaced by the new image.
* As the jump is higher this is how much the new image has less presence.
*
* @param newImagePath
* @param jump
*/
public void combineWithPicture(String newImagePath, int jump){
try {
BufferedImage bufferedImage2 = ImageIO.read(new File(newImagePath));
combineWithPicture(bufferedImage2, jump, null);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void combineWithPicture(EasyImage image2){
combineWithPicture(image2.getAsBufferedImage(), 2, null);
}
public void combineWithPicture(EasyImage image2, int jump){
combineWithPicture(image2.getAsBufferedImage(), jump, null);
}
public void combineWithPicture(EasyImage image2, Color ignoreColor){
combineWithPicture(image2.getAsBufferedImage(), 2, ignoreColor);
}
public void combineWithPicture(EasyImage image2, int jump, Color ignoreColor){
combineWithPicture(image2.getAsBufferedImage(), jump, ignoreColor);
}
/**
* Combines the image with another image.
* jump = 2 means that every two pixels the new image is replaced.
* This makes the 2 images equal in presence. If jump=3 than every 3rd
* pixel is replaced by the new image.
* As the jump is higher this is how much the new image has less presence.
*
* ignoreColor is a color in the new image that will not be copied -
* this is good where there is a background which you do not want to copy.
*
* @param bufferedImage2
* @param jump
* @param ignoreColor
*/
private void combineWithPicture(BufferedImage bufferedImage2,
int jump, Color ignoreColor){
checkJump(jump);
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
int width2 = bufferedImage2.getWidth();
int height2 = bufferedImage2.getHeight();
int ignoreColorRgb = -1;
if(ignoreColor != null){
ignoreColorRgb = ignoreColor.getRGB();
}
for (int y = 0; y < height; y ++) {
for (int x = y%jump; x < width; x +=jump) {
if(x >= width2 || y>= height2){
continue;
}
int rgb = bufferedImage2.getRGB(x, y);
if( rgb != ignoreColorRgb ){
bufferedImage.setRGB(x, y, rgb);
}
}
}
}
public void crop(int startX, int startY, int endX, int endY){
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if(startX == -1){
startX = 0;
}
if(startY == -1){
startY = 0;
}
if(endX == -1){
endX = width-1;
}
if(endY == -1){
endY = height-1;
}
/*
* 2017-03-23:ziry
* 旧版本endY-startY+1,endX-startX+1有黑边
* BufferedImage result = new BufferedImage(endX-startX+1, endY-startY+1, BufferedImage.TYPE_INT_BGR);
*/
BufferedImage result = new BufferedImage(endX-startX, endY-startY, BufferedImage.TYPE_INT_BGR);
for (int y = startY; y < endY; y ++) {
for (int x = startX; x < endX; x ++) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(x-startX, y-startY, rgb);
}
}
bufferedImage = result;
}
private void saveImage(File file) {
try {
ImageIO.write(bufferedImage, getFileType(file), file);
} catch (IOException e) {
e.printStackTrace();
}
}
public void emphasize(int startX, int startY, int endX, int endY){
emphasize(startX, startY, endX, endY, Color.BLACK, 3 );
}
public void emphasize(int startX, int startY, int endX, int endY, Color backgroundColor){
emphasize(startX, startY, endX, endY, backgroundColor, 3 );
}
public void emphasize(int startX, int startY, int endX, int endY,int jump){
emphasize(startX, startY, endX, endY, Color.BLACK, jump );
}
public void emphasize(int startX, int startY, int endX, int endY, Color backgroundColor,int jump){
checkJump(jump);
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if(startX == -1){
startX = 0;
}
if(startY == -1){
startY = 0;
}
if(endX == -1){
endX = width-1;
}
if(endY == -1){
endY = height-1;
}
for (int y = 0; y < height; y ++) {
for (int x = y%jump; x < width; x +=jump) {
if(y >= startY && y <= endY && x >= startX && x <= endX){
continue;
}
bufferedImage.setRGB(x, y, backgroundColor.getRGB());
}
}
}
private void checkJump(int jump) {
if(jump<1){
throw new RuntimeException("Error: jump can not be less than 1");
}
}
public void addColorToImage(Color color, int jump){
addColorToImage(color.getRGB(),jump);
}
public void addColorToImage(int rgb, int jump){
checkJump(jump);
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
for (int y = 0; y < height; y ++) {
for (int x = y%jump; x < width; x +=jump) {
bufferedImage.setRGB(x, y, rgb);
}
}
}
public void affineTransform (double fShxFactor, double fShyFactor) {
try {
AffineTransform shearer =
AffineTransform.getShearInstance (fShxFactor, fShyFactor);
AffineTransformOp shear_op =
new AffineTransformOp (shearer, null);
bufferedImage = shear_op.filter (bufferedImage, null);
}
catch (Exception e) {
System.out.println("Shearing exception = " + e);
}
}
private String getFileType(File file) {
String fileName = file.getName();
int idx = fileName.lastIndexOf(".");
if(idx == -1){
throw new RuntimeException("Invalid file name");
}
return fileName.substring(idx+1);
}
public int getWidth(){
return bufferedImage.getWidth();
}
public int getHeight(){
return bufferedImage.getHeight();
}
public static void main(String[] args) {
/*
Image image = new Image("c:/pics/p1.jpg");
image.resize(10);
image.multiply(5, 5, 11111);
image.saveAs("c:/pics/multiply+color.jpg");
*/
/*
Image image = new Image("c:/pics/israel_flag.gif");
Image image2 = new Image("c:/pics/palestine_flag.gif");
//image.resize(50);
//image2.resize(50);
//image.affineTransform(0, 0.3);
//image2.affineTransform(0, -0.3);
image.combineWithPicture(image2);
image.saveAs("c:/pics/affineTransformAndCombine2.jpg");
*/
/*
Image image = new Image("c:/pics/p1.jpg");
image.resize(50);
image.affineTransform(0.0, 0.5);
image.saveAs("c:/pics/affineTransform.jpg");
*/
/*
Image image = new Image("c:/pics/heart.gif");
image.multiply(20, 20);
Image image2 = new Image("c:/pics/p6.jpg");
image2.crop(800, 0, -1, -1);
image2.resize(50);
image2.combineWithPicture(image,3,Color.white);
image2.saveAs("c:/pics/combineWithPictureWithoutBackground.jpg");
/*
image.resize(5);
image.multiply(20, 20);
image.combineWithPicture("c:/p2.jpg");
//image.addColorToImage(Color.yellow, 3);
//image.addColorToImage(Color.red, 5);
//image.combineWithPicture("c:/p2.jpg",3);
*/
EasyImage image = new EasyImage("c:/pics/p1.jpg");
int width = image.getWidth();
int height = image.getHeight();
for(int i=0,c=0;i<height;c++,i+=50){
int x = width/2 - i;
int y = height/2 - i;
image.emphasize(x, y, width-1-x, height-1-y, Color.BLACK, 12 - c/4);
}
image.saveAs("c:/pics/emphesizeTrick.jpg");
// */
// image.saveAs("c:/xxx.jpg");
/*
Image image = new Image("c:/pics/p1.jpg");
image.addColorToImage(Color.red, 5);
image.saveAs("c:/pics/addColorToImage.jpg");
*/
}
}
| mit |
Microsoft/vso-httpclient-java | Rest/alm-vss-client/src/main/java/com/microsoft/alm/visualstudio/services/webapi/ReferenceLinks.java | 687 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
package com.microsoft.alm.visualstudio.services.webapi;
import java.util.Map;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonDeserialize(using = ReferenceLinksDeserializer.class)
@JsonSerialize(using = ReferenceLinksSerializer.class)
public class ReferenceLinks {
private Map<String, Object> links;
public Map<String, Object> getLinks() {
return links;
}
public void setLinks(final Map<String, Object> links) {
this.links = links;
}
}
| mit |
mtracy/Data-Structures | src/structures/DoubleLinkedList.java | 8242 | package structures;
import java.io.Serializable;
import java.util.AbstractSequentialList;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class DoubleLinkedList<E> extends AbstractSequentialList<E> implements List<E>, Serializable {
static final long serialVersionUID = 1;
private Node<E> head;
private Node<E> tail;
private int size;
public DoubleLinkedList() {
this.head = null;
this.tail = null;
this.size = 0;
}
public Node<E> getHead() {
return head;
}
public void setHead(Node<E> head) {
this.head = head;
}
public Node<E> getTail() {
return tail;
}
public void setTail(Node<E> tail) {
this.tail = tail;
}
@Override
public boolean add(E elt) {
if (this.head == null) {
setHead(new Node<E>(elt));
setTail(this.head);
} else {
this.tail.next = new Node<E>(elt);
this.tail.next.prev = this.tail;
this.tail = this.tail.next;
}
this.size++;
return true;
}
public boolean add(Node<E> n) {
if (this.head == null) {
this.head = n;
this.tail = this.head;
} else {
this.tail.next = n;
n.prev = this.tail;
n.next = null;
this.tail = n;
}
this.size++;
return true;
}
@Override
public void add(int index, E elt) {
if (index < 0 || index > this.size) {
throw new IndexOutOfBoundsException("Specified index " + index + " is greater than size " + size);
}
if (index == 0) {
Node<E> newhead = new Node<E>(elt);
newhead.next = this.head;
this.head.prev = newhead;
this.head = newhead;
} else if (index == this.size) {
Node<E> newtail = new Node<E>(elt);
newtail.prev = this.tail;
this.tail.next = newtail;
this.tail = newtail;
} else {
Node<E> curr;
if (index < (size >> 1)) {
for (curr = this.head; index > 1; index--) {
curr = curr.next;
}
} else {
index = this.size - 1 - index;
for (curr = this.tail; index >= 0; index--) {
curr = curr.prev;
}
}
Node<E> temp = curr.next;
curr.next = new Node<E>(elt);
curr.next.next = temp;
curr.next.prev = curr;
temp.prev = curr.next;
}
this.size++;
}
public void add(int index, Node<E> n) {
if (index < 0 || index > this.size) {
throw new IndexOutOfBoundsException("Specified index " + index + " is greater than size " + size);
}
if (index == 0) {
Node<E> newhead = n;
newhead.next = this.head;
this.head.prev = newhead;
this.head = newhead;
} else if (index == this.size) {
Node<E> newtail = n;
newtail.prev = this.tail;
this.tail.next = newtail;
this.tail = newtail;
} else {
Node<E> curr;
if (index < (size >> 1)) {
for (curr = this.head; index > 1; index--) {
curr = curr.next;
}
} else {
index = this.size - 1 - index;
for (curr = this.tail; index >= 0; index--) {
curr = curr.prev;
}
}
Node<E> temp = curr.next;
curr.next = n;
curr.next.next = temp;
curr.next.prev = curr;
temp.prev = curr.next;
}
this.size++;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
for (E elt : c) {
this.add(index, elt);
index++;
}
return true;
}
@Override
public void clear() {
this.size = 0;
this.head = this.tail = null;
}
@Override
public boolean contains(Object o) {
return this.indexOf(o) >= 0;
}
@Override
public E get(int index) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException("Specified index " + index + " is greater than size " + size);
}
Node<E> curr;
if (index < (size >> 1)) {
for (curr = this.head; index > 0; index--) {
curr = curr.next;
}
} else {
index = this.size - 1 - index;
for (curr = this.tail; index > 0; index--) {
curr = curr.prev;
}
}
return curr.value;
}
@Override
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> e = head; e != null; e = e.next) {
if (e.value == null)
return index;
index++;
}
} else {
for (Node<E> e = head; e != null; e = e.next) {
if (o.equals(e.value))
return index;
index++;
}
}
return -1;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int lastIndexOf(Object o) {
int index = size - 1;
if (o == null) {
for (Node<E> e = tail; e != null; e = e.prev) {
if (e.value == null)
return index;
index--;
}
} else {
for (Node<E> e = tail; e != null; e = e.prev) {
if (o.equals(e.value))
return index;
index--;
}
}
return -1;
}
@Override
public ListIterator<E> listIterator() {
return new MyListIterator(0);
}
@Override
public ListIterator<E> listIterator(int index) {
return new MyListIterator(index);
}
public E removeNode(Node<E> node) {
if (node.prev != null)
node.prev.next = node.next;
if (node.next != null)
node.next.prev = node.prev;
if (node == head)
head = head.next;
if (node == tail)
tail = tail.prev;
size--;
return node.value;
}
@Override
public boolean remove(Object o) {
if (o == null) {
for (Node<E> e = head; e != null; e = e.next) {
if (e.value == null) {
removeNode(e);
return true;
}
}
} else {
for (Node<E> e = head; e != null; e = e.next) {
if (o.equals(e.value)) {
removeNode(e);
return true;
}
}
}
return false;
}
@Override
public E remove(int index) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException("Specified index " + index + " is greater than size " + size);
}
Node<E> curr;
if (index < (size >> 1)) {
for (curr = this.head; index > 0; index--) {
curr = curr.next;
}
} else {
index = this.size - 1 - index;
for (curr = this.tail; index > 0; index--) {
curr = curr.prev;
}
}
return removeNode(curr);
}
@Override
public int size() {
return size;
}
private class MyListIterator implements ListIterator<E> {
private Node<E> current = head;
private Node<E> previous;
private Node<E> lastreturned;
int currindex = 0;
public MyListIterator(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Specified index " + index + " is greater than size " + size);
}
currindex = index;
if (index == size) {
current = null;
previous = tail;
} else {
Node<E> curr;
if (index < (size >> 1)) {
for (curr = head; index > 0; index--) {
curr = curr.next;
}
} else {
index = size - 1 - index;
for (curr = tail; index > 0; index--) {
curr = curr.prev;
}
}
previous = curr.prev;
current = curr;
}
}
@Override
public void add(E e) {
if (size == 0) {
current = null;
previous = new Node<E>(e);
previous.next = current;
head = previous;
tail = previous;
} else if (previous == null) {
previous = new Node<E>(e);
previous.next = current;
head = previous;
} else {
previous.next = new Node<E>(e);
previous.next.next = current;
previous.next.prev = previous;
previous = previous.next;
}
if (current != null) {
current.prev = previous;
}
size++;
currindex++;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public boolean hasPrevious() {
return previous != null;
}
@Override
public E next() {
if (current == null)
throw new NoSuchElementException();
E elt = current.value;
previous = current;
current = current.next;
currindex++;
lastreturned = previous;
return elt;
}
@Override
public int nextIndex() {
return currindex;
}
@Override
public E previous() {
if (previous == null)
throw new NoSuchElementException();
current = previous;
previous = previous.prev;
currindex--;
lastreturned = current;
return current.value;
}
@Override
public int previousIndex() {
return currindex - 1;
}
@Override
public void remove() {
if (lastreturned == null)
throw new IllegalStateException();
removeNode(lastreturned);
}
@Override
public void set(E e) {
if (lastreturned == null)
throw new IllegalStateException();
lastreturned.value = e;
}
}
}
| mit |
partnet/ads-proto | fta/src/test/java/com/partnet/test/SearchFormTests.java | 587 | package com.partnet.test;
import com.partnet.junit.SeAuto;
import com.partnet.junit.annotations.browser.Firefox;
import com.partnet.junit.annotations.browser.PhantomJs;
import com.partnet.step.SearchSteps;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
/**
* @author bbarker
*/
@RunWith(SeAuto.class)
public class SearchFormTests {
@Inject
private SearchSteps searchSteps;
@Test
@PhantomJs
public void test_ensureListOfDrugsIsAccurate()
{
searchSteps.givenIAmOnTheSearchPage();
searchSteps.thenValidateListOfDrugs();
}
}
| mit |
mtpro/neural-backprop | InputLayerNeuron.java | 715 | package com.proetsch.ann;
// A Neuron which sends out a constant value
// Only the link weight to hidden-layer neurons
// should be modified - this Neuron's activation function
// should be identity
public class InputLayerNeuron extends Neuron {
public InputLayerNeuron(Layer l) {
super(l);
}
public void setInput(double in_val) {
this.weighted_inputs_sum = in_val;
this.output_value = in_val;
}
@Override
protected double activation_function(double x) {
return x;
}
@Override
protected double d_activation_function() {
return 1;
}
@Override
protected double calculate_delta(double training_val) {
return 0.0d;
}
@Override
public void calculateOutput() {
return;
}
}
| mit |
RobertTheNerd/sc2geeks | web-api/website/service.client/src/main/java/api/sc2geeks/client/ServiceConfig.java | 1839 | package api.sc2geeks.client;
import api.sc2geeks.entity.RefinementField;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Hashtable;
/**
* Created with IntelliJ IDEA.
* User: robert
* Date: 4/15/12
* Time: 10:33 PM
* To change this template use File | Settings | File Templates.
*/
class ServiceConfig
{
String serviceUrl;
private static ServiceConfig replayServiceConfig;
private static ServiceConfig playerServiceConfig;
private Hashtable<RefinementField, String> refinementFieldSetting;
static {
try
{
ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
replayServiceConfig = context.getBean("replayServiceConfig", ServiceConfig.class);
playerServiceConfig = context.getBean("playerServiceConfig", ServiceConfig.class);
}catch(Exception e)
{
e.printStackTrace();
}
}
public static ServiceConfig getReplayServiceConfig()
{
return replayServiceConfig;
}
public static ServiceConfig getPlayerServiceConfig()
{
return playerServiceConfig;
}
private ServiceConfig(){}
public String getServiceUrl()
{
return serviceUrl;
}
public void setServiceUrl(String serviceUrl)
{
this.serviceUrl = processPath(serviceUrl);
}
public Hashtable<RefinementField, String> getRefinementFieldSetting()
{
return refinementFieldSetting;
}
public void setRefinementFieldSetting(Hashtable<RefinementField, String> refinementFieldSetting)
{
this.refinementFieldSetting = refinementFieldSetting;
}
public String getRefinementParamName(RefinementField field)
{
if (refinementFieldSetting == null)
return null;
return refinementFieldSetting.get(field);
}
static String processPath(String input)
{
return input.endsWith("/") ? input : input + "/";
}
}
| mit |
TechShroom/UnplannedDescent | api/src/main/java/com/techshroom/unplanned/event/mouse/MouseEvent.java | 1467 | /*
* This file is part of unplanned-descent, licensed under the MIT License (MIT).
*
* Copyright (c) TechShroom Studios <https://techshroom.com>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.techshroom.unplanned.event.mouse;
import com.techshroom.unplanned.event.Event;
import com.techshroom.unplanned.input.Mouse;
public interface MouseEvent extends Event {
Mouse getSource();
}
| mit |
valerielashvili/SoftUni-Software-University | Java OOP Basics - October 2017/03. Inheritance - Lab/src/p04_Fragile_Base_Class/Animal.java | 408 | package p04_Fragile_Base_Class;
import java.util.ArrayList;
class Animal {
protected ArrayList<Food> foodEaten;
public Animal(ArrayList<Food> foodEaten) {
this.foodEaten = foodEaten;
}
public final void eat(Food food) {
this.foodEaten.add(food);
}
public void eatAll(Food[] foods) {
for (Food food : foods) {
this.eat(food);
}
}
}
| mit |
jgaltidor/VarJ | analyzed_libs/jdk1.6.0_06_src/java/rmi/UnexpectedException.java | 1311 | /*
* @(#)UnexpectedException.java 1.13 05/11/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.rmi;
/**
* An <code>UnexpectedException</code> is thrown if the client of a
* remote method call receives, as a result of the call, a checked
* exception that is not among the checked exception types declared in the
* <code>throws</code> clause of the method in the remote interface.
*
* @version 1.13, 11/17/05
* @author Roger Riggs
* @since JDK1.1
*/
public class UnexpectedException extends RemoteException {
/* indicate compatibility with JDK 1.1.x version of class */
private static final long serialVersionUID = 1800467484195073863L;
/**
* Constructs an <code>UnexpectedException</code> with the specified
* detail message.
*
* @param s the detail message
* @since JDK1.1
*/
public UnexpectedException(String s) {
super(s);
}
/**
* Constructs a <code>UnexpectedException</code> with the specified
* detail message and nested exception.
*
* @param s the detail message
* @param ex the nested exception
* @since JDK1.1
*/
public UnexpectedException(String s, Exception ex) {
super(s, ex);
}
}
| mit |