code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*
* Copyright (c) 2011 Urs P. Stettler, https://github.com/cryxli
*
* 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 li.cryx.expcraft.perm;
import li.cryx.expcraft.module.ExpCraftModule;
import org.bukkit.entity.Player;
/**
* This class is an implementation of an {@link AbstractPermissionManager} that
* covers the case when Bukkit is running without any permissions plugin. By
* default all player can use all loaded {@link ExpCraftModule}s and only
* Operators can execute admin commands.
*
* @author cryxli
*/
public class NoPermissionManager extends AbstractPermissionManager {
/** Is <code>true</code>, if the player is an Operator. */
@Override
public boolean hasAdminCommand(final Player player, final String command) {
return player.isOp();
}
/** Will always return <code>true</code> */
@Override
public boolean hasLevel(final ExpCraftModule module, final Player player) {
return true;
}
}
| cryxli/ExpCraft | ExpCraftCore/src/main/java/li/cryx/expcraft/perm/NoPermissionManager.java | Java | mit | 1,969 |
package org.robolectric.shadows;
import static android.os.Build.VERSION_CODES.M;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;
import static org.robolectric.Shadows.shadowOf;
import static org.robolectric.util.ReflectionHelpers.ClassParameter.from;
import static org.robolectric.util.ReflectionHelpers.callConstructor;
import static org.robolectric.util.ReflectionHelpers.callInstanceMethod;
import static org.robolectric.util.ReflectionHelpers.setField;
import static org.robolectric.util.reflector.Reflector.reflector;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowMessage._Message_;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.Scheduler;
@RunWith(AndroidJUnit4.class)
public class ShadowMessageQueueTest {
private Looper looper;
private MessageQueue queue;
private ShadowMessageQueue shadowQueue;
private Message testMessage;
private TestHandler handler;
private Scheduler scheduler;
private String quitField;
private static class TestHandler extends Handler {
public List<Message> handled = new ArrayList<>();
public TestHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
handled.add(msg);
}
}
private static Looper newLooper() {
return newLooper(true);
}
private static Looper newLooper(boolean canQuit) {
return callConstructor(Looper.class, from(boolean.class, canQuit));
}
@Before
public void setUp() throws Exception {
// Queues and loopers are closely linked; can't easily test one without the other.
looper = newLooper();
handler = new TestHandler(looper);
queue = looper.getQueue();
shadowQueue = shadowOf(queue);
scheduler = shadowQueue.getScheduler();
scheduler.pause();
testMessage = handler.obtainMessage();
quitField = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? "mQuitting" : "mQuiting";
}
@Test
public void test_setGetHead() {
shadowQueue.setHead(testMessage);
assertThat(shadowQueue.getHead()).named("getHead()").isSameAs(testMessage);
}
private boolean enqueueMessage(Message msg, long when) {
return callInstanceMethod(queue, "enqueueMessage",
from(Message.class, msg),
from(long.class, when)
);
}
private void removeMessages(Handler handler, int what, Object token) {
callInstanceMethod(queue, "removeMessages",
from(Handler.class, handler),
from(int.class, what),
from(Object.class, token)
);
}
@Test
public void enqueueMessage_setsHead() {
enqueueMessage(testMessage, 100);
assertThat(shadowQueue.getHead()).named("head").isSameAs(testMessage);
}
@Test
public void enqueueMessage_returnsTrue() {
assertThat(enqueueMessage(testMessage, 100)).named("retval").isTrue();
}
@Test
public void enqueueMessage_setsWhen() {
enqueueMessage(testMessage, 123);
assertThat(testMessage.getWhen()).named("when").isEqualTo(123);
}
@Test
public void enqueueMessage_returnsFalse_whenQuitting() {
setField(queue, quitField, true);
assertThat(enqueueMessage(testMessage, 1)).named("enqueueMessage()").isFalse();
}
@Test
public void enqueueMessage_doesntSchedule_whenQuitting() {
setField(queue, quitField, true);
enqueueMessage(testMessage, 1);
assertThat(scheduler.size()).named("scheduler_size").isEqualTo(0);
}
@Test
public void enqueuedMessage_isSentToHandler() {
enqueueMessage(testMessage, 200);
scheduler.advanceTo(199);
assertThat(handler.handled).named("handled:before").isEmpty();
scheduler.advanceTo(200);
assertThat(handler.handled).named("handled:after").containsExactly(testMessage);
}
@Test
public void removedMessage_isNotSentToHandler() {
enqueueMessage(testMessage, 200);
assertThat(scheduler.size()).named("scheduler size:before").isEqualTo(1);
removeMessages(handler, testMessage.what, null);
scheduler.advanceToLastPostedRunnable();
assertThat(scheduler.size()).named("scheduler size:after").isEqualTo(0);
assertThat(handler.handled).named("handled").isEmpty();
}
@Test
public void enqueueMessage_withZeroWhen_postsAtFront() {
enqueueMessage(testMessage, 0);
Message m2 = handler.obtainMessage(2);
enqueueMessage(m2, 0);
scheduler.advanceToLastPostedRunnable();
assertThat(handler.handled).named("handled").containsExactly(m2, testMessage);
}
@Test
public void dispatchedMessage_isMarkedInUse_andRecycled() {
Handler handler =
new Handler(looper) {
@Override
public void handleMessage(Message msg) {
boolean inUse = callInstanceMethod(msg, "isInUse");
assertThat(inUse).named(msg.what + ":inUse").isTrue();
Message next = reflector(_Message_.class, msg).getNext();
assertThat(next).named(msg.what + ":next").isNull();
}
};
Message msg = handler.obtainMessage(1);
enqueueMessage(msg, 200);
Message msg2 = handler.obtainMessage(2);
enqueueMessage(msg2, 205);
scheduler.advanceToNextPostedRunnable();
// Check that it's been properly recycled.
assertThat(msg.what).named("msg.what").isEqualTo(0);
scheduler.advanceToNextPostedRunnable();
assertThat(msg2.what).named("msg2.what").isEqualTo(0);
}
@Test
public void reset_shouldClearMessageQueue() {
Message msg = handler.obtainMessage(1234);
Message msg2 = handler.obtainMessage(5678);
handler.sendMessage(msg);
handler.sendMessage(msg2);
assertThat(handler.hasMessages(1234)).named("before-1234").isTrue();
assertThat(handler.hasMessages(5678)).named("before-5678").isTrue();
shadowQueue.reset();
assertThat(handler.hasMessages(1234)).named("after-1234").isFalse();
assertThat(handler.hasMessages(5678)).named("after-5678").isFalse();
}
@Test
public void postAndRemoveSyncBarrierToken() {
int token = postSyncBarrier(queue);
removeSyncBarrier(queue, token);
}
@Test
// TODO(b/74402484): enable once workaround is removed
@Ignore
public void removeInvalidSyncBarrierToken() {
try {
removeSyncBarrier(queue, 99);
fail("Expected exception when sync barrier not present on MessageQueue");
} catch (IllegalStateException expected) {
}
}
@Test
public void postAndRemoveSyncBarrierToken_messageBefore() {
enqueueMessage(testMessage, SystemClock.uptimeMillis());
int token = postSyncBarrier(queue);
removeSyncBarrier(queue, token);
assertThat(shadowQueue.getHead()).isEqualTo(testMessage);
}
@Test
public void postAndRemoveSyncBarrierToken_messageBeforeConsumed() {
enqueueMessage(testMessage, SystemClock.uptimeMillis());
int token = postSyncBarrier(queue);
scheduler.advanceToLastPostedRunnable();
removeSyncBarrier(queue, token);
assertThat(shadowQueue.getHead()).isNull();
assertThat(handler.handled).named("handled:after").containsExactly(testMessage);
}
@Test
public void postAndRemoveSyncBarrierToken_messageAfter() {
enqueueMessage(testMessage, SystemClock.uptimeMillis() + 100);
int token = postSyncBarrier(queue);
removeSyncBarrier(queue, token);
assertThat(shadowQueue.getHead()).isEqualTo(testMessage);
scheduler.advanceToLastPostedRunnable();
assertThat(shadowQueue.getHead()).isNull();
assertThat(handler.handled).named("handled:after").containsExactly(testMessage);
}
@Test
public void postAndRemoveSyncBarrierToken_syncBefore() {
int token = postSyncBarrier(queue);
enqueueMessage(testMessage, SystemClock.uptimeMillis());
scheduler.advanceToLastPostedRunnable();
removeSyncBarrier(queue, token);
assertThat(shadowQueue.getHead()).isNull();
assertThat(handler.handled).named("handled:after").containsExactly(testMessage);
}
private static void removeSyncBarrier(MessageQueue queue, int token) {
ReflectionHelpers.callInstanceMethod(
MessageQueue.class, queue, "removeSyncBarrier", from(int.class, token));
}
private static int postSyncBarrier(MessageQueue queue) {
if (RuntimeEnvironment.getApiLevel() >= M) {
return queue.postSyncBarrier();
} else {
return ReflectionHelpers.callInstanceMethod(
MessageQueue.class,
queue,
"enqueueSyncBarrier",
from(long.class, SystemClock.uptimeMillis()));
}
}
}
| spotify/robolectric | robolectric/src/test/java/org/robolectric/shadows/ShadowMessageQueueTest.java | Java | mit | 8,875 |
package com.github.gquintana.beepbeep.sql;
import java.sql.Connection;
import java.sql.SQLException;
public interface SqlConnectionProvider extends AutoCloseable {
Connection getConnection() throws SQLException;
}
| gquintana/beepbeep | src/main/java/com/github/gquintana/beepbeep/sql/SqlConnectionProvider.java | Java | mit | 220 |
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 TechReborn
*
* 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 techreborn.blockentity.generator.basic;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import reborncore.api.IToolDrop;
import reborncore.common.blockentity.MachineBaseBlockEntity;
import reborncore.common.powerSystem.PowerAcceptorBlockEntity;
import techreborn.config.TechRebornConfig;
import techreborn.init.TRBlockEntities;
import techreborn.init.TRContent;
/**
* Created by modmuss50 on 25/02/2016.
*/
public class WindMillBlockEntity extends PowerAcceptorBlockEntity implements IToolDrop {
public float bladeAngle;
public float spinSpeed;
public WindMillBlockEntity(BlockPos pos, BlockState state) {
super(TRBlockEntities.WIND_MILL, pos, state);
}
@Override
public void tick(World world, BlockPos pos, BlockState state, MachineBaseBlockEntity blockEntity) {
super.tick(world, pos, state, blockEntity);
if (world == null) {
return;
}
boolean generating = pos.getY() > 64;
if (world.isClient) {
bladeAngle += spinSpeed;
if (generating) {
spinSpeed = Math.min(0.2F, spinSpeed + 0.002f);
} else {
spinSpeed = Math.max(0.0f, spinSpeed - 0.005f);
}
}
if (generating) {
int actualPower = TechRebornConfig.windMillBaseEnergy;
if (world.isThundering()) {
actualPower *= TechRebornConfig.windMillThunderMultiplier;
}
addEnergy(actualPower); // Value taken from
// http://wiki.industrial-craft.net/?title=Wind_Mill
// Not worth making more complicated
}
}
@Override
public long getBaseMaxPower() {
return TechRebornConfig.windMillMaxEnergy;
}
@Override
public boolean canProvideEnergy(@Nullable Direction side) {
return true;
}
@Override
public long getBaseMaxOutput() {
return TechRebornConfig.windMillMaxOutput;
}
@Override
public long getBaseMaxInput() {
return 0;
}
@Override
public ItemStack getToolDrop(PlayerEntity playerIn) {
return TRContent.Machine.WIND_MILL.getStack();
}
}
| TechReborn/TechReborn | src/main/java/techreborn/blockentity/generator/basic/WindMillBlockEntity.java | Java | mit | 3,332 |
package eu.bcvsolutions.idm.core.api.dto.theme;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* Action colors.
*
* @author Radek TomiΕ‘ka
* @since 12.0.0
*/
@JsonInclude(Include.NON_NULL)
public class ActionDto implements Serializable {
private static final long serialVersionUID = 1L;
//
private String loading;
public String getLoading() {
return loading;
}
public void setLoading(String loading) {
this.loading = loading;
}
}
| bcvsolutions/CzechIdMng | Realization/backend/core/core-api/src/main/java/eu/bcvsolutions/idm/core/api/dto/theme/ActionDto.java | Java | mit | 555 |
package com.chocolatefactory.android.dailyfit;
/**
* Created by HyeonSu on 2015-03-23.
*/
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.chocolatefactory.android.dailyfit.records.Tab1;
import com.chocolatefactory.android.dailyfit.records.Tab2;
/**
* Created by hp1 on 21-01-2015.
*/
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab2 tab2 = new Tab2();
return tab2;
}
}
// This method return the titles for the Tabs in the Tab Strip
@Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
@Override
public int getCount() {
return NumbOfTabs;
}
} | ChocolateFactory/dailyfit-android | Dailyfit/app/src/main/java/com/chocolatefactory/android/dailyfit/ViewPagerAdapter.java | Java | mit | 1,821 |
package com.carlosgracite.katamorph;
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);
}
} | carlosgracite/katamorph | katamorph/src/androidTest/java/com/carlosgracite/katamorph/ApplicationTest.java | Java | mit | 358 |
// This is a generated file. Not intended for manual editing.
package name.kropp.intellij.makefile.psi.impl;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import name.kropp.intellij.makefile.psi.MakefileFunction;
import name.kropp.intellij.makefile.psi.MakefileIdentifier;
import name.kropp.intellij.makefile.psi.MakefileVariableUsage;
import name.kropp.intellij.makefile.psi.MakefileVisitor;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class MakefileIdentifierImpl extends ASTWrapperPsiElement implements MakefileIdentifier {
public MakefileIdentifierImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull MakefileVisitor visitor) {
visitor.visitIdentifier(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof MakefileVisitor) accept((MakefileVisitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public List<MakefileFunction> getFunctionList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, MakefileFunction.class);
}
@Override
@NotNull
public List<MakefileVariableUsage> getVariableUsageList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, MakefileVariableUsage.class);
}
}
| kropp/intellij-makefile | gen/name/kropp/intellij/makefile/psi/impl/MakefileIdentifierImpl.java | Java | mit | 1,380 |
package com.suaft.bountyboard.init;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
public class Recipies {
public static void init()
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(ModItems.test), " s ", "sss", " s ", 's', "stickWood"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(ModBlocks.foo), new ItemStack(ModItems.test), new ItemStack(ModItems.test)));
}
}
| AlexVanLeyen/BountyBoard | src/java/com/suaft/bountyboard/init/Recipies.java | Java | mit | 593 |
package com.lfk.justweengine.Utils.logger;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
/**
* Logger is a wrapper for logging utils
* But more pretty, simple and powerful
*/
final class LoggerPrinter implements Printer {
private static final int DEBUG = 3;
private static final int ERROR = 6;
private static final int ASSERT = 7;
private static final int INFO = 4;
private static final int VERBOSE = 2;
private static final int WARN = 5;
/**
* Android's max limit for a log entry is ~4076 bytes,
* so 4000 bytes is used as chunk size since default charset
* is UTF-8
*/
private static final int CHUNK_SIZE = 4000;
/**
* It is used for json pretty print
*/
private static final int JSON_INDENT = 4;
/**
* The minimum stack trace index, starts at this class after two native calls.
*/
private static final int MIN_STACK_OFFSET = 3;
/**
* Drawing toolbox
*/
private static final char TOP_LEFT_CORNER = 'β';
private static final char BOTTOM_LEFT_CORNER = 'β';
private static final char MIDDLE_CORNER = 'β';
private static final char HORIZONTAL_DOUBLE_LINE = 'β';
private static final String DOUBLE_DIVIDER = "ββββββββββββββββββββββββββββββββββββββββββββ";
private static final String SINGLE_DIVIDER = "ββββββββββββββββββββββββββββββββββββββββββββ";
private static final String TOP_BORDER = TOP_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER;
private static final String BOTTOM_BORDER = BOTTOM_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER;
private static final String MIDDLE_BORDER = MIDDLE_CORNER + SINGLE_DIVIDER + SINGLE_DIVIDER;
/**
* tag is used for the Log, the name is a little different
* in order to differentiate the logs easily with the filter
*/
private String tag;
/**
* Localize single tag and method count for each thread
*/
private final ThreadLocal<String> localTag = new ThreadLocal<>();
private final ThreadLocal<Integer> localMethodCount = new ThreadLocal<>();
/**
* It is used to determine log settings such as method count, thread info visibility
*/
private Settings settings;
/**
* It is used to change the tag
*
* @param tag is the given string which will be used in Logger
*/
@Override
public Settings init(String tag) {
if (tag == null) {
throw new NullPointerException("tag may not be null");
}
if (tag.trim().length() == 0) {
throw new IllegalStateException("tag may not be empty");
}
this.tag = tag;
this.settings = new Settings();
return settings;
}
@Override
public Settings getSettings() {
return settings;
}
@Override
public Printer t(String tag, int methodCount) {
if (tag != null) {
localTag.set(tag);
}
localMethodCount.set(methodCount);
return this;
}
@Override
public void d(String message, Object... args) {
log(DEBUG, message, args);
}
@Override
public void e(String message, Object... args) {
e(null, message, args);
}
@Override
public void e(Throwable throwable, String message, Object... args) {
if (throwable != null && message != null) {
message += " : " + throwable.toString();
}
if (throwable != null && message == null) {
message = throwable.toString();
}
if (message == null) {
message = "No message/exception is set";
}
log(ERROR, message, args);
}
@Override
public void w(String message, Object... args) {
log(WARN, message, args);
}
@Override
public void i(String message, Object... args) {
log(INFO, message, args);
}
@Override
public void v(String message, Object... args) {
log(VERBOSE, message, args);
}
@Override
public void wtf(String message, Object... args) {
log(ASSERT, message, args);
}
/**
* Formats the json content and print it
*
* @param json the json content
*/
@Override
public void json(String json) {
if (TextUtils.isEmpty(json)) {
d("Empty/Null json content");
return;
}
try {
if (json.startsWith("{")) {
JSONObject jsonObject = new JSONObject(json);
String message = jsonObject.toString(JSON_INDENT);
d(message);
return;
}
if (json.startsWith("[")) {
JSONArray jsonArray = new JSONArray(json);
String message = jsonArray.toString(JSON_INDENT);
d(message);
}
} catch (JSONException e) {
e(e.getCause().getMessage() + "\n" + json);
}
}
/**
* Formats the json content and print it
*
* @param xml the xml content
*/
@Override
public void xml(String xml) {
if (TextUtils.isEmpty(xml)) {
d("Empty/Null xml content");
return;
}
try {
Source xmlInput = new StreamSource(new StringReader(xml));
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n"));
} catch (TransformerException e) {
e(e.getCause().getMessage() + "\n" + xml);
}
}
@Override
public void clear() {
settings = null;
}
/**
* This method is synchronized in order to avoid messy of logs' order.
*/
private synchronized void log(int logType, String msg, Object... args) {
if (settings.getLogLevel() == LogLevel.NONE) {
return;
}
String tag = getTag();
String message = createMessage(msg, args);
int methodCount = getMethodCount();
logTopBorder(logType, tag);
logHeaderContent(logType, tag, methodCount);
//get bytes of message with system's default charset (which is UTF-8 for Android)
byte[] bytes = message.getBytes();
int length = bytes.length;
if (length <= CHUNK_SIZE) {
if (methodCount > 0) {
logDivider(logType, tag);
}
logContent(logType, tag, message);
logBottomBorder(logType, tag);
return;
}
if (methodCount > 0) {
logDivider(logType, tag);
}
for (int i = 0; i < length; i += CHUNK_SIZE) {
int count = Math.min(length - i, CHUNK_SIZE);
//create a new String with system's default charset (which is UTF-8 for Android)
logContent(logType, tag, new String(bytes, i, count));
}
logBottomBorder(logType, tag);
}
private void logTopBorder(int logType, String tag) {
logChunk(logType, tag, TOP_BORDER);
}
private void logHeaderContent(int logType, String tag, int methodCount) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (settings.isShowThreadInfo()) {
logChunk(logType, tag, HORIZONTAL_DOUBLE_LINE + " Thread: " + Thread.currentThread().getName());
logDivider(logType, tag);
}
String level = "";
int stackOffset = getStackOffset(trace) + settings.getMethodOffset();
//corresponding method count with the current stack may exceeds the stack trace. Trims the count
if (methodCount + stackOffset > trace.length) {
methodCount = trace.length - stackOffset - 1;
}
for (int i = methodCount; i > 0; i--) {
int stackIndex = i + stackOffset;
if (stackIndex >= trace.length) {
continue;
}
StringBuilder builder = new StringBuilder();
builder.append("β ")
.append(level)
.append(getSimpleClassName(trace[stackIndex].getClassName()))
.append(".")
.append(trace[stackIndex].getMethodName())
.append(" ")
.append(" (")
.append(trace[stackIndex].getFileName())
.append(":")
.append(trace[stackIndex].getLineNumber())
.append(")");
level += " ";
logChunk(logType, tag, builder.toString());
}
}
private void logBottomBorder(int logType, String tag) {
logChunk(logType, tag, BOTTOM_BORDER);
}
private void logDivider(int logType, String tag) {
logChunk(logType, tag, MIDDLE_BORDER);
}
private void logContent(int logType, String tag, String chunk) {
String[] lines = chunk.split(System.getProperty("line.separator"));
for (String line : lines) {
logChunk(logType, tag, HORIZONTAL_DOUBLE_LINE + " " + line);
}
}
private void logChunk(int logType, String tag, String chunk) {
String finalTag = formatTag(tag);
switch (logType) {
case ERROR:
settings.getLogTool().e(finalTag, chunk);
break;
case INFO:
settings.getLogTool().i(finalTag, chunk);
break;
case VERBOSE:
settings.getLogTool().v(finalTag, chunk);
break;
case WARN:
settings.getLogTool().w(finalTag, chunk);
break;
case ASSERT:
settings.getLogTool().wtf(finalTag, chunk);
break;
case DEBUG:
// Fall through, log debug by default
default:
settings.getLogTool().d(finalTag, chunk);
break;
}
}
private String getSimpleClassName(String name) {
int lastIndex = name.lastIndexOf(".");
return name.substring(lastIndex + 1);
}
private String formatTag(String tag) {
if (!TextUtils.isEmpty(tag) && !TextUtils.equals(this.tag, tag)) {
return this.tag + "-" + tag;
}
return this.tag;
}
/**
* @return the appropriate tag based on local or global
*/
private String getTag() {
String tag = localTag.get();
if (tag != null) {
localTag.remove();
return tag;
}
return this.tag;
}
private String createMessage(String message, Object... args) {
return args.length == 0 ? message : String.format(message, args);
}
private int getMethodCount() {
Integer count = localMethodCount.get();
int result = settings.getMethodCount();
if (count != null) {
localMethodCount.remove();
result = count;
}
if (result < 0) {
throw new IllegalStateException("methodCount cannot be negative");
}
return result;
}
/**
* Determines the starting index of the stack trace, after method calls made by this class.
*
* @param trace the stack trace
* @return the stack offset
*/
private int getStackOffset(StackTraceElement[] trace) {
for (int i = MIN_STACK_OFFSET; i < trace.length; i++) {
StackTraceElement e = trace[i];
String name = e.getClassName();
if (!name.equals(LoggerPrinter.class.getName()) && !name.equals(Logger.class.getName())) {
return --i;
}
}
return -1;
}
}
| Sonnydch/dzwfinal | AndroidFinal/engine/src/main/java/com/lfk/justweengine/Utils/logger/LoggerPrinter.java | Java | mit | 12,550 |
package com.teamderpy.victusludus.gui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Slider;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.teamderpy.victusludus.VictusLudusGame;
import com.teamderpy.victusludus.engine.ISettings;
import com.teamderpy.victusludus.engine.SettingsImpl;
import com.teamderpy.victusludus.game.Game;
public class UINewOrganismMenu extends UI {
private TextField organismNameField;
private TextField organismSeedField;
private Slider worldAgeSlider;
/* whether a name has been typed in */
private boolean typedInName = false;
@Override
public void create () {
this.stage = new Stage();
this.stage.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
VictusLudusGame.engine.inputMultiplexer.addProcessor(0, this.stage);
Table tableContent = new Table();
tableContent.setFillParent(true);
tableContent.setBackground(this.skin.newDrawable("white", Color.BLACK));
// tableContent.debug();
tableContent.center();
this.stage.addActor(tableContent);
Table tableTitle = new Table();
tableTitle.setFillParent(true);
// tableTitle.debug();
tableTitle.top();
this.stage.addActor(tableTitle);
Table tableFooter = new Table();
tableFooter.setFillParent(true);
// tableFooter.debug();
tableFooter.bottom();
this.stage.addActor(tableFooter);
/************ TITLE */
final Label titleText = new Label("New Organism", this.skin, "medium");
tableTitle.add(titleText);
tableTitle.row();
/************ TOOLTIP */
final Label tooltipText = new Label("Create a new organism to play with", this.skin);
/************ ORGANISM NAME */
final Label organismLabelField = new Label("Organism name", this.skin);
this.organismNameField = new TextField("", this.skin);
tableContent.add(organismLabelField).pad(UI.CELL_PADDING).padRight(UI.CELL_PADDING * 10).left();
tableContent.add(this.organismNameField).pad(UI.CELL_PADDING).colspan(3);
tableContent.row();
this.organismNameField.addListener(new ClickListener() {
@Override
public void enter (final InputEvent event, final float x, final float y, final int pointer, final Actor fromActor) {
tooltipText.setText("The name of your organism");
}
});
this.organismNameField.addListener(new InputListener() {
@Override
public boolean keyTyped (final InputEvent event, final char character) {
if (!UINewOrganismMenu.this.organismNameField.getText().isEmpty()) {
UINewOrganismMenu.this.typedInName = true;
} else {
UINewOrganismMenu.this.typedInName = false;
}
return true;
}
});
/************ WORLD AGE */
final Label worldAgeLabel = new Label("World age", this.skin);
final Label worldAgeLessLabel = new Label("Young", this.skin);
final Label worldAgeMoreLabel = new Label("Old", this.skin);
this.worldAgeSlider = new Slider(0.5F, 60.5F, 0.5F, false, this.skin);
this.worldAgeSlider.setValue(12);
tableContent.add(worldAgeLabel).pad(UI.CELL_PADDING).padRight(UI.CELL_PADDING * 10).left();
tableContent.add(worldAgeLessLabel).pad(UI.CELL_PADDING).right();
tableContent.add(this.worldAgeSlider).pad(UI.CELL_PADDING);
tableContent.add(worldAgeMoreLabel).pad(UI.CELL_PADDING).left();
tableContent.row();
this.worldAgeSlider.addListener(new ClickListener() {
@Override
public void enter (final InputEvent event, final float x, final float y, final int pointer, final Actor fromActor) {
tooltipText.setText("The age of the world");
}
});
/************ SEED */
final Label organismSeedLabel = new Label("Seed", this.skin);
this.organismSeedField = new TextField("", this.skin);
tableContent.add(organismSeedLabel).pad(UI.CELL_PADDING).padRight(UI.CELL_PADDING * 10).left();
tableContent.add(this.organismSeedField).pad(UI.CELL_PADDING).colspan(3);
tableContent.row();
this.organismSeedField.addListener(new ClickListener() {
@Override
public void enter (final InputEvent event, final float x, final float y, final int pointer, final Actor fromActorr) {
tooltipText.setText("The random seed for the world");
}
});
this.organismSeedField.addListener(new InputListener() {
@Override
public boolean keyTyped (final InputEvent event, final char character) {
if (!UINewOrganismMenu.this.typedInName) {
UINewOrganismMenu.this.organismNameField.setText(UINewOrganismMenu.this.organismSeedField.getText());
}
return true;
}
});
/************ CONTINUE */
final TextButton continueButton = new TextButton("Continue", this.skin);
tableFooter.add(continueButton).pad(UI.CELL_PADDING);
tableFooter.row();
continueButton.addListener(new ChangeListener() {
@Override
public void changed (final ChangeEvent event, final Actor actor) {
UINewOrganismMenu.this.soundSelect.play();
if (UINewOrganismMenu.this.organismNameField.getText().length() > 0) {
ISettings requestedSettings = new SettingsImpl();
requestedSettings.addValue("organismAge", UINewOrganismMenu.this.worldAgeSlider.getValue());
requestedSettings.addValue("seed",
UINewOrganismMenu.longHashString(UINewOrganismMenu.this.organismSeedField.getText()));
if (UINewOrganismMenu.this.organismNameField.getText().equals("ortho")) {
requestedSettings.addValue("useOrtho", true);
} else {
requestedSettings.addValue("useOrtho", false);
}
requestedSettings.addValue("mapHeight", 5);
requestedSettings.addValue("mapWidth", 5);
requestedSettings.addValue("mapSmoothness", 2.0f); // 0-10
requestedSettings.addValue("mapRandomness", 0.25f); // 0-1.5
requestedSettings.addValue("mapScale", 8f); // 1-12
requestedSettings.addValue("mapPlateauFactor", 0.2f); // 0-0.3
VictusLudusGame.engine.changeUI(null);
VictusLudusGame.engine.changeView(new Game(), requestedSettings);
} else {
new Dialog("Organism name?", UINewOrganismMenu.this.skin, "dialog") {
}.text("You forgot to enter a name!").button("OK!", true).key(Keys.ENTER, true).key(Keys.ESCAPE, true)
.show(UINewOrganismMenu.this.stage);
}
}
});
continueButton.addListener(new ClickListener() {
@Override
public void enter (final InputEvent event, final float x, final float y, final int pointer, final Actor fromActorr) {
tooltipText.setText("Create the organism!");
}
});
/************ BACK */
final TextButton backButton = new TextButton("Back", this.skin);
tableFooter.add(backButton).pad(UI.CELL_PADDING);
tableFooter.row();
backButton.addListener(new ChangeListener() {
@Override
public void changed (final ChangeEvent event, final Actor actor) {
UINewOrganismMenu.this.soundSelect.play();
VictusLudusGame.engine.changeUI(new UIMainMenu());
}
});
backButton.addListener(new ClickListener() {
@Override
public void enter (final InputEvent event, final float x, final float y, final int pointer, final Actor fromActorr) {
tooltipText.setText("Returns to the main menu");
}
});
// add tooltip at end
tableFooter.add(tooltipText);
tableFooter.row();
}
/**
* Returns a hash code for this string as a long value
*
* @param string to hash
* @return a long hash code
*/
private static long longHashString (final String string) {
if (string.isEmpty()) {
return VictusLudusGame.rand.nextLong();
}
long hash = 0L;
for (int i = 0; i < string.length(); i++) {
hash += Math.pow((string.charAt(i) * 63), string.length() - i);
}
return hash;
}
}
| sabarjp/VictusLudus | victusludus/src/com/teamderpy/victusludus/gui/UINewOrganismMenu.java | Java | mit | 8,117 |
package com.freetymekiyan.algorithms.level.medium;
/**
* Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every
* character in T appears no less than k times.
* <p>
* Example 1:
* <p>
* Input:
* s = "aaabb", k = 3
* <p>
* Output:
* 3
* <p>
* The longest substring is "aaa", as 'a' is repeated 3 times.
* <p>
* Example 2:
* <p>
* Input:
* s = "ababbc", k = 2
* <p>
* Output:
* 5
* <p>
* The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
*/
public class LongestSubstringwithAtLeastKRepeatingCharacters {
/**
* Divide and conquer.
* For those characters in string which repeat less than k times, we try to divide the string into two parts:
* 1) left part: from the beginning to character's left
* 2) right part: from the character's right to the end
* The result is the larger one of these two parts.
*/
public int longestSubstring(String s, int k) {
return helper(s, 0, s.length(), k);
}
private int helper(String s, int start, int end, int k) {
if (end < start) {
return 0;
}
if (end - start < k) { // String length less than k
return 0;
}
int[] count = new int[26]; // Character count for current string
for (int i = start; i < end; i++) {
count[s.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (count[i] == 0) {
continue;
}
if (count[i] < k) {
for (int j = start; j < end; j++) {
if (s.charAt(j) == i + 'a') {
int left = helper(s, start, j, k);
int right = helper(s, j + 1, end, k);
return Math.max(left, right);
}
}
}
}
return end - start;
}
}
| bssrdf/LeetCode-Sol-Res | src/com/freetymekiyan/algorithms/level/medium/LongestSubstringwithAtLeastKRepeatingCharacters.java | Java | mit | 1,962 |
package com.sid.leetcode.problem.permutation;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import com.sid.leetcode.problem.permutation.Subsets;
public class SubsetsTest {
private Subsets problem;
@Before
public void setUp() throws Exception {
problem = new Subsets();
}
@Test
public void testSubsets() throws Exception {
assertEquals(
Arrays.asList(
Arrays.asList(),
Arrays.asList(1),
Arrays.asList(2),
Arrays.asList(1, 2)),
problem.subsets(new int[] { 1, 2 }));
assertEquals(
Arrays.asList(
Arrays.asList(),
Arrays.asList(1),
Arrays.asList(2),
Arrays.asList(1, 2),
Arrays.asList(3),
Arrays.asList(1, 3),
Arrays.asList(2, 3),
Arrays.asList(1, 2, 3)),
problem.subsets(new int[] { 1, 2, 3 }));
}
}
| rencht/LeetCode | src/test/java/com/sid/leetcode/problem/permutation/SubsetsTest.java | Java | mit | 924 |
package com.github.visgeek.utils.collections.test.testcase.ienumerable.ienumerable;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.github.visgeek.utils.collections.IEnumerable;
import com.github.visgeek.utils.testing.CollectionCreator;
public class Max01 {
@Rule
public final ExpectedException expectedException = ExpectedException.none();
@Test
public void empty() {
Integer[] source = new Integer[] {};
Integer expected = null;
IEnumerable<Integer> enumerable = () -> CollectionCreator.iterator(source);
Integer actual = enumerable.max();
Assert.assertEquals(expected, actual);
}
@Test
public void uncomparable() {
this.expectedException.expect(IllegalArgumentException.class);
Object[] source = new Object[] { new Object(), new Object(), new Object() };
IEnumerable<Object> enumerable = () -> CollectionCreator.iterator(source);
enumerable.max();
}
@Test
public void normal() {
Integer[] source = new Integer[] { 2, 1, null, 3 };
Integer expected = 3;
IEnumerable<Integer> enumerable = () -> CollectionCreator.iterator(source);
Integer actual = enumerable.max();
Assert.assertEquals(expected, actual);
}
}
| visGeek/JavaVisGeekCollections | src/src/test/java/com/github/visgeek/utils/collections/test/testcase/ienumerable/ienumerable/Max01.java | Java | mit | 1,279 |
package org.nmrml.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* A collection of CVParam and UserParam elements that can be referenced from
* elsewhere in this nmrML document by using the 'paramGroupRef' element in that location to
* reference the 'id' attribute value of this element.
*
* <p>Java class for ReferenceableParamGroupType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ReferenceableParamGroupType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cvParam" type="{http://nmrml.org/schema}CVParamType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="userParam" type="{http://nmrml.org/schema}UserParamType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}ID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ReferenceableParamGroupType", namespace = "http://nmrml.org/schema", propOrder = {
"cvParam",
"userParam"
})
public class ReferenceableParamGroupType {
@XmlElement(namespace = "http://nmrml.org/schema")
protected List<CVParamType> cvParam;
@XmlElement(namespace = "http://nmrml.org/schema")
protected List<UserParamType> userParam;
@XmlAttribute(name = "id", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
/**
* Gets the value of the cvParam property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cvParam property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCvParam().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CVParamType }
*
*
*/
public List<CVParamType> getCvParam() {
if (cvParam == null) {
cvParam = new ArrayList<CVParamType>();
}
return this.cvParam;
}
/**
* Gets the value of the userParam property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the userParam property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUserParam().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link UserParamType }
*
*
*/
public List<UserParamType> getUserParam() {
if (userParam == null) {
userParam = new ArrayList<UserParamType>();
}
return this.userParam;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
| nmrML/nmrML | tools/Parser_and_Converters/Java/src/main/java/org/nmrml/model/ReferenceableParamGroupType.java | Java | mit | 4,228 |
/*
* Abora-Gold
* Part of the Abora hypertext project: http://www.abora.org
* Copyright 2003, 2005 David G Jones
*
* Translated from Udanax-Gold source code: http://www.udanax.com
* Copyright 1979-1999 Udanax.com. All rights reserved
*/
package info.dgjones.abora.gold.rcmain;
import info.dgjones.abora.gold.gchooks.CloseExecutor;
import info.dgjones.abora.gold.java.AboraSocketSupport;
import info.dgjones.abora.gold.java.AboraSupport;
import info.dgjones.abora.gold.java.exception.SubclassResponsibilityException;
import info.dgjones.abora.gold.java.missing.smalltalk.Set;
import info.dgjones.abora.gold.rcmain.FDListener;
import info.dgjones.abora.gold.rcmain.ServerChunk;
import info.dgjones.abora.gold.rcmain.ServerLoop;
import info.dgjones.abora.gold.xcvr.Rcvr;
import info.dgjones.abora.gold.xpp.basic.Heaper;
/**
* This is the superclass for Listeners that use Berkeley UNIX sockets.
*/
public class FDListener extends ServerChunk {
protected int myFD;
/*
udanax-top.st:50826:
ServerChunk subclass: #FDListener
instanceVariableNames: 'myFD {int NOCOPY}'
classVariableNames: ''
poolDictionaries: ''
category: 'Xanadu-rcmain'!
*/
/*
udanax-top.st:50830:
FDListener comment:
'This is the superclass for Listeners that use Berkeley UNIX sockets.'!
*/
/*
udanax-top.st:50832:
(FDListener getOrMakeCxxClassDescription)
attributes: ((Set new) add: #DEFERRED; add: #EQ; yourself)!
*/
/*
udanax-top.st:50878:
FDListener class
instanceVariableNames: ''!
*/
/*
udanax-top.st:50881:
(FDListener getOrMakeCxxClassDescription)
attributes: ((Set new) add: #DEFERRED; add: #EQ; yourself)!
*/
public static void initializeClassAttributes() {
AboraSupport.findAboraClass(FDListener.class).setAttributes( new Set().add("DEFERRED").add("EQ"));
/*
Generated during transformation: AddMethod
*/
}
public int descriptor() {
return myFD;
/*
udanax-top.st:50837:FDListener methodsFor: 'accessing'!
{int} descriptor
^myFD.!
*/
}
/**
* Attempt to execute another chunk. Return whether there is more to be done.
*/
public boolean execute() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:50841:FDListener methodsFor: 'accessing'!
{BooleanVar} execute
"Attempt to execute another chunk. Return whether there is more to be done."
self subclassResponsibility.!
*/
}
/**
* There should be data waiting on this FD. Return TRUE if I am still in a reasonable state
* to continue, FALSE if not (in which case the Listener will be destroyed by the caller)
*/
public boolean shouldBeReady() {
throw new SubclassResponsibilityException();
/*
udanax-top.st:50846:FDListener methodsFor: 'accessing'!
{BooleanVar} shouldBeReady
"There should be data waiting on this FD. Return TRUE if I am still in a reasonable state to continue, FALSE if not (in which case the Listener will be destroyed by the caller)"
self subclassResponsibility.!
*/
}
public FDListener() {
super();
AboraSupport.smalltalkOnly();
{
myFD = 0;
}
AboraSupport.translateOnly();
{
/* myFD = (int) Int32Zero; */
}
/*
udanax-top.st:50853:FDListener methodsFor: 'creation'!
create
super create.
[myFD _ Int32Zero] smalltalkOnly.
'myFD = (int) Int32Zero;' translateOnly.!
*/
}
public void destruct() {
AboraSupport.smalltalkOnly();
{
AboraSocketSupport.close(myFD);
}
AboraSupport.translateOnly();
{
/* close (myFD); */
}
super.destruct();
/*
udanax-top.st:50859:FDListener methodsFor: 'creation'!
{void} destruct
[myFD close] smalltalkOnly.
'close (myFD);' translateOnly.
super destruct.!
*/
}
public void registerFor(int anFD) {
myFD = anFD;
CloseExecutor.registerHolder(this, anFD);
ServerLoop.introduceChunk(this);
/*
udanax-top.st:50865:FDListener methodsFor: 'creation'!
{void} registerFor: anFD {int}
myFD _ anFD.
CloseExecutor registerHolder: self with: anFD.
ServerLoop introduceChunk: self!
*/
}
public int actualHashForEqual() {
return asOop();
/*
udanax-top.st:50873:FDListener methodsFor: 'generated:'!
actualHashForEqual ^self asOop!
*/
}
public boolean isEqual(Heaper other) {
return this == other;
/*
udanax-top.st:50875:FDListener methodsFor: 'generated:'!
isEqual: other ^self == other!
*/
}
public static void initTimeNonInherited() {
/* Removed translateOnly */
/*
udanax-top.st:50886:FDListener class methodsFor: 'smalltalk: init'!
initTimeNonInherited
'
#ifdef unix
signal(SIGPIPE, SIG_IGN);
#endif
' translateOnly!
*/
}
/*
udanax-top.st:50896:FDListener class methodsFor: 'exceptions: exceptions'!
problems.SOCKET.U.ERRS
^self signals: #(SOCKET.U.RECV.U.ERROR SOCKET.U.SEND.U.ERROR)!
*/
public FDListener(Rcvr receiver) {
super(receiver);
/*
Generated during transformation
*/
}
}
| jonesd/udanax-gold2java | abora-gold/src/generated-sources/translator/info/dgjones/abora/gold/rcmain/FDListener.java | Java | mit | 4,629 |
package mobi.tarantino.stub.auto.feature.notifications;
import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity;
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState;
import com.hannesdorfmann.mosby.mvp.viewstate.lce.data.ParcelableDataLceViewState;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import mobi.tarantino.stub.auto.Consts;
import mobi.tarantino.stub.auto.IntentStarter;
import mobi.tarantino.stub.auto.MobiApplication;
import mobi.tarantino.stub.auto.R;
import mobi.tarantino.stub.auto.decoration.ToolbarColorizer;
import mobi.tarantino.stub.auto.decoration.ToolbarDecorator;
import mobi.tarantino.stub.auto.decoration.WhiteToolbarColorizer;
import mobi.tarantino.stub.auto.feature.dashboard.DashBoardActivity;
import mobi.tarantino.stub.auto.feature.dashboard.services.notificationCard.NotificationDTO;
import mobi.tarantino.stub.auto.helper.ResourcesHelper;
import mobi.tarantino.stub.auto.model.database.dbo.ArticleDBO;
public class NotificationsActivity extends MvpViewStateActivity<NotificationsView,
NotificationsPresenter>
implements ToolbarDecorator, NotificationsView {
@BindView(R.id.toolbar_shadow)
View toolbarShadow;
@BindView(R.id.events_container)
ViewGroup eventsContainer;
@BindView(R.id.fines_container)
ViewGroup finesContainer;
@BindView(R.id.laws_container)
ViewGroup lawsContainer;
@BindView(R.id.content)
ViewGroup content;
@BindView(R.id.progress)
ProgressBar progressBar;
@BindView(R.id.error_container)
ViewGroup errorContainer;
@BindView(R.id.retry_button)
Button retryButton;
@Inject
ResourcesHelper resourcesHelper;
@Inject
IntentStarter intentStarter;
private Unbinder unbinder;
private Toolbar toolbar;
private NotificationDTO data;
private NotificationsComponent component;
private View.OnClickListener onFineClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
openFines();
}
};
private View.OnClickListener onLawClickListener = new ArticleClickListener(ArticleDBO.TYPE_LAW);
private View.OnClickListener onEventClickListener = new ArticleClickListener(ArticleDBO
.TYPE_PARTNER_ACTIONS);
public static Intent createIntent(Context context, NotificationDTO notificationDTO) {
Intent intent = new Intent(context, NotificationsActivity.class);
intent.putExtra(Consts.Key.NOTIFICATION_DTO, notificationDTO);
return intent;
}
private void showArticle(ArticleDBO article, String type) {
intentStarter.showArticle(this, type, article);
}
private void openFines() {
Intent intent = new Intent(this, DashBoardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Consts.Notification.CATEGORY_NEW_FINE);
startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
initComponent();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
unbinder = ButterKnife.bind(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void initComponent() {
component = MobiApplication.get(this).getComponentContainer()
.createNotificationsComponent();
component.inject(this);
}
private void initUI() {
initEvents();
initFines();
initLaws();
}
private void initLaws() {
lawsContainer.removeAllViews();
for (ArticleDBO article : data.getAllLaws()) {
View item = getView(article, R.drawable.ic_traffic_laws_grey_36);
item.setOnClickListener(onLawClickListener);
lawsContainer.addView(item);
}
}
private void initEvents() {
eventsContainer.removeAllViews();
for (ArticleDBO article : data.getAllEvents()) {
if (article != null) {
View item = getView(article, R.drawable.ic_event);
item.setOnClickListener(onEventClickListener);
eventsContainer.addView(item);
}
}
}
@NonNull
private View getView(ArticleDBO article, int icon) {
View item = getLayoutInflater().inflate(R.layout.notification_item_layout, lawsContainer,
false);
((ImageView) item.findViewById(R.id.notification_imageView))
.setImageDrawable(resourcesHelper.getVectorDrawable(icon));
((TextView) item.findViewById(R.id.title_textView)).setText(article.getTitle());
item.setTag(article);
return item;
}
private void initFines() {
finesContainer.removeAllViews();
int finesCount = data.getFinesCount();
if (finesCount > 0) {
View item = getLayoutInflater().inflate(R.layout.notification_item_layout,
finesContainer, false);
((ImageView) item.findViewById(R.id.notification_imageView))
.setImageDrawable(resourcesHelper.getVectorDrawable(R.drawable.ic_new_fine));
((TextView) item.findViewById(R.id.title_textView)).setText(
getString(R.string.new_fine_notification_title_pattern,
getResources().getQuantityString(R.plurals.finesCount, finesCount,
finesCount)));
item.setOnClickListener(onFineClickListener);
finesContainer.addView(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
onBackPressed();
break;
}
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
initToolbar();
return super.onPrepareOptionsMenu(menu);
}
private void initToolbar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbarShadow.setVisibility(View.GONE);
}
applyToolbarColorizer(new WhiteToolbarColorizer(this));
}
@Override
public void applyToolbarColorizer(ToolbarColorizer toolbarColorizer) {
toolbar.setBackgroundColor(toolbarColorizer.getBackgroundColor());
toolbar.setTitleTextColor(toolbarColorizer.getTitleColor());
toolbar.setSubtitleTextColor(toolbarColorizer.getSubTitleColor());
PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(toolbarColorizer
.getIconColor(), PorterDuff.Mode.SRC_ATOP);
Drawable navigationIcon = toolbar.getNavigationIcon();
if (navigationIcon != null) {
navigationIcon.setColorFilter(colorFilter);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(toolbarColorizer.getStatusBarColor());
}
}
@Override
protected void onDestroy() {
unbinder.unbind();
if (isFinishing()) {
MobiApplication.get(this).getComponentContainer().releaseNotificationsComponent();
}
super.onDestroy();
}
@Override
public void finish() {
MobiApplication.get(this).getComponentContainer().releaseNotificationsComponent();
super.finish();
}
@NonNull
@Override
public NotificationsPresenter createPresenter() {
return component.notificationsPresenter();
}
@Override
public void showLoading(boolean pullToRefresh) {
getViewState().setStateShowLoading(pullToRefresh);
progressBar.setVisibility(View.VISIBLE);
content.setVisibility(View.GONE);
errorContainer.setVisibility(View.GONE);
}
@Override
public void showContent() {
getViewState().setStateShowContent(data);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
errorContainer.setVisibility(View.GONE);
initUI();
}
@Override
public void showError(Throwable e, boolean pullToRefresh) {
getViewState().setStateShowError(e, pullToRefresh);
progressBar.setVisibility(View.GONE);
content.setVisibility(View.GONE);
errorContainer.setVisibility(View.VISIBLE);
}
@Override
public void setData(NotificationDTO data) {
this.data = data;
}
@Override
public void loadData(boolean pullToRefresh) {
presenter.load(false);
}
@OnClick(R.id.retry_button)
public void onRetryButtonClick() {
presenter.load(true);
}
@Override
public ViewState<NotificationsView> createViewState() {
return new ParcelableDataLceViewState<NotificationDTO, NotificationsView>();
}
@Override
public void onNewViewStateInstance() {
loadData(false);
}
@Override
public ParcelableDataLceViewState<NotificationDTO, NotificationsView> getViewState() {
return (ParcelableDataLceViewState<NotificationDTO, NotificationsView>) super
.getViewState();
}
class ArticleClickListener implements View.OnClickListener {
private String typeLaw;
ArticleClickListener(String typeLaw) {
this.typeLaw = typeLaw;
}
@Override
public void onClick(View v) {
ArticleDBO article = (ArticleDBO) v.getTag();
showArticle(article, typeLaw);
}
}
}
| kolipass/tarantino-stub | app/src/main/java/mobi/tarantino/stub/auto/feature/notifications/NotificationsActivity.java | Java | mit | 10,757 |
package cards;
import server.Card;
import java.util.Set;
public class Gold extends Card {
@Override
public String name() {
return "Gold";
}
@Override
public Set<Type> types() {
return types(Type.TREASURE);
}
@Override
public int cost() {
return 6;
}
@Override
public String[] description() {
return new String[]{"3$"};
}
@Override
public int treasureValue() {
return 3;
}
@Override
public int startingSupply(int numPlayers) {
return 30;
}
}
| chadsprice/dominion-bot-arena | src/main/java/cards/Gold.java | Java | mit | 481 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// 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: 2013.07.27 at 08:11:57 PM EEST
//
package eu.datex2.schema._1_0._1_0;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* A location defined by reference to a predefined location.
*
* <p>Java class for LocationByReference complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LocationByReference">
* <complexContent>
* <extension base="{http://datex2.eu/schema/1_0/1_0}Location">
* <sequence>
* <element name="predefinedLocationReference" type="{http://datex2.eu/schema/1_0/1_0}Reference"/>
* <element name="locationByReferenceExtension" type="{http://datex2.eu/schema/1_0/1_0}ExtensionType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LocationByReference", propOrder = {
"predefinedLocationReference",
"locationByReferenceExtension"
})
public class LocationByReference
extends Location
{
@XmlElement(required = true)
protected String predefinedLocationReference;
protected ExtensionType locationByReferenceExtension;
/**
* Gets the value of the predefinedLocationReference property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPredefinedLocationReference() {
return predefinedLocationReference;
}
/**
* Sets the value of the predefinedLocationReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPredefinedLocationReference(String value) {
this.predefinedLocationReference = value;
}
/**
* Gets the value of the locationByReferenceExtension property.
*
* @return
* possible object is
* {@link ExtensionType }
*
*/
public ExtensionType getLocationByReferenceExtension() {
return locationByReferenceExtension;
}
/**
* Sets the value of the locationByReferenceExtension property.
*
* @param value
* allowed object is
* {@link ExtensionType }
*
*/
public void setLocationByReferenceExtension(ExtensionType value) {
this.locationByReferenceExtension = value;
}
}
| ITSFactory/itsfactory.siri.bindings.v13 | src/main/java/eu/datex2/schema/_1_0/_1_0/LocationByReference.java | Java | mit | 2,888 |
/**
* Copyright (c) 2013-2014 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released 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 oculus.aperture.icons.coded;
import java.awt.Font;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Singleton;
/**
* @author djonker
*
*/
@Singleton
public class DefaultFontProvider implements FontProvider {
private final Font boldFont;
private final Font normalFont;
final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Constructs a default font provider.
*/
public DefaultFontProvider() {
boldFont = loadFont("/oculus/aperture/common/fonts/DroidSans-Bold.ttf",
new Font("SansSerif", Font.BOLD, 12));
normalFont = loadFont("/oculus/aperture/common/fonts/DroidSans.ttf",
new Font("SansSerif", Font.PLAIN, 12));
}
/* (non-Javadoc)
* @see oculus.aperture.icons.FontProvider#getFont(int, int)
*/
@Override
public Font getFont(int fontStyle, float size) {
if (fontStyle == Font.BOLD) {
return boldFont.deriveFont(size);
} else {
return normalFont.deriveFont(size);
}
}
/**
* Loads a font from a stream
*/
private Font loadFont(String path, Font fallbackFont) {
final InputStream is = getClass().getResourceAsStream(path);
Font font = null;
if (is != null) {
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch (Exception e) {
logger.warn("Failed to load default font "+ path, e);
}
try {
is.close();
} catch (IOException e) {
}
}
return font != null? font : fallbackFont;
}
}
| unchartedsoftware/aperturejs | aperture-icons/src/main/java/oculus/aperture/icons/coded/DefaultFontProvider.java | Java | mit | 2,709 |
/*
* MIT License
* <p>
* Copyright (c) 2017 David Krebs
* <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.dkarv.jdcallgraph.util.config;
import com.dkarv.jdcallgraph.util.options.Target;
/**
* Some config options that are computed with others.
*/
public class ComputedConfig {
public static boolean dataDependence() {
for (Target t : Config.getInst().writeTo()) {
if (t.isDataDependency()) {
return true;
}
}
return false;
}
public static boolean callDependence() {
for (Target t : Config.getInst().writeTo()) {
if (!t.isDataDependency()) {
return true;
}
}
return false;
}
public static boolean lineNeeded() {
return Config.getInst().format().contains("{line}");
}
}
| dkarv/jdcallgraph | jdcallgraph/src/main/java/com/dkarv/jdcallgraph/util/config/ComputedConfig.java | Java | mit | 1,810 |
package li.seiji.minichess;
import com.sun.media.sound.InvalidFormatException;
import li.seiji.helpers.MoveHelper;
import li.seiji.minichess.board.Board;
import li.seiji.minichess.board.GameState;
import li.seiji.minichess.board.State;
import li.seiji.minichess.move.Move;
import org.junit.Test;
import javax.swing.plaf.synth.SynthTabbedPaneUI;
import java.io.IOException;
import java.io.StringReader;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class StateTest {
public static final String promotionTestField =
"....." + System.lineSeparator() +
"P...." + System.lineSeparator() +
"....." + System.lineSeparator() +
"....." + System.lineSeparator() +
"...p." + System.lineSeparator() +
"....." + System.lineSeparator();
public static final String captureTestField =
"....." + System.lineSeparator() +
"..k.." + System.lineSeparator() +
"...p." + System.lineSeparator() +
"..P.." + System.lineSeparator() +
"....." + System.lineSeparator() +
"....." + System.lineSeparator();
public static final String gameStateRestoreTestField =
"kqbnr" + System.lineSeparator() +
"p..pp" + System.lineSeparator() +
".Pp.." + System.lineSeparator() +
"..P.." + System.lineSeparator() +
".P.PP" + System.lineSeparator() +
"RNBQK";
@Test
public void testExecutePhysicallyInvalidMove() {
Board board = new Board();
board.state.initialize();
for(int i = 0; i < 5; ++i) {
Move move = MoveHelper.generateRandomPhysicallyInvalidMove(board.state);
try {
board.move(move);
fail("Expected InvalidMoveException");
} catch (InvalidMoveException e) {}
}
}
@Test
public void testMoveUnmove_Promotion() throws IOException, InvalidMoveException {
State state = new State();
state.read(new StringReader(promotionTestField));
Move move0 = new Move("a5-a6");
Move move1 = new Move("d2-d1");
assertEquals('P', new Square("a5").getFieldValue(state));
assertEquals('.', new Square("a6").getFieldValue(state));
assertEquals('p', new Square("d2").getFieldValue(state));
assertEquals('.', new Square("d1").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
state.move(move0);
assertEquals('.', new Square("a5").getFieldValue(state));
assertEquals('Q', new Square("a6").getFieldValue(state));
assertEquals('p', new Square("d2").getFieldValue(state));
assertEquals('.', new Square("d1").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.BLACK, state.turn);
state.move(move1);
assertEquals('.', new Square("a5").getFieldValue(state));
assertEquals('Q', new Square("a6").getFieldValue(state));
assertEquals('.', new Square("d2").getFieldValue(state));
assertEquals('q', new Square("d1").getFieldValue(state));
assertEquals(1, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
state.unmove(move1);
assertEquals('.', new Square("a5").getFieldValue(state));
assertEquals('Q', new Square("a6").getFieldValue(state));
assertEquals('p', new Square("d2").getFieldValue(state));
assertEquals('.', new Square("d1").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.BLACK, state.turn);
state.unmove(move0);
assertEquals('P', new Square("a5").getFieldValue(state));
assertEquals('.', new Square("a6").getFieldValue(state));
assertEquals('p', new Square("d2").getFieldValue(state));
assertEquals('.', new Square("d1").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
}
@Test
public void testUnmoveCapturing() throws IOException, InvalidMoveException {
State state = new State();
state.read(new StringReader(captureTestField));
Move captureBlack = new Move("c3-d4");
Move captureWhite = new Move("c5-d4");
//do
assertEquals('P', new Square("c3").getFieldValue(state));
assertEquals('p', new Square("d4").getFieldValue(state));
assertEquals('k', new Square("c5").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
state.move(captureBlack);
assertEquals('.', new Square("c3").getFieldValue(state));
assertEquals('P', new Square("d4").getFieldValue(state));
assertEquals('k', new Square("c5").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.BLACK, state.turn);
state.move(captureWhite);
assertEquals('.', new Square("c3").getFieldValue(state));
assertEquals('k', new Square("d4").getFieldValue(state));
assertEquals('.', new Square("c5").getFieldValue(state));
assertEquals(1, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
//undo
state.unmove(captureWhite);
assertEquals('.', new Square("c3").getFieldValue(state));
assertEquals('P', new Square("d4").getFieldValue(state));
assertEquals('k', new Square("c5").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.BLACK, state.turn);
state.unmove(captureBlack);
assertEquals('P', new Square("c3").getFieldValue(state));
assertEquals('p', new Square("d4").getFieldValue(state));
assertEquals('k', new Square("c5").getFieldValue(state));
assertEquals(0, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
}
@Test
public void testUnmoveGameStateRestore() throws IOException, InvalidMoveException {
State state = new State();
state.read(new StringReader(gameStateRestoreTestField));
state.turn = Player.BLACK;
Move move0 = new Move("a5-b4");
Move move1 = new Move("a1-a6");
assertEquals('p', new Square("a5").getFieldValue(state));
assertEquals('P', new Square("b4").getFieldValue(state));
assertEquals('R', new Square("a1").getFieldValue(state));
assertEquals('k', new Square("a6").getFieldValue(state));
assertEquals(GameState.ONGOING, state.gameState);
assertEquals(0, state.turnCounter);
assertEquals(Player.BLACK, state.turn);
state.move(move0);
assertEquals('.', new Square("a5").getFieldValue(state));
assertEquals('p', new Square("b4").getFieldValue(state));
assertEquals('R', new Square("a1").getFieldValue(state));
assertEquals('k', new Square("a6").getFieldValue(state));
assertEquals(GameState.ONGOING, state.gameState);
assertEquals(1, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
state.move(move1);
assertEquals('.', new Square("a5").getFieldValue(state));
assertEquals('p', new Square("b4").getFieldValue(state));
assertEquals('.', new Square("a1").getFieldValue(state));
assertEquals('R', new Square("a6").getFieldValue(state));
assertEquals(GameState.WIN_WHITE, state.gameState);
assertEquals(1, state.turnCounter);
assertEquals(Player.BLACK, state.turn);
//undo
state.unmove(move1);
assertEquals('.', new Square("a5").getFieldValue(state));
assertEquals('p', new Square("b4").getFieldValue(state));
assertEquals('R', new Square("a1").getFieldValue(state));
assertEquals('k', new Square("a6").getFieldValue(state));
assertEquals(GameState.ONGOING, state.gameState);
assertEquals(1, state.turnCounter);
assertEquals(Player.WHITE, state.turn);
state.unmove(move0);
assertEquals('p', new Square("a5").getFieldValue(state));
assertEquals('P', new Square("b4").getFieldValue(state));
assertEquals('R', new Square("a1").getFieldValue(state));
assertEquals('k', new Square("a6").getFieldValue(state));
assertEquals(GameState.ONGOING, state.gameState);
assertEquals(0, state.turnCounter);
assertEquals(Player.BLACK, state.turn);
}
@Test
public void testTieDetection() throws InvalidFormatException, InvalidMoveException {
Board board = new Board();
Move[] moves = {
new Move("b1-c3"),
new Move("d6-e4"),
new Move("c3-b1"),
new Move("e4-d6")
};
int turnCnt = 0;
while(board.state.gameState == GameState.ONGOING) {
board.move(moves[turnCnt % moves.length]);
turnCnt++;
}
assertEquals(80, turnCnt);
}
}
| seijikun/MiniChess | test/li/seiji/minichess/StateTest.java | Java | mit | 9,091 |
package Dlib.Models;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "tblcmsmoduleoptionvalue")
@IdClass(CmsModuleTypeOptionValuePK.class)
public class CmsModuleTypeOptionValue implements Serializable{
@javax.persistence.Id
private int moduleId;
@javax.persistence.Id
private int optionId;
private String value;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "moduleId", insertable=false, updatable=false, nullable = false)
private CmsModule module;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "optionId", insertable=false, updatable=false, nullable = false)
private CmsModuleTypeOption option;
@Transient
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "moduleId", unique = true, nullable = false)
public int getModuleId() {
return moduleId;
}
public void setModuleId(int value) {
moduleId = value;
}
@Transient
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "optionId", unique = true, nullable = false)
public int getOptionId() {
return optionId;
}
public void setOptionId(int value) {
optionId = value;
}
@Column(name="value", nullable = false)
public String getValue() {
return value;
}
public void setValue(String _value) {
value = _value;
}
public CmsModule getModule() {
return module;
}
public void setModule(CmsModule value) {
this.module=value;
}
public CmsModuleTypeOption getModuleTypeOption() {
return option;
}
public void setModuleTypeOption(CmsModuleTypeOption value) {
this.option=value;
}
}
| hamidrh/dLib | src/Dlib/Models/CmsModuleTypeOptionValue.java | Java | mit | 1,740 |
/* Source:
* Google Inc. (2014b). Google Play Game Services: Android Samples: TypeANumber [Software].
* Available from https://github.com/playgameservices/android-basic-samples
*/
package poorskeletongames.alibi_project;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
public class TutorialFragment extends Fragment implements OnClickListener {
public interface Listener {
public void onTutorialScreenDismissed();
}
Listener mListener = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tutorial, container, false);
v.findViewById(R.id.return_menu).setOnClickListener(this);
return v;
}
public void setListener(Listener l) {
mListener = l;
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onClick(View view){
mListener.onTutorialScreenDismissed();
}
}
| sofiegrant/Alibi | Alibi2/app/src/main/java/poorskeletongames/alibi_project/TutorialFragment.java | Java | mit | 1,196 |
package connect.ui.activity.wallet.contract;
import connect.ui.base.BasePresenter;
import connect.ui.base.BaseView;
import protos.Connect;
/**
* Created by Administrator on 2017/4/18 0018.
*/
public interface PacketDetailContract {
interface View extends BaseView<PacketDetailContract.Presenter> {
void updataView(int status,long openMoney,long bestAmount,Connect.RedPackageInfo redPackageInfo);
void updataSendView(Connect.UserInfo sendUserInfo);
}
interface Presenter extends BasePresenter {
void requestRedDetail(String hashId,int type);
}
}
| connectim/Android | app/src/main/java/connect/ui/activity/wallet/contract/PacketDetailContract.java | Java | mit | 594 |
package com.ts.timeseries.matlab;
import com.google.common.collect.ImmutableList;
import com.ts.timeseries.unit.LangAssert;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class PrimitivesTest {
@Test
public void testConstructor() throws Exception {
LangAssert.assertUtilityClass(Primitives.class);
}
@Test
public void testConvertDouble() throws Exception {
List<Double> list = ImmutableList.of(2.0, 3.0);
double[] x = Primitives.convertDouble(list);
Assert.assertArrayEquals(x, new double[]{2.0,3.0},1e-10);
}
@Test
public void testConvertLong() throws Exception {
List<Long> list = ImmutableList.of(2L, 3L);
long[] x = Primitives.convertLong(list);
Assert.assertArrayEquals(x, new long[]{2L,3L});
}
}
| tschm/ts-timeseries | src/test/java/com/ts/timeseries/matlab/PrimitivesTest.java | Java | mit | 831 |
package fr.adrienbrault.idea.symfony2plugin.tests.translation;
import com.jetbrains.php.lang.PhpFileType;
import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase;
import java.io.File;
/**
* @author Daniel Espendiller <[email protected]>
* @see fr.adrienbrault.idea.symfony2plugin.translation.ValidatorTranslationGotoCompletionRegistrar
*/
public class ValidatorTranslationGotoCompletionRegistrarTest extends SymfonyLightCodeInsightFixtureTestCase {
public void setUp() throws Exception {
super.setUp();
myFixture.copyFileToProject("classes.php");
myFixture.copyFileToProject("validators.de.yml", "Resources/translations/validators.de.yml");
}
protected String getTestDataPath() {
return new File(this.getClass().getResource("fixtures").getFile()).getAbsolutePath();
}
public void testThatMessageValueForConstraintProvideValidatorTranslations() {
assertCompletionContains(PhpFileType.INSTANCE, "<?php\n" +
"$f = new MyConstraintMessage(['message' => '<caret>'])",
"foo_yaml.symfony.great"
);
assertNavigationMatch(PhpFileType.INSTANCE, "<?php\n" +
"$f = new MyConstraintMessage(['message' => 'foo_yaml.symfony<caret>.great'])"
);
}
public void testThatExecutionContextProvidesTranslation() {
assertCompletionContains(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $f \\Symfony\\Component\\Validator\\Context\\ExecutionContextInterface */\n" +
"$f->addViolation('<caret>');",
"foo_yaml.symfony.great"
);
assertNavigationMatch(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $f \\Symfony\\Component\\Validator\\Context\\ExecutionContextInterface */\n" +
"$f->addViolation('foo_yaml.sym<caret>fony.great');"
);
}
public void testThatConstraintViolationBuilderProvidesSetTranslationDomain() {
assertCompletionContains(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $f \\Symfony\\Component\\Validator\\Violation\\ConstraintViolationBuilderInterface */\n" +
"$f->setTranslationDomain('<caret>');",
"validators"
);
assertNavigationMatch(PhpFileType.INSTANCE, "<?php\n" +
"/** @var $f \\Symfony\\Component\\Validator\\Violation\\ConstraintViolationBuilderInterface */\n" +
"$f->setTranslationDomain('vali<caret>dators');"
);
}
}
| gencer/idea-php-symfony2-plugin | tests/fr/adrienbrault/idea/symfony2plugin/tests/translation/ValidatorTranslationGotoCompletionRegistrarTest.java | Java | mit | 2,504 |
package org.lodder.subtools.multisubdownloader;
import java.util.Calendar;
import org.apache.commons.lang3.time.DateUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.lodder.subtools.multisubdownloader.settings.model.UpdateCheckPeriod;
import org.lodder.subtools.sublibrary.ConfigProperties;
import org.lodder.subtools.sublibrary.Manager;
import org.lodder.subtools.sublibrary.ManagerException;
import org.lodder.subtools.sublibrary.ManagerSetupException;
import org.lodder.subtools.sublibrary.util.http.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UpdateAvailableDropbox {
private final String url;
private String updatedUrl;
private Manager manager;
private static final Logger LOGGER = LoggerFactory.getLogger(UpdateAvailableDropbox.class);
private final static String programName = ConfigProperties.getInstance().getProperty(
"updateProgramName");
private final static String extension = ConfigProperties.getInstance().getProperty(
"updateProgramExtension");
public UpdateAvailableDropbox(Manager manager) {
url = ConfigProperties.getInstance().getProperty("updateUrlDropbox");
this.manager = manager;
updatedUrl = "";
}
public boolean checkProgram(UpdateCheckPeriod updateCheckPeriod) {
try {
Calendar date = Calendar.getInstance();
switch (updateCheckPeriod) {
case DAILY:
return check(programName, extension);
case MANUAL:
break;
case MONTHLY:
date.set(Calendar.DAY_OF_MONTH, 1);
if (DateUtils.isSameDay(date, Calendar.getInstance())) {
LOGGER.info(Messages.getString("UpdateAvailableDropbox.CheckingForUpdate"));
return check(programName, extension);
}
break;
case WEEKLY:
date.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
if (DateUtils.isSameDay(date, Calendar.getInstance())) {
LOGGER.info(Messages.getString("UpdateAvailableDropbox.CheckingForUpdate"));
return check(programName, extension);
}
break;
default:
break;
}
} catch (Exception e) {
LOGGER.error("checkProgram", e);
}
return false;
}
public boolean checkMapping() {
try {
return check("Mapping", "xml");
} catch (Exception e) {
LOGGER.error("checkMapping", e);
}
return false;
}
public String getUpdateUrl() {
return updatedUrl;
}
private boolean check(String baseName, String extension) {
try {
String newFoundVersion =
ConfigProperties.getInstance().getProperty("version").replace("-SNAPSHOT", "");
String source = manager.getContent(url, null, false);
Document sourceDoc = Jsoup.parse(source);
Elements results = sourceDoc.getElementsByClass("filename-link");
for (Element result : results) {
String href = result.attr("href");
if (href.contains(baseName)) {
String foundVersion =
href.substring(href.lastIndexOf("/") + 1, href.length()).replace(baseName, "")
.replace("-v", "").replace("-r", "").replace("." + extension, "").trim()
.replace("?dl=0", "");
int compare =
compareVersions(
ConfigProperties.getInstance().getProperty("version").replace("-SNAPSHOT", ""),
foundVersion);
if (compare < 0) {
if (compareVersions(newFoundVersion, foundVersion) <= 0) {
newFoundVersion = foundVersion;
updatedUrl = href;
}
}
}
}
if (HttpClient.isUrl(updatedUrl)) {
return true;
}
} catch (ManagerSetupException | ManagerException e) {
LOGGER.error("", e);
}
return false;
}
private int compareVersions(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
return Integer.signum(vals1.length - vals2.length);
}
}
| phdelodder/SubTools | MultiSubDownloader/src/main/java/org/lodder/subtools/multisubdownloader/UpdateAvailableDropbox.java | Java | mit | 4,397 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
package fixtures.bodyfile;
import com.microsoft.rest.ServiceCall;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceResponse;
import fixtures.bodyfile.models.ErrorException;
import java.io.InputStream;
import java.io.IOException;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in Files.
*/
public interface Files {
/**
* Get file.
*
* @throws ErrorException exception thrown from REST call
* @throws IOException exception thrown from serialization/deserialization
* @return the InputStream object if successful.
*/
InputStream getFile() throws ErrorException, IOException;
/**
* Get file.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @return the {@link ServiceCall} object
*/
ServiceCall<InputStream> getFileAsync(final ServiceCallback<InputStream> serviceCallback);
/**
* Get file.
*
* @return the observable to the InputStream object
*/
Observable<InputStream> getFileAsync();
/**
* Get file.
*
* @return the observable to the InputStream object
*/
Observable<ServiceResponse<InputStream>> getFileWithServiceResponseAsync();
/**
* Get a large file.
*
* @throws ErrorException exception thrown from REST call
* @throws IOException exception thrown from serialization/deserialization
* @return the InputStream object if successful.
*/
InputStream getFileLarge() throws ErrorException, IOException;
/**
* Get a large file.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @return the {@link ServiceCall} object
*/
ServiceCall<InputStream> getFileLargeAsync(final ServiceCallback<InputStream> serviceCallback);
/**
* Get a large file.
*
* @return the observable to the InputStream object
*/
Observable<InputStream> getFileLargeAsync();
/**
* Get a large file.
*
* @return the observable to the InputStream object
*/
Observable<ServiceResponse<InputStream>> getFileLargeWithServiceResponseAsync();
/**
* Get empty file.
*
* @throws ErrorException exception thrown from REST call
* @throws IOException exception thrown from serialization/deserialization
* @return the InputStream object if successful.
*/
InputStream getEmptyFile() throws ErrorException, IOException;
/**
* Get empty file.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @return the {@link ServiceCall} object
*/
ServiceCall<InputStream> getEmptyFileAsync(final ServiceCallback<InputStream> serviceCallback);
/**
* Get empty file.
*
* @return the observable to the InputStream object
*/
Observable<InputStream> getEmptyFileAsync();
/**
* Get empty file.
*
* @return the observable to the InputStream object
*/
Observable<ServiceResponse<InputStream>> getEmptyFileWithServiceResponseAsync();
}
| tbombach/autorest | src/generator/AutoRest.Java.Tests/src/main/java/fixtures/bodyfile/Files.java | Java | mit | 3,507 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 Marc de Verdelhan & respective authors (see AUTHORS)
*
* 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 eu.verdelhan.ta4j.indicators.simple;
import eu.verdelhan.ta4j.Decimal;
import eu.verdelhan.ta4j.TimeSeries;
import eu.verdelhan.ta4j.indicators.CachedIndicator;
/**
* Open price indicator.
* <p>
*/
public class OpenPriceIndicator extends CachedIndicator<Decimal> {
private TimeSeries series;
public OpenPriceIndicator(TimeSeries series) {
super(series);
this.series = series;
}
@Override
protected Decimal calculate(int index) {
return series.getTick(index).getOpenPrice();
}
} | troestergmbh/ta4j | ta4j/src/main/java/eu/verdelhan/ta4j/indicators/simple/OpenPriceIndicator.java | Java | mit | 1,729 |
/*
* This file is part of Openrouteservice.
*
* Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library;
* if not, see <https://www.gnu.org/licenses/>.
*/
package org.heigit.ors.api.responses.routing.json;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.heigit.ors.routing.ExtraSummaryItem;
import org.heigit.ors.routing.RouteSegmentItem;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
@ApiModel(value = "JSONExtra", description = "An object representing one of the extra info items requested")
public class JSONExtra {
private List<List<Long>> values;
private List<JSONExtraSummary> summary;
public JSONExtra(List<RouteSegmentItem> segments, List<ExtraSummaryItem> summaryItems) {
values = new ArrayList<>();
for(RouteSegmentItem item : segments) {
List<Long> segment = new ArrayList<>();
segment.add(Long.valueOf(item.getFrom()));
segment.add(Long.valueOf(item.getTo()));
segment.add(item.getValue());
values.add(segment);
}
summary = new ArrayList<>();
for(ExtraSummaryItem item : summaryItems) {
summary.add(new JSONExtraSummary(item.getValue(), item.getDistance(), item.getAmount()));
}
}
@ApiModelProperty(value = "A list of values representing a section of the route. The individual values are: \n" +
"Value 1: Indice of the staring point of the geometry for this section,\n" +
"Value 2: Indice of the end point of the geoemetry for this sections,\n" +
"Value 3: [Value](https://GIScience.github.io/openrouteservice/documentation/extra-info/Extra-Info.html) assigned to this section.",
example = "[[0,3,26],[3,10,12]]")
@JsonProperty("values")
private List<List<Long>> getValues() {
return values;
}
@ApiModelProperty(value = "List representing the summary of the extra info items.")
@JsonProperty("summary")
private List<JSONExtraSummary> getSummary() {
return summary;
}
}
| GIScience/openrouteservice-core | openrouteservice/src/main/java/org/heigit/ors/api/responses/routing/json/JSONExtra.java | Java | mit | 2,695 |
package org.scribe.builder.api;
import org.scribe.model.Token;
public class TumblrApi extends DefaultApi10a
{
private static final String AUTHORIZE_URL = "https://www.tumblr.com/oauth/authorize?oauth_token=%s";
private static final String REQUEST_TOKEN_RESOURCE = "http://www.tumblr.com/oauth/request_token";
private static final String ACCESS_TOKEN_RESOURCE = "http://www.tumblr.com/oauth/access_token";
@Override
public String getAccessTokenEndpoint()
{
return ACCESS_TOKEN_RESOURCE;
}
@Override
public String getRequestTokenEndpoint()
{
return REQUEST_TOKEN_RESOURCE;
}
@Override
public String getAuthorizationUrl(Token requestToken)
{
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
}
| masonevans/scribe-java | src/main/java/org/scribe/builder/api/TumblrApi.java | Java | mit | 754 |
package com.tormosoft.calendarwidget;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
public class AppWidgetConfigureActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize SharedPreferences with default values if it hasn't already.
PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.preferences, false);
setContentView(R.layout.appwidget_settings);
findViewById(R.id.ok_button).setOnClickListener(mOnClickListener);
}
@Override
protected void onPause() {
super.onPause();
refreshWidgets();
}
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
refreshWidgets();
finish();
}
};
private void refreshWidgets() {
// Obtain all app widget IDs.
Context context = getApplicationContext();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName cn = new ComponentName(context, CalendarWidgetProvider.class);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(cn);
if (appWidgetIds != null && appWidgetIds.length != 0) {
// Broadcast update action to all running app widgets.
Intent intent = new Intent(context, CalendarWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
context.sendBroadcast(intent);
}
}
}
| T4d3o/CalendarWidget | app/src/main/java/com/tormosoft/calendarwidget/AppWidgetConfigureActivity.java | Java | mit | 1,928 |
package org.esfinge.querybuilder.neo4j;
import org.esfinge.querybuilder.neo4j.oomapper.Neo4J;
import net.sf.esfinge.querybuilder.annotation.ServicePriority;
import net.sf.esfinge.querybuilder.methodparser.EntityClassProvider;
import net.sf.esfinge.querybuilder.utils.ServiceLocator;
@ServicePriority(1)
public class Neo4JEntityClassProvider implements EntityClassProvider {
@Override
public Class<?> getEntityClass(String name) {
DatastoreProvider dsp = ServiceLocator.getServiceImplementation(DatastoreProvider.class);
Neo4J neo = dsp.getDatastore();
return neo.getEntityClass(name);
}
}
| EsfingeFramework/querybuilder | QueryBuilder_Neo4J/src/org/esfinge/querybuilder/neo4j/Neo4JEntityClassProvider.java | Java | mit | 622 |
package com.merchantry.goncharov;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ClientRequestExecutor implements Runnable {
static Logger log = Logger.getLogger(ClientRequestExecutor.class);
private final ClientRequestEnvelope requestEnvelope;
private final ObjectOutputStream outputStream;
public ClientRequestExecutor(ClientRequestEnvelope requestEnvelope, ObjectOutputStream out) {
this.requestEnvelope = requestEnvelope;
this.outputStream = out;
}
private ServerResponse execute() {
ClientRequest request = requestEnvelope.getRequest();
try {
Object result;
if (request instanceof MethodInvocationRequest) {
MethodInvocationRequest r = (MethodInvocationRequest) request;
result = ServiceInvoker.getInstance().invoke(r.getService(), r.getMethod(), r.getParameters());
} else {
throw new InvalidCommunicationProtocolException("Unknown request type");
}
ServerResponseStatus status = ServerResponseStatus.SUCCESSFUL_WITH_CONTENT;
if (!(result instanceof Serializable)) {
status = ServerResponseStatus.SUCCESSFUL_WITHOUT_CONTENT;
result = null;
}
return new ServerResponse(request.getId(), status, (Serializable) result);
} catch (Exception e) {
log.error(String.format("During execution of request #%d from %s", request.getId(), requestEnvelope.getClientInfo()), e);
return new ServerResponse(request.getId(), ServerResponseStatus.FAILED, e);
}
}
@Override
public void run() {
try {
if (requestEnvelope.getStatus() == ClientRequestStatus.CANCELLED) return;
ServerResponse result = execute();
if (requestEnvelope.getStatus() == ClientRequestStatus.CANCELLED) return;
synchronized (outputStream) {
outputStream.writeObject(result);
outputStream.flush();
}
requestEnvelope.setStatus(ClientRequestStatus.PROCESSED);
} catch (IOException e) {
log.error(String.format("Cannot send result of request #%d from %s", requestEnvelope.getRequest().getId(), requestEnvelope.getClientInfo()), e);
}
}
} | metaflow/sample-java-rpc-server | server/src/com/merchantry/goncharov/ClientRequestExecutor.java | Java | mit | 2,473 |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package openblocks.codeblockutil;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JProgressBar;
/**
* A CConnectingProgressBar is an extension around the swing progress bar,
* which provides methods to disable and re-enable its functionality and
* update its appearance accordingly.
*
* @author [email protected] (Debby Wallach)
*
*/
public class CConnectingProgressBar extends JProgressBar {
private boolean live = false;
public CConnectingProgressBar() {
super(0, 100);
setStringPainted(false);
setVisible(false);
}
public void startProgress() {
live = true;
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
setIndeterminate(true);
setVisible(true);
repaint();
}
// Returns false if the progress bar was not running
public boolean endProgress() {
if (! live) return false;
setVisible(false);
setCursor(null); // turn off the wait cursor
setIndeterminate(false);
repaint();
live = false;
return true;
}
}
| ajhalbleib/aicg | appinventor/blockslib/src/openblocks/codeblockutil/CConnectingProgressBar.java | Java | mit | 1,525 |
/**
* The MIT License
* Copyright (c) 2002-2016 dc4j.info
*
* 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 info.dc4j.toolbox.block;
import info.dc4j.toolbox.connector.DoubleConnector;
import info.dc4j.toolbox.element.DataType;
public class DoubleSocket extends SocketImpl {
public DoubleSocket(int id, String name) {
super(id, name);
set(0.0);
}
@Override
public Double get() {
return (double) super.get();
}
@Override
public DoubleConnector getConnector() {
return (DoubleConnector) super.getConnector();
}
@Override
public DataType socketType() {
return DataType.DOUBLE;
}
}
| dc4j/dc4j-toolbox | src/main/java/info/dc4j/toolbox/block/DoubleSocket.java | Java | mit | 1,666 |
package org.winterblade.minecraft.harmony.scripting.deserializers;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.winterblade.minecraft.harmony.common.utility.LogHelper;
import org.winterblade.minecraft.harmony.scripting.ComponentRegistry;
import java.util.List;
public abstract class BaseComponentDeserializer <T, TComponent> extends BaseMirroredDeserializer {
private final Class<TComponent> componentClass;
protected BaseComponentDeserializer(Class<TComponent> componentClass) {
this.componentClass = componentClass;
}
protected abstract T newInstance(String type);
@Override
protected Object DeserializeMirror(ScriptObjectMirror mirror) {
T output = newInstance(mirror.containsKey("type") ? mirror.get("type").toString() : "");
if(output == null) return null;
// Get our registry data...
ComponentRegistry registry = ComponentRegistry.compileRegistryFor(new Class[]{
componentClass}, mirror);
List<TComponent> components = registry.getComponentsOf(componentClass);
// Allow the actual deserializer to do its work:
try {
update(mirror, output, components);
} catch(Exception ex) {
LogHelper.error("Unable to deserialize object due to an error.", ex);
return null;
}
return output;
}
protected abstract void update(ScriptObjectMirror mirror, T output, List<TComponent> components);
}
| legendblade/CraftingHarmonics | src/main/java/org/winterblade/minecraft/harmony/scripting/deserializers/BaseComponentDeserializer.java | Java | mit | 1,487 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.worker.art.executionEngine.session;
import madgik.exareme.common.art.PlanSessionID;
import madgik.exareme.worker.art.executionEngine.ExecutionEngine;
import org.apache.log4j.Logger;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* @author Herald Kllapi<br>
* @author Dimitris Paparas<br>
* @author Eva Sitaridi<br>
* {herald,paparas,evas}@di.uoa.gr<br>
* University of Athens /
* Department of Informatics and Telecommunications.
* @since 1.0
*/
public class ExecutionEngineSession implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(ExecutionEngineSession.class);
private ExecutionEngine engine = null;
private List<ExecutionEngineSessionPlan> planList = null;
public ExecutionEngineSession(ExecutionEngine engine) {
this.engine = engine;
this.planList = Collections.synchronizedList(new LinkedList<ExecutionEngineSessionPlan>());
}
public ExecutionEngineSessionPlan startSession() throws RemoteException {
PlanSessionID sessionID = engine.createNewSession();
ExecutionEngineSessionPlan sessionPlan = new ExecutionEngineSessionPlan(sessionID, engine);
planList.add(sessionPlan);
return sessionPlan;
}
public ExecutionEngineSessionPlan startSessionElasticTree() throws RemoteException {
PlanSessionID sessionID = engine.createNewSessionElasticTree();
ExecutionEngineSessionPlan sessionPlan = new ExecutionEngineSessionPlan(sessionID, engine);
planList.add(sessionPlan);
return sessionPlan;
}
public List<ExecutionEngineSessionPlan> listPlans() throws RemoteException {
return Collections.unmodifiableList(planList);
}
public void close() throws RemoteException {
for (ExecutionEngineSessionPlan sessionPlan : planList) {
if (sessionPlan.isClosed() == false) {
sessionPlan.close();
}
}
}
}
| madgik/exareme | Exareme-Docker/src/exareme/exareme-worker/src/main/java/madgik/exareme/worker/art/executionEngine/session/ExecutionEngineSession.java | Java | mit | 2,152 |
package org.gluu.oxtrust.ldap.service;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import org.gluu.oxtrust.model.OxAuthClient;
import org.gluu.oxtrust.model.OxAuthSectorIdentifier;
import org.gluu.oxtrust.util.OxTrustConstants;
import org.gluu.persist.ldap.impl.LdapEntryManager;
import org.gluu.search.filter.Filter;
import org.slf4j.Logger;
import org.xdi.util.StringHelper;
/**
* Provides operations with Sector Identifiers
*
* @author Javier Rojas Blum
* @version January 15, 2016
*/
@Stateless
@Named
public class SectorIdentifierService implements Serializable {
private static final long serialVersionUID = -9167587377957719153L;
@Inject
private Logger log;
@Inject
private LdapEntryManager ldapEntryManager;
@Inject
private OrganizationService organizationService;
@Inject
private ClientService clientService;
/**
* Build DN string for sector identifier
*
* @param oxId Sector Identifier oxId
* @return DN string for specified sector identifier or DN for sector identifiers branch if oxId is null
* @throws Exception
*/
public String getDnForSectorIdentifier(String oxId) {
String orgDn = organizationService.getDnForOrganization();
if (StringHelper.isEmpty(oxId)) {
return String.format("ou=sector_identifiers,%s", orgDn);
}
return String.format("oxId=%s,ou=sector_identifiers,%s", oxId, orgDn);
}
/**
* Search sector identifiers by pattern
*
* @param pattern Pattern
* @param sizeLimit Maximum count of results
* @return List of sector identifiers
*/
public List<OxAuthSectorIdentifier> searchSectorIdentifiers(String pattern, int sizeLimit) {
String[] targetArray = new String[]{pattern};
Filter searchFilter = Filter.createSubstringFilter(OxTrustConstants.oxId, null, targetArray, null);
List<OxAuthSectorIdentifier> result = ldapEntryManager.findEntries(getDnForSectorIdentifier(null), OxAuthSectorIdentifier.class, searchFilter, sizeLimit);
return result;
}
public List<OxAuthSectorIdentifier> getAllSectorIdentifiers() {
return ldapEntryManager.findEntries(getDnForSectorIdentifier(null), OxAuthSectorIdentifier.class, null);
}
/**
* Get sector identifier by oxId
*
* @param oxId Sector identifier oxId
* @return Sector identifier
*/
public OxAuthSectorIdentifier getSectorIdentifierById(String oxId) {
OxAuthSectorIdentifier result = null;
try {
result = ldapEntryManager.find(OxAuthSectorIdentifier.class, getDnForSectorIdentifier(oxId));
} catch (Exception e) {
log.error("Failed to find sector identifier by oxId " + oxId, e);
}
return result;
}
/**
* Generate new oxId for sector identifier
*
* @return New oxId for sector identifier
* @throws Exception
*/
public String generateIdForNewSectorIdentifier() {
OxAuthSectorIdentifier sectorIdentifier = new OxAuthSectorIdentifier();
String newId = null;
do {
newId = generateIdForNewSectorIdentifierImpl();
String newDn = getDnForSectorIdentifier(newId);
sectorIdentifier.setDn(newDn);
} while (ldapEntryManager.contains(sectorIdentifier));
return newId;
}
/**
* Generate new oxId for sector identifier
*
* @return New oxId for sector identifier
*/
private String generateIdForNewSectorIdentifierImpl(){
return UUID.randomUUID().toString();
}
/**
* Add new sector identifier entry
*
* @param sectorIdentifier Sector identifier
*/
public void addSectorIdentifier(OxAuthSectorIdentifier sectorIdentifier) {
ldapEntryManager.persist(sectorIdentifier);
}
/**
* Update sector identifier entry
*
* @param sectorIdentifier Sector identifier
*/
public void updateSectorIdentifier(OxAuthSectorIdentifier sectorIdentifier) {
ldapEntryManager.merge(sectorIdentifier);
}
/**
* Remove sector identifier entry
*
* @param sectorIdentifier Sector identifier
*/
public void removeSectorIdentifier(OxAuthSectorIdentifier sectorIdentifier) {
if (sectorIdentifier.getClientIds() != null) {
List<String> clientDNs = sectorIdentifier.getClientIds();
// clear references in Client entries
for (String clientDN : clientDNs) {
OxAuthClient client = clientService.getClientByDn(clientDN);
client.setSectorIdentifierUri(null);
clientService.updateClient(client);
}
}
ldapEntryManager.remove(sectorIdentifier);
}
public static void main(String[] args) {
System.out.println(UUID.randomUUID().toString());
}
}
| madumlao/oxTrust | server/src/main/java/org/gluu/oxtrust/ldap/service/SectorIdentifierService.java | Java | mit | 5,010 |
package org.nodes.rdf;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.nodes.DNode;
import org.nodes.DTGraph;
import org.nodes.DTNode;
import org.nodes.Node;
import nl.peterbloem.kit.MaxObserver;
public class FlatInstances implements Instances
{
protected DTGraph<String, String> graph;
protected int instanceSize, maxDepth;
protected Scorer scorer;
protected Comparator<Token> comp;
protected boolean directed;
public FlatInstances(DTGraph<String, String> graph, int instanceSize,
int maxDepth, Scorer scorer)
{
this(graph, instanceSize, maxDepth, scorer, true);
}
public FlatInstances(DTGraph<String, String> graph, int instanceSize,
int maxDepth, Scorer scorer, boolean directed)
{
this.directed = directed;
this.graph = graph;
this.instanceSize = instanceSize;
this.maxDepth = maxDepth;
this.scorer = scorer;
comp = new ScorerComparator(scorer);
}
@SuppressWarnings("unchecked")
@Override
public List<DTNode<String, String>> instance(DNode<String> instanceNode)
{
List<Token> nodes = neighborhood(instanceNode, maxDepth, directed);
if(instanceSize == -1)
{
List<DTNode<String, String>> result = new ArrayList<DTNode<String,String>>(nodes.size());
for(Token token : nodes)
result.add((DTNode<String, String>)token.node());
return result;
}
MaxObserver<W> observer = new MaxObserver<FlatInstances.W>(instanceSize);
for(Token token : nodes)
observer.observe(new W(token));
List<DTNode<String, String>> result = new ArrayList<DTNode<String,String>>(instanceSize);
for(W w : observer.elements())
result.add(w.node());
return result;
}
public static List<Token> neighborhood(DNode<String> center, int depth, boolean directed)
{
Set<DNode<String>> nb = new LinkedHashSet<DNode<String>>();
nb.add(center);
List<Token> tokens = new ArrayList<Token>();
tokens.add(new Token(center, 0));
nbInner(tokens, nb, depth, directed);
return tokens;
}
private static void nbInner(List<Token> tokens, Set<DNode<String>> nodes, int depth, boolean directed)
{
if(depth == 0)
return;
List<Token> newTokens = new ArrayList<Token>();
for(Token token : tokens)
for(DNode<String> neighbor : directed ? token.node().neighbors() : token.node().neighbors())
if(! nodes.contains(neighbor))
newTokens.add(new Token(neighbor, token.depth() + 1));
tokens.addAll(newTokens);
for(Token token : newTokens)
nodes.add(token.node());
nbInner(tokens, nodes, depth - 1, directed);
}
private class W implements Comparable<W>
{
private Token token;
private double score;
public W(Token token)
{
this.token = token;
this.score = scorer.score(token.node(), token.depth());
}
@Override
public int compareTo(W o)
{
return Double.compare(this.score, o.score);
}
public DTNode<String, String> node()
{
return (DTNode<String, String>) token.node();
}
}
}
| Data2Semantics/nodes | nodes/src/main/java/org/nodes/rdf/FlatInstances.java | Java | mit | 3,089 |
package com.left.peter.data;
import java.util.HashMap;
import java.util.Map;
public enum AreaPosition
{
INSIDE((byte)0),
AROUND((byte)1),
AROUND_AROUND((byte)2),
NONE(Byte.MAX_VALUE);
final private byte value;
static private Map<Byte, AreaPosition> values;
private AreaPosition(final byte value)
{
this.value = value;
}
public byte getValue()
{
return value;
}
static public AreaPosition valueOf(final byte value)
{
if (null == values)
{
values = new HashMap<>();
for (final AreaPosition pos : AreaPosition.values())
{
values.put(pos.value, pos);
}
}
if (!values.containsKey(value))
{
throw new IllegalArgumentException("Unknown value :" + value);
}
else
{
return values.get(value);
}
}
}
| huzhiguan/cloudProject | src/com/left/peter/data/AreaPosition.java | Java | mit | 759 |
package org.ethereum.gui;
import org.ethereum.core.Block;
import org.ethereum.core.Transaction;
import org.ethereum.facade.Blockchain;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.Utils;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.DocumentFilter;
import javax.swing.text.Highlighter;
/**
* @author Adrian Benko
* @since 27.08.14
*/
public class BlockChainTable extends JFrame implements ActionListener {
final static int BLOCK_CHECK_INTERVAL = 1000;
final static String FONT_NAME = "Courier New";
final static int FONT_SIZE_TITLE = 20;
final static int FONT_SIZE = 13;
final static Font boldTitle = new Font(FONT_NAME, Font.BOLD, FONT_SIZE_TITLE);
final static Font bold = new Font(FONT_NAME, Font.BOLD, FONT_SIZE);
final static Font plain = new Font(FONT_NAME, Font.PLAIN, FONT_SIZE);
final static Color HILIT_COLOR = Color.LIGHT_GRAY;
class MyDocumentFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int off
, String str, AttributeSet attr)
throws BadLocationException {
// remove non-digits
fb.insertString(off, str.replaceAll("\\D++", ""), attr);
}
@Override
public void replace(FilterBypass fb, int off
, int len, String str, AttributeSet attr)
throws BadLocationException {
// remove non-digits
fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
}
}
private volatile boolean running;
private TransactionData transactionDataWindow = null;
private JPanel topPanel;
private JPanel titlePanel;
private JPanel blockPanel;
private JPanel transactionsPanel;
private JScrollPane scrollPane;
JTextField blockNumberText;
JButton firstBlock;
JButton prevBlock;
JButton nextBlock;
JButton lastBlock;
JLabel blocksCount;
JTextField findText;
JButton findPrev;
JButton findNext;
JTextField blockN;
JTextField minGasPrice;
JTextField gasLimit;
JTextField gasUsed;
JTextField timestamp;
JTextField difficulty;
JTextField hash;
JTextField parentHash;
JTextField uncleHash;
JTextField stateRoot;
JTextField trieRoot;
JTextField coinbase;
JTextField nonce;
JTextField extraData;
Thread t;
private int lastFindIndex = -1;
private String textToFind = "";
private java.util.List<Long> foundBlocks;
final Highlighter.HighlightPainter painter;
ToolBar toolBar;
public BlockChainTable(ToolBar toolBar) {
this.toolBar = toolBar;
addCloseAction();
foundBlocks = new ArrayList<>();
painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
setTitle("Block Chain Table");
setSize(900, 400);
setLocation(315, 270);
setBackground(Color.gray);
java.net.URL url = ClassLoader.getSystemResource("ethereum-icon.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
this.setIconImage(img);
// Create a panel to hold all other components
topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.PAGE_AXIS));
getContentPane().add(topPanel, BorderLayout.LINE_START);
titlePanel = new JPanel(new FlowLayout());
titlePanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
createTitlePanel(this);
blockPanel = new JPanel(new GridBagLayout());
blockPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 160));
createBlockPanel();
transactionsPanel = new JPanel(new GridBagLayout());
scrollPane = new JScrollPane(transactionsPanel);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setAlignmentX(0);
fillBlock(this);
titlePanel.setAlignmentX(0);
topPanel.add(titlePanel);
blockPanel.setAlignmentX(0);
topPanel.add(blockPanel);
JLabel transactionsLabel = new JLabel("Transactions ");
transactionsLabel.setFont(bold);
transactionsLabel.setAlignmentX(0);
transactionsLabel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
topPanel.add(transactionsLabel);
topPanel.add(scrollPane);
topPanel.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK), "Copy");
topPanel.getActionMap().put("Copy", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if (UIEthereumManager.ethereum.getBlockchain().getSize() - 1 < lastFindIndex) return;
Block block = UIEthereumManager.ethereum.getBlockchain().getBlockByNumber(lastFindIndex);
StringSelection selection = new StringSelection(block.toString());
Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();
system.setContents(selection, selection);
}
});
t = new Thread() {
public void run() {
running = true;
while (running) {
blocksCount.setText("" + UIEthereumManager.ethereum.getBlockchain().getSize());
try {
sleep(BLOCK_CHECK_INTERVAL);
} catch (InterruptedException e) {
}
}
}
};
t.start();
}
public void actionPerformed(ActionEvent e) {
long blockNum = Long.parseLong(blockNumberText.getText());
if ("firstBlock".equals(e.getActionCommand())) {
blockNum = 0;
} else if ("prevBlock".equals(e.getActionCommand())) {
if (blockNum > 0) {
blockNum--;
}
} else if ("nextBlock".equals(e.getActionCommand())) {
if (blockNum < UIEthereumManager.ethereum.getBlockchain().getSize() - 1) {
blockNum++;
}
} else if ("lastBlock".equals(e.getActionCommand())) {
blockNum = UIEthereumManager.ethereum.getBlockchain().getSize() - 1;
} else if ("findPrev".equals(e.getActionCommand())) {
if (findText.getText().length() > 0) {
if (textToFind.equals(findText.getText())) {
if (lastFindIndex > 0) {
blockNum = foundBlocks.get(lastFindIndex - 1);
lastFindIndex--;
} else {
blockNum = findBlock(textToFind, blockNum, false);
}
} else {
textToFind = findText.getText();
lastFindIndex = -1;
foundBlocks.clear();
blockNum = findBlock(textToFind, blockNum, false);
}
}
} else if ("findNext".equals(e.getActionCommand())) {
if (findText.getText().length() > 0) {
if (textToFind.equals(findText.getText())) {
if (lastFindIndex > -1 && foundBlocks.size() > lastFindIndex + 1) {
blockNum = foundBlocks.get(lastFindIndex + 1);
lastFindIndex++;
} else {
blockNum = findBlock(textToFind, blockNum, true);
}
} else {
textToFind = findText.getText();
lastFindIndex = -1;
foundBlocks.clear();
blockNum = findBlock(textToFind, blockNum, true);
}
}
}
blockNumberText.setText("" + blockNum);
fillBlock(this);
}
private long findBlock(String textToFind, long blockNum, boolean forward) {
if (forward) {
for (long i = blockNum + 1; i < UIEthereumManager.ethereum.getBlockchain().getSize(); i++) {
Block block = UIEthereumManager.ethereum.getBlockchain().getBlockByNumber(i);
if (block.toString().toLowerCase().contains(textToFind.toLowerCase())) {
foundBlocks.add(i);
lastFindIndex = foundBlocks.size() - 1;
break;
}
}
} else {
for (long i = blockNum - 1; i >= 0; i--) {
Block block = UIEthereumManager.ethereum.getBlockchain().getBlockByNumber(i);
if (block.toString().toLowerCase().contains(textToFind.toLowerCase())) {
foundBlocks.add(0, i);
lastFindIndex = 0;
break;
}
}
}
return foundBlocks.get(lastFindIndex);
}
public void terminate() {
running = false;
}
public void addCloseAction() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
toolBar.chainToggle.setSelected(false);
if (transactionDataWindow != null) {
transactionDataWindow.setVisible(false);
}
}
});
}
public static void main(String args[]) {
BlockChainTable mainFrame = new BlockChainTable(null);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createTitlePanel(final BlockChainTable blockchainTable) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JLabel blockNumberLabel = new JLabel("Block #");
blockNumberLabel.setFont(boldTitle);
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 10, 0, 0);
titlePanel.add(blockNumberLabel, c);
blockNumberText = new JTextField("0", 7);
((AbstractDocument) blockNumberText.getDocument()).setDocumentFilter(
new MyDocumentFilter());
// Listen for changes in the text
blockNumberText.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
fillBlock(blockchainTable);
}
public void removeUpdate(DocumentEvent e) {
fillBlock(blockchainTable);
}
public void insertUpdate(DocumentEvent e) {
fillBlock(blockchainTable);
}
});
blockNumberText.setFont(boldTitle);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.insets = new Insets(0, 0, 0, 10);
titlePanel.add(blockNumberText, c);
firstBlock = new JButton("|<");
firstBlock.setFont(plain);
firstBlock.setActionCommand("firstBlock");
firstBlock.addActionListener(this);
c.gridx = 2;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 0, 0, 0);
titlePanel.add(firstBlock, c);
prevBlock = new JButton("<");
prevBlock.setFont(plain);
prevBlock.setActionCommand("prevBlock");
prevBlock.addActionListener(this);
c.gridx = 3;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 0, 0, 0);
titlePanel.add(prevBlock, c);
nextBlock = new JButton(">");
nextBlock.setFont(plain);
nextBlock.setActionCommand("nextBlock");
nextBlock.addActionListener(this);
c.gridx = 4;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 0, 0, 0);
titlePanel.add(nextBlock, c);
lastBlock = new JButton(">|");
lastBlock.setFont(plain);
lastBlock.setActionCommand("lastBlock");
lastBlock.addActionListener(this);
c.gridx = 5;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 0, 0, 0);
titlePanel.add(lastBlock, c);
JLabel blocksCountLabel = new JLabel("Total blocks: ");
blocksCountLabel.setFont(plain);
c.gridx = 6;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 10, 0, 0);
titlePanel.add(blocksCountLabel, c);
blocksCount = new JLabel();
blocksCount.setFont(plain);
c.gridx = 7;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 0, 0, 0);
titlePanel.add(blocksCount, c);
JLabel findLabel = new JLabel("Find ");
findLabel.setFont(plain);
c.gridx = 8;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 10, 0, 0);
titlePanel.add(findLabel, c);
findText = new JTextField(12);
findText.setFont(plain);
c.gridx = 9;
c.gridy = 0;
c.weightx = 3.0;
c.insets = new Insets(0, 0, 0, 0);
titlePanel.add(findText, c);
findPrev = new JButton("<");
findPrev.setFont(plain);
findPrev.setActionCommand("findPrev");
findPrev.addActionListener(this);
c.gridx = 10;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 10, 0, 0);
titlePanel.add(findPrev, c);
findNext = new JButton(">");
findNext.setFont(plain);
findNext.setActionCommand("findNext");
findNext.addActionListener(this);
c.gridx = 11;
c.gridy = 0;
c.weightx = 0.0;
c.insets = new Insets(0, 0, 0, 10);
titlePanel.add(findNext, c);
}
private void createBlockPanel() {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JLabel summaryLabel = new JLabel("Summary ");
summaryLabel.setFont(bold);
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 10, 0, 0);
blockPanel.add(summaryLabel, c);
JLabel blocknLabel = new JLabel("Block#");
blocknLabel.setFont(plain);
c.weightx = 1.0;
c.gridx = 0;
c.gridy = 2;
blockPanel.add(blocknLabel, c);
blockN = new JTextField();
blockN.setEditable(false);
blockN.setBorder(null);
blockN.setFont(plain);
c.gridx = 1;
c.gridy = 2;
blockPanel.add(blockN, c);
JLabel minGasPriceLabel = new JLabel("Min gas price");
minGasPriceLabel.setFont(plain);
c.weightx = 1.0;
c.gridx = 0;
c.gridy = 3;
blockPanel.add(minGasPriceLabel, c);
minGasPrice = new JTextField();
minGasPrice.setEditable(false);
minGasPrice.setBorder(null);
minGasPrice.setFont(plain);
c.gridx = 1;
c.gridy = 3;
blockPanel.add(minGasPrice, c);
JLabel gasLimitLabel = new JLabel("Gas limit");
gasLimitLabel.setFont(plain);
c.gridx = 0;
c.gridy = 4;
blockPanel.add(gasLimitLabel, c);
gasLimit = new JTextField();
gasLimit.setEditable(false);
gasLimit.setBorder(null);
gasLimit.setFont(plain);
c.gridx = 1;
c.gridy = 4;
blockPanel.add(gasLimit, c);
JLabel gasUsedLabel = new JLabel("Gas used");
gasUsedLabel.setFont(plain);
c.gridx = 0;
c.gridy = 5;
blockPanel.add(gasUsedLabel, c);
gasUsed = new JTextField();
gasUsed.setEditable(false);
gasUsed.setBorder(null);
gasUsed.setFont(plain);
c.gridx = 1;
c.gridy = 5;
blockPanel.add(gasUsed, c);
JLabel timestampLabel = new JLabel("Timestamp");
timestampLabel.setFont(plain);
c.gridx = 0;
c.gridy = 6;
blockPanel.add(timestampLabel, c);
timestamp = new JTextField();
timestamp.setEditable(false);
timestamp.setBorder(null);
timestamp.setFont(plain);
c.gridx = 1;
c.gridy = 6;
blockPanel.add(timestamp, c);
JLabel difficultyLabel = new JLabel("Difficulty");
difficultyLabel.setFont(plain);
c.gridx = 0;
c.gridy = 7;
blockPanel.add(difficultyLabel, c);
difficulty = new JTextField();
difficulty.setEditable(false);
difficulty.setBorder(null);
difficulty.setFont(plain);
c.gridx = 1;
c.gridy = 7;
blockPanel.add(difficulty, c);
JLabel extraDataLabel = new JLabel("Extra data");
extraDataLabel.setFont(plain);
c.gridx = 0;
c.gridy = 9;
blockPanel.add(extraDataLabel, c);
extraData = new JTextField();
extraData.setEditable(false);
extraData.setBorder(null);
extraData.setFont(plain);
c.ipady = 1;
c.ipadx = 1;
c.gridx = 1;
c.gridy = 9;
c.gridwidth = GridBagConstraints.REMAINDER;
blockPanel.add(extraData, c);
JLabel hashesLabel = new JLabel("Hashes ");
hashesLabel.setFont(bold);
c.gridx = 3;
c.gridy = 1;
c.gridwidth = 1;
blockPanel.add(hashesLabel, c);
JLabel hashLabel = new JLabel("Hash");
hashLabel.setFont(plain);
c.gridx = 3;
c.gridy = 2;
blockPanel.add(hashLabel, c);
hash = new JTextField();
hash.setEditable(false);
hash.setBorder(null);
hash.setFont(plain);
c.weightx = 3.0;
c.gridx = 4;
c.gridy = 2;
blockPanel.add(hash, c);
JLabel parentHashLabel = new JLabel("Parent hash");
parentHashLabel.setFont(plain);
c.weightx = 1.0;
c.gridx = 3;
c.gridy = 3;
blockPanel.add(parentHashLabel, c);
parentHash = new JTextField();
parentHash.setEditable(false);
parentHash.setBorder(null);
parentHash.setFont(plain);
c.gridx = 4;
c.gridy = 3;
blockPanel.add(parentHash, c);
JLabel uncleHashLabel = new JLabel("Uncle hash");
uncleHashLabel.setFont(plain);
c.gridx = 3;
c.gridy = 4;
blockPanel.add(uncleHashLabel, c);
uncleHash = new JTextField();
uncleHash.setEditable(false);
uncleHash.setBorder(null);
uncleHash.setFont(plain);
c.gridx = 4;
c.gridy = 4;
blockPanel.add(uncleHash, c);
JLabel stateRootLabel = new JLabel("State root");
stateRootLabel.setFont(plain);
c.weightx = 1.0;
c.gridx = 3;
c.gridy = 5;
blockPanel.add(stateRootLabel, c);
stateRoot = new JTextField();
stateRoot.setEditable(false);
stateRoot.setBorder(null);
stateRoot.setFont(plain);
c.gridx = 4;
c.gridy = 5;
blockPanel.add(stateRoot, c);
JLabel trieRootLabel = new JLabel("Trie root");
trieRootLabel.setFont(plain);
c.gridx = 3;
c.gridy = 6;
blockPanel.add(trieRootLabel, c);
trieRoot = new JTextField();
trieRoot.setEditable(false);
trieRoot.setBorder(null);
trieRoot.setFont(plain);
c.gridx = 4;
c.gridy = 6;
blockPanel.add(trieRoot, c);
JLabel coinbaseLabel = new JLabel("Coinbase");
coinbaseLabel.setFont(plain);
c.gridx = 3;
c.gridy = 7;
blockPanel.add(coinbaseLabel, c);
coinbase = new JTextField();
coinbase.setEditable(false);
coinbase.setBorder(null);
coinbase.setFont(plain);
c.gridx = 4;
c.gridy = 7;
blockPanel.add(coinbase, c);
JLabel nonceLabel = new JLabel("Nonce");
nonceLabel.setFont(plain);
c.gridx = 3;
c.gridy = 8;
blockPanel.add(nonceLabel, c);
nonce = new JTextField();
nonce.setEditable(false);
nonce.setBorder(null);
nonce.setFont(plain);
c.gridx = 4;
c.gridy = 8;
blockPanel.add(nonce, c);
}
private void fillBlock(final BlockChainTable blockchainTable) {
if (blockNumberText.getText().length() == 0) return;
Blockchain blockchain = UIEthereumManager.ethereum.getBlockchain();
long blockNum = Long.parseLong(blockNumberText.getText());
if (blockNum > blockchain.getSize() - 1) {
blockNum = blockchain.getSize() - 1;
}
Block block = blockchain.getBlockByNumber(blockNum);
blockN.setText("" + block.getNumber());
highlightText(blockN);
minGasPrice.setText("" + 42);
highlightText(minGasPrice);
gasLimit.setText("" + block.getGasLimit());
highlightText(gasLimit);
gasUsed.setText("" + block.getGasUsed());
highlightText(gasUsed);
timestamp.setText(Utils.longToDateTime(block.getTimestamp()));
highlightText(timestamp);
difficulty.setText(ByteUtil.toHexString(block.getDifficulty()));
highlightText(difficulty);
hash.setText(ByteUtil.toHexString(block.getHash()));
highlightText(hash);
parentHash.setText(ByteUtil.toHexString(block.getParentHash()));
highlightText(parentHash);
uncleHash.setText(ByteUtil.toHexString(block.getUnclesHash()));
highlightText(uncleHash);
stateRoot.setText(ByteUtil.toHexString(block.getStateRoot()));
highlightText(stateRoot);
trieRoot.setText(ByteUtil.toHexString(block.getTxTrieRoot()));
highlightText(trieRoot);
coinbase.setText(ByteUtil.toHexString(block.getCoinbase()));
highlightText(coinbase);
nonce.setText(ByteUtil.toHexString(block.getNonce()));
highlightText(nonce);
if (block.getExtraData() != null) {
extraData.setText(ByteUtil.toHexString(block.getExtraData()));
highlightText(extraData);
}
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
transactionsPanel.removeAll();
int row = 1;
for (Transaction transaction : block.getTransactionsList()) {
JPanel transactionPanel = createTransactionPanel(blockchainTable, transaction);
c.gridx = 0;
c.gridy = row;
c.weighty = 1;
c.weightx = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(10, 10, 0, 10);
transactionsPanel.add(transactionPanel, c);
row++;
}
transactionsPanel.repaint();
scrollPane.revalidate();
}
private JPanel createTransactionPanel(final BlockChainTable blockchainTable, final Transaction transaction) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JPanel transactionPanel = new JPanel(new GridBagLayout());
transactionPanel.setBorder(BorderFactory.createLineBorder(Color.black));
JLabel senderLabel = new JLabel("Sender");
senderLabel.setFont(plain);
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 0, 0, 0);
transactionPanel.add(senderLabel, c);
JTextField sender = new JTextField(ByteUtil.toHexString(transaction.getSender()));
highlightText(sender);
sender.setEditable(false);
sender.setBorder(null);
sender.setFont(plain);
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(sender, c);
JLabel gasPriceLabel = new JLabel("Gas price");
gasPriceLabel.setFont(plain);
c.gridx = 2;
c.gridy = 0;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(gasPriceLabel, c);
JTextField gasPrice = new JTextField(ByteUtil.toHexString(transaction.getGasPrice()));
highlightText(gasPrice);
gasPrice.setEditable(false);
gasPrice.setBorder(null);
gasPrice.setFont(plain);
c.gridx = 3;
c.gridy = 0;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(gasPrice, c);
JLabel receiveAddressLabel = new JLabel("Receive address");
receiveAddressLabel.setFont(plain);
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
transactionPanel.add(receiveAddressLabel, c);
JTextField receiveAddress = new JTextField(ByteUtil.toHexString(transaction.getReceiveAddress()));
highlightText(receiveAddress);
receiveAddress.setEditable(false);
receiveAddress.setBorder(null);
receiveAddress.setFont(plain);
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(receiveAddress, c);
JLabel gasLimitLabel = new JLabel("Gas limit");
gasLimitLabel.setFont(plain);
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(gasLimitLabel, c);
JTextField gasLimit = new JTextField(ByteUtil.toHexString(transaction.getGasLimit()));
highlightText(gasLimit);
gasLimit.setEditable(false);
gasLimit.setBorder(null);
gasLimit.setFont(plain);
c.gridx = 3;
c.gridy = 1;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(gasLimit, c);
JLabel hashLabel = new JLabel("Hash");
hashLabel.setFont(plain);
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0, 0, 0, 0);
transactionPanel.add(hashLabel, c);
JTextField hash = new JTextField(ByteUtil.toHexString(transaction.getHash()));
highlightText(hash);
hash.setEditable(false);
hash.setBorder(null);
hash.setFont(plain);
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(hash, c);
JLabel valueLabel = new JLabel("Value");
valueLabel.setFont(plain);
c.gridx = 2;
c.gridy = 2;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(valueLabel, c);
JTextField value = new JTextField(transaction.getValue() != null ? ByteUtil.toHexString(transaction.getValue
()) : "");
highlightText(value);
value.setEditable(false);
value.setBorder(null);
value.setFont(plain);
c.gridx = 3;
c.gridy = 2;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(value, c);
JLabel nonceLabel = new JLabel("Nonce");
nonceLabel.setFont(plain);
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(0, 0, 0, 0);
transactionPanel.add(nonceLabel, c);
JTextField nonce = new JTextField(ByteUtil.toHexString(transaction.getNonce()));
highlightText(nonce);
nonce.setEditable(false);
nonce.setBorder(null);
nonce.setFont(plain);
c.gridx = 1;
c.gridy = 3;
c.insets = new Insets(0, 10, 0, 0);
transactionPanel.add(nonce, c);
JButton data = new JButton("Data");
data.addActionListener(event -> {
if (transactionDataWindow == null)
transactionDataWindow = new TransactionData(blockchainTable);
transactionDataWindow.setData(transaction.getData());
transactionDataWindow.setVisible(true);
transactionDataWindow.highlightText(findText.getText(), painter);
});
data.setFont(plain);
if (findText.getText().length() > 0 && ByteUtil.toHexString(transaction.getData()).contains(findText.getText
())) {
data.setBackground(HILIT_COLOR);
}
c.gridx = 3;
c.gridy = 3;
c.insets = new Insets(0, 0, 10, 0);
transactionPanel.add(data, c);
return transactionPanel;
}
private void highlightText(JTextField textField) {
if (findText.getText().length() > 0 && textField.getText().contains(findText.getText())) {
try {
int end = textField.getText().indexOf(findText.getText()) + findText.getText().length();
textField.getHighlighter().addHighlight(textField.getText().indexOf(findText.getText()), end, painter);
} catch (BadLocationException e) {
}
}
}
}
| swaldman/ethereumj | ethereumj-studio/src/main/java/org/ethereum/gui/BlockChainTable.java | Java | mit | 28,840 |
/*########################################################################
*# #
*# Copyright (c) 2014 by #
*# Shanghai Stock Exchange (SSE), Shanghai, China #
*# All rights reserved. #
*# #
*########################################################################
*/
package sse.ngts.common.plugin.step.field;
import sse.ngts.common.plugin.fieldtype.StringField;
public class Password extends StringField {
static final long serialVersionUID = 20131121;
public static final int FIELD = 554;
public Password() {
super(FIELD);
}
public Password(String data) {
super(FIELD, data);
}
}
| zkkz/OrientalExpress | source/step/src/sse/ngts/common/plugin/step/field/Password.java | Java | mit | 883 |
package com.lenddo.sample;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lenddo.javaapi.*;
import com.lenddo.javaapi.models.*;
import com.lenddo.javaapi.utils.ApiUtils;
import java.net.InetSocketAddress;
import java.net.Proxy;
/**
* Created by Joey Mar Antonio on 1/18/16.
*/
public class Sample {
public Sample () {}
public static class Credentials {
public String api_key;
public String api_secret;
public String partner_script_id;
Credentials (String api_key, String api_secret, String partner_script_id) {
this.api_key = api_key;
this.api_secret = api_secret;
this.partner_script_id = partner_script_id;
}
}
public static void main(String[] args) {
// Enter your credentials here:
String api_key = "API KEY";
String partner_script_id = "PARTNERSCRIPT ID";
String private_key = "Sample\\private.pem";
String api_secret = "API SECRET";
String document_id = "DOCUMENT ID";
double pageSize = 100;
double pageNumber = 1;
// Format 2019-05-30 20:00
String startDate = "START DATE";
String endDate = "END DATE";
Credentials credentials = new Credentials(api_key, api_secret, partner_script_id);
// Test ApplicationScore API
String applicationId = "APPLICATION ID";
getApplicationScore(credentials, applicationId);
// Test ApplicationScorecards API
getApplicationScorecards(credentials, applicationId);
// Test ApplicationVerification API
getApplicationVerification(credentials, applicationId);
// Test Whitelable API
String provider = WhiteLabelApi.PROVIDER_WINDOWSLIVE;
samplePostPartnerToken(credentials, applicationId, provider);
// Replace with your Proxy Configuration
java.net.Proxy proxy = new Proxy(
Proxy.Type.HTTP,
new InetSocketAddress("localhost", 8080));
samplePostCommitPartnerJobWithProxy(
credentials,
applicationId,
provider,
proxy
);
// For invoking application endpoints, set to qa or prod
LenddoConfig.setApplicationMode("prod");
// Test Applications API
sampleGetApplications(credentials, private_key);
sampleGetApplicationsWithFilter(credentials, private_key, pageSize, pageNumber, startDate, endDate);
sampleGetApplicationDetails(credentials, private_key, applicationId);
sampleGetDocumentDetails(credentials, private_key, applicationId, document_id);
}
// TEST CODE FOR GETTING AUTHORIZE HEALTHCHECK
private static void sampleGetAuthorizeHealtcheck(Credentials credentials, String applicationId) {
AuthorizeApi authorizeApi = new AuthorizeApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
// Set this to true to see debug messages during debug build.
authorizeApi.debugMode(true);
authorizeApi.getAuthorizeHealthcheck(applicationId, new LenddoApiCallback<JsonElement>() {
@Override
public void onResponse(JsonElement response) {
System.out.println("Resulting healthcheck: "+ response.toString());
}
@Override
public void onFailure(Throwable throwable) {
System.out.println("Network Connection Failed: "+ throwable.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+ errormessage);
}
});
}
// TEST CODE FOR POST AUTHORIZE ONBOARDING PRIORITYDATA
private static void samplePostAuthorizeOnboardingPriorityData(Credentials credentials, String applicationId, PriorityDataRequestBody body) {
AuthorizeApi authorizeApi = new AuthorizeApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
AuthorizeApi.debugMode(true);
if (body == null) {
body = new PriorityDataRequestBody();
}
authorizeApi.postAuthorizeOnboardingPrioritydata(applicationId, body, new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response="+ ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
// TEST CODE FOR GETTING APPLICATION SCORE
private static void getApplicationScore(Credentials credentials, String applicationId) {
LenddoScoreApi lenddoapi = new LenddoScoreApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
// Set this to true to see debug messages during debug build.
lenddoapi.debugMode(true);
lenddoapi.getApplicationScore(applicationId, new LenddoApiCallback<ApplicationScore>() {
@Override
public void onResponse(ApplicationScore applicationScore) {
System.out.println("Resulting application score: "+ applicationScore.score);
System.out.println("Resulting application flags: "+ applicationScore.flags);
}
@Override
public void onFailure(Throwable throwable) {
System.out.println("Network Connection Failed: "+ throwable.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+ errormessage);
}
});
}
// TEST CODE FOR GETTING APPLICATION MULTIPLE SCORE
private static void getApplicationMultipleScores(Credentials credentials, String applicationId) {
LenddoScoreApi lenddoapi = new LenddoScoreApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
// Set this to true to see debug messages during debug build.
lenddoapi.debugMode(true);
lenddoapi.getApplicationMultipleScores(applicationId, new LenddoApiCallback<ApplicationMultipleScores>() {
@Override
public void onResponse(ApplicationMultipleScores applicationMultipleScores) {
System.out.println("Result:\n"+ ApiUtils.convertObjectToPrettyJsonString(applicationMultipleScores));
System.out.println("XML Result:\n"+ ApiUtils.convertObjectToXML(applicationMultipleScores));
}
@Override
public void onFailure(Throwable throwable) {
System.out.println("Network Connection Failed: "+ throwable.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+ errormessage);
}
});
}
// TEST CODE FOR GETTING APPLICATION VERIFICATION
private static void getApplicationVerification(Credentials credentials, String applicationId) {
LenddoScoreApi lenddoapi = new LenddoScoreApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
// Set this to true to see debug messages during debug build.
lenddoapi.debugMode(true);
lenddoapi.getApplicationVerification(applicationId, new LenddoApiCallback<ApplicationVerification>() {
@Override
public void onResponse(ApplicationVerification response) {
// Sample responses
System.out.println("ApplicationVerification: "+ ApiUtils.convertObjectToJsonString(response));
System.out.println("probes: "+ ApiUtils.convertObjectToJsonString(response.probes));
System.out.println("probe name: "+ response.probes.name);
System.out.println("probe firstname: "+ response.probes.name.get(0));
}
@Override
public void onFailure(Throwable throwable) {
System.out.println("Network Connection Failed: "+ throwable.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+ errormessage);
}
});
}
// TEST CODE FOR GETTING APPLICATION SCORE CARDS
private static void getApplicationScorecards(Credentials credentials, String applicationId) {
LenddoScoreApi lenddoapi = new LenddoScoreApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
// Set this to true to see debug messages during debug build.
lenddoapi.debugMode(true);
lenddoapi.getApplicationScorecards(applicationId, new LenddoApiCallback<ApplicationScorecards>() {
@Override
public void onResponse(ApplicationScorecards applicationScorecards) {
System.out.println("Resulting application score: "+ applicationScorecards.scorecards);
System.out.println("Resulting application flags: "+ applicationScorecards.flags);
}
@Override
public void onFailure(Throwable throwable) {
System.out.println("Network Connection Failed: "+ throwable.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+ errormessage);
}
});
}
// TEST CODE FOR PARTNERTOKEN API
private static void samplePostPartnerToken(final Credentials credentials, final String applicationId, String provider) {
WhiteLabelApi whiteLabelApi = new WhiteLabelApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
WhitelabelRequestBody.WLPartnerTokenRqBody.token_data td = new WhitelabelRequestBody.WLPartnerTokenRqBody.token_data();
// add a token in the td.key and a secret in td.secret
td.key = "ACCESS TOKEN FROM YOUR CHOSEN PROVIDER";
// td.secret = "SECRET FROM YOUR CHOSEN PROVIDER (IF APPLICABLE)";
whiteLabelApi.postPartnerToken(applicationId, provider, td, new LenddoApiCallback<PartnerToken>() {
@Override
public void onResponse(PartnerToken response) {
System.out.println("response="+ response.profile_id);
// get the profile ids from the response and use postCommitPartnerJob() to send the profile ids.
samplePostCommitPartnerJob(credentials, applicationId, response.profile_id);
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
// TEST CODE FOR COMMITPARTNERJOB API
private static void samplePostCommitPartnerJob(Credentials credentials, String applicationId, String profileId) {
WhiteLabelApi whiteLabelApi = new WhiteLabelApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
JsonArray profile_ids = new JsonArray();
profile_ids.add(profileId);
Verification verification = new Verification();
// at this point, you need to add details for the verification object. (name, employer, etc).
verification.name.first="firstname";
verification.name.last="lastname";
JsonObject partner_data = new JsonObject();
partner_data.addProperty("sample_partner_data_1", 1);
partner_data.addProperty("sample_partner_data_2", "This is a string data");
partner_data.addProperty("sample_partner_data_3", true);
whiteLabelApi.postCommitPartnerJob(applicationId, profile_ids, verification, partner_data, new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response="+ ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
private static void samplePostCommitPartnerJobWithProxy(Credentials credentials,
String applicationId,
String profileId,
Proxy proxy) {
WhiteLabelApi whiteLabelApi = new WhiteLabelApi(
credentials.api_key,
credentials.api_secret,
credentials.partner_script_id,
proxy);
JsonArray profile_ids = new JsonArray();
profile_ids.add(profileId);
Verification verification = new Verification();
// at this point, you need to add details for the verification object. (name, employer, etc).
verification.name.first="firstname";
verification.name.last="lastname";
JsonObject partner_data = new JsonObject();
partner_data.addProperty("sample_partner_data_1", 1);
partner_data.addProperty("sample_partner_data_2", "This is a string data");
partner_data.addProperty("sample_partner_data_3", true);
whiteLabelApi.postCommitPartnerJob(applicationId, profile_ids, verification, partner_data, new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response="+ ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
// TEST CODE FOR SEND EXTRA PARTNER DATA
private static void samplePostExtraPartnerData(Credentials credentials, String applicationId, JsonObject extraData) {
NetworkApi networkApi = new NetworkApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id);
NetworkApi.debugMode(true);
networkApi.postExtraApplicationData(applicationId, extraData, new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response="+ ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
// TEST CODE FOR APPLICATIONS
private static void sampleGetApplications(Credentials credentials, String privateKey) {
LenddoApplicationApi lenddoApplicationApi = new LenddoApplicationApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id, privateKey);
LenddoApplicationApi.debugMode(true);
lenddoApplicationApi.getApplications(credentials.partner_script_id, new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response=" + ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
private static void sampleGetApplicationsWithFilter(Credentials credentials,
String privateKey,
double pageSize,
double pageNumber,
String startDate,
String endDate) {
LenddoApplicationApi lenddoApplicationApi = new LenddoApplicationApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id, privateKey);
LenddoApplicationApi.debugMode(true);
lenddoApplicationApi.getApplicationsWithFilter(
credentials.partner_script_id,
pageSize,
pageNumber,
startDate,
endDate,
new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response=" + ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
private static void sampleGetApplicationDetails(Credentials credentials, String privateKey, String applicationId) {
LenddoApplicationApi lenddoApplicationApi = new LenddoApplicationApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id, privateKey);
LenddoApplicationApi.debugMode(true);
lenddoApplicationApi.getApplicationDetails(credentials.partner_script_id, applicationId, new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response="+ ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
private static void sampleGetDocumentDetails(Credentials credentials, String privateKey, String applicationId, String documentId) {
LenddoApplicationApi lenddoApplicationApi = new LenddoApplicationApi(credentials.api_key, credentials.api_secret, credentials.partner_script_id, privateKey);
LenddoApplicationApi.debugMode(true);
lenddoApplicationApi.getDocumentDetails(credentials.partner_script_id, applicationId, documentId, new LenddoApiCallback() {
@Override
public void onResponse(Object response) {
System.out.println("response="+ ApiUtils.convertObjectToJsonString(response));
}
@Override
public void onFailure(Throwable t) {
System.out.println("Connection Failure: "+t.getMessage());
}
@Override
public void onError(String errormessage) {
System.out.println("Returned error: "+errormessage);
}
});
}
}
| Lenddo/java-lenddo | Sample/src/com/lenddo/sample/Sample.java | Java | mit | 19,874 |
package com.example.reactnativedocumentpicker;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.reactnativedocumentpicker.DocumentPickerPackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for DocumentPickerExample:
// packages.add(new MyReactNativePackage());
packages.add(new DocumentPickerPackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); // Remove this line if you don't want Flipper enabled
}
/**
* Loads Flipper in React Native templates.
*
* @param context
*/
private static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.reactnativedocumentpickerExample.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
| Elyx0/react-native-document-picker | example/android/app/src/main/java/com/example/reactnativedocumentpicker/MainApplication.java | Java | mit | 2,658 |
/**
* Copyright HZCW (He Zhong Chuang Wei) Technologies Co.,Ltd. 2013-2015. All rights reserved.
*/
package com.weheros.im2.message;
/**
* @ClassName: LogService
* @author Administrator
* @date 2014εΉ΄4ζ2ζ₯ δΈε12:07:16
*/
public class LogService {
public static void debug(Class<?> aclass,String info,Throwable e){
org.apache.log4j.Logger log4 = org.apache.log4j.Logger.getLogger(aclass);
log4.debug(info, e);
}
public static void info(Class<?> aclass,String info,Throwable e){
org.apache.log4j.Logger log4 = org.apache.log4j.Logger.getLogger(aclass);
log4.info(info, e);
}
public static void error(Class<?> aclass,String info,Throwable e){
org.apache.log4j.Logger log4 = org.apache.log4j.Logger.getLogger(aclass);
log4.error(info, e);
}
public static void warn(Class<?> aclass,String info,Throwable e){
org.apache.log4j.Logger log4 = org.apache.log4j.Logger.getLogger(aclass);
log4.warn(info, e);
}
}
| appleseedez/im2-message | src/main/java/com/weheros/im2/message/LogService.java | Java | mit | 1,031 |
package com.maxml.timer.api.interfaces;
import java.util.List;
import com.maxml.timer.entity.Slice;
public interface OnResultList {
public void OnResultSlices(List<Slice> listSlice);
} | maxml/AutoTimeHelper | previous/project/MainProject/src/com/maxml/timer/api/interfaces/OnResultList.java | Java | mit | 190 |
package com.ultraflynn.sygrl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
public class MainTest {
@Test
public void shouldConvertAuthorizationResponse() throws Exception {
String json = "{\"access_token\":\"ZypW9izIh2_MU1dXgzog1Y3SNUL1lP-2AI48tL2j9qu8frZaW4oQujmVyUSAIS1NRyGsrjhkNUNAqN_N3H6mYQ2\",\"token_type\":\"Bearer\",\"expires_in\":1200,\"refresh_token\":\"1TCITXtRxsO2Kf5xAHDiv-LFh3fqt-lGWDP0g_1y8pzZKvGvtiw-3_KXdp5gWF020\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
JsonNode access_token = jsonNode.get("access_type");
}
} | ultraflynn/sygrl | src/test/java/com/ultraflynn/sygrl/MainTest.java | Java | mit | 700 |
//-------------------------------------------------------------------------------------------------------------//
// Code based on a tutorial by Shekhar Gulati of SparkJava at
// https://blog.openshift.com/developing-single-page-web-applications-using-java-8-spark-mongodb-and-angularjs/
//-------------------------------------------------------------------------------------------------------------//
package com.srinivas.dots;
import com.google.gson.Gson;
import spark.Response;
import spark.ResponseTransformer;
import java.util.HashMap;
public class JsonTransformer implements ResponseTransformer {
private Gson gson = new Gson();
@Override
public String render(Object model) {
if (model instanceof Response) {
return gson.toJson(new HashMap<>());
}
return gson.toJson(model);
}
}
| thewickedaxe/600.421-OOSE | src/main/java/com/srinivas/dots/JsonTransformer.java | Java | mit | 844 |
package contagionJVM.Repository;
import contagionJVM.Data.DataContext;
import contagionJVM.Entities.CustomEffectEntity;
import contagionJVM.Entities.PCCustomEffectEntity;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import java.util.List;
public class CustomEffectRepository {
public List<PCCustomEffectEntity> GetPCEffects(String uuid)
{
List<PCCustomEffectEntity> entities;
try(DataContext context = new DataContext())
{
Criteria criteria = context.getSession()
.createCriteria(PCCustomEffectEntity.class)
.add(Restrictions.eq("playerID", uuid));
entities = criteria.list();
}
return entities;
}
public PCCustomEffectEntity GetPCEffectByID(String uuid, int customEffectID)
{
PCCustomEffectEntity entity;
try(DataContext context = new DataContext())
{
Criteria criteria = context.getSession()
.createCriteria(PCCustomEffectEntity.class)
.createAlias("customEffect", "c")
.add(Restrictions.eq("playerID", uuid))
.add(Restrictions.eq("c.customEffectID", customEffectID));
entity = (PCCustomEffectEntity)criteria.uniqueResult();
}
return entity;
}
public CustomEffectEntity GetEffectByID(int customEffectID)
{
CustomEffectEntity entity;
try(DataContext context = new DataContext())
{
Criteria criteria = context.getSession()
.createCriteria(CustomEffectEntity.class)
.add(Restrictions.eq("customEffectID", customEffectID));
entity = (CustomEffectEntity)criteria.uniqueResult();
}
return entity;
}
public void Save(Object entity)
{
try(DataContext context = new DataContext())
{
context.getSession().saveOrUpdate(entity);
}
}
public void Delete(Object entity)
{
try(DataContext context = new DataContext())
{
context.getSession().delete(entity);
}
}
}
| zunath/Contagion_JVM | src/contagionJVM/Repository/CustomEffectRepository.java | Java | mit | 2,181 |
package blog.service;
import org.springframework.data.mongodb.repository.MongoRepository;
import blog.model.Post;
public interface BlogRepository extends MongoRepository<Post, String> {
public Post findByTitle(String title);
} | himanshuy/boot_blog | src/main/java/blog/service/BlogRepository.java | Java | mit | 232 |
// This file is automatically generated.
package adila.db;
/*
* Spice Xlife-441Q
*
* DEVICE: Spice
* MODEL: Xlife-415
*/
final class spice_xlife2d415 {
public static final String DATA = "Spice|Xlife-441Q|";
}
| karim/adila | database/src/main/java/adila/db/spice_xlife2d415.java | Java | mit | 220 |
/*
*
* * Copyright (c) 2019 Alexander GrΓΌn
* *
* * 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.unknownreality.dataframe;
/**
* Created by Alex on 07.07.2016.
*/
public class DataFrameException extends Exception {
public DataFrameException(String message) {
super(message);
}
public DataFrameException(String message, Throwable throwable) {
super(message, throwable);
}
}
| nRo/DataFrame | src/main/java/de/unknownreality/dataframe/DataFrameException.java | Java | mit | 1,507 |
package eu.bcvsolutions.idm.vs.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import eu.bcvsolutions.idm.acc.entity.SysSystem_;
import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto;
import eu.bcvsolutions.idm.core.api.service.AbstractReadWriteDtoService;
import eu.bcvsolutions.idm.core.api.service.IdmIdentityService;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentity_;
import eu.bcvsolutions.idm.core.model.entity.IdmRole_;
import eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType;
import eu.bcvsolutions.idm.vs.dto.VsSystemImplementerDto;
import eu.bcvsolutions.idm.vs.dto.filter.VsSystemImplementerFilter;
import eu.bcvsolutions.idm.vs.entity.VsSystemImplementer;
import eu.bcvsolutions.idm.vs.entity.VsSystemImplementer_;
import eu.bcvsolutions.idm.vs.repository.VsSystemImplementerRepository;
import eu.bcvsolutions.idm.vs.service.api.VsSystemImplementerService;
/**
* Service for relation between system in virtual system and identity
*
* @author Svanda
*
*/
@Service
public class DefaultVsSystemImplementerService
extends AbstractReadWriteDtoService<VsSystemImplementerDto, VsSystemImplementer, VsSystemImplementerFilter>
implements VsSystemImplementerService {
private final IdmIdentityService identityService;
@Autowired
public DefaultVsSystemImplementerService(VsSystemImplementerRepository repository,
IdmIdentityService identityService) {
super(repository);
Assert.notNull(identityService, "Service is required.");
this.identityService = identityService;
}
@Override
protected List<Predicate> toPredicates(Root<VsSystemImplementer> root, CriteriaQuery<?> query,
CriteriaBuilder builder, VsSystemImplementerFilter filter) {
List<Predicate> predicates = super.toPredicates(root, query, builder, filter);
// System ID
if (filter.getSystemId() != null) {
predicates
.add(builder.equal(root.get(VsSystemImplementer_.system).get(SysSystem_.id), filter.getSystemId()));
}
// Identity ID
if (filter.getIdentityId() != null) {
predicates.add(builder.equal(root.get(VsSystemImplementer_.identity).get(IdmIdentity_.id),
filter.getIdentityId()));
}
// Role ID
if (filter.getRoleId() != null) {
predicates.add(builder.equal(root.get(VsSystemImplementer_.role).get(IdmRole_.id),
filter.getRoleId()));
}
return predicates;
}
@Override
public AuthorizableType getAuthorizableType() {
return null;
}
@Override
public List<IdmIdentityDto> findRequestImplementers(UUID vsSystemId) {
return this.findRequestImplementers(vsSystemId, 1000);
}
@Override
public List<IdmIdentityDto> findRequestImplementers(UUID vsSystemId, long limit) {
if (vsSystemId == null) {
return null;
}
VsSystemImplementerFilter filter = new VsSystemImplementerFilter();
filter.setSystemId(vsSystemId);
List<VsSystemImplementerDto> requestImplementers = this.find(filter, null).getContent();
Set<IdmIdentityDto> identities = requestImplementers.stream()//
.filter(sysImp -> sysImp.getIdentity() != null)//
.limit(limit)//
.map(VsSystemImplementerDto::getIdentity)//
.map(identityService::get)//
.collect(Collectors.toSet());
// Add identities from all roles
Set<UUID> roles = requestImplementers.stream()//
.filter(sysImp -> sysImp.getRole() != null)//
.map(VsSystemImplementerDto::getRole)//
.collect(Collectors.toSet());
roles.forEach(role -> {
if (identities.size() < limit) {
List<IdmIdentityDto> identitiesFromRole = identityService
.findValidByRolePage(role, PageRequest.of(0, (int) limit - identities.size())).getContent();
identities.addAll(identitiesFromRole);
}
});
return new ArrayList<>(identities);
}
}
| bcvsolutions/CzechIdMng | Realization/backend/vs/src/main/java/eu/bcvsolutions/idm/vs/service/impl/DefaultVsSystemImplementerService.java | Java | mit | 4,172 |
package org.estonlabs.mongodb.oplog;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import org.bson.*;
import org.slf4j.*;
import com.mongodb.*;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 antlen
*
* 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.
*
*
*
*
* Monitors the oplog of the mongo client and will call back on the listens when events are detected.
*
* <pre>
* {@code
* final MongoClient mongoClient = new MongoClient("localhost" , 3001 );
*
* final OplogMonitor mongo = new OplogMonitor(mongoClient);
*
* mongo.start();
*
* final Namespace namespace = new Namespace( "meteor", "markets" );
*
* //only listen to the insert and delete events.
* mongo.listenToNameSpace(namespace, this, OplogEventType.INSERT, OplogEventType.DELETE);
*
*
* //when finished monitoring call
* mongo.stop();
* }
* </pre>
* @author antlen
*
*/
public class OplogMonitor {
private static final Logger LOGGER = LoggerFactory.getLogger(OplogMonitor.class);
private static final String OPLOG = "oplog.rs";
private static final String LOCAL_DB = "local";
private final MongoClient mongoClient;
private final ListenerCollection listeners = new ListenerCollection();
private OplogTail tail = new OplogTail();
public OplogMonitor(MongoClient cl){
mongoClient = cl;
}
/**
* Starts listening to the oplog on a separate thread.
*
* @throws IllegalStateException - if the monitor is already running.
*/
public synchronized void start() throws IllegalStateException{
if(isRunning()) throw new IllegalStateException("OplogMonitor is already running.");
tail.start();
}
/**
* Stops monitoring.
*/
public synchronized void stop(){
tail.stop();
}
public boolean isRunning(){
return tail.isActive.get();
}
/**
* Listens to all events for the mongo namespace
*
* @param ns
* @param listener
*/
public void listenToNameSpace(Namespace ns, OplogListener listener){
listenToNameSpace(ns, listener, OplogEventType.values());
}
/**
* Listens to events of the specified type for the mongo namespace
*
*
* @param ns
* @param listener
* @param types
*/
public void listenToNameSpace(Namespace ns, OplogListener listener, OplogEventType ... types){
listeners.addListener(listener, ns.getKey(), types);
}
/**
* Removes the listener if it was present.
*
* @param l
* @return
*/
public boolean removeListener(OplogListener l){
return listeners.remove(l);
}
private class OplogTail implements Runnable{
protected final AtomicBoolean isActive = new AtomicBoolean(false);
private Thread runner;
private MongoCursor<Document> cursor;
public void run() {
while(cursor.hasNext() && isActive.get()) { // will block until the next record is added into the oplog
try{
final Document o = cursor.next();
OplogEventType updateType = OplogEventType.getOplogEventType(o.getString("op"));
for(OplogListener ul : listeners.get(o.getString("ns"), updateType)){
final Document doc = (((Document)o.get(updateType.getObjectPropertyId())));
updateType.notify(ul, doc);
}
}
catch(Exception e){
LOGGER.error("Error while polling the oplog", e);
}
}
}
protected void start(){
isActive.set(true);
final MongoCollection<Document> oplog = getOpLog();
cursor = createTail(oplog);
//call run and execute in a new thread
runner = new Thread(this);
runner.start();
}
protected void stop(){
isActive.set(false);
if(runner != null)runner.interrupt();
runner = null;
cursor = null;
}
/**
* sorts by reverse chronological order and restricts to one record.
* @param records
* @return
*/
protected FindIterable<Document> findLastRecord(final FindIterable<Document> records)
{
return records.sort(new BasicDBObject("ts",-1)).limit(1);
}
/**
* Returns the timestamp of the first record in the collection.
*
* @param records
* @return
*/
protected BsonTimestamp getFirstTimestamp(final FindIterable<Document> records)
{
Document first = records.first();
return first==null? null : (BsonTimestamp)first.get("ts");
}
private MongoCursor<Document> createTail(final MongoCollection<Document> oplog)
{
//get the timestamp of the last record in the oplog.
final BsonTimestamp lastEntryTime = getFirstTimestamp(findLastRecord(oplog.find()));
//find all records after the last timestamp.
final FindIterable<Document> resultset = find(oplog, lastEntryTime).noCursorTimeout(true);
resultset.cursorType(CursorType.Tailable); // make sure the iterator is tailable.
return resultset.iterator();
}
private FindIterable<Document> find(final MongoCollection<Document> oplog, final BsonTimestamp lastEntryTime) {
if(lastEntryTime == null){
//this is rare. It means there were no entries in the oplog
LOGGER.info("Tailing all events");
return oplog.find();
}else{
LOGGER.info("Tailing for events after " + lastEntryTime.toString());
return oplog.find(Filters.gt("ts", lastEntryTime));
}
}
private MongoCollection<Document> getOpLog() {
final MongoDatabase local = mongoClient.getDatabase(LOCAL_DB);
return local.getCollection(OPLOG);
}
}
private class ListenerCollection {
private final Iterable<OplogListener> empty = Collections.<OplogListener> emptyList();
private final ConcurrentHashMap<String, Map<OplogEventType,Set<OplogListener>>>listeners = new ConcurrentHashMap<>();
public void addListener(OplogListener listener, String ns, OplogEventType... types) {
final Map<OplogEventType, Set<OplogListener>> m = getListenerMap(ns);
for(OplogEventType t : types){
Collection<OplogListener> l = m.get(t);
l.add(listener);
}
}
public boolean remove(OplogListener l){
boolean removed = false;
for(Map<OplogEventType,Set<OplogListener>> m : listeners.values()){
for(Set<OplogListener> s : m.values()){
removed |= s.remove(l);
}
}
return removed;
}
public Iterable<OplogListener> get(String ns, OplogEventType t){
final Map<OplogEventType,Set<OplogListener>> m = listeners.get(ns);
return m == null ? empty : m.get(t);
}
private Map<OplogEventType, Set<OplogListener>> getListenerMap(String ns) {
final Map<OplogEventType,Set<OplogListener>> m = listeners.get(ns);
if(m == null){
Map<OplogEventType,Set<OplogListener>> newMap = buildEnumMap();
return listeners.putIfAbsent(ns, newMap) == null ? newMap : listeners.get(ns);
}
return m;
}
private Map<OplogEventType, Set<OplogListener>> buildEnumMap() {
final Map<OplogEventType, Set<OplogListener>> m = new EnumMap<>(OplogEventType.class);
for(OplogEventType t : OplogEventType.values()){
m.put(t, new CopyOnWriteArraySet<>());
}
return m;
}
}
}
| antlen/mongo-utils | src/main/java/org/estonlabs/mongodb/oplog/OplogMonitor.java | Java | mit | 8,087 |
/*
The MIT License (MIT)
Copyright (c) 2015, Hans-Georg Becker
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.tu_dortmund.ub.api.daia.ils.model;
import de.tu_dortmund.ub.api.daia.model.Item;
import de.tu_dortmund.ub.api.daia.model.Message;
import java.util.ArrayList;
import java.util.HashMap;
public class Document {
// DAIA parameters
private String id;
private String href;
private ArrayList<Item> item;
private ArrayList<Message> messages;
// more parameter
private String erschform;
private String veroefart;
private String issn;
private HashMap<String,String> url;
private HashMap<String,String> urlbem;
private HashMap<String,String> lokaleurl;
private HashMap<String,String> lokaleurlbem;
private String zdbid;
private String issnwww;
private String issnprint;
private String mediatype;
private String ausgabe;
private String erschjahr;
private String umfang;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public ArrayList<Item> getItem() {
return item;
}
public void setItem(ArrayList<Item> item) {
this.item = item;
}
public ArrayList<Message> getMessages() {
return messages;
}
public void setMessages(ArrayList<Message> messages) {
this.messages = messages;
}
public String getErschform() {
return erschform;
}
public void setErschform(String erschform) {
this.erschform = erschform;
}
public String getVeroefart() {
return veroefart;
}
public void setVeroefart(String veroefart) {
this.veroefart = veroefart;
}
public String getIssn() {
return issn;
}
public void setIssn(String issn) {
this.issn = issn;
}
public HashMap<String,String> getUrl() {
return url;
}
public void setUrl(HashMap<String,String> url) {
this.url = url;
}
public HashMap<String,String> getUrlbem() {
return urlbem;
}
public void setUrlbem(HashMap<String,String> urlbem) {
this.urlbem = urlbem;
}
public HashMap<String,String> getLokaleurl() {
return lokaleurl;
}
public void setLokaleurl(HashMap<String,String> lokaleurl) {
this.lokaleurl = lokaleurl;
}
public HashMap<String,String> getLokaleurlbem() {
return lokaleurlbem;
}
public void setLokaleurlbem(HashMap<String,String> lokaleurlbem) {
this.lokaleurlbem = lokaleurlbem;
}
public String getZdbid() {
return zdbid;
}
public void setZdbid(String zdbid) {
this.zdbid = zdbid;
}
public String getIssnwww() {
return issnwww;
}
public void setIssnwww(String issnwww) {
this.issnwww = issnwww;
}
public String getIssnprint() {
return issnprint;
}
public void setIssnprint(String issnprint) {
this.issnprint = issnprint;
}
public String getMediatype() {
return mediatype;
}
public void setMediatype(String mediatype) {
this.mediatype = mediatype;
}
public String getAusgabe() {
return ausgabe;
}
public void setAusgabe(String ausgabe) {
this.ausgabe = ausgabe;
}
public String getErschjahr() {
return erschjahr;
}
public void setErschjahr(String erschjahr) {
this.erschjahr = erschjahr;
}
public String getUmfang() {
return umfang;
}
public void setUmfang(String umfang) {
this.umfang = umfang;
}
}
| hagbeck/ApiDaiaService | src/main/java/de/tu_dortmund/ub/api/daia/ils/model/Document.java | Java | mit | 4,678 |
package insanityradio.insanityradio;
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);
}
} | dylanmaryk/InsanityRadio-Android | app/src/androidTest/java/insanityradio/insanityradio/ApplicationTest.java | Java | mit | 358 |
package edu.softserve.zoo.exception;
import edu.softserve.zoo.exceptions.ApplicationException;
import edu.softserve.zoo.exceptions.ExceptionReason;
import edu.softserve.zoo.converter.ModelConverter;
/**
* ModelConverterException signals that problem has occurred during working process of {@link ModelConverter}
*
* @author Vadym Holub
*/
public class ModelConverterException extends ApplicationException {
public ModelConverterException(String message, ExceptionReason reason, Throwable cause) {
super(message, reason, cause);
}
public enum Reason implements ExceptionReason {
MAPPING_STRATEGY_NOT_FOUND("reason.web.mapping_strategy_not_found"),
MAPPING_TO_DTO_FAILED("reason.web.mapping_to_dto_failed"),
MAPPING_TO_ENTITY_FAILED("reason.web.mapping_to_entity_failed");
private final String message;
Reason(String message) {
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
}
| ITsvetkoFF/Kv-014 | web/src/main/java/edu/softserve/zoo/exception/ModelConverterException.java | Java | mit | 1,045 |
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.interop;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.gluu.oxauth.BaseTest;
import org.gluu.oxauth.client.AuthorizationRequest;
import org.gluu.oxauth.client.AuthorizationResponse;
import org.gluu.oxauth.client.RegisterClient;
import org.gluu.oxauth.client.RegisterRequest;
import org.gluu.oxauth.client.RegisterResponse;
import org.gluu.oxauth.client.TokenClient;
import org.gluu.oxauth.client.TokenRequest;
import org.gluu.oxauth.client.TokenResponse;
import org.gluu.oxauth.client.UserInfoResponse;
import org.gluu.oxauth.model.common.AuthenticationMethod;
import org.gluu.oxauth.model.common.GrantType;
import org.gluu.oxauth.model.common.ResponseType;
import org.gluu.oxauth.model.jwt.JwtClaimName;
import org.gluu.oxauth.model.register.ApplicationType;
import org.gluu.oxauth.model.util.StringUtils;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
/**
* OC5:FeatureTest-Support scope Requesting profile Claims
*
* @author Javier Rojas Blum
* @version October 14, 2019
*/
public class SupportScopeRequestingProfileClaims extends BaseTest {
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void supportScopeRequestingProfileClaims(
final String userId, final String userSecret, final String redirectUris, final String redirectUri,
final String sectorIdentifierUri) throws Exception {
showTitle("OC5:FeatureTest-Support scope Requesting profile Claims");
List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
// 1. Register client
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
StringUtils.spaceSeparatedToList(redirectUris));
registerRequest.setResponseTypes(responseTypes);
registerRequest.setSectorIdentifierUri(sectorIdentifierUri);
RegisterClient registerClient = newRegisterClient(registerRequest);
RegisterResponse registerResponse = registerClient.exec();
showClient(registerClient);
assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
assertNotNull(registerResponse.getClientId());
assertNotNull(registerResponse.getClientSecret());
assertNotNull(registerResponse.getRegistrationAccessToken());
assertNotNull(registerResponse.getClientIdIssuedAt());
assertNotNull(registerResponse.getClientSecretExpiresAt());
String clientId = registerResponse.getClientId();
String clientSecret = registerResponse.getClientSecret();
// 2. Request authorization
List<String> scopes = Arrays.asList("openid", "profile");
String nonce = UUID.randomUUID().toString();
String state = UUID.randomUUID().toString();
AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
authorizationRequest.setState(state);
AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
authorizationEndpoint, authorizationRequest, userId, userSecret);
assertNotNull(authorizationResponse.getLocation());
assertNotNull(authorizationResponse.getCode());
assertNotNull(authorizationResponse.getState());
String authorizationCode = authorizationResponse.getCode();
// 3. Get Access Token
TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
tokenRequest.setCode(authorizationCode);
tokenRequest.setRedirectUri(redirectUri);
tokenRequest.setAuthUsername(clientId);
tokenRequest.setAuthPassword(clientSecret);
tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
TokenClient tokenClient = newTokenClient(tokenRequest);
TokenResponse tokenResponse = tokenClient.exec();
showClient(tokenClient);
assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
assertNotNull(tokenResponse.getEntity(), "The entity is null");
assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
assertNotNull(tokenResponse.getTokenType(), "The token type is null");
assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
String accessToken = tokenResponse.getAccessToken();
// 4. Request user info
UserInfoResponse userInfoResponse = requestUserInfo(accessToken);
assertEquals(userInfoResponse.getStatus(), 200, "Unexpected response code: " + userInfoResponse.getStatus());
assertNotNull(userInfoResponse.getClaim(JwtClaimName.SUBJECT_IDENTIFIER));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.WEBSITE));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.ZONEINFO));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.BIRTHDATE));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.GENDER));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.PROFILE));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.PREFERRED_USERNAME));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.GIVEN_NAME));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.MIDDLE_NAME));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.LOCALE));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.PICTURE));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.UPDATED_AT));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.NAME));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.NICKNAME));
assertNotNull(userInfoResponse.getClaim(JwtClaimName.FAMILY_NAME));
}
} | GluuFederation/oxAuth | Client/src/test/java/org/gluu/oxauth/interop/SupportScopeRequestingProfileClaims.java | Java | mit | 6,233 |
package fr.insee.eno.test;
import java.io.File;
import javax.xml.transform.stream.StreamSource;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.Diff;
import org.xmlunit.input.CommentLessSource;
/**
* Created by I6VWID on 15/01/18.
*/
public class XMLDiff {
public XMLDiff() {
}
public Diff getDiff(File input, File expected) throws Exception {
System.out.println(String.format("Diff %s with %s", input.getAbsolutePath(), expected.getAbsolutePath()));
CommentLessSource inputStream = null;
CommentLessSource expectedStream = null;
try {
inputStream = new CommentLessSource(new StreamSource(input));
expectedStream = new CommentLessSource(new StreamSource(expected));
return DiffBuilder
.compare(expectedStream)
.withAttributeFilter(attr -> !attr.getName().equals("enoCoreVersion"))
.withTest(inputStream)
.ignoreWhitespace()
.normalizeWhitespace()
.checkForIdentical()
.build();
} catch (Exception e) {
throw e;
}
}
public Diff getDiff(String inputFilePath, String expectedFilePath) throws Exception {
File inputFile = new File(inputFilePath);
File expectedFile = new File(expectedFilePath);
try {
return getDiff(inputFile, expectedFile);
} catch (Exception e) {
throw e;
}
}
}
| InseeFr/Eno | src/test/java/fr/insee/eno/test/XMLDiff.java | Java | mit | 1,550 |
package com.astrofizzbizz.pixie;
/**
* @author mcginnis
*
*/
public class PixieImageFilters
{
private static int skeletonPass(PixieImage image, double dthreshold)
{
int ii;
int ij;
int ik;
PixieImage tempImage = new PixieImage(image);
double[][] doutpix = null;
double[][] dimage = null;
int inum_pixel_cut;
int[] ipix = new int[11];
int isum;
int istep;
Pixie pmax = new Pixie();
dimage = image.getPix();
doutpix = tempImage.getPix();
pmax.setRow(image.getRowCount());
pmax.setCol(image.getColCount());
inum_pixel_cut = 0;
for (ii = 0; ii < pmax.getRow(); ii++)
{
for (ij = 0; ij < pmax.getCol(); ij++)
{
if (dimage[ii][ij] < dthreshold)
{
dimage[ii][ij] = 0.0;
doutpix[ii][ij] = 0.0;
}
}
}
for (ii = 1; ii < pmax.getRow() - 1; ii++)
{
for (ij = 1; ij < pmax.getCol() - 1; ij++)
{
if (dimage[ii][ij] >= dthreshold)
{
for (ik = 0; ik <= 10; ik++) ipix[ik] = 0;
if (dimage[ii][ij] >= dthreshold) ipix[1] = 1;
if (dimage[ii - 1][ij] >= dthreshold) ipix[2] = 1;
if (dimage[ii - 1][ij + 1] >= dthreshold) ipix[3] = 1;
if (dimage[ii][ij + 1] >= dthreshold) ipix[4] = 1;
if (dimage[ii + 1][ij + 1] >= dthreshold) ipix[5] = 1;
if (dimage[ii + 1][ij] >= dthreshold) ipix[6] = 1;
if (dimage[ii + 1][ij - 1] >= dthreshold) ipix[7] = 1;
if (dimage[ii][ij - 1] >= dthreshold) ipix[8] = 1;
if (dimage[ii - 1][ij - 1] >= dthreshold) ipix[9] = 1;
if (dimage[ii - 1][ij] >= dthreshold) ipix[10] = 1;
isum = 0;
for (ik = 2; ik <= 9; ik++) isum = isum + ipix[ik];
if ((2 <= isum) && (isum <= 6))
{
istep = 0;
for (ik = 2; ik <= 9; ik++)
{
if ((ipix[ik] == 0) && (ipix[ik + 1] == 1))
istep = istep + 1;
}
if (istep == 1)
{
if ((ipix[2] * ipix[4] * ipix[6]) == 0)
{
if ((ipix[4] * ipix[6] * ipix[8]) == 0)
{
doutpix[ii][ij] = 0.0;
inum_pixel_cut = inum_pixel_cut + 1;
}
}
}
}
}
}
}
for (ii = 0; ii < pmax.getRow(); ii++)
{
for (ij = 0; ij < pmax.getCol(); ij++)
{
dimage[ii][ij] = doutpix[ii][ij];
}
}
for (ii = 1; ii < pmax.getRow() - 1; ii++)
{
for (ij = 1; ij < pmax.getCol() - 1; ij++)
{
if (doutpix[ii][ij] >= dthreshold)
{
for (ik = 0; ik <= 10; ik++) ipix[ik] = 0;
if (doutpix[ii][ij] >= dthreshold) ipix[1] = 1;
if (doutpix[ii - 1][ij] >= dthreshold) ipix[2] = 1;
if (doutpix[ii - 1][ij + 1] >= dthreshold) ipix[3] = 1;
if (doutpix[ii][ij + 1] >= dthreshold) ipix[4] = 1;
if (doutpix[ii + 1][ij + 1] >= dthreshold) ipix[5] = 1;
if (doutpix[ii + 1][ij] >= dthreshold) ipix[6] = 1;
if (doutpix[ii + 1][ij - 1] >= dthreshold) ipix[7] = 1;
if (doutpix[ii][ij - 1] >= dthreshold) ipix[8] = 1;
if (doutpix[ii - 1][ij - 1] >= dthreshold) ipix[9] = 1;
if (doutpix[ii - 1][ij] >= dthreshold) ipix[10] = 1;
isum = 0;
for (ik = 2; ik <= 9; ik++) isum = isum + ipix[ik];
if ((2 <= isum) && (isum <= 6))
{
istep = 0;
for (ik = 2; ik <= 9; ik++)
{
if ((ipix[ik] == 0) && (ipix[ik + 1] == 1))
istep = istep + 1;
}
if (istep == 1)
{
if ((ipix[2] * ipix[4] * ipix[8]) == 0)
{
if ((ipix[2] * ipix[6] * ipix[8]) == 0)
{
dimage[ii][ij] = 0.0;
inum_pixel_cut = inum_pixel_cut + 1;
}
}
}
}
}
}
}
tempImage = null;
return inum_pixel_cut;
}
/**
* @param inputImage
* @param dthreshold
* @return PixieImage
*/
public static PixieImage skeletonFilter(PixieImage inputImage, double dthreshold)
{
PixieImage outputImage = new PixieImage(inputImage);
int inum_pixel_cut = 1;
while (inum_pixel_cut > 0)
{
inum_pixel_cut = skeletonPass(outputImage, dthreshold);
}
return outputImage;
}
} | mcnowinski/various-and-sundry | astroimage/Pixie/src/com/astrofizzbizz/pixie/PixieImageFilters.java | Java | mit | 4,017 |
package ru.bartwell.exfilepickersample;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("ru.bartwell.exfilepickersample", appContext.getPackageName());
}
}
| bartwell/ExFilePicker | sample/src/androidTest/java/ru/bartwell/exfilepickersample/ExampleInstrumentedTest.java | Java | mit | 764 |
package xdb.query;
import org.w3c.dom.Element;
import xdb.control.Query;
/**
* Class for initializing queries from their configuration.
*/
public final class QueryInit {
private QueryInit() {
}
/**
* Init the query from its configuration.
*
* @param configElement
* The configuration element.
* @param fileName
* The file name.
* @return The query.
*/
public static Query init(Element configElement, String fileName) {
if ("xpath-query".equals(configElement.getNodeName())) {
return XPathQuery.init(configElement);
} else if ("multi-id-query".equals(configElement.getNodeName())) {
return MultiIdQuery.init(configElement);
} else if ("multi-key-query".equals(configElement.getNodeName())) {
return MultiKeyQuery.init(configElement);
} else if ("whole-doc-query".equals(configElement.getNodeName())) {
return WholeDocQuery.init(configElement);
} else {
String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName();
throw new IllegalStateException(msg);
}
}
}
| pfstrack/eldamo | src/main/java/xdb/query/QueryInit.java | Java | mit | 1,189 |
/**
* NullConnectionConstantProvidedException.java
*
* @author Andrew Koerner
* @version 1.0
*/
package cashier.exceptions.connection;
public class NullConnectionConstantProvidedException extends Exception {
private static final long serialVersionUID = -1406826280511132882L;
private String message;
public NullConnectionConstantProvidedException(String rootUrl, String apiKey, String apiSecret, String token){
super();
String message = "Null connection constant provided conneciton constants must not be null. Please provide" +
"not null values for the following constants: ";
if(rootUrl == null){
message += "rootUrl ";
}
if(apiKey == null){
message += "apiKey ";
}
if(apiSecret == null){
message += "apiSecret ";
}
if(token == null){
message += "token";
}
this.message = message;
}
public String getMessage() {
return message;
}
}
| akoerner/cashier.java | src/cashier/exceptions/connection/NullConnectionConstantProvidedException.java | Java | mit | 895 |
/*
* The MIT License
*
* Copyright (c) 2017 The Things Network
*
* 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.thethingsnetwork.account.common;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Collections;
import java.util.List;
/**
*
* @author Romain Cambier
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Collaborator {
private String username;
private String email;
private List<String> rights;
/**
* Create an empty Collaborator. Used only by jackson
*/
public Collaborator() {
}
/**
* Create a new Collaborator
*
* @param _username The username of the Collaborator
* @param _rights The rights of the Collaborator
*/
public Collaborator(String _username, List<String> _rights) {
username = _username;
email = null;
rights = _rights;
}
/**
* Get the username
*
* @return The username
*/
public String getUsername() {
return username;
}
/**
* Get the email address
*
* @return The email address
*/
public String getEmail() {
return email;
}
/**
* Get the rights
*
* @return The rights
*/
public List<String> getRights() {
return Collections.unmodifiableList(rights);
}
}
| TheThingsNetwork/java-app-sdk | account/src/main/java/org/thethingsnetwork/account/common/Collaborator.java | Java | mit | 2,389 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_05_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2020_05_01.implementation.NetworkManager;
import com.microsoft.azure.management.network.v2020_05_01.implementation.ApplicationGatewaySslPredefinedPolicyInner;
import java.util.List;
/**
* Type representing ApplicationGatewaySslPredefinedPolicy.
*/
public interface ApplicationGatewaySslPredefinedPolicy extends HasInner<ApplicationGatewaySslPredefinedPolicyInner>, HasManager<NetworkManager> {
/**
* @return the cipherSuites value.
*/
List<ApplicationGatewaySslCipherSuite> cipherSuites();
/**
* @return the id value.
*/
String id();
/**
* @return the minProtocolVersion value.
*/
ApplicationGatewaySslProtocol minProtocolVersion();
/**
* @return the name value.
*/
String name();
}
| selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2020_05_01/src/main/java/com/microsoft/azure/management/network/v2020_05_01/ApplicationGatewaySslPredefinedPolicy.java | Java | mit | 1,209 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.deploymentmanager.v2019_11_01_preview.implementation;
import com.microsoft.azure.management.deploymentmanager.v2019_11_01_preview.ServiceUnitResource;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import java.util.Map;
import com.microsoft.azure.management.deploymentmanager.v2019_11_01_preview.DeploymentMode;
import com.microsoft.azure.management.deploymentmanager.v2019_11_01_preview.ServiceUnitArtifacts;
class ServiceUnitResourceImpl extends CreatableUpdatableImpl<ServiceUnitResource, ServiceUnitResourceInner, ServiceUnitResourceImpl> implements ServiceUnitResource, ServiceUnitResource.Definition, ServiceUnitResource.Update {
private final DeploymentManagerManager manager;
private String resourceGroupName;
private String serviceTopologyName;
private String serviceName;
private String serviceUnitName;
ServiceUnitResourceImpl(String name, DeploymentManagerManager manager) {
super(name, new ServiceUnitResourceInner());
this.manager = manager;
// Set resource name
this.serviceUnitName = name;
//
}
ServiceUnitResourceImpl(ServiceUnitResourceInner inner, DeploymentManagerManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.serviceUnitName = inner.name();
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.serviceTopologyName = IdParsingUtils.getValueFromIdByName(inner.id(), "serviceTopologies");
this.serviceName = IdParsingUtils.getValueFromIdByName(inner.id(), "services");
this.serviceUnitName = IdParsingUtils.getValueFromIdByName(inner.id(), "serviceUnits");
//
}
@Override
public DeploymentManagerManager manager() {
return this.manager;
}
@Override
public Observable<ServiceUnitResource> createResourceAsync() {
ServiceUnitsInner client = this.manager().inner().serviceUnits();
return client.createOrUpdateAsync(this.resourceGroupName, this.serviceTopologyName, this.serviceName, this.serviceUnitName, this.inner())
.map(innerToFluentMap(this));
}
@Override
public Observable<ServiceUnitResource> updateResourceAsync() {
ServiceUnitsInner client = this.manager().inner().serviceUnits();
return client.createOrUpdateAsync(this.resourceGroupName, this.serviceTopologyName, this.serviceName, this.serviceUnitName, this.inner())
.map(innerToFluentMap(this));
}
@Override
protected Observable<ServiceUnitResourceInner> getInnerAsync() {
ServiceUnitsInner client = this.manager().inner().serviceUnits();
return client.getAsync(this.resourceGroupName, this.serviceTopologyName, this.serviceName, this.serviceUnitName);
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
@Override
public ServiceUnitArtifacts artifacts() {
return this.inner().artifacts();
}
@Override
public DeploymentMode deploymentMode() {
return this.inner().deploymentMode();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String location() {
return this.inner().location();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public Map<String, String> tags() {
return this.inner().getTags();
}
@Override
public String targetResourceGroup() {
return this.inner().targetResourceGroup();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public ServiceUnitResourceImpl withExistingService(String resourceGroupName, String serviceTopologyName, String serviceName) {
this.resourceGroupName = resourceGroupName;
this.serviceTopologyName = serviceTopologyName;
this.serviceName = serviceName;
return this;
}
@Override
public ServiceUnitResourceImpl withDeploymentMode(DeploymentMode deploymentMode) {
this.inner().withDeploymentMode(deploymentMode);
return this;
}
@Override
public ServiceUnitResourceImpl withLocation(String location) {
this.inner().withLocation(location);
return this;
}
@Override
public ServiceUnitResourceImpl withTargetResourceGroup(String targetResourceGroup) {
this.inner().withTargetResourceGroup(targetResourceGroup);
return this;
}
@Override
public ServiceUnitResourceImpl withArtifacts(ServiceUnitArtifacts artifacts) {
this.inner().withArtifacts(artifacts);
return this;
}
@Override
public ServiceUnitResourceImpl withTags(Map<String, String> tags) {
this.inner().withTags(tags);
return this;
}
}
| selvasingh/azure-sdk-for-java | sdk/deploymentmanager/mgmt-v2019_11_01_preview/src/main/java/com/microsoft/azure/management/deploymentmanager/v2019_11_01_preview/implementation/ServiceUnitResourceImpl.java | Java | mit | 5,252 |
package com.msci.carrental.client.application;
import com.msci.carrental.client.gui.implementation.ConsoleWindow;
import com.msci.carrental.client.interpreter.CommandInterpreter;
/**
* Main application
*/
public class Application {
private ConsoleWindow consoleWindow;
public Application() {
super();
consoleWindow = new ConsoleWindow();
CommandInterpreter.registerCommandInterpreter(consoleWindow);
}
private void run() {
consoleWindow.runMainLoop();
}
public static void main(String[] args) {
Application application = new Application();
application.run();
}
}
| nemethakos/car-rental | car-rental/src/main/java/com/msci/carrental/client/application/Application.java | Java | mit | 627 |
package com.github.ryjen.kata.graph.exceptions;
/**
* Created by ryan on 2017-04-01.
*/
public class GraphCyclicException extends Exception {
private static final String CYCLIC = "Graph is cyclic";
private static final String ACYCLIC = "Graph is acyclic";
public GraphCyclicException() {
this(true);
}
public GraphCyclicException(Throwable throwable) {
this(true, throwable);
}
public GraphCyclicException(boolean value) {
super(value ? CYCLIC : ACYCLIC);
}
public GraphCyclicException(boolean value, Throwable throwable) {
super(value ? CYCLIC : ACYCLIC, throwable);
}
}
| ryjen/kata | java/src/main/java/com/github/ryjen/kata/graph/exceptions/GraphCyclicException.java | Java | mit | 652 |
/*
Copyright (c) 2013 AWARE Mobile Context Instrumentation Middleware/Framework
http://www.awareframework.com
AWARE is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your option) any later version (GPLv3+).
AWARE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details: http://www.gnu.org/licenses/gpl.html
*/
package com.aware;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import com.aware.providers.Gyroscope_Provider;
import com.aware.providers.Gyroscope_Provider.Gyroscope_Data;
import com.aware.providers.Gyroscope_Provider.Gyroscope_Sensor;
import com.aware.utils.Aware_Sensor;
/**
* Service that logs gyroscope readings from the device
* @author df
*
*/
public class Gyroscope extends Aware_Sensor implements SensorEventListener {
/**
* Logging tag (default = "AWARE::Gyroscope")
*/
private static String TAG = "AWARE::Gyroscope";
/**
* Sensor update frequency ( default = {@link SensorManager#SENSOR_DELAY_NORMAL})
*/
private static int SENSOR_DELAY = 200000;
private static SensorManager mSensorManager;
private static Sensor mGyroscope;
private static HandlerThread sensorThread = null;
private static Handler sensorHandler = null;
private static PowerManager powerManager = null;
private static PowerManager.WakeLock wakeLock = null;
/**
* Broadcasted event: new gyroscope values
* ContentProvider: Gyroscope_Provider
*/
public static final String ACTION_AWARE_GYROSCOPE = "ACTION_AWARE_GYROSCOPE";
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//we log accuracy on the sensor changed values
}
@Override
public void onSensorChanged(SensorEvent event) {
ContentValues rowData = new ContentValues();
rowData.put(Gyroscope_Data.DEVICE_ID, Aware.getSetting(getContentResolver(),Aware_Preferences.DEVICE_ID));
rowData.put(Gyroscope_Data.TIMESTAMP, System.currentTimeMillis());
rowData.put(Gyroscope_Data.VALUES_0, event.values[0]);
rowData.put(Gyroscope_Data.VALUES_1, event.values[1]);
rowData.put(Gyroscope_Data.VALUES_2, event.values[2]);
rowData.put(Gyroscope_Data.ACCURACY, event.accuracy);
try {
getContentResolver().insert(Gyroscope_Data.CONTENT_URI, rowData);
Intent gyroData = new Intent(ACTION_AWARE_GYROSCOPE);
sendBroadcast(gyroData);
if( Aware.DEBUG ) Log.d(TAG, "Gyroscope:"+ rowData.toString());
}catch( SQLiteException e ) {
if(Aware.DEBUG) Log.d(TAG,e.getMessage());
}catch( SQLException e ) {
if(Aware.DEBUG) Log.d(TAG,e.getMessage());
}
}
private void saveGyroscopeDevice(Sensor gyro) {
Cursor gyroInfo = getContentResolver().query(Gyroscope_Sensor.CONTENT_URI, null, null, null, null);
if( gyroInfo == null || ! gyroInfo.moveToFirst() ) {
ContentValues rowData = new ContentValues();
rowData.put(Gyroscope_Sensor.DEVICE_ID, Aware.getSetting(getContentResolver(),Aware_Preferences.DEVICE_ID));
rowData.put(Gyroscope_Sensor.TIMESTAMP, System.currentTimeMillis());
rowData.put(Gyroscope_Sensor.MAXIMUM_RANGE, gyro.getMaximumRange());
rowData.put(Gyroscope_Sensor.MINIMUM_DELAY, gyro.getMinDelay());
rowData.put(Gyroscope_Sensor.NAME, gyro.getName());
rowData.put(Gyroscope_Sensor.POWER_MA, gyro.getPower());
rowData.put(Gyroscope_Sensor.RESOLUTION, gyro.getResolution());
rowData.put(Gyroscope_Sensor.TYPE, gyro.getType());
rowData.put(Gyroscope_Sensor.VENDOR, gyro.getVendor());
rowData.put(Gyroscope_Sensor.VERSION, gyro.getVersion());
try {
getContentResolver().insert(Gyroscope_Sensor.CONTENT_URI, rowData);
if( Aware.DEBUG ) Log.d(TAG, "Gyroscope info: "+ rowData.toString());
}catch( SQLiteException e ) {
if(Aware.DEBUG) Log.d(TAG,e.getMessage());
}catch( SQLException e ) {
if(Aware.DEBUG) Log.d(TAG,e.getMessage());
}
} else gyroInfo.close();
}
@Override
public void onCreate() {
super.onCreate();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if(mGyroscope == null) {
if(Aware.DEBUG) Log.w(TAG,"This device does not have a gyroscope!");
stopSelf();
}
TAG = Aware.getSetting(getContentResolver(),Aware_Preferences.DEBUG_TAG).length()>0?Aware.getSetting(getContentResolver(), Aware_Preferences.DEBUG_TAG):TAG;
try {
SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(), Aware_Preferences.FREQUENCY_GYROSCOPE));
}catch(NumberFormatException e) {
Aware.setSetting(getContentResolver(), Aware_Preferences.FREQUENCY_GYROSCOPE, 200000);
SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(), Aware_Preferences.FREQUENCY_GYROSCOPE));
}
sensorThread = new HandlerThread(TAG);
sensorThread.start();
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.acquire();
sensorHandler = new Handler(sensorThread.getLooper());
mSensorManager.registerListener(this, mGyroscope, SENSOR_DELAY, sensorHandler);
saveGyroscopeDevice(mGyroscope);
DATABASE_TABLES = Gyroscope_Provider.DATABASE_TABLES;
TABLES_FIELDS = Gyroscope_Provider.TABLES_FIELDS;
CONTEXT_URIS = new Uri[]{ Gyroscope_Sensor.CONTENT_URI, Gyroscope_Data.CONTENT_URI };
if(Aware.DEBUG) Log.d(TAG,"Gyroscope service created!");
}
@Override
public void onDestroy() {
super.onDestroy();
sensorHandler.removeCallbacksAndMessages(null);
mSensorManager.unregisterListener(this, mGyroscope);
sensorThread.quit();
wakeLock.release();
if(Aware.DEBUG) Log.d(TAG,"Gyroscope service terminated...");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
TAG = Aware.getSetting(getContentResolver(),Aware_Preferences.DEBUG_TAG).length()>0?Aware.getSetting(getContentResolver(), Aware_Preferences.DEBUG_TAG):TAG;
try {
SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(), Aware_Preferences.FREQUENCY_GYROSCOPE));
}catch(NumberFormatException e) {
Aware.setSetting(getContentResolver(), Aware_Preferences.FREQUENCY_GYROSCOPE, 200000);
SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(), Aware_Preferences.FREQUENCY_GYROSCOPE));
}
if(intent.getBooleanExtra("refresh", false)) {
sensorHandler.removeCallbacksAndMessages(null);
mSensorManager.unregisterListener(this, mGyroscope);
mSensorManager.registerListener(this, mGyroscope, SENSOR_DELAY, sensorHandler);
}
if(Aware.DEBUG) Log.d(TAG,"Gyroscope service active...");
return START_STICKY;
}
//Singleton instance of this service
private static Gyroscope gyroSrv = Gyroscope.getService();
/**
* Get singleton instance to Gyroscope service
* @return Gyroscope obj
*/
public static Gyroscope getService() {
if( gyroSrv == null ) gyroSrv = new Gyroscope();
return gyroSrv;
}
private final IBinder serviceBinder = new ServiceBinder();
public class ServiceBinder extends Binder {
Gyroscope getService() {
return Gyroscope.getService();
}
}
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
} | EEXCESS/android-app | Frameworks/aware_framework_v2/src/com/aware/Gyroscope.java | Java | mit | 8,885 |
package io.github.joseerodrigues.utils.properties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import io.github.joseerodrigues.utils.Checks;
/**
* ObtΓ©m ResourceBundles que permitam interpolaΓ§Γ£o de propriedades (props a referenciar props)
*
* @see InterpolationResourceBundle
* @author 92429
*/
public final class ResourceBundles {
private ResourceBundles(){
throw new IllegalAccessError();
}
public static ResourceBundle fromFile(String baseName){
Checks.checkNullOrEmpty(baseName, "baseName");
return new InterpolationResourceBundle(ResourceBundle.getBundle(baseName));
}
/**
* Agrega ResourceBundles, e permite interpolaΓ§Γ£o de propriedades entre eles.
*
* Ex:
*
* ResourceBundle sgdBundle = ResourceBundles.fromFile("sgd");
* ResourceBundle tabelasBundle = ResourceBundles.fromDB(conn, "TABELAS");
*
* ResourceBundle bundle = ResourceBundles.fromMultiple(sgdBundle, tabelasBundle);
*
*
* Ao obter o valor de uma propriedade, a ordem de pesquisa nos ResourceBundles Γ© a especificada
* no argumento. No exemplo acima, primeiro seria tentado o sgdBundle, e sΓ³ depois o tabelasBundle.
*
* Se a propriedade nΓ£o for encontrada em nenhum deles, entΓ£o mantΓ©m-se o contracto do ResourceBundle e
* οΏ½ emitida uma MissingResourceException.
*
*
* @param bundles Lista de bundles a pesquisar, por ordem.
* @return Um ResourceBundle que obtem os dados de vΓ‘rios ResourceBundles
* @author 92429
*/
public static ResourceBundle fromMultiple(ResourceBundle ... bundles){
Checks.checkNull(bundles, "bundles");
List<ResourceBundle> filteredBundles = filterNotNull(Arrays.asList(bundles));
return new InterpolationResourceBundle(new CompoundResourceBundle(filteredBundles));
}
private static List<ResourceBundle> filterNotNull(List<ResourceBundle> list) {
ArrayList<ResourceBundle> ret = new ArrayList<>(list.size());
for (ResourceBundle rb : list) {
if (rb != null) {
ret.add(rb);
}
}
return ret;
}
}
| joseerodrigues/db_utils | src/main/java/io/github/joseerodrigues/utils/properties/ResourceBundles.java | Java | mit | 2,059 |
package client.widgets.dashboard;
import client.widgets.graph.GraphWidget;
import client.widgets.tasks.TasksWidget;
import client.widgets.toolbar.ToolbarWidget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;
import shared.User;
/**
* Created by dmitry on 27.04.15.
*/
public class DashboardWidget extends Composite {
@UiField
FlowPanel panel;
interface DashboardUiBinder extends UiBinder<Widget, DashboardWidget>{
}
public static DashboardUiBinder uiBinder = GWT.create(DashboardUiBinder.class);
public DashboardWidget(SimpleEventBus eventBus, User user) {
initWidget(uiBinder.createAndBindUi(this));
panel.add(new ToolbarWidget(eventBus, user));
panel.add(new TasksWidget(eventBus));
panel.add(new GraphWidget(eventBus));
}
}
| DmitryDorofeev/TM | src/client/widgets/dashboard/DashboardWidget.java | Java | mit | 973 |
package com.edwinanaya.t_shirtime;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TipoDeRopa extends Activity {
TextView item;
Button camiseta,pantalon, accesorios, camisas, interior, shorts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tipo_de_ropa);
camiseta=(Button)findViewById(R.id.button2);
pantalon=(Button)findViewById(R.id.button3);
accesorios=(Button)findViewById(R.id.button4);
camisas=(Button)findViewById(R.id.button5);
interior=(Button)findViewById(R.id.button6);
item=(TextView)findViewById(R.id.textView2);
shorts=(Button)findViewById(R.id.button7);
accesorios.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasarView();
//item.setText("");
}
});
camisas.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasarView();
//item.setText("");
}
});
camiseta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasarView();
// item.setText("");
}
});
pantalon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasarView();
// item.setText("");
}
} );
accesorios.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasarView();
//item.setText("");
}
});
interior.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PasarView();
// item.setText("");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tipo_de_ropa, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
void PasarView(){
Intent next= new Intent(TipoDeRopa.this,MostrarActivity.class);
startActivity(next);
}
}
| Edwik/CartagenaCapacitate2015 | T-shirtime/app/src/main/java/com/edwinanaya/t_shirtime/TipoDeRopa.java | Java | mit | 3,150 |
package de.fau.cs.mad.yasme.android.asyncTasks.server;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import java.io.IOException;
import de.fau.cs.mad.yasme.android.connection.UserTask;
import de.fau.cs.mad.yasme.android.controller.FragmentObservable;
import de.fau.cs.mad.yasme.android.controller.Log;
import de.fau.cs.mad.yasme.android.controller.ObservableRegistry;
import de.fau.cs.mad.yasme.android.controller.SpinnerObservable;
import de.fau.cs.mad.yasme.android.entities.User;
import de.fau.cs.mad.yasme.android.exception.RestServiceException;
import de.fau.cs.mad.yasme.android.storage.DatabaseManager;
import de.fau.cs.mad.yasme.android.storage.PictureManager;
import de.fau.cs.mad.yasme.android.ui.AbstractYasmeActivity;
import de.fau.cs.mad.yasme.android.ui.UserAdapter;
import de.fau.cs.mad.yasme.android.ui.fragments.OwnProfileFragment;
/**
* Created by Benedikt Lorch <[email protected]> on 09.07.14.
*/
public class GetProfilePictureTask extends AsyncTask<Long, Void, Boolean> {
private BitmapDrawable profilePicture;
private Class classToNotify;
private boolean isSelf;
public GetProfilePictureTask(Class classToNotify) {
this.classToNotify = classToNotify;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
SpinnerObservable.getInstance().registerBackgroundTask(this);
}
/**
* @param params 0 is userId
* @return true on success, false on error
*/
@Override
protected Boolean doInBackground(Long... params) {
long userId = params[0];
try {
profilePicture = UserTask.getInstance().getProfilePicture(userId);
} catch (RestServiceException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
return false;
}
if (profilePicture == null) {
Log.e(this.getClass().getSimpleName(), "profilePicture was null");
return false;
}
isSelf = (userId == DatabaseManager.INSTANCE.getUserId());
//store the picture
if (isSelf) {
String path;
SharedPreferences.Editor editor = DatabaseManager.INSTANCE.getSharedPreferences().edit();
try {
User self = new User();
self.setId(DatabaseManager.INSTANCE.getUserId());
path = PictureManager.INSTANCE.storePicture(self, profilePicture.getBitmap());
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
return false;
}
editor.putString(AbstractYasmeActivity.PROFILE_PICTURE, path);
editor.apply();
} else {
User user = DatabaseManager.INSTANCE.getUserDAO().get(userId);
if (user == null) {
return false;
}
String path;
try {
path = PictureManager.INSTANCE.storePicture(user, profilePicture.getBitmap());
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
return false;
}
if (path != null && !path.isEmpty()) {
user.setProfilePicture(path);
DatabaseManager.INSTANCE.getUserDAO().update(user);
}
}
return true;
}
@Override
protected void onPostExecute(Boolean success) {
SpinnerObservable.getInstance().removeBackgroundTask(this);
if (success) {
if (classToNotify == null) {
//No one to notify
return;
}
if (classToNotify == UserAdapter.class) {
// Adapter benachrichtigen, dass Bild da ist
return;
}
if (isSelf) {
// Notify registered fragments
FragmentObservable<OwnProfileFragment, Drawable> obs =
ObservableRegistry.getObservable(classToNotify);
obs.notifyFragments(profilePicture);
}
}
}
}
| FAU-Inf2/yasme-android | yasme/src/main/java/de/fau/cs/mad/yasme/android/asyncTasks/server/GetProfilePictureTask.java | Java | mit | 4,215 |
package fi.ni.ifc2x3;
import fi.ni.ifc2x3.interfaces.*;
import fi.ni.*;
import java.util.*;
/*
* IFC Java class
* @author Jyrki Oraskari
* @license This work is licensed under a Creative Commons Attribution 3.0 Unported License.
* http://creativecommons.org/licenses/by/3.0/
*/
public class IfcStructuralReaction extends IfcStructuralActivity
{
// The inverse attributes
InverseLinksList<IfcStructuralAction> causes= new InverseLinksList<IfcStructuralAction>();
// Getters and setters of inverse values
public InverseLinksList<IfcStructuralAction> getCauses() {
return causes;
}
public void setCauses(IfcStructuralAction value){
this.causes.add(value);
}
}
| jyrkio/Open-IFC-to-RDF-converter | IFC_RDF/src/fi/ni/ifc2x3/IfcStructuralReaction.java | Java | mit | 686 |
/*******************************************************************************
* Copyright 2009-2016 Amazon Services. All Rights Reserved.
* 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://aws.amazon.com/apache2.0
* This file 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.
*******************************************************************************
* Get Pallet Labels Request
* API Version: 2010-10-01
* Library Version: 2016-10-05
* Generated: Wed Oct 05 06:15:34 PDT 2016
*/
package com.amazonservices.mws.FulfillmentInboundShipment.model;
import javax.xml.bind.annotation.*;
import com.amazonservices.mws.client.*;
/**
* GetPalletLabelsRequest complex type.
*
* XML schema:
*
* <pre>
* <complexType name="GetPalletLabelsRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="SellerId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="MWSAuthToken" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ShipmentId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="PageType" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="NumberOfPallets" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="GetPalletLabelsRequest", propOrder={
"sellerId",
"mwsAuthToken",
"shipmentId",
"pageType",
"numberOfPallets"
})
@XmlRootElement(name = "GetPalletLabelsRequest")
public class GetPalletLabelsRequest extends AbstractMwsObject {
@XmlElement(name="SellerId",required=true)
private String sellerId;
@XmlElement(name="MWSAuthToken")
private String mwsAuthToken;
@XmlElement(name="ShipmentId",required=true)
private String shipmentId;
@XmlElement(name="PageType",required=true)
private String pageType;
@XmlElement(name="NumberOfPallets",required=true)
private int numberOfPallets;
/**
* Get the value of SellerId.
*
* @return The value of SellerId.
*/
public String getSellerId() {
return sellerId;
}
/**
* Set the value of SellerId.
*
* @param sellerId
* The new value to set.
*/
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
/**
* Check to see if SellerId is set.
*
* @return true if SellerId is set.
*/
public boolean isSetSellerId() {
return sellerId != null;
}
/**
* Set the value of SellerId, return this.
*
* @param sellerId
* The new value to set.
*
* @return This instance.
*/
public GetPalletLabelsRequest withSellerId(String sellerId) {
this.sellerId = sellerId;
return this;
}
/**
* Get the value of MWSAuthToken.
*
* @return The value of MWSAuthToken.
*/
public String getMWSAuthToken() {
return mwsAuthToken;
}
/**
* Set the value of MWSAuthToken.
*
* @param mwsAuthToken
* The new value to set.
*/
public void setMWSAuthToken(String mwsAuthToken) {
this.mwsAuthToken = mwsAuthToken;
}
/**
* Check to see if MWSAuthToken is set.
*
* @return true if MWSAuthToken is set.
*/
public boolean isSetMWSAuthToken() {
return mwsAuthToken != null;
}
/**
* Set the value of MWSAuthToken, return this.
*
* @param mwsAuthToken
* The new value to set.
*
* @return This instance.
*/
public GetPalletLabelsRequest withMWSAuthToken(String mwsAuthToken) {
this.mwsAuthToken = mwsAuthToken;
return this;
}
/**
* Get the value of ShipmentId.
*
* @return The value of ShipmentId.
*/
public String getShipmentId() {
return shipmentId;
}
/**
* Set the value of ShipmentId.
*
* @param shipmentId
* The new value to set.
*/
public void setShipmentId(String shipmentId) {
this.shipmentId = shipmentId;
}
/**
* Check to see if ShipmentId is set.
*
* @return true if ShipmentId is set.
*/
public boolean isSetShipmentId() {
return shipmentId != null;
}
/**
* Set the value of ShipmentId, return this.
*
* @param shipmentId
* The new value to set.
*
* @return This instance.
*/
public GetPalletLabelsRequest withShipmentId(String shipmentId) {
this.shipmentId = shipmentId;
return this;
}
/**
* Get the value of PageType.
*
* @return The value of PageType.
*/
public String getPageType() {
return pageType;
}
/**
* Set the value of PageType.
*
* @param pageType
* The new value to set.
*/
public void setPageType(String pageType) {
this.pageType = pageType;
}
/**
* Check to see if PageType is set.
*
* @return true if PageType is set.
*/
public boolean isSetPageType() {
return pageType != null;
}
/**
* Set the value of PageType, return this.
*
* @param pageType
* The new value to set.
*
* @return This instance.
*/
public GetPalletLabelsRequest withPageType(String pageType) {
this.pageType = pageType;
return this;
}
/**
* Get the value of NumberOfPallets.
*
* @return The value of NumberOfPallets.
*/
public int getNumberOfPallets() {
return numberOfPallets;
}
/**
* Set the value of NumberOfPallets.
*
* @param numberOfPallets
* The new value to set.
*/
public void setNumberOfPallets(int numberOfPallets) {
this.numberOfPallets = numberOfPallets;
}
/**
* Set the value of NumberOfPallets, return this.
*
* @param numberOfPallets
* The new value to set.
*
* @return This instance.
*/
public GetPalletLabelsRequest withNumberOfPallets(int numberOfPallets) {
this.numberOfPallets = numberOfPallets;
return this;
}
/**
* Read members from a MwsReader.
*
* @param r
* The reader to read from.
*/
@Override
public void readFragmentFrom(MwsReader r) {
sellerId = r.read("SellerId", String.class);
mwsAuthToken = r.read("MWSAuthToken", String.class);
shipmentId = r.read("ShipmentId", String.class);
pageType = r.read("PageType", String.class);
numberOfPallets = r.read("NumberOfPallets", int.class);
}
/**
* Write members to a MwsWriter.
*
* @param w
* The writer to write to.
*/
@Override
public void writeFragmentTo(MwsWriter w) {
w.write("SellerId", sellerId);
w.write("MWSAuthToken", mwsAuthToken);
w.write("ShipmentId", shipmentId);
w.write("PageType", pageType);
w.write("NumberOfPallets", numberOfPallets);
}
/**
* Write tag, xmlns and members to a MwsWriter.
*
* @param w
* The Writer to write to.
*/
@Override
public void writeTo(MwsWriter w) {
w.write("http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/", "GetPalletLabelsRequest",this);
}
/** Value constructor. */
public GetPalletLabelsRequest(String sellerId,String mwsAuthToken,String shipmentId,String pageType,int numberOfPallets) {
this.sellerId = sellerId;
this.mwsAuthToken = mwsAuthToken;
this.shipmentId = shipmentId;
this.pageType = pageType;
this.numberOfPallets = numberOfPallets;
}
/** Value constructor. */
public GetPalletLabelsRequest(String sellerId,String shipmentId,String pageType,int numberOfPallets) {
this.sellerId = sellerId;
this.shipmentId = shipmentId;
this.pageType = pageType;
this.numberOfPallets = numberOfPallets;
}
/** Default constructor. */
public GetPalletLabelsRequest() {
super();
}
}
| kenyonduan/amazon-mws | src/main/java/com/amazonservices/mws/FulfillmentInboundShipment/model/GetPalletLabelsRequest.java | Java | mit | 8,752 |
package com.shawn.model.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* @author Xiaoyue Xiao
*/
@Accessors(chain = true)
@NoArgsConstructor
@Getter
@Setter
@ToString
public class User implements Serializable {
private static final long serialVersionUID = 7698862379923111158L;
private Long id;
private String username;
private String password;
}
| xueshoulong/longFirstTest | src/main/java/com/shawn/model/entity/User.java | Java | mit | 504 |
/*
* Created on Feb 14, 2008
*
* TODO
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package edu.psu.compbio.seqcode.gse.viz.graphs;
import java.util.*;
import edu.psu.compbio.seqcode.gse.utils.Pair;
import edu.psu.compbio.seqcode.gse.utils.graphs.*;
public class UndirectedGraphAdapter {
private UndirectedGraph graph;
private GraphView view;
private Map<String,NodeView> nodeViews;
private Map<Pair<String,String>,EdgeView> edgeViews;
public UndirectedGraphAdapter(UndirectedGraph dg) {
graph = dg;
view = new GraphView();
nodeViews = new TreeMap<String,NodeView>();
edgeViews = new HashMap<Pair<String,String>,EdgeView>();
buildViews();
}
private void buildViews() {
for(String node : graph.getVertices()) {
NodeView nview = view.createNode();
nview.setOption("name", node);
nodeViews.put(node, nview);
}
for(String from : graph.getVertices()) {
NodeView fromView = nodeViews.get(from);
for(String to : graph.getNeighbors(from)) {
if(from.compareTo(to) <= 0) {
NodeView toView = nodeViews.get(to);
EdgeView edge = view.createEdge(fromView, toView);
edge.setDirected(false);
edgeViews.put(new Pair<String,String>(from, to), edge);
}
}
}
}
public UndirectedGraph getGraph() {
return graph;
}
public GraphView getView() {
return view;
}
}
| shaunmahony/seqcode | src/edu/psu/compbio/seqcode/gse/viz/graphs/UndirectedGraphAdapter.java | Java | mit | 1,772 |
package com.solvedbysunrise.wastedtime.service;
import com.solvedbysunrise.wastedtime.data.dto.WastedTime;
import java.util.Collection;
public interface WastedTimeService {
Collection<WastedTime> recordWastedTime(WastedTime wastedTime);
Collection<WastedTime> getAllWastedTime();
Collection<String> getAllWastedTimeActivities();
Collection<String> getEveryoneWhoHasWastedTime();
}
| arranbartish/wasted-time | wasted-app/src/main/java/com/solvedbysunrise/wastedtime/service/WastedTimeService.java | Java | mit | 404 |
package com.app.dextrous.barbara.model;
import java.io.Serializable;
import java.util.Date;
public class UserPreference implements Serializable {
private Integer id;
private Integer userId;
private float budget;
private String securityQuestion;
private String nickName;
private Date createdTS;
private Date lastUpdatedTS;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public float getBudget() {
return budget;
}
public void setBudget(float budget) {
this.budget = budget;
}
public String getSecurityQuestion() {
return securityQuestion;
}
public void setSecurityQuestion(String securityQuestion) {
this.securityQuestion = securityQuestion;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Date getCreatedTS() {
return createdTS;
}
public void setCreatedTS(Date createdTS) {
this.createdTS = createdTS;
}
public Date getLastUpdatedTS() {
return lastUpdatedTS;
}
public void setLastUpdatedTS(Date lastUpdatedTS) {
this.lastUpdatedTS = lastUpdatedTS;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Override
public String toString() {
return "UserPreference{" +
"id=" + id +
"userId=" + userId +
", budget=" + budget +
", securityQuestion='" + securityQuestion + '\'' +
", nickName='" + nickName + '\'' +
", createdTS=" + createdTS +
", lastUpdatedTS=" + lastUpdatedTS +
'}';
}
}
| rajagopal28/Barbara | app/src/main/java/com/app/dextrous/barbara/model/UserPreference.java | Java | mit | 1,880 |
package hu.interconnect.hr.dao;
import java.util.List;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import hu.interconnect.hr.backend.api.enumeration.ErtekkeszletElemTipus;
import hu.interconnect.hr.domain.ErtekkeszletElem;
@Repository
public class ErtekkeszletElemDAO extends BaseDAO<ErtekkeszletElem, Integer> {
@SuppressWarnings("unchecked")
public List<ErtekkeszletElem> getOsszesAdottTipusu(ErtekkeszletElemTipus tipus) {
String sql = "SELECT elem FROM ErtekkeszletElem elem ";
if (tipus != null) {
sql += " WHERE elem.tipus = :tipus ";
}
sql += " ORDER BY tipus ASC, megnevezesMagyar ASC ";
Query query = em.createQuery(sql);
if (tipus != null) {
query.setParameter("tipus", tipus);
}
return query.getResultList();
}
public ErtekkeszletElemDAO() {
super(ErtekkeszletElem.class);
}
} | tornaia/hr2 | hr2-java-parent/hr2-backend-impl/src/main/java/hu/interconnect/hr/dao/ErtekkeszletElemDAO.java | Java | mit | 868 |
package thahn.java.agui.controller;
import thahn.java.agui.app.Activity;
import thahn.java.agui.app.Bundle;
import thahn.java.agui.app.Intent;
import thahn.java.agui.utils.Log;
import thahn.java.agui.view.View;
import thahn.java.agui.view.View.OnClickListener;
public class IntroActivity extends Activity {
public static final int REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.layout3);
findViewById(R.id.view1).setOnClickListener(onClickListener);
findViewById(R.id.view2).setOnClickListener(onClickListener);
findViewById(R.id.view3).setOnClickListener(onClickListener);
// start service
Intent intent = new Intent(IntroActivity.this, TestService.class);
startService(intent);
}
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
Log.e("click : " + v.getId());
}
};
}
| thahn0720/agui_framework | agui_manager/src/main/java/thahn/java/agui/controller/IntroActivity.java | Java | mit | 941 |
package se.paap.sqluserlistapplication;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("se.paap.solutionrecyclerviewexercise", appContext.getPackageName());
}
}
| PatrikAppelqvist/Android-C3L | week3/day1/code/SqlUserListApplication/app/src/androidTest/java/se/paap/sqluserlistapplication/ExampleInstrumentedTest.java | Java | mit | 770 |
/**
* The event package associated with the DesignFramework.
*/
package io.github.kunonx.DesignFramework.event; | kunonx/DesignFramework | src/main/java/io/github/kunonx/DesignFramework/event/package-info.java | Java | mit | 113 |
package com.moumou.locate;
import android.support.test.runner.AndroidJUnit4;
import org.junit.runner.RunWith;
/**
* Created by MouMou on 23-01-17.
*/
@RunWith(AndroidJUnit4.class)
public class LocationServiceTest {
}
| dennism1997/Locate | app/src/androidTest/java/com/moumou/locate/LocationServiceTest.java | Java | mit | 225 |
/*
* @(#)Delayed.java 1.7 05/11/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.util.concurrent;
import java.util.*;
/**
* A mix-in style interface for marking objects that should be
* acted upon after a given delay.
*
* <p>An implementation of this interface must define a
* <tt>compareTo</tt> method that provides an ordering consistent with
* its <tt>getDelay</tt> method.
*
* @since 1.5
* @author Doug Lea
*/
public interface Delayed extends Comparable<Delayed> {
/**
* Returns the remaining delay associated with this object, in the
* given time unit.
*
* @param unit the time unit
* @return the remaining delay; zero or negative values indicate
* that the delay has already elapsed
*/
long getDelay(TimeUnit unit);
}
| jgaltidor/VarJ | analyzed_libs/jdk1.6.0_06_src/java/util/concurrent/Delayed.java | Java | mit | 884 |
package ca.canucksoftware.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author Jason Robitaille
*/
public class JarResource {
protected Class specific;
private String path;
private String prefix;
private String suffix;
public JarResource(String resource) {
this(resource, null);
}
public JarResource(String resource, Class specificClass) {
path = resource;
specific = specificClass;
prefix = "";
suffix = "";
}
public void prepend(String text) {
prefix = text;
}
public void append(String text) {
suffix = text;
}
public File extract() {
String tmpFilePath = System.getProperty("java.io.tmpdir");
File dest = new File(tmpFilePath, path.substring(path.lastIndexOf("/")+1));
return extract(dest);
}
public File extract(String dest) {
return extract(new File(dest));
}
public File extract(File dest) {
try {
if(dest.exists())
dest.delete();
InputStream in = null;
if(specific==null) {
in = new BufferedInputStream(this.getClass().getResourceAsStream(path));
} else {
in = new BufferedInputStream(specific.getResourceAsStream(path));
}
OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
out.write(prefix.getBytes());
byte[] buffer = new byte[2048];
for (;;) {
int nBytes = in.read(buffer);
if (nBytes <= 0)
break;
out.write(buffer, 0, nBytes);
}
out.write(suffix.getBytes());
out.flush();
out.close();
in.close();
return dest;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| JayCanuck/webos-clock-themer | src/ca/canucksoftware/utils/JarResource.java | Java | mit | 2,077 |
package laurenyew.photogalleryapp.list;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
/**
* Created by laurenyew on 3/27/16.
*/
public class ImagePreviewRecyclerViewAdapter extends RecyclerView.Adapter<ImagePreviewViewHolder>{
@Override
public ImagePreviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(ImagePreviewViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
}
| laurenyew/PhotoGalleryApp | app/src/main/java/laurenyew/photogalleryapp/list/ImagePreviewRecyclerViewAdapter.java | Java | mit | 567 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos.rx;
import com.azure.data.cosmos.internal.AsyncDocumentClient;
import com.azure.data.cosmos.CosmosClientException;
import com.azure.data.cosmos.internal.Database;
import com.azure.data.cosmos.internal.*;
import com.azure.data.cosmos.internal.DocumentCollection;
import com.azure.data.cosmos.FeedOptions;
import com.azure.data.cosmos.FeedResponse;
import com.azure.data.cosmos.PermissionMode;
import com.azure.data.cosmos.internal.TestSuiteBase;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.testng.annotations.Ignore;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import reactor.core.publisher.Flux;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
//TODO: change to use external TestSuiteBase
//FIXME beforeClass times out inconsistently
@Ignore
public class PermissionQueryTest extends TestSuiteBase {
public final String databaseId = DatabaseForTest.generateId();
private Database createdDatabase;
private User createdUser;
private List<Permission> createdPermissions = new ArrayList<>();
private AsyncDocumentClient client;
@Factory(dataProvider = "clientBuilders")
public PermissionQueryTest(AsyncDocumentClient.Builder clientBuilder) {
super(clientBuilder);
}
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void queryWithFilter() throws Exception {
String filterId = createdPermissions.get(0).id();
String query = String.format("SELECT * from c where c.id = '%s'", filterId);
FeedOptions options = new FeedOptions();
options.maxItemCount(5);
Flux<FeedResponse<Permission>> queryObservable = client
.queryPermissions(getUserLink(), query, options);
List<Permission> expectedDocs = createdPermissions.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList());
assertThat(expectedDocs).isNotEmpty();
int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount();
FeedResponseListValidator<Permission> validator = new FeedResponseListValidator.Builder<Permission>()
.totalSize(expectedDocs.size())
.exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList()))
.numberOfPages(expectedPageSize)
.pageSatisfy(0, new FeedResponseValidator.Builder<Permission>()
.requestChargeGreaterThanOrEqualTo(1.0).build())
.build();
validateQuerySuccess(queryObservable, validator, TIMEOUT);
}
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void query_NoResults() throws Exception {
String query = "SELECT * from root r where r.id = '2'";
FeedOptions options = new FeedOptions();
options.enableCrossPartitionQuery(true);
Flux<FeedResponse<Permission>> queryObservable = client
.queryPermissions(getUserLink(), query, options);
FeedResponseListValidator<Permission> validator = new FeedResponseListValidator.Builder<Permission>()
.containsExactly(new ArrayList<>())
.numberOfPages(1)
.pageSatisfy(0, new FeedResponseValidator.Builder<Permission>()
.requestChargeGreaterThanOrEqualTo(1.0).build())
.build();
validateQuerySuccess(queryObservable, validator);
}
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void queryAll() throws Exception {
String query = "SELECT * from root";
FeedOptions options = new FeedOptions();
options.maxItemCount(3);
options.enableCrossPartitionQuery(true);
Flux<FeedResponse<Permission>> queryObservable = client
.queryPermissions(getUserLink(), query, options);
int expectedPageSize = (createdPermissions.size() + options.maxItemCount() - 1) / options.maxItemCount();
FeedResponseListValidator<Permission> validator = new FeedResponseListValidator
.Builder<Permission>()
.exactlyContainsInAnyOrder(createdPermissions
.stream()
.map(d -> d.resourceId())
.collect(Collectors.toList()))
.numberOfPages(expectedPageSize)
.allPagesSatisfy(new FeedResponseValidator.Builder<Permission>()
.requestChargeGreaterThanOrEqualTo(1.0).build())
.build();
validateQuerySuccess(queryObservable, validator);
}
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void invalidQuerySytax() throws Exception {
String query = "I am an invalid query";
FeedOptions options = new FeedOptions();
options.enableCrossPartitionQuery(true);
Flux<FeedResponse<Permission>> queryObservable = client
.queryPermissions(getUserLink(), query, options);
FailureValidator validator = new FailureValidator.Builder()
.instanceOf(CosmosClientException.class)
.statusCode(400)
.notNullActivityId()
.build();
validateQueryFailure(queryObservable, validator);
}
@BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT)
public void beforeClass() {
client = clientBuilder().build();
Database d = new Database();
d.id(databaseId);
createdDatabase = createDatabase(client, d);
createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition());
for(int i = 0; i < 5; i++) {
createdPermissions.add(createPermissions(client, i));
}
waitIfNeededForReplicasToCatchUp(clientBuilder());
}
@AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true)
public void afterClass() {
safeDeleteDatabase(client, createdDatabase);
safeClose(client);
}
private static User getUserDefinition() {
User user = new User();
user.id(UUID.randomUUID().toString());
return user;
}
public Permission createPermissions(AsyncDocumentClient client, int index) {
DocumentCollection collection = new DocumentCollection();
collection.id(UUID.randomUUID().toString());
Permission permission = new Permission();
permission.id(UUID.randomUUID().toString());
permission.setPermissionMode(PermissionMode.READ);
permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgT" + Integer.toString(index) + "=");
return client.createPermission(getUserLink(), permission, null).single().block().getResource();
}
private String getUserLink() {
return "dbs/" + getDatabaseId() + "/users/" + getUserId();
}
private String getDatabaseId() {
return createdDatabase.id();
}
private String getUserId() {
return createdUser.id();
}
}
| navalev/azure-sdk-for-java | sdk/cosmos/microsoft-azure-cosmos/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java | Java | mit | 7,266 |
package com.mongodash.monitor;
import com.mongodash.exception.MonitorException;
import com.mongodash.model.Server;
public interface Monitor {
void execute(int seconds) throws MonitorException;
void setServer(Server server);
Server getServer();
}
| rfceron/mongo-monitor-webapp-boot | src/main/java/com/mongodash/monitor/Monitor.java | Java | mit | 258 |
/**
* MIT License
*
* Copyright (c) 2017 grndctl
*
* 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.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.12.06 at 02:17:36 PM EST
//
package com.grndctl.model.pirep;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* Java class for anonymous complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}receipt_time" minOccurs="0"/>
* <element ref="{}observation_time" minOccurs="0"/>
* <element ref="{}quality_control_flags" minOccurs="0"/>
* <element ref="{}aircraft_ref" minOccurs="0"/>
* <element ref="{}latitude" minOccurs="0"/>
* <element ref="{}longitude" minOccurs="0"/>
* <element ref="{}altitude_ft_msl" minOccurs="0"/>
* <element ref="{}sky_condition" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{}turbulence_condition" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{}icing_condition" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{}visibility_statute_mi" minOccurs="0"/>
* <element ref="{}wx_string" minOccurs="0"/>
* <element ref="{}temp_c" minOccurs="0"/>
* <element ref="{}wind_dir_degrees" minOccurs="0"/>
* <element ref="{}wind_speed_kt" minOccurs="0"/>
* <element ref="{}vert_gust_kt" minOccurs="0"/>
* <element ref="{}pirep_type" minOccurs="0"/>
* <element ref="{}raw_text" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "receiptTime", "observationTime",
"qualityControlFlags", "aircraftRef", "latitude", "longitude",
"altitudeFtMsl", "skyCondition", "turbulenceCondition",
"icingCondition", "visibilityStatuteMi", "wxString", "tempC",
"windDirDegrees", "windSpeedKt", "vertGustKt", "pirepType", "rawText" })
@XmlRootElement(name = "PIREP")
public class PIREP {
@XmlElement(name = "receipt_time")
protected String receiptTime;
@XmlElement(name = "observation_time")
protected String observationTime;
@XmlElement(name = "quality_control_flags")
protected QualityControlFlags qualityControlFlags;
@XmlElement(name = "aircraft_ref")
protected String aircraftRef;
protected Float latitude;
protected Float longitude;
@XmlElement(name = "altitude_ft_msl")
protected Integer altitudeFtMsl;
@XmlElement(name = "sky_condition")
protected List<SkyCondition> skyCondition;
@XmlElement(name = "turbulence_condition")
protected List<TurbulenceCondition> turbulenceCondition;
@XmlElement(name = "icing_condition")
protected List<IcingCondition> icingCondition;
@XmlElement(name = "visibility_statute_mi")
protected Integer visibilityStatuteMi;
@XmlElement(name = "wx_string")
protected String wxString;
@XmlElement(name = "temp_c")
protected Float tempC;
@XmlElement(name = "wind_dir_degrees")
protected Integer windDirDegrees;
@XmlElement(name = "wind_speed_kt")
protected Integer windSpeedKt;
@XmlElement(name = "vert_gust_kt")
protected Integer vertGustKt;
@XmlElement(name = "pirep_type")
protected String pirepType;
@XmlElement(name = "raw_text")
protected String rawText;
/**
* Gets the value of the receiptTime property.
*
* @return possible object is {@link String }
*
*/
public String getReceiptTime() {
return receiptTime;
}
/**
* Sets the value of the receiptTime property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setReceiptTime(String value) {
this.receiptTime = value;
}
/**
* Gets the value of the observationTime property.
*
* @return possible object is {@link String }
*
*/
public String getObservationTime() {
return observationTime;
}
/**
* Sets the value of the observationTime property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setObservationTime(String value) {
this.observationTime = value;
}
/**
* Gets the value of the qualityControlFlags property.
*
* @return possible object is {@link QualityControlFlags }
*
*/
public QualityControlFlags getQualityControlFlags() {
return qualityControlFlags;
}
/**
* Sets the value of the qualityControlFlags property.
*
* @param value
* allowed object is {@link QualityControlFlags }
*
*/
public void setQualityControlFlags(QualityControlFlags value) {
this.qualityControlFlags = value;
}
/**
* Gets the value of the aircraftRef property.
*
* @return possible object is {@link String }
*
*/
public String getAircraftRef() {
return aircraftRef;
}
/**
* Sets the value of the aircraftRef property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setAircraftRef(String value) {
this.aircraftRef = value;
}
/**
* Gets the value of the latitude property.
*
* @return possible object is {@link Float }
*
*/
public Float getLatitude() {
return latitude;
}
/**
* Sets the value of the latitude property.
*
* @param value
* allowed object is {@link Float }
*
*/
public void setLatitude(Float value) {
this.latitude = value;
}
/**
* Gets the value of the longitude property.
*
* @return possible object is {@link Float }
*
*/
public Float getLongitude() {
return longitude;
}
/**
* Sets the value of the longitude property.
*
* @param value
* allowed object is {@link Float }
*
*/
public void setLongitude(Float value) {
this.longitude = value;
}
/**
* Gets the value of the altitudeFtMsl property.
*
* @return possible object is {@link Integer }
*
*/
public Integer getAltitudeFtMsl() {
return altitudeFtMsl;
}
/**
* Sets the value of the altitudeFtMsl property.
*
* @param value
* allowed object is {@link Integer }
*
*/
public void setAltitudeFtMsl(Integer value) {
this.altitudeFtMsl = value;
}
/**
* Gets the value of the skyCondition property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the skyCondition property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getSkyCondition().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SkyCondition }
*
*
*/
public List<SkyCondition> getSkyCondition() {
if (skyCondition == null) {
skyCondition = new ArrayList<SkyCondition>();
}
return this.skyCondition;
}
/**
* Gets the value of the turbulenceCondition property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the turbulenceCondition property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getTurbulenceCondition().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TurbulenceCondition }
*
*
*/
public List<TurbulenceCondition> getTurbulenceCondition() {
if (turbulenceCondition == null) {
turbulenceCondition = new ArrayList<TurbulenceCondition>();
}
return this.turbulenceCondition;
}
/**
* Gets the value of the icingCondition property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the icingCondition property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getIcingCondition().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link IcingCondition }
*
*
*/
public List<IcingCondition> getIcingCondition() {
if (icingCondition == null) {
icingCondition = new ArrayList<IcingCondition>();
}
return this.icingCondition;
}
/**
* Gets the value of the visibilityStatuteMi property.
*
* @return possible object is {@link Integer }
*
*/
public Integer getVisibilityStatuteMi() {
return visibilityStatuteMi;
}
/**
* Sets the value of the visibilityStatuteMi property.
*
* @param value
* allowed object is {@link Integer }
*
*/
public void setVisibilityStatuteMi(Integer value) {
this.visibilityStatuteMi = value;
}
/**
* Gets the value of the wxString property.
*
* @return possible object is {@link String }
*
*/
public String getWxString() {
return wxString;
}
/**
* Sets the value of the wxString property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setWxString(String value) {
this.wxString = value;
}
/**
* Gets the value of the tempC property.
*
* @return possible object is {@link Float }
*
*/
public Float getTempC() {
return tempC;
}
/**
* Sets the value of the tempC property.
*
* @param value
* allowed object is {@link Float }
*
*/
public void setTempC(Float value) {
this.tempC = value;
}
/**
* Gets the value of the windDirDegrees property.
*
* @return possible object is {@link Integer }
*
*/
public Integer getWindDirDegrees() {
return windDirDegrees;
}
/**
* Sets the value of the windDirDegrees property.
*
* @param value
* allowed object is {@link Integer }
*
*/
public void setWindDirDegrees(Integer value) {
this.windDirDegrees = value;
}
/**
* Gets the value of the windSpeedKt property.
*
* @return possible object is {@link Integer }
*
*/
public Integer getWindSpeedKt() {
return windSpeedKt;
}
/**
* Sets the value of the windSpeedKt property.
*
* @param value
* allowed object is {@link Integer }
*
*/
public void setWindSpeedKt(Integer value) {
this.windSpeedKt = value;
}
/**
* Gets the value of the vertGustKt property.
*
* @return possible object is {@link Integer }
*
*/
public Integer getVertGustKt() {
return vertGustKt;
}
/**
* Sets the value of the vertGustKt property.
*
* @param value
* allowed object is {@link Integer }
*
*/
public void setVertGustKt(Integer value) {
this.vertGustKt = value;
}
/**
* Gets the value of the pirepType property.
*
* @return possible object is {@link String }
*
*/
public String getPirepType() {
return pirepType;
}
/**
* Sets the value of the pirepType property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setPirepType(String value) {
this.pirepType = value;
}
/**
* Gets the value of the rawText property.
*
* @return possible object is {@link String }
*
*/
public String getRawText() {
return rawText;
}
/**
* Sets the value of the rawText property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setRawText(String value) {
this.rawText = value;
}
}
| mdisalvo/grndctl | src/main/java/com/grndctl/model/pirep/PIREP.java | Java | mit | 14,946 |
package com.mateoi.gp.tree;
import java.util.function.BiFunction;
import com.mateoi.gp.exceptions.NoConstructorsSet;
/**
* Abstract class of nodes with two children.
*
* @author mateo
*
*/
public abstract class Arity2Node extends Node {
/** Function to evaluate */
private final BiFunction<Double, Double, Double> function;
/**
* Create a new node with the given name, depth and function.
*
* @param name
* @param depth
* @param function
*/
public Arity2Node(String name, int depth, BiFunction<Double, Double, Double> function) {
super(name, depth);
this.function = function;
}
/**
* @return This node's function.
*/
public BiFunction<Double, Double, Double> getFunction() {
return function;
}
@Override
public double evaluate() {
Node child1 = getArguments().get(0);
double value1 = child1.evaluate();
Node child2 = getArguments().get(1);
double value2 = child2.evaluate();
return function.apply(value1, value2);
}
@Override
public void createChildren() {
try {
getArguments().clear();
Node child1 = NodeFactory.getInstance().createRandomNode(getDepth() - 1);
getArguments().add(child1);
Node child2 = NodeFactory.getInstance().createRandomNode(getDepth() - 1);
getArguments().add(child2);
} catch (NoConstructorsSet e) {
System.out.println("No constructors set!");
System.exit(1);
}
}
}
| mateoi/CallYourGP | src/com/mateoi/gp/tree/Arity2Node.java | Java | mit | 1,570 |
package com.flextrade.jfixture.customisation;
import com.flextrade.jfixture.NoSpecimen;
import com.flextrade.jfixture.SpecimenBuilder;
import com.flextrade.jfixture.SpecimenContext;
import com.flextrade.jfixture.exceptions.ObjectCreationException;
import com.flextrade.jfixture.requests.MethodRequest;
import com.flextrade.jfixture.utility.PrimitiveTypeMap;
import com.flextrade.jfixture.utility.PropertyUtil;
import java.lang.reflect.Method;
public class OverridePropertyBuilder implements SpecimenBuilder {
private final Class clazz;
private final String propertyName;
private final Object propertyValue;
OverridePropertyBuilder(Class clazz, String propertyName, Object propertyValue) {
this.clazz = clazz;
this.propertyName = propertyName;
this.propertyValue = propertyValue;
}
@Override
public Object create(Object request, SpecimenContext context) {
if (!(request instanceof MethodRequest)) {
return new NoSpecimen();
}
MethodRequest methodRequest = (MethodRequest)request;
//noinspection EqualsBetweenInconvertibleTypes SpecimenType knows how to do equals(Class<?>)
if(!methodRequest.getContainingType().equals(this.clazz)) {
return new NoSpecimen();
}
if(!PropertyUtil.isMethodASetterProperty(methodRequest.getMethod(), methodRequest.getContainingType().getRawType())) {
return new NoSpecimen();
}
if(!methodNameMatchesOverriddenProperty(methodRequest.getMethod(), this.propertyName)) {
return new NoSpecimen();
}
Class<?> propertyValueClass = nonPrimitiveType(propertyValue.getClass());
Class<?> methodParamClass = nonPrimitiveType(methodRequest.getMethod().getParameterTypes()[0]);
boolean isAssignable = methodParamClass.isAssignableFrom(propertyValueClass);
if(!isAssignable) { // Don't return NoSpecimen here because it's almost certainly a user error so it shouldn't be ignored
throw new ObjectCreationException(
"The property " + methodRequest.getMethod() + " has been overridden with an instance that does not match the expected type.\n" +
"The type of the property is " + methodParamClass + " but the overriding object is of type " + propertyValueClass);
}
return propertyValue;
}
private static Class nonPrimitiveType(Class clazz) {
if(!(clazz.isPrimitive())) return clazz;
return PrimitiveTypeMap.map.get(clazz);
}
private static boolean methodNameMatchesOverriddenProperty(Method method, String propertyName) {
if(method.getName().equalsIgnoreCase(propertyName)) return true; // e.g. propertyName = "setSize"
String methodPropertyName = PropertyUtil.getMemberNameFromMethod(method); // e.g. propertyName = "size"
return methodPropertyName.equalsIgnoreCase(propertyName);
}
}
| FlexTradeUKLtd/jfixture | jfixture/src/main/java/com/flextrade/jfixture/customisation/OverridePropertyBuilder.java | Java | mit | 2,949 |
package com.jay.open.libs.jtree.exceptions;
/**
* Created with IntelliJ IDEA.
* User: suweijie
* Date: 14-10-23
* Time: 10:18
* To change this template use File | Settings | File Templates.
*/
public class ETreeException extends RuntimeException {
public ETreeException(){}
public ETreeException(String msg){super(msg);}
}
| Snuby/jtree | src/main/java/com/jay/open/libs/jtree/exceptions/ETreeException.java | Java | mit | 340 |
package com.codepath.apps.restclienttemplate.models;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by trandhawa on 10/1/17.
*/
public class User {
public String name;
public Long uid;
public String screenName;
public String profileImageUrl;
public String tagLine;
public int followersCount;
public int followingCount;
// de-serialize the json
public static User fromJson(JSONObject jsonObject) throws JSONException {
User user = new User();
user.name = jsonObject.getString("name");
user.uid = jsonObject.getLong("id");
user.screenName = jsonObject.getString("screen_name");
user.profileImageUrl = jsonObject.getString("profile_image_url");
user.tagLine = jsonObject.getString("description");
user.followersCount = jsonObject.getInt("followers_count");
user.followingCount = jsonObject.getInt("friends_count");
return user;
}
}
| tanveersr/MySimpleTweets | app/src/main/java/com/codepath/apps/restclienttemplate/models/User.java | Java | mit | 976 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
package com.azure.search.documents.indexes.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
/** Defines weights on index fields for which matches should boost scoring in search queries. */
@Fluent
public final class TextWeights {
/*
* The dictionary of per-field weights to boost document scoring. The keys
* are field names and the values are the weights for each field.
*/
@JsonProperty(value = "weights", required = true)
private Map<String, Double> weights;
/**
* Creates an instance of TextWeights class.
*
* @param weights the weights value to set.
*/
@JsonCreator
public TextWeights(@JsonProperty(value = "weights", required = true) Map<String, Double> weights) {
this.weights = weights;
}
/**
* Get the weights property: The dictionary of per-field weights to boost document scoring. The keys are field names
* and the values are the weights for each field.
*
* @return the weights value.
*/
public Map<String, Double> getWeights() {
return this.weights;
}
}
| selvasingh/azure-sdk-for-java | sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextWeights.java | Java | mit | 1,461 |
package pl.grzeslowski.jsupla.protocoljava.impl.parsers.dcs;
import pl.grzeslowski.jsupla.protocol.api.structs.dcs.SuplaPingServer;
import pl.grzeslowski.jsupla.protocoljava.api.entities.dcs.PingServer;
import pl.grzeslowski.jsupla.protocoljava.api.parsers.TimevalParser;
import pl.grzeslowski.jsupla.protocoljava.api.parsers.dcs.PingServerParser;
import javax.validation.constraints.NotNull;
import static java.util.Objects.requireNonNull;
public class PingServerParserImpl implements PingServerParser {
private final TimevalParser timevalParser;
public PingServerParserImpl(final TimevalParser timevalParser) {
this.timevalParser = requireNonNull(timevalParser);
}
@Override
public PingServer parse(@NotNull final SuplaPingServer proto) {
return new PingServer(timevalParser.parse(proto.timeval));
}
}
| magx2/jSupla | protocol-java/src/main/java/pl/grzeslowski/jsupla/protocoljava/impl/parsers/dcs/PingServerParserImpl.java | Java | mit | 850 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vic Lau
*
* 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.swordess.common.lang.java.io;
import org.junit.Test;
import org.swordess.common.lang.io.ResourcesKt;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
public class ResourcesTest {
@Test
public void testResourceNameAsStreamCanFindFilesystemFile() {
InputStream stream = ResourcesKt.resourceNameAsStream("src/test/resources/message.properties");
assertNotNull(stream);
}
@Test
public void testResourceNameAsStreamCanFindClasspathFile() {
InputStream stream = ResourcesKt.resourceNameAsStream("message.properties");
assertNotNull(stream);
}
@Test
public void testResourceNameAsSteamShouldThrowExceptionIfNotFound() {
try {
ResourcesKt.resourceNameAsStream("not_exist.properties");
fail("RuntimeException is expected");
} catch (RuntimeException e) {
assertEquals("resource not found: not_exist.properties", e.getMessage());
}
}
@Test
public void testResourceNameAsURLCanFindFilesystemFile() {
URL url = ResourcesKt.resourceNameAsURL("src/test/resources/message.properties");
assertNotNull(url);
}
@Test
public void testResourceNameAsURLCanFindClasspathFile() {
URL url = ResourcesKt.resourceNameAsURL("message.properties");
assertNotNull(url);
}
@Test
public void testResourceNameAsURLShouldThrowExceptionIfNotFound() {
try {
ResourcesKt.resourceNameAsURL("not_exist.properties");
fail("RuntimeException is expected");
} catch (RuntimeException e) {
assertEquals("resource not found: not_exist.properties", e.getMessage());
}
}
@Test
public void testResourceNameAsFileAbsolutePath() {
String expected = new File("src/test/resources/message.properties").getAbsolutePath();
String actual = ResourcesKt.resourceNameAsFileAbsolutePath("src/test/resources/message.properties");
assertEquals(expected, actual);
}
}
| xingyuli/swordess-common-lang | src/test/java/org/swordess/common/lang/java/io/ResourcesTest.java | Java | mit | 3,311 |
package de.geithonline.android.basics.preferences;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.DialogPreference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import de.geithonline.android.basics.widgets.rangeseekbar.RangeSeekBar;
import de.geithonline.android.basics.widgets.rangeseekbar.RangeSeekBar.OnRangeSeekBarChangeListener;
/**
* @author geith
*
* How to use: Import lib and in preferences xml: <br>
*
* <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"<br>
* xmlns:seekbarpreference="http://schemas.android.com/apk/lib/de.geithonline.android.basics.preferences"><br>
*
* <de.geithonline.android.basics.preferences.SeekBarPreference <br>
* android:key="anzahlPatterns"<br>
* android:title="@string/pattern_anzahlPatterns"<br>
* seekbarpreference:minValue="10"<br>
* seekbarpreference:maxValue="1500"<br>
* android:summary="Draw %1$d Patterns" <br>
* android:defaultValue="1000"<br>
* android:dialogMessage="@string/pattern_anzahlPatterns" /><br>
*
*
*
*/
public final class RangeSeekBarPreference extends DialogPreference {
// Namespaces to read attributes
// http://schemas.android.com/apk/lib/de.geithonline.android.basics.preferences
private static final String PREFERENCE_NS = "http://schemas.android.com/apk/lib/de.geithonline.android.basics.preferences";
// private static final String ANDROID_NS = "http://schemas.android.com/apk/res/android";
// Real defaults
private final int absoluteMaxValue;
private final int absoluteMinValue;
private final int stepValue;
// Current value
private int currentMinValue = 0;
private int currentMaxValue = 0;
// View elements
private RangeSeekBar<Integer> rangeSeekBar;
private final String keyMinValue;
private final String keyMaxValue;
private final int defaultMaxValue;
private final int defaultMinValue;
public RangeSeekBarPreference(final Context context, final AttributeSet attrs) {
super(context, attrs);
// Read parameters from attributes
defaultMinValue = attrs.getAttributeIntValue(PREFERENCE_NS, "defaultMinValue", 0);
defaultMaxValue = attrs.getAttributeIntValue(PREFERENCE_NS, "defaultMaxValue", 100);
absoluteMinValue = attrs.getAttributeIntValue(PREFERENCE_NS, "absoluteMinValue", 0);
absoluteMaxValue = attrs.getAttributeIntValue(PREFERENCE_NS, "absoluteMaxValue", 100);
stepValue = attrs.getAttributeIntValue(PREFERENCE_NS, "step", 1);
keyMinValue = attrs.getAttributeValue(PREFERENCE_NS, "keyMinValue");
keyMaxValue = attrs.getAttributeValue(PREFERENCE_NS, "keyMaxValue");
// Get current value from preferences
readPreferences();
}
@SuppressLint("InflateParams")
@SuppressWarnings("unchecked")
@Override
protected View onCreateDialogView() {
// reading the things to show
readPreferences();
// Inflate layout
final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.range_seek_bar_preference, null);
rangeSeekBar = (RangeSeekBar<Integer>) view.findViewById(R.id.rangebar);
rangeSeekBar.setRangeValues(absoluteMinValue, absoluteMaxValue, stepValue);
rangeSeekBar.setSelectedMinValue(currentMinValue);
rangeSeekBar.setSelectedMaxValue(currentMaxValue);
rangeSeekBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
@Override
public void onRangeSeekBarValuesChanged(final RangeSeekBar<Integer> bar, final Integer minValue, final Integer maxValue) {
currentMinValue = minValue.intValue();
currentMaxValue = maxValue.intValue();
}
});
return view;
}
private String generateValueString() {
if (currentMinValue == currentMaxValue) {
return "" + currentMinValue;
}
return currentMinValue + " -> " + currentMaxValue;
}
@Override
protected void onDialogClosed(final boolean positiveResult) {
super.onDialogClosed(positiveResult);
// Return if change was cancelled
if (!positiveResult) {
return;
}
if (shouldPersist()) {
persistPreferences();
}
// Notify activity about changes (to update preference summary line)
notifyChanged();
}
public void persistPreferences() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
prefs.edit().putInt(keyMinValue, currentMinValue).commit();
prefs.edit().putInt(keyMaxValue, currentMaxValue).commit();
// Log.i("RangeSeekBarPreference", "persistPreferences: " + generateValueString());
}
private void readPreferences() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
currentMinValue = readIntegerPref(prefs, keyMinValue, defaultMinValue);
currentMaxValue = readIntegerPref(prefs, keyMaxValue, defaultMaxValue);
// Log.i("RangeSeekBarPreference", "readPreferences: " + generateValueString());
}
private static int readIntegerPref(final SharedPreferences prefs, final String key, final int defaultValue) {
if (prefs == null) {
return defaultValue;
}
return prefs.getInt(key, defaultValue);
}
@Override
public CharSequence getSummary() {
// Format summary string with current value
String summary = "";
if (super.getSummary() != null) {
summary = super.getSummary().toString();
}
final String value = generateValueString();
return String.format(summary, value);
}
} | olivergeith/android_BasicsPreference | src/de/geithonline/android/basics/preferences/RangeSeekBarPreference.java | Java | mit | 6,112 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.