hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
71c795ec344f63e226f0358aa63ddfed0f330904 | 12,928 | package cl.uchile.dcc.scrabble.type;
import java.math.BigInteger;
import java.util.Objects;
/**
* Implementation of a Scrabble int as a class.
* @author Victor Vidal Paz
*/
public class ScrabbleInt extends AbstractType {
private final int value;
/**
* Constructor of ScrabbleInt.
* @param value Java int.
*/
public ScrabbleInt(int value) {
this.value = value;
}
/**
* getValue: Getter of this class's value.
* @return Java int being the value of this instance.
*/
public int getValue() { return value; }
/**
* toString: Method for transforming a Scrabble type to a Java String.
* @return String representing the value of the Scrabble int.
*/
@Override
public String toString() {
return String.valueOf(this.getValue());
}
@Override
public ScrabbleString addToString(IType sType) {
return null;
}
/**
* negate: Method for negating the value of a Scrabble type.
* @return IType with the negated value. In this case the int value is negated.
*/
@Override
public IType negate() {
return new ScrabbleInt(-this.getValue());
}
/**
* and: Logical conjunction operator between two Scrabble logical types.
*
* @param sLogical ScrabbleLogical type to operate on the right side.
* @return IType being the result of the conjunction.
*/
@Override
public IType and(IType sLogical) {
return null;
}
/**
* or: Logical disjunction operator between two Scrabble logical types.
*
* @param sLogical ScrabbleLogical type to operate on the right side.
* @return IType being the result of the disjunction.
*/
@Override
public IType or(IType sLogical) {
return null;
}
/**
* hashCode: Override from Object, used for proper hashing of the types using its value.
* @return int being the hash code of the object.
*/
@Override
public int hashCode() {
return Objects.hash(ScrabbleInt.class, value);
}
/**
* equals: Override from Object, used for comparing two different objects.
* @param obj Object to compare.
* @return boolean that determines if two objects have the exact same values and share the same instance.
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof ScrabbleInt) {
var o = (ScrabbleInt) obj;
return this.getValue() == o.getValue();
}
return false;
}
/**
* toScrabbleFloat: Method for transforming a Scrabble numeral type to a Scrabble Float
* @return ScrabbleFloat being the result of the transformation.
*/
@Override
public ScrabbleFloat toScrabbleFloat() {
return new ScrabbleFloat(Double.parseDouble(this.toString()));
}
/**
* toScrabbleBool: Method for transforming a Scrabble boolean type to a ScrabbleBool
*
* @return ScrabbleBool being the result of the transformation.
*/
@Override
public ScrabbleBool toScrabbleBool() {
return null;
}
/**
* toScrabbleInt: Method for transforming a Scrabble int to a Scrabble int. Useful for making copies.
* @return ScrabbleInt being the copy of this object.
*/
@Override
public ScrabbleInt toScrabbleInt() {
return new ScrabbleInt(this.getValue());
}
/**
* toScrabbleBinary: Method for transforming a Scrabble int to a Scrabble binary. For this, the two's component
* format is used for representing negative int values.
* @return ScrabbleBinary being the result of the transformation.
*/
public ScrabbleBinary toScrabbleBinary() {
int num = Math.abs(this.getValue());
String binary = positiveIntToBinary(num);
if (this.getValue() < 0) {
binary = TwosComplement(binary);
}
return new ScrabbleBinary(binary);
}
/**
* TwosComponent: Algorithm to invert a positive binary to it's negative value.
* <p>Algorithm:</p>
* <ol>
* <li>Shift the '1' bits to '0' and vice versa</li>
* <li>Add a bit to the binary number</li>
* </ol>
* @param binary String containing the binary number.
* @return String being the result of the algorithm.
*/
private String TwosComplement(String binary) {
binary = binary.replaceAll("0", "x");
binary = binary.replaceAll("1", "0");
binary = binary.replaceAll("x", "1");
int i = 63; // 64 bits
while (binary.charAt(i) == '1') { i--; }
String ans = binary.substring(0, i) + "1";
if (i == 63) {
return ans;
} else {
return ans + String.format("%0" + (63 - i) + "d", 0);
}
}
/**
* positiveIntToBinary: Method for transforming a positive int to a two's component binary.
* @param num int to transform
* @return String being the binary resulting from this.
*/
private String positiveIntToBinary(int num) {
String ans = Integer.toBinaryString(num);
return "0".repeat(64-ans.length()) + ans;
}
/**
* add: Method for adding two Scrabble numerals.
* @param sNumber ScrabbleNumber added to the right.
* @return IType being the result of the addition. It can be a ScrabbleInt or a ScrabbleFloat.
*/
@Override
public IType add(IType sNumber) {
return sNumber.intPlus(this);
}
/**
* subtract: Method for subtracting two Scrabble numerals.
* @param sNumber ScrabbleNumber subtracted to the right.
* @return IType being the result of the subtraction. It can be a ScrabbleInt or a ScrabbleFloat.
*/
@Override
public IType subtract(IType sNumber) {
return sNumber.intMinus(this);
}
/**
* multiply: Method for multiplying two Scrabble numerals.
* @param sNumber ScrabbleNumber multiplied to the right.
* @return IType being the result of the multiplication. It can be a ScrabbleInt or a ScrabbleFloat.
*/
@Override
public IType multiply(IType sNumber) {
return sNumber.intTimes(this);
}
/**
* divide: Method for dividing two Scrabble Numerals.
* @param sNumber ScrabbleNumber divided to the right. Its value mustn't be zero.
* @return IType being the result of the division. It can be a ScrabbleInt or a ScrabbleFloat.
*/
@Override
public IType divide(IType sNumber) {
return sNumber.intDividedBy(this);
}
/**
* intPlus: Method that adds a Scrabble int with a Scrabble numeral.
* @param sInt ScrabbleInt being operated on the left.
* @return IType being the result of the addition. Its priority is trying to be a ScrabbleInt.
*/
@Override
public IType intPlus(ScrabbleInt sInt) {
return new ScrabbleInt(sInt.getValue() + this.getValue());
}
/**
* intMinus: Method that subtracts a Scrabble int with a Scrabble numeral.
* @param sInt ScrabbleInt being operated on the left.
* @return IType being the result of the subtraction. Its priority is trying to be a ScrabbleInt.
*/
@Override
public IType intMinus(ScrabbleInt sInt) {
return new ScrabbleInt(sInt.getValue() - this.getValue());
}
/**
* intTimes: Method that multiplies a Scrabble int with a Scrabble numeral.
* @param sInt ScrabbleInt being operated on the left.
* @return IType being the result of the multiplication. Its priority is trying to be a ScrabbleInt.
*/
@Override
public IType intTimes(ScrabbleInt sInt) {
return new ScrabbleInt(sInt.getValue() * this.getValue());
}
/**
* intDividedBy: Method that divides a Scrabble int with a Scrabble numeral. The value of the ScrabbleNumber
* mustn't be zero.
* @param sInt ScrabbleInt being operated on the left.
* @return IType being the result of the division. Its priority is to be a ScrabbleInt.
*/
@Override
public IType intDividedBy(ScrabbleInt sInt) {
if (this.getValue() != 0) {
return new ScrabbleInt(sInt.getValue() / this.getValue());
}
return null; // Can't divide by zero
}
/**
* floatPlus: Method that adds a Scrabble float with a Scrabble numeral.
* @param sFloat ScrabbleFloat being operated on the left.
* @return ScrabbleFloat being the result of the addition.
*/
@Override
public ScrabbleFloat floatPlus(ScrabbleFloat sFloat) {
return new ScrabbleFloat(sFloat.getValue() + this.getValue());
}
/**
* floatMinus: Method that subtracts a Scrabble float with a Scrabble numeral.
* @param sFloat ScrabbleFloat being operated on the left.
* @return ScrabbleFloat being the result of the subtraction.
*/
@Override
public ScrabbleFloat floatMinus(ScrabbleFloat sFloat) {
return new ScrabbleFloat(sFloat.getValue() - this.getValue());
}
/**
* floatTimes: Method that multiplies a Scrabble float with a Scrabble numeral.
* @param sFloat ScrabbleFloat being operated on the left.
* @return ScrabbleFloat being the result of the multiplication.
*/
@Override
public ScrabbleFloat floatTimes(ScrabbleFloat sFloat) {
return new ScrabbleFloat(sFloat.getValue() * this.getValue());
}
/**
* floatDividedBy: Method that divides a Scrabble float with a Scrabble numeral. The value of the ScrabbleNumber
* mustn't be zero.
* @param sFloat ScrabbleFloat being operated on the left.
* @return ScrabbleFloat being the result of the multiplication.
*/
@Override
public ScrabbleFloat floatDividedBy(ScrabbleFloat sFloat) {
if (this.getValue() != 0) {
return new ScrabbleFloat(sFloat.getValue() / this.getValue());
}
return null;
}
/**
* binaryPlus: Method that adds a Scrabble binary with a Scrabble numeral.
* @param sBinary ScrabbleBinary being operated on the left.
* @return ScrabbleBinary being the result of the addition.
*/
@Override
public ScrabbleBinary binaryPlus(ScrabbleBinary sBinary) {
int num = binaryToInt(sBinary);
int ans = num + this.getValue();
String binaryAns = Integer.toBinaryString(Math.abs(ans));
binaryAns = "0".repeat(64 - binaryAns.length()) + binaryAns;
binaryAns = ans >= 0 ? binaryAns : sBinary.inverseTwosComponent(binaryAns);
return new ScrabbleBinary(binaryAns);
}
/**
* binaryMinus: Method that subtracts a Scrabble binary with a Scrabble numeral.
* @param sBinary ScrabbleBinary being operated on the left.
* @return ScrabbleBinary being the result of the subtraction.
*/
@Override
public ScrabbleBinary binaryMinus(ScrabbleBinary sBinary) {
int num = binaryToInt(sBinary);
int ans = num - this.getValue();
String binaryAns = Integer.toBinaryString(Math.abs(ans));
binaryAns = "0".repeat(64 - binaryAns.length()) + binaryAns;
binaryAns = ans >= 0 ? binaryAns : sBinary.inverseTwosComponent(binaryAns);
return new ScrabbleBinary(binaryAns);
}
/**
* binaryTimes: Method that multiplies a Scrabble binary with a Scrabble numeral.
* @param sBinary ScrabbleBinary being operated on the left.
* @return ScrabbleBinary being the result of the multiplication.
*/
@Override
public ScrabbleBinary binaryTimes(ScrabbleBinary sBinary) {
int num = binaryToInt(sBinary);
int ans = num * this.getValue();
String binaryAns = Integer.toBinaryString(Math.abs(ans));
binaryAns = "0".repeat(64 - binaryAns.length()) + binaryAns;
binaryAns = ans >= 0 ? binaryAns : sBinary.inverseTwosComponent(binaryAns);
return new ScrabbleBinary(binaryAns);
}
/**
* binaryDividedBy: Method that divides a Scrabble binary with a Scrabble numeral. The value of the ScrabbleNumber
* mustn't be zero.
* @param sBinary ScrabbleBinary being operated on the left.
* @return ScrabbleBinary being the result of the division.
*/
@Override
public ScrabbleBinary binaryDividedBy(ScrabbleBinary sBinary) {
if (this.getValue() != 0) {
int num = this.binaryToInt(sBinary);
int ans = num / this.getValue();
String binaryAns = Integer.toBinaryString(Math.abs(ans));
binaryAns = "0".repeat(64 - binaryAns.length()) + binaryAns;
binaryAns = ans >= 0 ? binaryAns : sBinary.inverseTwosComponent(binaryAns);
return new ScrabbleBinary(binaryAns);
}
return null; // Can't divide by zero
}
/**
* pseudoCodeString: Method for printing pseudo-code for a tree.
*/
@Override
public String pseudoCodeString() {
return "new Int(" + value + ")";
}
}
| 34.752688 | 118 | 0.644879 |
fd9075d9e93de886e224fe3a15648d5c0a376d86 | 1,151 | package triton.coreModules.robot.ally.advancedSkills;
import triton.config.globalVariblesAndConstants.GvcPathfinder;
import triton.coreModules.ball.Ball;
import triton.coreModules.robot.ally.Ally;
import triton.misc.math.linearAlgebra.Vec2D;
import static triton.misc.math.coordinates.PerspectiveConverter.normAng;
public class StaticIntercept {
public static void exec(Ally ally, Ball ball, Vec2D anchorPos) {
// To-do (future) : edge case: ball going opposite dir
Vec2D currPos = ally.getPos();
Vec2D ballPos = ball.getPos();
Vec2D ballVelDir = ball.getVel().normalized();
Vec2D ballToAnchor = anchorPos.sub(ballPos);
Vec2D receivePoint = ballPos.add(ballVelDir.scale(ballToAnchor.dot(ballVelDir)));
if (currPos.sub(ballPos).mag() < GvcPathfinder.AUTOCAP_DIST_THRESH) {
ally.getBall(ball);
} else {
if (ball.getVel().mag() < 750) { // To-do: magic number && comment vel unit
ally.getBall(ball);
} else {
ally.strafeTo(receivePoint, normAng(ballVelDir.toPlayerAngle() + 180));
}
}
}
}
| 37.129032 | 89 | 0.664639 |
56fe1f0d4a94c6e3fb547b91ac0cf9d612d2a7ec | 3,009 | package constants;
import java.util.Arrays;
import java.util.List;
public class ServerConstants {
public static final int MAPLE_LOCALE = 6;
public static final short MAPLE_VERSION = 145;
public static final String MAPLE_PATCH = "1";
public static final String WZ_PATH = "./wz";
public static String SERVER_IP = "127.0.0.1";
public static String SERVER_NAME = "小喵谷 v145";
public static double DonateRate = 2;
public static boolean BLOCK_CASH_SHOP = false;
public static boolean DEBUG = true;
public static boolean isEnhanceEnable = true;
public static boolean ADMIN_ONLY = false;
public static boolean ONLY_LOCALHOST = false; // Only allow accounted admins to connect pass login server
public static boolean USE_SECOND_PASSWORD_AUTH = false;
public static int CHANNEL_LOAD = 120; // players per channel
// 登入畫面氣球
private static final List<MapleLoginBalloon> mapleLoginBalloonList = Arrays.asList(
new MapleLoginBalloon("歡迎來到" + ServerConstants.SERVER_NAME, 240, 140),
new MapleLoginBalloon("禁止開外掛", 100, 150),
new MapleLoginBalloon("遊戲愉快", 370, 150));
public static final int Currency = 4000999;
public static final boolean MerchantsUseCurrency = false; // Log Packets = true | Allow people to connect = false
public static boolean dropUndroppables = true;
public static boolean moreThanOne = true;
// 歡迎訊息
public static String SERVER_MESSAGE = "歡迎來到小喵谷 v145.1,歡迎各位小喵喵們的蒞臨";
public static String WELCOME_MESSAGE = "【歡迎加入 小喵谷 v145.1】";
public static List<MapleLoginBalloon> getBalloons() {
return mapleLoginBalloonList;
}
public enum PlayerGMRank {
NORMAL('@', 0),
INTERN('!', 3),
GM('!', 4),
SUPER_GM('!', 5),
ADMIN('!', 6),
GOD('!', 100);
private char commandPrefix;
private int level;
PlayerGMRank(char ch, int level) {
commandPrefix = ch;
this.level = level;
}
public char getCommandPrefix() {
return commandPrefix;
}
public int getLevel() {
return level;
}
public static PlayerGMRank getByLevel(int level) {
for (PlayerGMRank i : PlayerGMRank.values()) {
if (i.getLevel() == level) {
return i;
}
}
return PlayerGMRank.NORMAL;
}
}
public enum CommandType {
NORMAL(0),
TRADE(1),
MERCH(2);
private int level;
CommandType(int level) {
this.level = level;
}
public int getType() {
return level;
}
}
public static class MapleLoginBalloon {
public int nX, nY;
public String sMessage;
public MapleLoginBalloon(String sMessage, int nX, int nY) {
this.sMessage = sMessage;
this.nX = nX;
this.nY = nY;
}
}
}
| 28.657143 | 117 | 0.603855 |
967889e0559ff41ac39dde6d17880f94ec94b509 | 4,844 | package org.blondin.mpg.root;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import org.blondin.mpg.AbstractMockTestClient;
import org.blondin.mpg.config.Config;
import org.blondin.mpg.root.model.Coach;
import org.blondin.mpg.root.model.Dashboard;
import org.blondin.mpg.root.model.Player;
import org.blondin.mpg.root.model.TransferBuy;
import org.junit.Assert;
import org.junit.Test;
public class MpgClientTest extends AbstractMockTestClient {
@Test
public void testMockSignInKo() throws Exception {
stubFor(post("/user/signIn")
.willReturn(aResponse().withStatus(401).withHeader("Content-Type", "application/json").withBodyFile("mpg.user-signIn.bad.json")));
Config config = getConfig();
String url = "http://localhost:" + server.port();
try {
MpgClient.build(config, url);
Assert.fail("Invalid password is invalid");
} catch (UnsupportedOperationException e) {
Assert.assertEquals("Bad credentials",
"Unsupported status code: 401 Unauthorized / Content: {\"success\":false,\"error\":\"incorrectPasswordUser\"}", e.getMessage());
}
}
@Test
public void testMockSignInOk() throws Exception {
stubFor(post("/user/signIn")
.withRequestBody(equalToJson("{\"email\":\"[email protected]\",\"password\":\"foobar\",\"language\":\"fr-FR\"}"))
.willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("mpg.user-signIn.fake.json")));
MpgClient.build(getConfig(), "http://localhost:" + server.port());
Assert.assertTrue(true);
}
@Test
public void testMockCoach() throws Exception {
stubFor(post("/user/signIn")
.willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("mpg.user-signIn.fake.json")));
stubFor(get("/league/KLGXSSUG/coach")
.willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("mpg.coach.20180926.json")));
MpgClient mpgClient = MpgClient.build(getConfig(), "http://localhost:" + server.port());
Coach coach = mpgClient.getCoach("KLGXSSUG");
Assert.assertNotNull(coach);
Assert.assertNotNull(coach.getPlayers());
Assert.assertTrue(coach.getPlayers().size() > 10);
for (Player player : coach.getPlayers()) {
Assert.assertNotNull(player);
Assert.assertNotNull(player.getId());
Assert.assertNotNull(player.getPosition());
Assert.assertNotNull(player.getName(), player.getFirstName());
Assert.assertNotNull(player.getName(), player.getLastName());
Assert.assertNotNull(player.getName());
Assert.assertEquals(player.getName(), (player.getLastName() + " " + player.getFirstName()).trim());
Assert.assertFalse(player.getName(), player.getName().contains("null"));
}
}
@Test
public void testMockDashboard() throws Exception {
stubFor(post("/user/signIn")
.willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("mpg.user-signIn.fake.json")));
stubFor(get("/user/dashboard")
.willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("mpg.dashboard.KLGXSSUG-status-4.json")));
MpgClient mpgClient = MpgClient.build(getConfig(), "http://localhost:" + server.port());
Dashboard dashboard = mpgClient.getDashboard();
Assert.assertNotNull(dashboard);
Assert.assertNotNull(dashboard.getLeagues());
Assert.assertEquals("KLGXSSUG", dashboard.getLeagues().get(0).getId());
Assert.assertEquals("Rock on the grass", dashboard.getLeagues().get(0).getName());
}
@Test
public void testMockTransferBuy() throws Exception {
stubFor(post("/user/signIn")
.willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("mpg.user-signIn.fake.json")));
stubFor(get("/league/KX24XMUG/transfer/buy")
.willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("mpg.transfer.buy.KX24XMUG.20190202.json")));
MpgClient mpgClient = MpgClient.build(getConfig(), "http://localhost:" + server.port());
TransferBuy tb = mpgClient.getTransferBuy("KX24XMUG");
Assert.assertEquals(1, tb.getBudget());
Assert.assertTrue(tb.getAvailablePlayers().size() > 10);
}
}
| 52.086022 | 148 | 0.670314 |
6ba7d28905df34d1a95e825c3d18a4ee4c6581b8 | 1,089 | package net.cactusthorn.routing.convert;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class StringConstructorConverter implements Converter<Object> {
private static final MethodType METHOD_TYPE = MethodType.methodType(void.class, String.class);
private final Map<Type, MethodHandle> constructors = new HashMap<>();
@Override //
public Object convert(Class<?> type, Type genericType, Annotation[] annotations, String value) throws Throwable {
if (value == null) {
return null;
}
return constructors.get(type).invoke(value);
}
boolean register(Class<?> type) {
try {
MethodHandle methodHandle = MethodHandles.publicLookup().findConstructor(type, METHOD_TYPE);
constructors.put(type, methodHandle);
return true;
} catch (Exception e) {
return false;
}
}
}
| 31.114286 | 117 | 0.687787 |
3eeb37dd6cac02884abf0a54c45aba167321c588 | 533 | package com.climate.mirage.cache.disk;
import android.support.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class DiskCacheStrategy {
public static final int NONE = 1;
public static final int SOURCE = 2;
public static final int RESULT = 4;
public static final int ALL = 8;
@IntDef({DiskCacheStrategy.SOURCE,
DiskCacheStrategy.RESULT,
DiskCacheStrategy.ALL,
DiskCacheStrategy.NONE})
@Retention(RetentionPolicy.SOURCE)
public @interface Enforce {}
} | 24.227273 | 44 | 0.780488 |
a11c04984b010ad5deda1904ace60799365ab6aa | 1,635 | package com.justbuyit.model.event.subscription;
import javax.xml.bind.annotation.XmlRootElement;
import com.justbuyit.model.Company;
import com.justbuyit.model.Order;
import com.justbuyit.model.event.Event;
import com.justbuyit.model.event.EventType;
import com.justbuyit.model.event.Payload;
import com.justbuyit.model.event.subscription.CreateSubscriptionEvent.CreateSubscriptionPayload;
@XmlRootElement(name = "event")
public class CreateSubscriptionEvent extends Event<CreateSubscriptionPayload> {
@XmlRootElement(name = "payload")
public static class CreateSubscriptionPayload extends Payload {
private Company company;
private Order order;
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
}
public CreateSubscriptionEvent() {
super(EventType.SUBSCRIPTION_ORDER);
}
@Override
public void setPayload(CreateSubscriptionPayload payload) {
super.setPayload(payload);
}
@Override
public CreateSubscriptionPayload getPayload() {
return super.getPayload();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.getClass().getSimpleName()).append(": ").append(getPayload().getCompany().getUuid()).append(" / ").append(getCreator().getUuid());
return builder.toString();
}
}
| 26.803279 | 158 | 0.679511 |
ac3102090e16341f40a3f0f806166225ce42e4cd | 1,723 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.internal.cast;
import android.view.Display;
import com.google.android.gms.common.api.Status;
final class zzdy
implements com.google.android.gms.cast.CastRemoteDisplay.CastRemoteDisplaySessionResult
{
public zzdy(Display display)
{
// 0 0:aload_0
// 1 1:invokespecial #15 <Method void Object()>
zzge = Status.RESULT_SUCCESS;
// 2 4:aload_0
// 3 5:getstatic #20 <Field Status Status.RESULT_SUCCESS>
// 4 8:putfield #22 <Field Status zzge>
zzbx = display;
// 5 11:aload_0
// 6 12:aload_1
// 7 13:putfield #24 <Field Display zzbx>
// 8 16:return
}
public zzdy(Status status)
{
// 0 0:aload_0
// 1 1:invokespecial #15 <Method void Object()>
zzge = status;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #22 <Field Status zzge>
zzbx = null;
// 5 9:aload_0
// 6 10:aconst_null
// 7 11:putfield #24 <Field Display zzbx>
// 8 14:return
}
public final Display getPresentationDisplay()
{
return zzbx;
// 0 0:aload_0
// 1 1:getfield #24 <Field Display zzbx>
// 2 4:areturn
}
public final Status getStatus()
{
return zzge;
// 0 0:aload_0
// 1 1:getfield #22 <Field Status zzge>
// 2 4:areturn
}
private final Display zzbx;
private final Status zzge;
}
| 27.349206 | 88 | 0.56123 |
b6456e1a6446d9896f645b320e2237be9afa50bc | 1,992 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.api.invokable.operator;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.windowing.policy.EvictionPolicy;
import org.apache.flink.streaming.api.windowing.policy.TriggerPolicy;
public class WindowReduceInvokable<IN> extends WindowInvokable<IN, IN> {
private static final long serialVersionUID = 1L;
ReduceFunction<IN> reducer;
public WindowReduceInvokable(ReduceFunction<IN> userFunction,
LinkedList<TriggerPolicy<IN>> triggerPolicies,
LinkedList<EvictionPolicy<IN>> evictionPolicies) {
super(userFunction, triggerPolicies, evictionPolicies);
this.reducer = userFunction;
}
@Override
protected void callUserFunction() throws Exception {
Iterator<IN> reducedIterator = buffer.iterator();
IN reduced = null;
while (reducedIterator.hasNext() && reduced == null) {
reduced = reducedIterator.next();
}
while (reducedIterator.hasNext()) {
IN next = reducedIterator.next();
if (next != null) {
reduced = reducer.reduce(reduced, next);
}
}
if (reduced != null) {
collector.collect(reduced);
}
}
}
| 33.2 | 75 | 0.75502 |
729e0d3ef89426d8d6126a41d172220b7786d3b6 | 7,491 | /*
* Copyright (C) 2015 Square, Inc.
* Copyright (C) 2021 Scality, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.scality.osis.security.crypto;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import static java.util.Objects.requireNonNull;
/**
* HMAC-based Extract-and-Expand Key Derivation Function (HKDF) from
* <a href="http://tools.ietf.org/html/rfc5869">RFC-5869</a>. HKDF is a standard means to generate
* a derived key of arbitrary length.
*
* <pre>{@code
* // Instantiate an Hkdf object with a hash function.
* Hkdf hkdf = new Hkdf(Hash.SHA256);
*
* // Using some protected input keying material (IKM), extract a pseudo-random key (PRK) with a
* // random salt. Remember to store the salt so the key can be derived again.
* SecretKey prk = hkdf.extract(Hkdf.randomSalt(), ikm);
*
* // Expand the prk with some information related to your data and the length of the output key.
* SecretKey derivedKey = hkdf.expand(prk, "id: 5".getBytes(StandardCharsets.UTF_8), 32);
* }</pre>
*
* HKDF is a generic means for generating derived keys. In some cases, you may want to use it in a
* different manner. Consult the RFC for security considerations, when to omit a salt, skipping the
* extraction step, etc.
*/
public class Hkdf {
public enum Hash {
SHA256("HmacSHA256", 32);
// MD5 intentionally omitted
private final String algorithm;
private final int byteLength;
Hash(String algorithm, int byteLength) {
if (byteLength <= 0) {
throw new IllegalArgumentException("byteLength must be positive");
}
this.algorithm = algorithm;
this.byteLength = byteLength;
}
/**
* @return JCA-recognized algorithm name.
*/
public String getAlgorithm() {
return algorithm;
}
/**
* @return length of HMAC output in bytes.
*/
public int getByteLength() {
return byteLength;
}
}
private static Hash DEFAULT_HASH = Hash.SHA256;
private final Hash hash;
private final Provider provider;
private Hkdf(Hash hash, Provider provider) {
this.hash = hash;
this.provider = provider;
}
/**
* @return Hkdf constructed with default hash and derivation provider
*/
public static Hkdf usingDefaults() {
return new Hkdf(DEFAULT_HASH, null);
}
/**
* @param hash Supported hash function constant
* @return Hkdf constructed with a specific hash function
*/
public static Hkdf usingHash(Hash hash) {
return new Hkdf(requireNonNull(hash), null);
}
/**
* @param provider provider for key derivation, particularly useful when using HSMs
* @return Hkdf constructed with a specific JCE provider for key derivation
*/
public static Hkdf usingProvider(Provider provider) {
return new Hkdf(DEFAULT_HASH, requireNonNull(provider));
}
/**
* HKDF-Extract(salt, IKM) -> PRK
*
* @param salt optional salt value (a non-secret random value); if not provided, it is set to a string of HashLen zeros.
* @param ikm input keying material
* @return a pseudorandom key (of HashLen bytes)
*/
public SecretKey extract(SecretKey salt, byte[] ikm) {
requireNonNull(ikm, "ikm must not be null");
if (salt == null) {
salt = new SecretKeySpec(new byte[hash.getByteLength()], hash.getAlgorithm());
}
Mac mac = initMac(salt);
byte[] keyBytes = mac.doFinal(ikm);
return new SecretKeySpec(keyBytes, hash.getAlgorithm());
}
/**
* HKDF-Expand(PRK, info, L) -> OKM
*
* @param key a pseudorandom key of at least HashLen bytes (usually, the output from the extract step)
* @param info context and application specific information (can be empty)
* @param outputLength length of output keying material in bytes (<= 255*HashLen)
* @return output keying material
*/
public byte[] expand(SecretKey key, byte[] info, int outputLength) {
requireNonNull(key, "key must not be null");
if (outputLength < 1) {
throw new IllegalArgumentException("outputLength must be positive");
}
int hashLen = hash.getByteLength();
if (outputLength > 255 * hashLen) {
throw new IllegalArgumentException("outputLength must be less than or equal to 255*HashLen");
}
if (info == null) {
info = new byte[0];
}
/*
The output OKM is calculated as follows:
N = ceil(L/HashLen)
T = T(1) | T(2) | T(3) | ... | T(N)
OKM = first L bytes of T
where:
T(0) = empty string (zero length)
T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
...
*/
int n = (outputLength % hashLen == 0) ?
outputLength / hashLen :
(outputLength / hashLen) + 1;
byte[] hashRound = new byte[0];
ByteBuffer generatedBytes = ByteBuffer.allocate(Math.multiplyExact(n, hashLen));
Mac mac = initMac(key);
for (int roundNum = 1; roundNum <= n; roundNum++) {
mac.reset();
ByteBuffer t = ByteBuffer.allocate(hashRound.length + info.length + 1);
t.put(hashRound);
t.put(info);
t.put((byte)roundNum);
hashRound = mac.doFinal(t.array());
generatedBytes.put(hashRound);
}
byte[] result = new byte[outputLength];
generatedBytes.rewind();
generatedBytes.get(result, 0, outputLength);
return result;
}
/**
* Generates a random salt value to be used with {@link #extract(javax.crypto.SecretKey, byte[])}.
*
* @return randomly generated SecretKey to use for PRK extraction.
*/
public SecretKey randomSalt() {
SecureRandom random = new SecureRandom();
byte[] randBytes = new byte[hash.getByteLength()];
random.nextBytes(randBytes);
return new SecretKeySpec(randBytes, hash.getAlgorithm());
}
private Mac initMac(SecretKey key) {
Mac mac;
try {
if (provider != null) {
mac = Mac.getInstance(hash.getAlgorithm(), provider);
} else {
mac = Mac.getInstance(hash.getAlgorithm());
}
mac.init(key);
return mac;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
throw new IllegalArgumentException(e);
}
}
}
| 34.05 | 124 | 0.623281 |
bbcddfa6829a9200d049926a854bc85e6af60580 | 2,077 | /**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2017 Ruhr University Bochum / Hackmanit GmbH
*
* Licensed under Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package de.rub.nds.tlsattacker.core.protocol.handler;
import de.rub.nds.tlsattacker.core.protocol.message.HeartbeatMessage;
import de.rub.nds.tlsattacker.core.protocol.parser.HeartbeatMessageParser;
import de.rub.nds.tlsattacker.core.protocol.preparator.HeartbeatMessagePreparator;
import de.rub.nds.tlsattacker.core.protocol.serializer.HeartbeatMessageSerializer;
import de.rub.nds.tlsattacker.core.state.TlsContext;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class HeartbeatMessageHandlerTest {
private HeartbeatMessageHandler handler;
private TlsContext context;
@Before
public void setUp() {
context = new TlsContext();
handler = new HeartbeatMessageHandler(context);
}
@After
public void tearDown() {
}
/**
* Test of getParser method, of class HeartbeatMessageHandler.
*/
@Test
public void testGetParser() {
assertTrue(handler.getParser(new byte[1], 0) instanceof HeartbeatMessageParser);
}
/**
* Test of getPreparator method, of class HeartbeatMessageHandler.
*/
@Test
public void testGetPreparator() {
assertTrue(handler.getPreparator(new HeartbeatMessage()) instanceof HeartbeatMessagePreparator);
}
/**
* Test of getSerializer method, of class HeartbeatMessageHandler.
*/
@Test
public void testGetSerializer() {
assertTrue(handler.getSerializer(new HeartbeatMessage()) instanceof HeartbeatMessageSerializer);
}
/**
* Test of adjustTLSContext method, of class HeartbeatMessageHandler.
*/
@Test
public void testAdjustTLSContext() {
HeartbeatMessage message = new HeartbeatMessage();
handler.adjustTLSContext(message);
// TODO check that context did not change
}
}
| 29.253521 | 104 | 0.718344 |
6333c5530628c07afd2177cc46038af79f64ad96 | 1,081 | package com.ps.domain;
public class WebResponse<T> {
private boolean ok;
private String message;
private T responseObject;
public WebResponse(boolean ok, String message) {
this.ok = ok;
this.message = message;
this.responseObject = null;
}
public WebResponse(boolean ok, String message, T responseObject) {
this.ok = ok;
this.message = message;
this.responseObject = responseObject;
}
@Override
public String toString() {
return "WebResponse{" +
"ok=" + ok +
", message='" + message + '\'' +
", responseObject=" + responseObject +
'}';
}
public boolean isOk() {
return ok;
}
public void setOk(boolean ok) {
this.ok = ok;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setResponseObject(T responseObject) {
this.responseObject = responseObject;
}
}
| 20.788462 | 70 | 0.560592 |
3f03f222a286b07edee723c13f398712e0dac0e4 | 2,492 | package org.jboss.resteasy.test.interceptor;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.resteasy.test.interceptor.resource.PriorityExecutionResource;
import org.jboss.resteasy.test.interceptor.resource.ResponseBuilderCustomResponseFilter;
//import org.jboss.resteasy.test.interceptor.resource.ResponseBuilderCustomRequestFilter;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.utils.PortProviderUtil;
import org.jboss.resteasy.utils.TestUtil;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
/**
* Demonstrates that a Response filter can process the entity data in a response object
* and the entity can be properly accessed by the client call.
*/
@RunWith(Arquillian.class)
@RunAsClient
public class ClientFilterResponseBuilderTest {
@Deployment
public static Archive<?> deploy() {
WebArchive war = TestUtil.prepareArchive(
ClientFilterResponseBuilderTest.class.getSimpleName());
war.addClasses(ResponseBuilderCustomResponseFilter.class,
PriorityExecutionResource.class);
return TestUtil.finishContainerPrepare(war, null);
}
static Client client;
@Before
public void setup() {
client = ClientBuilder.newClient();
}
@After
public void cleanup() {
client.close();
}
private String generateURL(String path) {
return PortProviderUtil.generateURL(path,
ClientFilterResponseBuilderTest.class.getSimpleName());
}
@Test
public void testResponse() throws Exception {
try {
client.register(ResponseBuilderCustomResponseFilter.class);
Response response = client.target(generateURL("/test")).request().get();
Object resultObj = response.getEntity();
String result = response.readEntity(String.class);
int status = response.getStatus();
Assert.assertEquals("test", result);
Assert.assertEquals(200, status);
} catch (ProcessingException pe) {
Assert.fail(pe.getMessage());
}
}
}
| 34.136986 | 89 | 0.721509 |
53797c2350409110bf27b75ebabc1520083e7e27 | 2,868 | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.client.validation.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.validation.TicketValidationException;
import java.io.IOException;
/**
* This is {@link JsonValidationResponseParser}.
*
* @author Misagh Moayyed
*/
final class JsonValidationResponseParser {
private final ObjectMapper objectMapper;
public JsonValidationResponseParser() {
this.objectMapper = new ObjectMapper();
this.objectMapper.findAndRegisterModules();
}
public TicketValidationJsonResponse parse(final String response) throws TicketValidationException, IOException {
if (CommonUtils.isBlank(response)) {
throw new TicketValidationException("Invalid JSON response; The response is empty");
}
final TicketValidationJsonResponse json = this.objectMapper.readValue(response, TicketValidationJsonResponse.class);
final TicketValidationJsonResponse.CasServiceResponseAuthentication serviceResponse = json.getServiceResponse();
if (serviceResponse.getAuthenticationFailure() != null
&& serviceResponse.getAuthenticationSuccess() != null) {
throw new TicketValidationException("Invalid JSON response; It indicates both a success "
+ "and a failure event, which is indicative of a server error. The actual response is " + response);
}
if (serviceResponse.getAuthenticationFailure() != null) {
final String error = json.getServiceResponse().getAuthenticationFailure().getCode()
+ " - " + serviceResponse.getAuthenticationFailure().getDescription();
throw new TicketValidationException(error);
}
final String principal = json.getServiceResponse().getAuthenticationSuccess().getUser();
if (CommonUtils.isEmpty(principal)) {
throw new TicketValidationException("No principal was found in the response from the CAS server.");
}
return json;
}
}
| 42.80597 | 124 | 0.724198 |
c27d2b13b392191aee8a597c86a7ad2875e94a10 | 3,500 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pt.inescid.nosqlundo.recovery;
import java.util.ArrayList;
import org.bson.Document;
import org.bson.types.ObjectId;
import pt.inescid.nosqlundo.MongoUndo;
/**
*
* @author davidmatos
*/
public class MongoRecoveryUndo extends MongoRecovery {
public MongoRecoveryUndo(ArrayList<OpLog> opLogsToRemove, String database) {
super(opLogsToRemove, database);
}
@Override
public void recover() {
if(MongoUndo.jFrameMain != null){
MongoUndo.jFrameMain.disableRecoveryButtons();
}
for (OpLog oplogToRemove : getOpLogsToRemove()) {
String databaseName = oplogToRemove.getNs().split("\\.")[0];
String collectionName = oplogToRemove.getNs().split("\\.")[1];
if (oplogToRemove.getOp() == 'i') {
MongoUndo.mongoClient.getDatabase(databaseName).getCollection(collectionName).deleteOne(oplogToRemove.getO());
continue;
}
// ArrayList<OpLog> documentOpLogs = RecoveryUtils.getDocumentOpLogs(oplogToRemove.getNs().split("\\.")[0],
// oplogToRemove.getNs().split("\\.")[1], oplogToRemove.getO().getObjectId("_id").toString(), 1);
ArrayList<OpLog> documentOpLogs = RecoveryUtils.getDocumentOpLogs(oplogToRemove.getNs().split("\\.")[0],
oplogToRemove.getNs().split("\\.")[1], oplogToRemove.getO().get("_id"), 1);
Document documentRecovered = new Document();
//start reconstructing the document
if(MongoUndo.jFrameMain != null){
MongoUndo.jFrameMain.setNrOperations(documentOpLogs.size());
}
for (OpLog oplog : documentOpLogs) {
if(MongoUndo.jFrameMain != null){
MongoUndo.jFrameMain.setCurrentOperation("Reverting " + oplog.toString());
}
if (!oplog.getTs().equals(oplogToRemove.getTs())) {
//if it's not the one to remove
Document updateSet = new Document();
if (oplog.getOp() == 'i') {
updateSet = oplog.getO();
} else if (oplog.getOp() == 'u') {
if (oplog.getO().containsKey("$set")) {
updateSet = (Document) oplog.getO().get("$set");
} else {
updateSet = oplog.getO();
}
}
for (String key : updateSet.keySet()) {
documentRecovered.put(key, updateSet.get(key));
}
}
}
ObjectId _id = (ObjectId) documentRecovered.get("_id");
MongoUndo.mongoClient.getDatabase(databaseName).getCollection(collectionName).deleteOne(new Document("_id", _id));
MongoUndo.mongoClient.getDatabase(databaseName).getCollection(collectionName).insertOne(documentRecovered);
System.out.println("Undo operation");
}
if(MongoUndo.jFrameMain != null){
MongoUndo.jFrameMain.setCurrentOperation("Recovery completed");
MongoUndo.jFrameMain.enableRecoveryButtons();
}
}
}
| 38.043478 | 126 | 0.560286 |
78bc347e775931a66e271c6a7c3277b7fb40902c | 4,447 | /*
*
* * Copyright 2013 Jive Software
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.jivesoftware.sdk.api.tile.data;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.Serializable;
/**
* Created by rrutan on 2/4/14.
*/
@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT)
public class CalendarEvent implements Serializable {
@JsonSerialize(include=JsonSerialize.Inclusion.ALWAYS)
private String start;
private String duration;
private String location;
@JsonSerialize(include=JsonSerialize.Inclusion.ALWAYS)
private String title;
private String description;
private int attendees;
private TileAction action;
public CalendarEvent() {
start = null;
duration = null;
location = null;
title = null;
description = null;
attendees = 0;
action = null;
} // end constructor
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getAttendees() {
return attendees;
}
public void setAttendees(int attendees) {
this.attendees = attendees;
}
public TileAction getAction() {
return action;
}
public void setAction(TileAction action) {
this.action = action;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CalendarEvent that = (CalendarEvent) o;
if (attendees != that.attendees) return false;
if (action != null ? !action.equals(that.action) : that.action != null) return false;
if (description != null ? !description.equals(that.description) : that.description != null) return false;
if (duration != null ? !duration.equals(that.duration) : that.duration != null) return false;
if (location != null ? !location.equals(that.location) : that.location != null) return false;
if (start != null ? !start.equals(that.start) : that.start != null) return false;
if (title != null ? !title.equals(that.title) : that.title != null) return false;
return true;
}
@Override
public int hashCode() {
int result = start != null ? start.hashCode() : 0;
result = 31 * result + (duration != null ? duration.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + attendees;
result = 31 * result + (action != null ? action.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "CalendarEvent{" +
"start='" + start + '\'' +
", duration='" + duration + '\'' +
", location='" + location + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
", attendees=" + attendees +
", action=" + action +
'}';
}
} // end class
| 28.324841 | 113 | 0.595233 |
9c0d798d566c8a362f1a7fe0c7641405ff8cc14c | 584 | package com.mz.model.weather;
import com.mz.model.cad.listener.IListener;
/**
* Created by Jamin on 8/5/15.
*/
public class WeatherManager {
private WeatherHandler mHandler = null;
private static final WeatherManager sManager = new WeatherManager();
public static WeatherManager getInstance() {
return sManager;
}
private WeatherManager() {
mHandler = new WeatherHandler();
}
public void fetchCurrentWeather(String cityId, final IListener<WeatherInfo> listener) {
mHandler.requestCurrentWeather(cityId, listener);
}
}
| 21.62963 | 91 | 0.700342 |
8bdc6503e1c04c90d5d082d1fd142153d2f7a300 | 396 | package io.airlift.http.client.spnego;
import java.net.URI;
import java.net.URISyntaxException;
class UriUtil
{
public static URI normalizedUri(URI uri)
{
try {
return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), null, null, null);
}
catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
}
| 22 | 98 | 0.618687 |
81b69ede8318e8d58f42200235cc989d497cffc9 | 3,063 | /**
* Copyright 2014 Google Inc. 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mr4c.nativec.jna;
import com.google.mr4c.nativec.ExternalAlgorithmDataSerializer;
import com.google.mr4c.nativec.ExternalAlgorithmSerializer;
import com.google.mr4c.nativec.ExternalFactory;
import com.google.mr4c.nativec.NativeAlgorithm;
import com.google.mr4c.nativec.jna.lib.Mr4cLibrary;
import com.google.mr4c.serialize.PropertiesSerializer;
import com.google.mr4c.util.MR4CLogging;
import com.sun.jna.NativeLibrary;
import java.io.File;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JnaNativeAlgorithm extends NativeAlgorithm {
protected static final Logger s_log = MR4CLogging.getLogger(JnaNativeAlgorithm.class);
private NativeLibrary m_lib;
private List<NativeLibrary> m_extras = new ArrayList<NativeLibrary>();
public JnaNativeAlgorithm(
ExternalAlgorithmSerializer algoSerializer,
ExternalAlgorithmDataSerializer dataSerializer,
PropertiesSerializer propsSerializer,
ExternalFactory factory
) {
super( algoSerializer, dataSerializer, propsSerializer, factory);
}
protected void loadNativeLibraries() {
s_log.info("Begin loading native libraries");
s_log.info("jna.library.path={}", System.getProperty("jna.library.path"));
s_log.info("jna.platform.library.path={}", System.getProperty("jna.platform.library.path"));
s_log.info("LD_LIBRARY_PATH={}", System.getenv("LD_LIBRARY_PATH"));
s_log.info("MR4C native library found at [{}]", Mr4cLibrary.JNA_NATIVE_LIB.getFile().getAbsolutePath());
String libName = getAlgorithmConfig().getArtifact();
s_log.info("Loading native algorithm library [{}]", libName);
m_lib = JnaUtils.loadLibrary(libName);
s_log.info("Native algorithm library found at [{}]", m_lib.getFile().getAbsolutePath());
for ( String name : getAlgorithmConfig().getExtras() ) {
s_log.info("Loading extra native library [{}]", name);
NativeLibrary lib = JnaUtils.loadLibrary(name);
s_log.info("Extra native library found at [{}]", lib.getFile().getAbsolutePath());
m_extras.add(lib);
}
s_log.info("End loading native libraries");
}
public Collection<File> getRequiredFiles() {
List<File> files = new ArrayList();
files.add(Mr4cLibrary.JNA_NATIVE_LIB.getFile());
files.add( m_lib.getFile());
for ( NativeLibrary lib : m_extras ) {
files.add(lib.getFile());
}
return files;
}
}
| 35.616279 | 106 | 0.755468 |
0d1146b1523f860abbaace6a1b43a3f77cbca5c9 | 4,812 | /**
* Copyright (c) 2015 See AUTHORS file
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.uats;
import org.mini2Dx.core.game.GameContainer;
import org.mini2Dx.core.graphics.Graphics;
import org.mini2Dx.core.screen.BasicGameScreen;
import org.mini2Dx.core.screen.GameScreen;
import org.mini2Dx.core.screen.ScreenManager;
import org.mini2Dx.core.screen.Transition;
import org.mini2Dx.core.screen.transition.FadeInTransition;
import org.mini2Dx.core.screen.transition.FadeOutTransition;
import org.mini2Dx.tiled.TiledMap;
import org.mini2Dx.tiled.TiledMapLoader;
import org.mini2Dx.tiled.exception.TiledException;
import org.mini2Dx.uats.util.ScreenIds;
import org.mini2Dx.uats.util.UATSelectionScreen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Color;
/**
* A {@link GameScreen} that allows visual user acceptance testing of orthogonal
* {@link TiledMap} rendering with layer caching enabled
*/
public class OrthogonalTiledMapWithCachingUAT extends BasicGameScreen {
private final AssetManager assetManager;
private TiledMap tiledMap;
public OrthogonalTiledMapWithCachingUAT(AssetManager assetManager) {
super();
this.assetManager = assetManager;
final TiledMapLoader.TiledMapParameter loadMapParameter = new TiledMapLoader.TiledMapParameter();
loadMapParameter.cacheLayers = true;
loadMapParameter.loadTilesets = true;
assetManager.load("orthogonal_tsx.tmx", TiledMap.class, loadMapParameter);
}
@Override
public void initialise(GameContainer gc) {
assetManager.finishLoading();
try {
tiledMap = assetManager.get("orthogonal_tsx.tmx", TiledMap.class);
} catch (TiledException e) {
e.printStackTrace();
}
}
@Override
public void update(GameContainer gc, ScreenManager<? extends GameScreen> screenManager,
float delta) {
if(Gdx.input.justTouched()) {
screenManager.enterGameScreen(UATSelectionScreen.SCREEN_ID, new FadeOutTransition(), new FadeInTransition());
}
tiledMap.update(delta);
}
@Override
public void interpolate(GameContainer gc, float alpha) {
}
@Override
public void render(GameContainer gc, Graphics g) {
g.setBackgroundColor(Color.WHITE);
g.setColor(Color.RED);
tiledMap.draw(g, 0, 0);
tiledMap.getTilesets().get(0).drawTileset(g, tiledMap.getWidth() * tiledMap.getTileWidth() + 32, 0);
g.scale(1.25f,1.25f);
g.rotate(5f, 0f, (tiledMap.getHeight() * tiledMap.getTileHeight()) * 2);
tiledMap.draw(g, 0, (tiledMap.getHeight() * tiledMap.getTileHeight()) * 2, 1, 1, 4, 8);
g.rotate(-5f, 0f, (tiledMap.getHeight() * tiledMap.getTileHeight()) * 2);
g.scale(0.8f,0.8f);
tiledMap.draw(g, 32, tiledMap.getHeight() * tiledMap.getTileHeight(), 1, 1, 4, 8);
}
@Override
public void preTransitionIn(Transition transitionIn) {
}
@Override
public void postTransitionIn(Transition transitionIn) {
}
@Override
public void preTransitionOut(Transition transitionOut) {
}
@Override
public void postTransitionOut(Transition transitionOut) {
}
@Override
public int getId() {
return ScreenIds.getScreenId(OrthogonalTiledMapWithCachingUAT.class);
}
}
| 41.843478 | 758 | 0.736492 |
d6808c4107e698bd76e599ea1d5784a178f857e7 | 849 | package com.lanking.cloud.domain.support.common.auth;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* 支撑系统权限-角色&菜单关系表
*
* @since 3.9.3
* @author <a href="mailto:[email protected]">sikai.wang</a>
* @version 2017年3月20日
*/
@MappedSuperclass
public class ConsoleRoleMenKey implements Serializable {
private static final long serialVersionUID = 2025797441329952696L;
/**
* 角色ID
*/
@Id
@Column(name = "role_id")
private Long roleId;
/**
* 菜单ID
*/
@Id
@Column(name = "menu_id")
private Long menuId;
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getMenuId() {
return menuId;
}
public void setMenuId(Long menuId) {
this.menuId = menuId;
}
}
| 16.98 | 67 | 0.706714 |
d6f5f3671e6f14b10e5de5f590092ecec7d227ff | 1,358 | package com.sunsharing.eos.common.serialize.support.json;
import com.alibaba.fastjson.parser.ParserConfig;
import com.sunsharing.eos.common.serialize.ObjectInput;
import com.sunsharing.eos.common.serialize.ObjectOutput;
import com.sunsharing.eos.common.serialize.Serialization;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FastJsonSerialization implements Serialization {
static {
ParserConfig.getGlobalInstance().putDeserializer(Object[].class,
new ObjectArrayDeserializer());
}
public byte getContentTypeId() {
return 6;
}
public String getContentType() {
return "text/json";
}
public ObjectOutput serialize(OutputStream output) throws IOException {
return new FastJsonObjectOutput(output);
}
public ObjectInput deserialize(InputStream input) throws IOException {
return new FastJsonObjectInput(input);
}
//
// public static void main(String[] args) {
// RpcParams rpc = new RpcParams();
// Map map = new HashMap();
// map.put("a", 1);
// rpc.setArguments(new Object[]{map, 1, "1", 1.1, new HeartPro()});
// String str = JSONObject.toJSONString(rpc);
// System.out.println(str);
// RpcParams de = JSON.parseObject(str, RpcParams.class);
// }
} | 30.177778 | 75 | 0.684831 |
0f3750630c907450687974fce73c8d66dbe03564 | 2,003 | package com.gongsir.wxapp.controller.admin;
import com.gongsir.wxapp.utils.SHA1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
/**
* @author gongsir
* @date 2020/2/24 15:32
* 编码不要畏惧变化,要拥抱变化
*/
@RestController
@RequestMapping("/admin/wx")
public class WxController {
private static final Logger LOGGER = LoggerFactory.getLogger(WxController.class);
private static final String TOKEN = "LssILoveYou";
@GetMapping(path = "")
public void get(HttpServletRequest request, HttpServletResponse response){
// 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
String signature = request.getParameter("signature");
// 时间戳
String timestamp = request.getParameter("timestamp");
// 随机数
String nonce = request.getParameter("nonce");
// 随机字符串
String echostr = request.getParameter("echostr");
LOGGER.info("the signature from wx server:{}",signature);
String[] array = new String[] { TOKEN, timestamp, nonce };
StringBuilder sb = new StringBuilder();
// 字符串排序
Arrays.sort(array);
for (String s : array) {
sb.append(s);
}
String str = sb.toString();
String code = SHA1.getSha1(str);
LOGGER.info("the signature from my server:{}",code);
try (PrintWriter out = response.getWriter()) {
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,否则接入失败
if (code.equals(signature)) {
out.print(echostr);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 31.296875 | 85 | 0.662007 |
f657fb16368bd72bf374660417fe8271d548e05f | 11,891 | package biz.paluch.logging.gelf.intern;
import org.json.simple.JSONValue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPOutputStream;
/**
* (c) https://github.com/t0xa/gelfj
*/
public class GelfMessage {
public static final String FIELD_HOST = "host";
public static final String FIELD_SHORT_MESSAGE = "short_message";
public static final String FIELD_FULL_MESSAGE = "full_message";
public static final String FIELD_TIMESTAMP = "timestamp";
public static final String FIELD_LEVEL = "level";
public static final String FIELD_FACILITY = "facility";
public static final String ID_NAME = "id";
public static final String GELF_VERSION = "1.0";
public static final String DEFAULT_FACILITY = "logstash-gelf";
public static final int DEFAULT_MESSAGE_SIZE = 8192;
private static final byte[] GELF_CHUNKED_ID = new byte[] { 0x1e, 0x0f };
private static final BigDecimal TIME_DIVISOR = new BigDecimal(1000);
private String version = GELF_VERSION;
private String host;
private byte[] hostBytes = lastFourAsciiBytes("none");
private String shortMessage;
private String fullMessage;
private long javaTimestamp;
private String level;
private String facility = DEFAULT_FACILITY;
private Map<String, String> additonalFields = new HashMap<String, String>();
private int maximumMessageSize = DEFAULT_MESSAGE_SIZE;
public GelfMessage() {
}
public GelfMessage(String shortMessage, String fullMessage, long timestamp, String level) {
this.shortMessage = shortMessage;
this.fullMessage = fullMessage;
this.javaTimestamp = timestamp;
this.level = level;
}
public String toJson(String additionalFieldPrefix) {
Map<String, Object> map = new HashMap<String, Object>();
if (!isEmpty(getHost())) {
map.put(FIELD_HOST, getHost());
}
if (!isEmpty(shortMessage)) {
map.put(FIELD_SHORT_MESSAGE, getShortMessage());
}
if (!isEmpty(getFullMessage())) {
map.put(FIELD_FULL_MESSAGE, getFullMessage());
}
if (getJavaTimestamp() != 0) {
map.put(FIELD_TIMESTAMP, getTimestamp());
}
if (!isEmpty(getLevel())) {
map.put(FIELD_LEVEL, getLevel());
}
if (!isEmpty(getFacility())) {
map.put(FIELD_FACILITY, getFacility());
}
for (Map.Entry<String, String> additionalField : additonalFields.entrySet()) {
if (!ID_NAME.equals(additionalField.getKey()) && additionalField.getValue() != null) {
// try adding the value as a double
Object value;
try {
value = Double.parseDouble(additionalField.getValue());
} catch (NumberFormatException ex) {
// fallback on the string value
value = additionalField.getValue();
}
map.put(additionalFieldPrefix + additionalField.getKey(), value);
}
}
return JSONValue.toJSONString(map);
}
public String toJson() {
return toJson("_");
}
public ByteBuffer[] toUDPBuffers() {
byte[] messageBytes = gzipMessage(toJson());
// calculate the length of the datagrams array
int diagrams_length = messageBytes.length / maximumMessageSize;
// In case of a remainder, due to the integer division, add a extra datagram
if (messageBytes.length % maximumMessageSize != 0) {
diagrams_length++;
}
ByteBuffer[] datagrams = new ByteBuffer[diagrams_length];
if (messageBytes.length > maximumMessageSize) {
sliceDatagrams(messageBytes, datagrams);
} else {
datagrams[0] = ByteBuffer.allocate(messageBytes.length);
datagrams[0].put(messageBytes);
datagrams[0].flip();
}
return datagrams;
}
public ByteBuffer toTCPBuffer() {
byte[] messageBytes;
// Do not use GZIP, as the headers will contain \0 bytes
// graylog2-server uses \0 as a delimiter for TCP frames
// see: https://github.com/Graylog2/graylog2-server/issues/127
String json = toJson();
json += '\0';
messageBytes = Charsets.utf8(json);
ByteBuffer buffer = ByteBuffer.allocate(messageBytes.length);
buffer.put(messageBytes);
buffer.flip();
return buffer;
}
private void sliceDatagrams(byte[] messageBytes, ByteBuffer[] datagrams) {
int messageLength = messageBytes.length;
byte[] messageId = ByteBuffer.allocate(8).putInt(getCurrentMillis()) // 4 least-significant-bytes of the time in millis
.put(hostBytes) // 4 least-significant-bytes of the host
.array();
// Reuse length of datagrams array since this is supposed to be the correct number of datagrams
int num = datagrams.length;
for (int idx = 0; idx < num; idx++) {
byte[] header = concatByteArray(GELF_CHUNKED_ID, concatByteArray(messageId, new byte[] { (byte) idx, (byte) num }));
int from = idx * maximumMessageSize;
int to = from + maximumMessageSize;
if (to >= messageLength) {
to = messageLength;
}
byte[] datagram = concatByteArray(header, Arrays.copyOfRange(messageBytes, from, to));
datagrams[idx] = ByteBuffer.allocate(datagram.length);
datagrams[idx].put(datagram);
datagrams[idx].flip();
}
}
public int getCurrentMillis() {
return (int) System.currentTimeMillis();
}
private byte[] gzipMessage(String message) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
GZIPOutputStream stream = new GZIPOutputStream(bos);
byte[] bytes = Charsets.utf8(message);
stream.write(bytes);
stream.finish();
Closer.close(stream);
byte[] zipped = bos.toByteArray();
Closer.close(bos);
return zipped;
} catch (IOException e) {
return null;
}
}
private byte[] lastFourAsciiBytes(String host) {
final String shortHost = host.length() >= 4 ? host.substring(host.length() - 4) : host;
return Charsets.ascii(shortHost);
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
if (host != null) {
this.hostBytes = lastFourAsciiBytes(host);
}
}
public String getShortMessage() {
return !isEmpty(shortMessage) ? shortMessage : "<empty>";
}
public void setShortMessage(String shortMessage) {
this.shortMessage = shortMessage;
}
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
public String getTimestamp() {
return new BigDecimal(javaTimestamp).divide(TIME_DIVISOR).toPlainString();
}
public Long getJavaTimestamp() {
return javaTimestamp;
}
public void setJavaTimestamp(long javaTimestamp) {
this.javaTimestamp = javaTimestamp;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getFacility() {
return facility;
}
public void setFacility(String facility) {
this.facility = facility;
}
/**
* Add multiple fields (key/value pairs)
*
* @param fields
* @return the current GelfMessage.
*/
public GelfMessage addFields(Map<String, String> fields) {
if (fields == null) {
throw new IllegalArgumentException("fields is null");
}
getAdditonalFields().putAll(fields);
return this;
}
/**
* Add a particular field.
*
* @param key
* @param value
* @return the current GelfMessage.
*/
public GelfMessage addField(String key, String value) {
getAdditonalFields().put(key, value);
return this;
}
public Map<String, String> getAdditonalFields() {
return additonalFields;
}
public boolean isValid() {
return isShortOrFullMessagesExists() && !isEmpty(version) && !isEmpty(host) && !isEmpty(facility);
}
private boolean isShortOrFullMessagesExists() {
return !isEmpty(shortMessage) || !isEmpty(fullMessage);
}
public boolean isEmpty(String str) {
return str == null || "".equals(str.trim());
}
private byte[] concatByteArray(byte[] first, byte[] second) {
byte[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public int getMaximumMessageSize() {
return maximumMessageSize;
}
public void setMaximumMessageSize(int maximumMessageSize) {
this.maximumMessageSize = maximumMessageSize;
}
public String getField(String fieldName) {
return getAdditonalFields().get(fieldName);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof GelfMessage)) {
return false;
}
GelfMessage that = (GelfMessage) o;
if (javaTimestamp != that.javaTimestamp) {
return false;
}
if (maximumMessageSize != that.maximumMessageSize) {
return false;
}
if (additonalFields != null ? !additonalFields.equals(that.additonalFields) : that.additonalFields != null) {
return false;
}
if (facility != null ? !facility.equals(that.facility) : that.facility != null) {
return false;
}
if (fullMessage != null ? !fullMessage.equals(that.fullMessage) : that.fullMessage != null) {
return false;
}
if (host != null ? !host.equals(that.host) : that.host != null) {
return false;
}
if (!Arrays.equals(hostBytes, that.hostBytes)) {
return false;
}
if (level != null ? !level.equals(that.level) : that.level != null) {
return false;
}
if (shortMessage != null ? !shortMessage.equals(that.shortMessage) : that.shortMessage != null) {
return false;
}
if (version != null ? !version.equals(that.version) : that.version != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = version != null ? version.hashCode() : 0;
result = 31 * result + (host != null ? host.hashCode() : 0);
result = 31 * result + (hostBytes != null ? Arrays.hashCode(hostBytes) : 0);
result = 31 * result + (shortMessage != null ? shortMessage.hashCode() : 0);
result = 31 * result + (fullMessage != null ? fullMessage.hashCode() : 0);
result = 31 * result + (int) (javaTimestamp ^ (javaTimestamp >>> 32));
result = 31 * result + (level != null ? level.hashCode() : 0);
result = 31 * result + (facility != null ? facility.hashCode() : 0);
result = 31 * result + (additonalFields != null ? additonalFields.hashCode() : 0);
result = 31 * result + maximumMessageSize;
return result;
}
}
| 31.965054 | 128 | 0.603818 |
d518c860afefb1264aeb060bf31c48a1d24697ee | 3,938 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package org.apache.storm.perf;
import org.apache.storm.Config;
import org.apache.storm.LocalCluster;
import org.apache.storm.generated.StormTopology;
import org.apache.storm.perf.bolt.CountBolt;
import org.apache.storm.perf.bolt.SplitSentenceBolt;
import org.apache.storm.perf.spout.FileReadSpout;
import org.apache.storm.perf.utils.Helper;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.tuple.Fields;
import org.apache.storm.utils.Utils;
import java.util.Map;
/***
* This topo helps measure speed of word count.
* Spout loads a file into memory on initialization, then emits the lines in an endless loop.
*/
public class FileReadWordCountTopo {
public static final String SPOUT_ID = "spout";
public static final String COUNT_ID = "counter";
public static final String SPLIT_ID = "splitter";
public static final String TOPOLOGY_NAME = "FileReadWordCountTopo";
// Config settings
public static final String SPOUT_NUM = "spout.count";
public static final String SPLIT_NUM = "splitter.count";
public static final String COUNT_NUM = "counter.count";
public static final String INPUT_FILE = "input.file";
public static final int DEFAULT_SPOUT_NUM = 1;
public static final int DEFAULT_SPLIT_BOLT_NUM = 2;
public static final int DEFAULT_COUNT_BOLT_NUM = 2;
public static StormTopology getTopology(Map config) {
final int spoutNum = Helper.getInt(config, SPOUT_NUM, DEFAULT_SPOUT_NUM);
final int spBoltNum = Helper.getInt(config, SPLIT_NUM, DEFAULT_SPLIT_BOLT_NUM);
final int cntBoltNum = Helper.getInt(config, COUNT_NUM, DEFAULT_COUNT_BOLT_NUM);
final String inputFile = Helper.getStr(config, INPUT_FILE);
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout(SPOUT_ID, new FileReadSpout(inputFile), spoutNum);
builder.setBolt(SPLIT_ID, new SplitSentenceBolt(), spBoltNum).localOrShuffleGrouping(SPOUT_ID);
builder.setBolt(COUNT_ID, new CountBolt(), cntBoltNum).fieldsGrouping(SPLIT_ID, new Fields(SplitSentenceBolt.FIELDS));
return builder.createTopology();
}
public static void main(String[] args) throws Exception {
if(args.length <= 0) {
// For IDE based profiling ... submit topology to local cluster
Config conf = new Config();
conf.put(INPUT_FILE, "resources/randomwords.txt");
LocalCluster cluster = Helper.runOnLocalCluster(TOPOLOGY_NAME, getTopology(conf));
Helper.setupShutdownHook(cluster, TOPOLOGY_NAME);
while (true) {// run indefinitely till Ctrl-C
Thread.sleep(20_000_000);
}
} else {
// Submit to Storm cluster
if (args.length !=2) {
System.err.println("args: runDurationSec confFile");
return;
}
Integer durationSec = Integer.parseInt(args[0]);
Map topoConf = Utils.findAndReadConfigFile(args[1]);
Helper.runOnClusterAndPrintMetrics(durationSec, TOPOLOGY_NAME, topoConf, getTopology(topoConf));
}
}
}
| 40.597938 | 126 | 0.711783 |
4e60df1df539abd12a7c47cccc7af5ad2aaab331 | 1,090 | package com.chisw.start.sandbox;
public class MyFirstProgram {
public static void main(String[] args) {
System.out.println("Hello, World1!");
hello();
hello("Test"); //вызов функции с параметром
System.out.println(area(8.90));
double a1 = 5;
double b1 = 7;
System.out.println(area(a1,b1));
//выполняем функцию через обект s класса Square
Square s = new Square(90);
System.out.println("квадрат со стороной " + s.l + " равен " + s.area());
Rectagular r = new Rectagular(70, 75);
System.out.println("прямоугольник со сторонами "+ r.a + " и " + r.b + " равен " + r.area());
}
//функция, которая может быть вызвана без создания класса
public static void hello() {
System.out.println("Hello, " + "World2!");
}
public static void hello(String smth) {
System.out.println("Hello, " + smth);
}
public static double area(double len){
return len*len;
}
public static double area(double a, double b) {
return a*b;
}
}
| 24.772727 | 100 | 0.581651 |
52438b9b82eda41cc8947a603085413ae0a01a43 | 7,545 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.blankm.progressmanager.demo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import me.blankm.progressmanager.ProgressListener;
import me.blankm.progressmanager.ProgressManager;
import me.blankm.progressmanager.body.ProgressInfo;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private ProgressBar mGlideProgress;
private ProgressBar mDownloadProgress;
private ProgressBar mUploadProgress;
private TextView mGlideProgressText;
private TextView mDownloadProgressText;
private TextView mUploadProgressText;
private View mRootView;
private ProgressInfo mLastDownloadingInfo;
private ProgressInfo mLastUploadingInfo;
private Handler mHandler;
private static final String URL_BUNDLE_KEY = "url_bundle_key";
public static MainFragment newInstance(String imageUrl, String downloadUrl, String uploadUrl) {
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
ArrayList<String> list = new ArrayList<>(Arrays.asList(imageUrl, downloadUrl, uploadUrl));
bundle.putStringArrayList(URL_BUNDLE_KEY, list);
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
return mRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mHandler = new Handler();
initView();
initData();
}
private void initView() {
mGlideProgress = mRootView.findViewById(R.id.glide_progress);
mDownloadProgress = mRootView.findViewById(R.id.download_progress);
mUploadProgress = mRootView.findViewById(R.id.upload_progress);
mGlideProgressText = mRootView.findViewById(R.id.glide_progress_text);
mDownloadProgressText = mRootView.findViewById(R.id.download_progress_text);
mUploadProgressText = mRootView.findViewById(R.id.upload_progress_text);
}
private void initData() {
Bundle arguments = getArguments();
ArrayList<String> list = arguments.getStringArrayList(URL_BUNDLE_KEY);
if (list == null || list.isEmpty())
return;
//Glide 加载监听
ProgressManager.getInstance().addResponseListener(list.get(0), getGlideListener());
//Okhttp/Retofit 下载监听
ProgressManager.getInstance().addResponseListener(list.get(1), getDownloadListener());
//Okhttp/Retofit 上传监听
ProgressManager.getInstance().addRequestListener(list.get(2), getUploadListener());
list.clear();//清理 list 里的引用
}
@NonNull
private ProgressListener getUploadListener() {
return new ProgressListener() {
@Override
public void onProgress(ProgressInfo progressInfo) {
// 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束,
// 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息
// 这里我就取最新的上传进度用来展示,顺便展示下 id 的用法
if (mLastUploadingInfo == null) {
mLastUploadingInfo = progressInfo;
}
//因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新
if (progressInfo.getId() < mLastUploadingInfo.getId()) {
return;
} else if (progressInfo.getId() > mLastUploadingInfo.getId()) {
mLastUploadingInfo = progressInfo;
}
int progress = mLastUploadingInfo.getPercent();
mUploadProgress.setProgress(progress);
mUploadProgressText.setText(progress + "%");
Log.d(TAG, "--Upload-- " + progress + " %");
}
@Override
public void onError(long id, Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
mUploadProgress.setProgress(0);
mUploadProgressText.setText("error");
}
});
}
};
}
@NonNull
private ProgressListener getDownloadListener() {
return new ProgressListener() {
@Override
public void onProgress(ProgressInfo progressInfo) {
// 如果你不屏蔽用户重复点击上传或下载按钮,就可能存在同一个 Url 地址,上一次的上传或下载操作都还没结束,
// 又开始了新的上传或下载操作,那现在就需要用到 id(请求开始时的时间) 来区分正在执行的进度信息
// 这里我就取最新的下载进度用来展示,顺便展示下 id 的用法
if (mLastDownloadingInfo == null) {
mLastDownloadingInfo = progressInfo;
}
//因为是以请求开始时的时间作为 Id ,所以值越大,说明该请求越新
if (progressInfo.getId() < mLastDownloadingInfo.getId()) {
return;
} else if (progressInfo.getId() > mLastDownloadingInfo.getId()) {
mLastDownloadingInfo = progressInfo;
}
int progress = mLastDownloadingInfo.getPercent();
mDownloadProgress.setProgress(progress);
mDownloadProgressText.setText(progress + "%");
Log.d(TAG, "--Download-- " + progress + " %");
}
@Override
public void onError(long id, Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
mDownloadProgress.setProgress(0);
mDownloadProgressText.setText("error");
}
});
}
};
}
@NonNull
private ProgressListener getGlideListener() {
return new ProgressListener() {
@Override
public void onProgress(ProgressInfo progressInfo) {
int progress = progressInfo.getPercent();
mGlideProgress.setProgress(progress);
mGlideProgressText.setText(progress + "%");
Log.d(TAG, "--Glide-- " + progress + " %");
}
@Override
public void onError(long id, Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
mGlideProgress.setProgress(0);
mGlideProgressText.setText("error");
}
});
}
};
}
}
| 36.100478 | 123 | 0.614314 |
ce1c06ea404796ae05a17fc79348492a4da5aaab | 3,615 | package com.github.megatronking.svg.iconlibs;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import com.github.megatronking.svg.support.SVGRenderer;
/**
* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* SVG-Generator. It should not be modified by hand.
*/
public class ic_cake extends SVGRenderer {
public ic_cake(Context context) {
super(context);
mAlpha = 1.0f;
mWidth = dip2px(24.0f);
mHeight = dip2px(24.0f);
}
@Override
public void render(Canvas canvas, int w, int h, ColorFilter filter) {
final float scaleX = w / 24.0f;
final float scaleY = h / 24.0f;
mPath.reset();
mRenderPath.reset();
mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f});
mFinalPathMatrix.postScale(scaleX, scaleY);
mPath.moveTo(12.0f, 6.0f);
mPath.rCubicTo(1.11f, 0.0f, 2.0f, -0.9f, 2.0f, -2.0f);
mPath.rCubicTo(0.0f, -0.38f, -0.1f, -0.73f, -0.29f, -1.03f);
mPath.lineTo(12.0f, 0.0f);
mPath.rLineTo(-1.71f, 2.97f);
mPath.rCubicTo(-0.19f, 0.3f, -0.29f, 0.65f, -0.29f, 1.03f);
mPath.rCubicTo(0.0f, 1.1f, 0.9f, 2.0f, 2.0f, 2.0f);
mPath.close();
mPath.moveTo(12.0f, 6.0f);
mPath.rMoveTo(4.6f, 9.99f);
mPath.rLineTo(-1.07f, -1.07f);
mPath.rLineTo(-1.08f, 1.07f);
mPath.rCubicTo(-1.3f, 1.3f, -3.58f, 1.31f, -4.89f, 0.0f);
mPath.rLineTo(-1.07f, -1.07f);
mPath.rLineTo(-1.09f, 1.07f);
mPath.cubicTo(6.75f, 16.64f, 5.88f, 17.0f, 4.96f, 17.0f);
mPath.rCubicTo(-0.73f, 0.0f, -1.4f, -0.23f, -1.96f, -0.61f);
mPath.lineTo(3.0f, 21.0f);
mPath.rCubicTo(0.0f, 0.55f, 0.45f, 1.0f, 1.0f, 1.0f);
mPath.rLineTo(16.0f, 0f);
mPath.rCubicTo(0.55f, 0.0f, 1.0f, -0.45f, 1.0f, -1.0f);
mPath.rLineTo(0f, -4.61f);
mPath.rCubicTo(-0.56f, 0.38f, -1.23f, 0.61f, -1.96f, 0.61f);
mPath.rCubicTo(-0.92f, 0.0f, -1.79f, -0.36f, -2.44f, -1.01f);
mPath.close();
mPath.moveTo(16.6f, 15.99f);
mPath.moveTo(18.0f, 9.0f);
mPath.rLineTo(-5.0f, 0f);
mPath.lineTo(13.0f, 7.0f);
mPath.rLineTo(-2.0f, 0f);
mPath.rLineTo(0f, 2.0f);
mPath.lineTo(6.0f, 9.0f);
mPath.rCubicTo(-1.66f, 0.0f, -3.0f, 1.34f, -3.0f, 3.0f);
mPath.rLineTo(0f, 1.54f);
mPath.rCubicTo(0.0f, 1.08f, 0.88f, 1.96f, 1.96f, 1.96f);
mPath.rCubicTo(0.52f, 0.0f, 1.02f, -0.2f, 1.38f, -0.57f);
mPath.rLineTo(2.14f, -2.13f);
mPath.rLineTo(2.13f, 2.13f);
mPath.rCubicTo(0.74f, 0.74f, 2.03f, 0.74f, 2.77f, 0.0f);
mPath.rLineTo(2.14f, -2.13f);
mPath.rLineTo(2.13f, 2.13f);
mPath.rCubicTo(0.37f, 0.37f, 0.86f, 0.57f, 1.38f, 0.57f);
mPath.rCubicTo(1.08f, 0.0f, 1.96f, -0.88f, 1.96f, -1.96f);
mPath.lineTo(20.990002f, 12.0f);
mPath.cubicTo(21.0f, 10.34f, 19.66f, 9.0f, 18.0f, 9.0f);
mPath.close();
mPath.moveTo(18.0f, 9.0f);
mRenderPath.addPath(mPath, mFinalPathMatrix);
if (mFillPaint == null) {
mFillPaint = new Paint();
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
}
mFillPaint.setColor(applyAlpha(-16777216, 1.0f));
mFillPaint.setColorFilter(filter);
canvas.drawPath(mRenderPath, mFillPaint);
}
} | 37.65625 | 102 | 0.562102 |
70a32888d0bd538ca74ad9f58b98f2975f48b1b2 | 2,578 | package com.cosium.spring.data.jpa.entity.graph.repository.support;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.util.Assert;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Created on 24/11/16.
*
* @author Reda.Housni-Alaoui
*/
class RepositoryQueryEntityGraphInjector implements MethodInterceptor {
private static final Logger LOG =
LoggerFactory.getLogger(RepositoryQueryEntityGraphInjector.class);
private static final List<String> EXECUTE_QUERY_METHODS =
Arrays.asList("getResultList", "getSingleResult");
private final EntityManager entityManager;
private final EntityGraphBean entityGraphCandidate;
private RepositoryQueryEntityGraphInjector(
EntityManager entityManager, EntityGraphBean entityGraphCandidate) {
Assert.notNull(entityManager);
Assert.notNull(entityGraphCandidate);
this.entityManager = entityManager;
this.entityGraphCandidate = entityGraphCandidate;
}
static Query proxy(
Query query, EntityManager entityManager, EntityGraphBean entityGraphCandidate) {
ProxyFactory proxyFactory = new ProxyFactory(query);
proxyFactory.addAdvice(
new RepositoryQueryEntityGraphInjector(entityManager, entityGraphCandidate));
return (Query) proxyFactory.getProxy();
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (EXECUTE_QUERY_METHODS.contains(invocation.getMethod().getName())) {
addEntityGraphToQuery((Query) invocation.getThis());
}
return invocation.proceed();
}
private void addEntityGraphToQuery(Query query) {
if (CountQueryDetector.isCountQuery()) {
LOG.trace("CountQuery detected.");
return;
}
if (!entityGraphCandidate.isPrimary()
&& QueryHintsUtils.containsEntityGraph(query.getHints())) {
LOG.trace(
"The query hints passed with the find method already hold an entity graph. Overriding aborted because the candidate EntityGraph is optional.");
return;
}
QueryHintsUtils.removeEntityGraphs(query.getHints());
Map<String, Object> hints =
QueryHintsUtils.buildQueryHints(entityManager, entityGraphCandidate);
for (Map.Entry<String, Object> hint : hints.entrySet()) {
query.setHint(hint.getKey(), hint.getValue());
}
}
}
| 33.921053 | 153 | 0.75834 |
744c21c24eed3cf11a722d017296618fbe1ecb7b | 273 | package com.cryptobase.coinmarketcap.api;
import com.cryptobase.coinmarketcap.model.CoinMarket;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface CoinMarketAPI {
@GET("ticker")
Call<List<CoinMarket>> listCoinMarket();
}
| 18.2 | 53 | 0.772894 |
84d2d538d2018a2ca4578a2c451c08607643c31d | 12,836 | package pro2E.model;
/**
* <pre>
* The <b><code>AntennaArrayFunctions</code></b> class contains a set of static methods to calculate various antenna array parameters.
* </pre>
*
* @author pro2E - Team3
*
*/
public class AntennaArrayFunctions {
public static final double C = 3e8;
public static final double T = 2 * Math.PI;
/**
* <pre>
* Calculates and returns the frequency from a given wavelength.
* </pre>
*
* @param wavelength
* @return the frequency
*/
public static double frequency(double wavelength) {
return (C / wavelength);
}
/**
* <pre>
* Calculates and returns the wavelength from a given frequency.
* </pre>
*
* @param frequency
* @return the wavelength
*/
public static double wavelength(double frequency) {
return (C / frequency);
}
/**
* <pre>
* Calculates and returns the free space wave number.
* </pre>
*
* @param wavelength
* @return the free space wave number
*/
public static double k(double wavelength) {
return (T / wavelength);
}
/**
* <pre>
* Calculates and returns the time delay of a radiator in dependence of the phase and period.
* </pre>
*
* @param p
* the phase of the radiator
* @param period
* the period
* @return the time delay of a radiator
*/
public static double timeDelay(double p, double period) {
double delay = period / T * (p - MatlabFunctions.fix(p / T) * T);
return delay;
}
/**
* <pre>
* Calculates and return the phase of a radiator in dependence of the radiators position, the rotation angle and the wavelength.
* </pre>
*
* @param r
* a Radiator object
* @param rotationAng
* the rotation angle
* @param wavelength
* @return the phase of the given radiator
*/
public static double phaseShift(Radiator r, double rotationAng, double wavelength) {
double x = r.getX();
double y = r.getY();
return AntennaArrayFunctions.phaseShift(x, y, rotationAng, wavelength);
}
/**
* <pre>
* Calculates and return the phase of a radiator in dependence of the radiators position, the rotation angle and the wavelength.
* </pre>
*
* @param x
* the x-value of the position
* @param y
* the y-value of the position
* @param rotationAng
* the rotation angle
* @param wavelength
* @return the phase of the given radiator
*/
public static double phaseShift(double x, double y, double rotationAng, double wavelength) {
double shift = k(wavelength) * Math.hypot(x, y) * Math.cos(rotationAng - Math.atan2(y, x));
return shift;
}
/**
* <pre>
* Calculates and returns the complex element factor as a Complex object.
* </pre>
*
* @param wavelength
* @param radiatorType
* the radiator type
* @param radiatorAng
* the angle of the radiator
* @param rotationAng
* the rotation angle
* @return the complex element factor as a Complex object
*/
public static Complex se(double wavelength, int radiatorType, double radiatorAng, double rotationAng) {
switch (radiatorType) {
case AntennaArray.ISOTROPIC:
return new Complex(1.0);
case AntennaArray.DIPOLE:
double epsilon = 1e-6;
double diff = rotationAng - radiatorAng;
// sin(diff) != 0 (to prevent a division by zero)
// => diff != k * pi k = { 0, 1, 2 }
if (Math.abs(diff) < epsilon || Math.abs(diff - Math.PI) < epsilon || Math.abs(diff - T) < epsilon) {
return new Complex(0.0);
} else {
double elementFactor = Math.cos(Math.PI / 2 * Math.cos(diff)) / Math.sin(diff);
return new Complex(elementFactor);
}
default:
return new Complex(1.0);
}
}
/**
* <pre>
* Calculates and returns the complex array factor as an array of Complex objects.
* </pre>
*
* @param r
* an array of Radiator objects
* @param wavelength
* @param radiatorType
* the radiator type
* @param radiatorAng
* the angle of the radiator
* @param startAng
* the start angle
* @param stopAng
* the stop angle
* @param points
* the amount of points to calculate the array factor at
* @return the complex array factor as an array of Complex objects
*/
public static Complex[] s(Radiator[] r, double wavelength, int radiatorType, double radiatorAng, double startAng,
double stopAng, int points) {
Complex[] s = new Complex[points];
double[] x = MatlabFunctions.linspace(startAng, stopAng, points);
for (int i = 0; i < points; i++) {
Complex c = new Complex();
for (int j = 0; j < r.length; j++) {
if (!r[j].getState()) {
double re = r[j].getA() * Math.cos(phaseShift(r[j], x[i], wavelength) - r[j].getP());
double im = r[j].getA() * Math.sin(phaseShift(r[j], x[i], wavelength) - r[j].getP());
Complex tmp = new Complex(re, im);
c = c.add(tmp);
}
}
s[i] = se(wavelength, radiatorType, radiatorAng, x[i]).mul(c);
}
return s;
}
/**
* <pre>
* Calculates and returns the complex array factor as an array of Complex objects with the reflector enabled.
* </pre>
*
* @param r
* an array of Radiator object
* @param wavelength
* @param radiatorType
* the radiator type
* @param radiatorAng
* the angle of the radiator
* @param reflectorOffset
* the offset of the reflector
* @param startAng
* the start angle
* @param stopAng
* the stop angle
* @param points
* the amount of points to calculate the array factor at
* @return the complex array factor as an array of Complex objects with the
* reflector enabled
*/
public static Complex[] sReflector(Radiator[] r, double wavelength, int radiatorType, double radiatorAng,
double reflectorOffset, double startAng, double stopAng, int points) {
Complex[] s = new Complex[points];
double[] x = MatlabFunctions.linspace(startAng, stopAng, points);
int numRadiators = r.length;
for (int i = 0; i < r.length; i++) {
if (r[i].getState()) {
numRadiators--;
}
}
double[] rX = new double[2 * numRadiators];
double[] rY = new double[2 * numRadiators];
double[] rA = new double[2 * numRadiators];
double[] rP = new double[2 * numRadiators];
int index = 0;
for (int i = 0; i < r.length; i++) {
if (!r[i].getState()) {
rX[index] = r[i].getX();
rX[numRadiators + index] = rX[index];
rY[index] = r[i].getY();
rY[numRadiators + index] = 2.0 * reflectorOffset - rY[index];
rA[index] = r[i].getA();
rA[numRadiators + index] = rA[index];
rP[index] = r[i].getP();
rP[numRadiators + index] = rP[index] + Math.PI;
index++;
}
}
for (int i = 0; i < points; i++) {
Complex c = new Complex();
// set the edges of the reflector to zero
if ((x[i] != 0.0) && (x[i] != Math.PI) && (x[i] != (2 * Math.PI))) {
for (int j = 0; j < numRadiators; j++) {
if (x[i] < Math.PI) { // 0 - 180 degrees
if (rY[j] > reflectorOffset) {
double re = rA[j] * Math.cos(phaseShift(rX[j], rY[j], x[i], wavelength) - rP[j]);
double im = rA[j] * Math.sin(phaseShift(rX[j], rY[j], x[i], wavelength) - rP[j]);
Complex tmp = new Complex(re, im);
tmp = se(wavelength, radiatorType, radiatorAng, x[i]).mul(tmp);
c = c.add(tmp);
re = rA[numRadiators + j]
* Math.cos(phaseShift(rX[numRadiators + j], rY[numRadiators + j], x[i], wavelength)
- rP[numRadiators + j]);
im = rA[numRadiators + j]
* Math.sin(phaseShift(rX[numRadiators + j], rY[numRadiators + j], x[i], wavelength)
- rP[numRadiators + j]);
tmp = new Complex(re, im);
tmp = se(wavelength, radiatorType, -radiatorAng, x[i]).mul(tmp);
c = c.add(tmp);
}
} else { // 180 - 360 degrees
if (rY[j] < reflectorOffset) {
double re = rA[j] * Math.cos(phaseShift(rX[j], rY[j], x[i], wavelength) - rP[j]);
double im = rA[j] * Math.sin(phaseShift(rX[j], rY[j], x[i], wavelength) - rP[j]);
Complex tmp = new Complex(re, im);
tmp = se(wavelength, radiatorType, radiatorAng, x[i]).mul(tmp);
c = c.add(tmp);
re = rA[numRadiators + j]
* Math.cos(phaseShift(rX[numRadiators + j], rY[numRadiators + j], x[i], wavelength)
- rP[numRadiators + j]);
im = rA[numRadiators + j]
* Math.sin(phaseShift(rX[numRadiators + j], rY[numRadiators + j], x[i], wavelength)
- rP[numRadiators + j]);
tmp = new Complex(re, im);
tmp = se(wavelength, radiatorType, -radiatorAng, x[i]).mul(tmp);
c = c.add(tmp);
}
}
}
}
s[i] = c;
}
return s;
}
/**
* <pre>
* Calculates and returns an array containing the normalized absolute values of the complex array factor.
* </pre>
*
* @param sAbs
* an array containing the absolute values of the complex array
* factor
* @param sAbsMax
* the maximum value of the absolute values of the complex array
* factor over the entire 360 degrees
* @return an array containing the normalized absolute values of the complex
* array factor
*/
public static double[] norm(double[] sAbs, double sAbsMax) {
double[] sNorm = new double[sAbs.length];
for (int i = 0; i < sNorm.length; i++) {
sNorm[i] = 20 * Math.log10(sAbs[i] / sAbsMax);
}
return sNorm;
}
/**
* <pre>
* Calculates and returns an array containing nx coordinates of points on a line equally spaced with the given gap dx between the points.
* - nx must be greater than 0
* - dx must be greater than 0
* </pre>
*
* @param nx
* the amount of points
* @param dx
* the gap between the points
* @return an array with the coordinates of the calculated points
*/
public static double[][] linear(int nx, double dx) {
return grid(nx, 1, dx, 0.0);
}
/**
* <pre>
* Calculates and returns an array containing (nx * ny) coordinates of points on a grid equally spaced with the given gaps dx and dy between the points.
* - nx, ny must be greater than 0
* - dx, dy must be greater than 0
* </pre>
*
* @param nx
* the amount of points in the horizontal direction
* @param ny
* the amount of points in the vertical direction
* @param dx
* the gap between horizontal points
* @param dy
* the gap between vertical points
* @return an array with the coordinates of the calculated points
*/
public static double[][] grid(int nx, int ny, double dx, double dy) {
double[][] pos = new double[nx * ny][2];
double xl = (nx - 1) * dx;
double yl = (ny - 1) * dy;
double[] x = MatlabFunctions.linspace(0.0, xl, nx);
double[] y = MatlabFunctions.linspace(yl, 0.0, ny);
for (int i = 0; i < ny; i++) {
for (int j = 0; j < nx; j++) {
pos[nx * i + j][0] = x[j] - xl / 2.0;
pos[nx * i + j][1] = y[i] - yl / 2.0;
}
}
return pos;
}
/**
* <pre>
* Calculates and returns an array containing n coordinates of points equally spaced on a circle with the given radius.
* - n must be greater than 0
* - r must be greater than 0
* </pre>
*
* @param n
* the amount of points
* @param r
* the radius of the circle
* @return an array with the coordinates of the calculated points
*/
public static double[][] circle(int n, double r) {
double[][] pos = new double[n][2];
for (int i = 0; i < pos.length; i++) {
pos[i][0] = r * Math.cos(T / n * i);
pos[i][1] = r * Math.sin(T / n * i);
}
return pos;
}
/**
* <pre>
* Calculates and returns an array containing n coordinates of points equally spaced on a square with the given side length.
* - n must be equal to (k * 4), k E N
* - sideLength must be greater than 0
* </pre>
*
* @param n
* the amount of points
* @param sideLength
* the side length
* @return an array with the coordinates of the calculated points
*/
public static double[][] square(int n, double sideLength) {
double[][] pos = new double[n][2];
int piecesPerSide = n / 4;
double pieceLength = sideLength / piecesPerSide;
double x = sideLength / 2 - pieceLength;
double y = -sideLength / 2;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < piecesPerSide; j++) {
if (i == 0 || i == 1) {
pos[piecesPerSide * i + j][i % 2] = x + pieceLength;
} else {
pos[piecesPerSide * i + j][i % 2] = x - pieceLength;
}
if (i == 0 || i == 3) {
pos[piecesPerSide * i + j][(i + 1) % 2] = y + j * pieceLength;
} else {
pos[piecesPerSide * i + j][(i + 1) % 2] = y - j * pieceLength;
}
}
x = pos[piecesPerSide * i + piecesPerSide - 1][(i + 1) % 2];
y = Math.pow(-1.0, (i + 1) % 2) * y;
}
return pos;
}
}
| 30.561905 | 153 | 0.597928 |
b2a27aad41900320585237b46b03e91ccb792742 | 643 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
public final class ePLANE_INTERSECTION_TYPE {
public final static int G_BACK_PLANE = 0;
public final static int G_COLLIDE_PLANE = G_BACK_PLANE + 1;
public final static int G_FRONT_PLANE = G_COLLIDE_PLANE + 1;
}
| 37.823529 | 83 | 0.566096 |
703a9be5abfd5c0b02bd819c24ebb46c4c27cec5 | 2,839 | package chapter7;
class QuickCount
{
protected long[] theArray;
protected int nElems;
protected static long copies;
protected static long comparisons;
public QuickCount(int maxSize)
{
theArray = new long[maxSize];
nElems = 0;
copies = 0;
comparisons = 0;
}
public void insert(long value)
{
theArray[nElems++] = value;
}
public void display()
{
for(int i = 0; i < nElems; i++)
{
if(i % 100 == 0)
System.out.println();
System.out.print(theArray[i] + " ");
}
System.out.println("");
}
public void quickSort2()
{
copies = comparisons = 0;
recQuickSort2(0, nElems - 1);
System.out.println("Copies: " + copies);
System.out.println("Comparisons: " + comparisons);
}
public void recQuickSort2(int left, int right)
{
int size = right-left+1;
if(size <=3)
{
comparisons++;
manualSort(left, right);
}
else
{
comparisons++;
long median = medianOf3(left, right);
int partition = partitionIt2(left, right, median);
recQuickSort2(left, partition-1);
recQuickSort2(partition+1, right);
}
}
public int partitionIt2(int left, int right, long pivot)
{
int leftPtr = left;
int rightPtr = right-1;
while(true)
{
while(theArray[++leftPtr] < pivot) comparisons++;
while(theArray[--rightPtr] > pivot) comparisons++;
if(leftPtr >= rightPtr)
{
comparisons++;
break;
}
else
{
comparisons++;
swap(leftPtr, rightPtr);
}
}
swap(leftPtr, right-1);
return leftPtr;
}
public void swap(int index1, int index2)
{
long temp = theArray[index1];
theArray[index1] = theArray[index2];
theArray[index2] = temp;
copies += 3;
}
public long medianOf3(int left, int right)
{
int center = (left+right)/2;
if(theArray[left] > theArray[center]) swap(left, center);
if(theArray[left] > theArray[right]) swap(left, right);
if(theArray[center] > theArray[right]) swap(center, right);
comparisons += 3;
swap(center, right-1);
return theArray[right-1];
}
public void manualSort(int left, int right)
{
int size = right-left+1;
if(size <= 1)
{
comparisons++;
return;
}
comparisons++;
if(size == 2)
{
comparisons++;
if(theArray[left] > theArray[right]) swap(left, right);
comparisons++;
return;
}
else
{
comparisons++;
if(theArray[left] > theArray[right-1]) swap(left, right-1);
if(theArray[left] > theArray[right]) swap(left, right);
if(theArray[right-1] > theArray[right]) swap(right-1, right);
comparisons += 3;
}
}
public static void main(String[] args)
{
QuickCount arr = new QuickCount(100);
for(int i = 0; i < 100; i++) arr.insert(100-i);
arr.quickSort2();
}
} | 20.278571 | 65 | 0.596337 |
b009cc83405d2bef6122b1c622df174f02fde621 | 1,577 | // Targeted by JavaCPP version 1.5.8-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.bullet.Bullet3OpenCL;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import org.bytedeco.bullet.Bullet3Common.*;
import static org.bytedeco.bullet.global.Bullet3Common.*;
import org.bytedeco.bullet.Bullet3Collision.*;
import static org.bytedeco.bullet.global.Bullet3Collision.*;
import org.bytedeco.bullet.Bullet3Dynamics.*;
import static org.bytedeco.bullet.global.Bullet3Dynamics.*;
import org.bytedeco.bullet.LinearMath.*;
import static org.bytedeco.bullet.global.LinearMath.*;
import static org.bytedeco.bullet.global.Bullet3OpenCL.*;
@NoOffset @Properties(inherit = org.bytedeco.bullet.presets.Bullet3OpenCL.class)
public class b3BufferInfoCL extends Pointer {
static { Loader.load(); }
//b3BufferInfoCL(){}
// template<typename T>
public b3BufferInfoCL(@Cast("cl_mem") Pointer buff, @Cast("bool") boolean isReadOnly/*=false*/) { super((Pointer)null); allocate(buff, isReadOnly); }
private native void allocate(@Cast("cl_mem") Pointer buff, @Cast("bool") boolean isReadOnly/*=false*/);
public b3BufferInfoCL(@Cast("cl_mem") Pointer buff) { super((Pointer)null); allocate(buff); }
private native void allocate(@Cast("cl_mem") Pointer buff);
public native @Cast("cl_mem") Pointer m_clBuffer(); public native b3BufferInfoCL m_clBuffer(Pointer setter);
public native @Cast("bool") boolean m_isReadOnly(); public native b3BufferInfoCL m_isReadOnly(boolean setter);
}
| 42.621622 | 150 | 0.775523 |
6953aba7be7935c83734353a92d6ea3d409991d0 | 5,424 | /*
* Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package thredds.inventory;
import ucar.nc2.time.CalendarDate;
import ucar.nc2.time.CalendarDateRange;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
/**
* Manage collections of files that we can assign date ranges to.
* Used by Composite Point Collections
* A wrap of MCollection.
*
* @author caron
* @since May 19, 2009
*/
public class TimedCollection {
private static final boolean debug = false;
private final MFileCollectionManager manager;
private List<TimedCollection.Dataset> datasets;
private CalendarDateRange dateRange;
/**
* Manage collections of files that we can assign date ranges to
*
* @param manager the collection manager
* @param errlog put error messsages here
* @see CollectionSpecParser
* @throws java.io.IOException on read error
*/
public TimedCollection(MFileCollectionManager manager, Formatter errlog) throws IOException {
this.manager = manager;
// get the inventory, sorted by path
if (manager != null) {
manager.scanIfNeeded();
}
update();
if (debug) {
System.out.printf("Datasets in collection=%s%n", manager.getCollectionName());
for (TimedCollection.Dataset d: datasets) {
System.out.printf(" %s %n",d);
}
System.out.printf("%n");
}
}
public CalendarDateRange update() throws IOException {
datasets = new ArrayList<>();
manager.scan(false);
for (MFile f : manager.getFilesSorted())
datasets.add(new Dataset(f));
if (manager.hasDateExtractor()) {
if (datasets.size() == 1) {
Dataset ds = datasets.get(0);
if (ds.start != null)
dateRange = CalendarDateRange.of(ds.start, ds.start); // LOOK ??
} else if (datasets.size() > 1) {
for (int i = 0; i < datasets.size() - 1; i++) {
Dataset d1 = datasets.get(i);
Dataset d2 = datasets.get(i + 1);
d1.setDateRange(CalendarDateRange.of(d1.start, d2.start));
if (i == datasets.size() - 2) // last one
d2.setDateRange(new CalendarDateRange(d2.start, d1.getDateRange().getDurationInSecs()));
}
Dataset first = datasets.get(0);
Dataset last = datasets.get(datasets.size() - 1);
dateRange = CalendarDateRange.of(first.getDateRange().getStart(), last.getDateRange().getEnd());
}
}
return dateRange;
}
private TimedCollection(TimedCollection from, CalendarDateRange want) {
this.manager = from.manager;
datasets = new ArrayList<>(from.datasets.size());
for (TimedCollection.Dataset d : from.datasets)
if (want.intersects(d.getDateRange()))
datasets.add(d);
this.dateRange = want;
}
public TimedCollection.Dataset getPrototype() {
int idx = manager.getProtoIndex(datasets.size());
return datasets.get(idx);
}
public List<TimedCollection.Dataset> getDatasets() {
return datasets;
}
public TimedCollection subset(CalendarDateRange range) {
return new TimedCollection(this, range);
}
public CalendarDateRange getDateRange() {
if (dateRange == null) try {
update();
} catch (IOException e) {
e.printStackTrace();
}
return dateRange;
}
@Override
public String toString() {
Formatter f = new Formatter();
f.format("CollectionManager{%n");
for (TimedCollection.Dataset d : datasets)
f.format(" %s%n", d);
f.format("}%n");
return f.toString();
}
/**
** The Dataset.getLocation() can be passed to FeatureDatasetFactoryManager.open().
*/
public class Dataset {
String location;
CalendarDateRange dateRange;
CalendarDate start;
Dataset(MFile f) {
this.location = f.getPath();
this.start = manager.extractDate(f);
}
public String getLocation() {
return location;
}
public CalendarDateRange getDateRange() {
return dateRange;
}
public void setDateRange(CalendarDateRange dateRange) {
this.dateRange = dateRange;
}
@Override
public String toString() {
return "Dataset{" +
"location='" + location + '\'' +
", dateRange=" + dateRange +
'}';
}
}
//////////////////////////////////////////////////////////////////////////
// debugging
private static void doit(String spec, Formatter errlog) throws IOException {
MFileCollectionManager dcm = MFileCollectionManager.open("test", spec, null, errlog);
TimedCollection specp = new TimedCollection(dcm, errlog);
System.out.printf("spec= %s%n%s%n", spec, specp);
String err = errlog.toString();
if (err.length() > 0)
System.out.printf("%s%n", err);
System.out.printf("-----------------------------------%n");
}
public static void main(String arg[]) throws IOException {
doit("C:/data/formats/gempak/surface/#yyyyMMdd#_sao.gem", new Formatter());
//doit("C:/data/formats/gempak/surface/#yyyyMMdd#_sao\\.gem", new Formatter());
// doit("Q:/station/ldm/metar/Surface_METAR_#yyyyMMdd_HHmm#.nc", new Formatter());
}
}
| 29.318919 | 105 | 0.612463 |
9faa093ae0e3bd9c558ee7fbe314c0fddcf4ae02 | 1,714 | package com.jpattern.service.log.reader;
import com.jpattern.service.log.AExecutor;
import com.jpattern.service.log.IExecutor;
import com.jpattern.service.log.NullExecutor;
import com.jpattern.service.log.event.DebugEvent;
import com.jpattern.service.log.event.ErrorEvent;
import com.jpattern.service.log.event.InfoEvent;
import com.jpattern.service.log.event.TraceEvent;
import com.jpattern.service.log.event.WarnEvent;
/**
* @author Francesco Cinà 07/ago/2009
*/
public class QueueExecutor extends AExecutor {
/**
*
*/
private static final long serialVersionUID = 1L;
private IQueueMessages queueMessages;
public QueueExecutor(IQueueMessages aQueueMessages) {
this(aQueueMessages, new NullExecutor());
}
public QueueExecutor(IQueueMessages aQueueMessages, IExecutor aExecutor) {
super(aExecutor);
this.queueMessages = aQueueMessages;
}
public void what(InfoEvent aEvent) {
queueMessages.offer( getMessageFormatter().toString(aEvent.getName(), aEvent.getMessage()));
}
public void what(DebugEvent aEvent) {
queueMessages.offer( getMessageFormatter().toString(aEvent.getName(), aEvent.getMessage()));
}
public void what(ErrorEvent aEvent) {
queueMessages.offer( getMessageFormatter().toStringWithStackTrace(aEvent.getName(), aEvent.getMessage()));
}
public void what(TraceEvent aEvent) {
queueMessages.offer( getMessageFormatter().toString(aEvent.getName(), aEvent.getMessage()));
}
public void what(WarnEvent aEvent) {
queueMessages.offer( getMessageFormatter().toString(aEvent.getName(), aEvent.getMessage()));
}
}
| 31.163636 | 112 | 0.710035 |
cc2fd76016f59ba48613c70556c7e9fc7aa9ff08 | 1,606 | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.api.core.time;
/**
* Generates client-side, microsecond-precision query timestamps.
*
* <p>These timestamps are used to order queries server-side, and resolve potential conflicts.
*/
public interface TimestampGenerator extends AutoCloseable {
/**
* Returns the next timestamp, in <b>microseconds</b>.
*
* <p>The timestamps returned by this method should be monotonic; that is, successive invocations
* should return strictly increasing results. Note that this might not be possible using the clock
* alone, if it is not precise enough; alternative strategies might include incrementing the last
* returned value if the clock tick hasn't changed, and possibly drifting in the future. See the
* built-in driver implementations for more details.
*
* @return the next timestamp, or {@link Long#MIN_VALUE} to indicate that the driver should not
* send one with the query (and let Cassandra generate a server-side timestamp).
*/
long next();
}
| 41.179487 | 100 | 0.742217 |
6c03f4a0202ffed59f884d0114a3f687b94a2d31 | 5,874 | package com.umiwi.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.umeng.analytics.MobclickAgent;
import com.umiwi.ui.R;
import com.umiwi.ui.activity.UmiwiContainerActivity;
import com.umiwi.ui.adapter.ActivityAdapter;
import com.umiwi.ui.beans.ActivityItemBean;
import com.umiwi.ui.main.BaseConstantFragment;
import com.umiwi.ui.main.UmiwiAPI;
import com.umiwi.ui.managers.NoticeManager;
import com.umiwi.ui.managers.YoumiRoomUserManager;
import com.umiwi.ui.parsers.UmiwiListParser;
import com.umiwi.ui.parsers.UmiwiListResult;
import java.util.ArrayList;
import cn.youmi.framework.http.AbstractRequest;
import cn.youmi.framework.http.AbstractRequest.Listener;
import cn.youmi.framework.http.GetRequest;
import cn.youmi.framework.util.ListViewPositionUtils;
import cn.youmi.framework.util.ListViewScrollLoader;
import cn.youmi.framework.view.LoadingFooter;
public class OfflineActivityListFragment extends BaseConstantFragment {
public static final String KEY_INPROGRESS = "key.inprogress";
private String status;
private ListView mListView;
private ActivityAdapter mAdapter;
private ArrayList<ActivityItemBean> mList;
private LoadingFooter mLoadingFooter;
private ListViewScrollLoader mScrollLoader;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_INPROGRESS, status);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
status = savedInstanceState.getString(KEY_INPROGRESS);
} else {
Bundle bundle = getArguments();
if (bundle != null) {
status = bundle.getString(KEY_INPROGRESS);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_frame_notoolbar_listview_layout, null);
mList = new ArrayList<>();
mListView = (ListView) view.findViewById(R.id.listView);
mAdapter = new ActivityAdapter(getActivity(), mList);
mLoadingFooter = new LoadingFooter(getActivity());
mListView.addFooterView(mLoadingFooter.getView());
mScrollLoader = new ListViewScrollLoader(this, mLoadingFooter);
mListView.setOnScrollListener(mScrollLoader);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListView.clearChoices();
ActivityItemBean mListBeans = mList.get(ListViewPositionUtils.indexInDataSource(position, mListView));
if (ListViewPositionUtils.isPositionCanClick(mListBeans, position, mListView, mList)) {
Intent i = new Intent(getActivity(), UmiwiContainerActivity.class);
i.putExtra(UmiwiContainerActivity.KEY_FRAGMENT_CLASS, ActivityDetailFragment.class);
i.putExtra(ActivityDetailFragment.KEY_ACTIVITY_TITLE, mListBeans.getTitle());
i.putExtra(ActivityDetailFragment.KEY_DETAIL_URL, mListBeans.getDetailURL());
i.putExtra(ActivityDetailFragment.KEY_IS_OVER, mListBeans.isEnd());
startActivity(i);
}
}
});
mScrollLoader.onLoadFirstPage();
return view;
}
@Override
public void onResume() {
super.onResume();
MobclickAgent.onPageStart(fragmentName);
}
@Override
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd(fragmentName);
}
@Override
public void onLoadData(int page) {
GetRequest<UmiwiListResult<ActivityItemBean>> get = new GetRequest<UmiwiListResult<ActivityItemBean>>(String.format(UmiwiAPI.HUO_DONG_LIST, status, page), UmiwiListParser.class, ActivityItemBean.class, listener);
get.go();
}
private Listener<UmiwiListResult<ActivityItemBean>> listener = new Listener<UmiwiListResult<ActivityItemBean>>() {
@Override
public void onResult(AbstractRequest<UmiwiListResult<ActivityItemBean>> request, UmiwiListResult<ActivityItemBean> t) {
if (t == null) {// 主要用于防止服务器数据出错
mScrollLoader.showLoadErrorView("未知错误,请重试");
return;
}
if (t.isLoadsEnd()) {// 判断是否是最后一页
mScrollLoader.setEnd(true);
}
if (t.isEmptyData()) {// 当前列表没有数据
mScrollLoader.showContentView("当前没有活动");
return;
}
mScrollLoader.setPage(t.getCurrentPage());// 用于分页请求
mScrollLoader.setloading(false);//
// 数据加载
ArrayList<ActivityItemBean> charts = t.getItems();
mList.addAll(charts);
if (mAdapter == null) {
mAdapter = new ActivityAdapter(getActivity().getApplication(), mList);
mListView.setAdapter(mAdapter);// 解析成功 播放列表
} else {
mAdapter.notifyDataSetChanged();
}
if (YoumiRoomUserManager.getInstance().isLogin())
NoticeManager.getInstance().loadNotice();
}
@Override
public void onError(AbstractRequest<UmiwiListResult<ActivityItemBean>> requet, int statusCode, String body) {
mScrollLoader.showLoadErrorView();
}
};
}
| 36.259259 | 220 | 0.672966 |
e297ff9754ffdeacfea4503036dfe529f09b5a1e | 2,717 | /**
*
*/
package de.kjEngine.scene.physics;
import java.util.ArrayList;
import java.util.List;
import de.kjEngine.component.Container.Implementation;
import de.kjEngine.math.Vec3;
import de.kjEngine.scene.Entity;
import de.kjEngine.scene.Scene;
import de.kjEngine.scene.physics.collission.Collider;
import de.kjEngine.scene.physics.collission.Collission;
import de.kjEngine.scene.physics.collission.CollissionSolver;
import de.kjEngine.scene.physics.solver.Solver;
import de.kjEngine.util.Timer;
import de.kjEngine.util.container.Array;
/**
* @author konst
*
*/
public class PhysicsSimulation implements Implementation<Scene> {
private final Array<PhysicsObject> objects = new Array<>();
private final Array<Collission> collissions = new Array<>();
public final List<Solver> solvers = new ArrayList<>();
public int subSteps = 1;
public PhysicsSimulation() {
}
@Override
public void updateEarly(Scene scene, float delta) {
objects.clear(false);
getObjects(scene.staticRoot);
getObjects(scene.dynamicRoot);
collissions.clear(false);
Collission currentCollission = new Collission();
Vec3 aMin = Vec3.create();
Vec3 bMin = Vec3.create();
Vec3 aMax = Vec3.create();
Vec3 bMax = Vec3.create();
Timer.start();
for (int i = 0; i < objects.length(); i++) {
PhysicsObject a = objects.get(i);
a.accelerate(Vec3.create(0f, -delta * 9.81f, 0f));
a.collider.getBounds(aMin, aMax);
for (int j = i + 1; j < objects.length(); j++) {
PhysicsObject b = objects.get(j);
b.collider.getBounds(bMin, bMax);
if (aMax.x < bMin.x || aMax.y < bMin.y ||aMax.z < bMin.z || bMax.x < aMin.x || bMax.y < aMin.y ||bMax.z < aMin.z) {
continue;
}
@SuppressWarnings("unchecked")
CollissionSolver<Collider, Collider> solver = (CollissionSolver<Collider, Collider>) Collider.Registry.getSolver(a.collider.type, b.collider.type);
if (solver.getCollission(a.collider, b.collider, currentCollission)) {
collissions.add(currentCollission);
currentCollission = new Collission();
}
}
}
for (int i = 0; i < solvers.size(); i++) {
solvers.get(i).solve(collissions);
}
Timer.printPassed();
}
private final Array<PhysicsComponent> componentBuffer = new Array<>();
private void getObjects(Entity entity) {
componentBuffer.clear(false);
entity.getAll(PhysicsComponent.class, componentBuffer);
for (int i = 0; i < componentBuffer.length(); i++) {
objects.add(componentBuffer.get(i).object);
}
List<Entity> entities = entity.getAll(Entity.class);
for (int i = 0; i < entities.size(); i++) {
getObjects(entities.get(i));
}
}
@Override
public void updateLate(Scene container, float delta) {
}
}
| 26.637255 | 151 | 0.694516 |
80de589e0092e9ba5557ca18eff8f50ff0f7668d | 1,225 | package api.longpoll.bots.methods.impl.stories;
import api.longpoll.bots.config.VkBotsConfig;
import api.longpoll.bots.methods.impl.VkMethod;
import api.longpoll.bots.model.response.IntegerResponse;
/**
* Implements <b>stories.hideAllReplies</b> method.
* <p>
* Hides all replies in the last 24 hours from the user to current user's stories.
*
* @see <a href="https://vk.com/dev/stories.hideAllReplies">https://vk.com/dev/stories.hideAllReplies</a>
*/
public class HideAllReplies extends VkMethod<IntegerResponse> {
public HideAllReplies(String accessToken) {
super(accessToken);
}
@Override
public String getUrl() {
return VkBotsConfig.getInstance().getBotMethods().getProperty("stories.hideAllReplies");
}
@Override
protected Class<IntegerResponse> getResponseType() {
return IntegerResponse.class;
}
public HideAllReplies setOwnerId(int ownerId) {
return addParam("owner_id", ownerId);
}
public HideAllReplies setGroupId(int groupId) {
return addParam("group_id", groupId);
}
@Override
public HideAllReplies addParam(String key, Object value) {
return (HideAllReplies) super.addParam(key, value);
}
}
| 29.166667 | 105 | 0.709388 |
30cb11e921e0eb9cdd4bd34b47439e42283ccac3 | 167 | package com.lyx.observer;
/**
* Created by FollowWinter on 11/10/2016.
*/
public class Observer {
protected Subject subject;
public void update(){
}
}
| 13.916667 | 41 | 0.658683 |
6e6d6f51bc16cfe8776ba073adc57ddf7b39d60a | 1,763 | /*
Copyright 2018 Samsung SDS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.samsungsds.analyst.code.api;
public class AnalysisProgress {
private ProgressEvent progressEvent;
private int totalSteps = 0;
private int completedSteps = 0;
private long elapsedTimeInMillisecond = 0;
public AnalysisProgress(int totalSteps, int completedSteps) {
this(totalSteps);
this.completedSteps = completedSteps;
}
public AnalysisProgress(int totalSteps) {
this.totalSteps = totalSteps;
}
public ProgressEvent getProgressEvent() {
return progressEvent;
}
public void setProgressEvent(ProgressEvent progressEvent) {
this.progressEvent = progressEvent;
}
public void addCompletedStep(int addedSteps) {
completedSteps += addedSteps;
if (completedSteps > totalSteps) {
completedSteps = totalSteps;
}
}
public int getCompletedPercent() {
return completedSteps * 100 / totalSteps;
}
public int getCompletedSteps() {
return completedSteps;
}
public long getElapsedTimeInMillisecond() {
return elapsedTimeInMillisecond;
}
public void setElapsedTimeInMillisecond(long elapsedTimeInMillisecond) {
this.elapsedTimeInMillisecond = elapsedTimeInMillisecond;
}
}
| 26.313433 | 74 | 0.744186 |
524ddadad47950219bccc9da842a5241a6065c2c | 2,508 | package com.civica.grads.boardgames.model;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.civica.grads.boardgames.enums.Colour;
import com.civica.grads.boardgames.enums.CounterType;
import com.civica.grads.boardgames.interfaces.Describable;
import com.civica.grads.boardgames.interfaces.Move;
import com.civica.grads.boardgames.interfaces.Storable;
/**
*
* @author Team.Rose
*
* Need to distinguish between turn and move, turn = Move[]
*
*
*/
public class MoveRecord implements Describable,Storable, Move {
private final Position positionStart;
private final Position positionFinish;
private final Colour player;
private final CounterType counterType;
private boolean counterTaken;
private static int totalMoveRecords;
private int moveRecordID;
/* (non-Javadoc)
* @see com.civica.grads.boardgames.model.Move#getPositionStart()
*/
@Override
public final Position getPositionStart() {
return positionStart;
}
/* (non-Javadoc)
* @see com.civica.grads.boardgames.model.Move#getPositionFinish()
*/
@Override
public final Position getPositionFinish() {
return positionFinish;
}
/**
* @param positionStart
* @param positionFinish
* @param player
* @param counterType
*/
public MoveRecord(Position positionStart, Position positionFinish, Colour player,
CounterType counterType, boolean counterTaken) {
this.positionStart = positionStart;
this.positionFinish = positionFinish;
this.player = player;
this.counterType = counterType;
this.counterTaken = counterTaken;
moveRecordID = totalMoveRecords++;
}
public boolean isCounterTaken() {
return counterTaken;
}
@Override
public void describe(OutputStream out) throws IOException {
out.write(this.toString().getBytes()) ;
}
@Override
public String toString() {
return "Move [positionStart=" + positionStart + ", positionFinish=" + positionFinish + ", player=" + player
+ ", counterType=" + counterType + "]";
}
@Override
public void save(InputStream sourceIs) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void load(OutputStream sourceIs) throws IOException {
// TODO Auto-generated method stub
}
public static int getTotalMoveRecords() {
return totalMoveRecords;
}
public int getMoveRecordID() {
return moveRecordID;
}
public boolean isChangedType() {
return false; // FIXME Real return value
}
}
| 17.416667 | 109 | 0.726475 |
0adc9dd7f1f48afb14a0bbbd0aa517016692bc8e | 5,531 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.quakereport;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.transition.Visibility;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.EventListener;
import java.util.GregorianCalendar;
import java.util.List;
public class EarthquakeActivity extends AppCompatActivity implements LoaderCallbacks<List<Earthquake>> {
public static final String LOG_TAG = EarthquakeActivity.class.getName();
private static String USGS_REQUEST_URL;
EarthquakeAdapter earthquakeAdapter;
/** TextView that is displayed when the list is empty */
private TextView mEmptyStateTextView;
private ProgressBar spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Calendar cal = Calendar.getInstance();
int day = cal.get(GregorianCalendar.DAY_OF_MONTH);
cal.set(GregorianCalendar.DAY_OF_MONTH, day-5);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(cal.getTime());
USGS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime="+ formattedDate +"&minmagnitude=5";
setContentView(R.layout.earthquake_activity);
updateUI(new ArrayList<Earthquake>());
// Get a reference to the ConnectivityManager to check state of network connectivity
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
// Get details on the currently active default data network
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
loaderManager.initLoader(1, null, this);
} else {
spinner = (ProgressBar) findViewById(R.id.loading_spinner);
spinner.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet);
}
}
@Override
public android.content.Loader<List<Earthquake>> onCreateLoader(int i, Bundle bundle) {
return new EarthquakeLoader(this, USGS_REQUEST_URL);
}
@Override
public void onLoadFinished(android.content.Loader<List<Earthquake>> loader, List<Earthquake> earthquakes) {
spinner = (ProgressBar) findViewById(R.id.loading_spinner);
spinner.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_earthquakes);
earthquakeAdapter.clear();
if (earthquakes != null && !earthquakes.isEmpty()){
earthquakeAdapter.addAll(earthquakes);
}
}
@Override
public void onLoaderReset(android.content.Loader<List<Earthquake>> loader) {
earthquakeAdapter.clear();
}
private void updateUI(final ArrayList<Earthquake> earthquakes) {
// Find a reference to the {@link ListView} in the layout
ListView earthquakeListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
earthquakeListView.setEmptyView(mEmptyStateTextView);
earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(earthquakes.get(i).getUrl()));
if (browserIntent.resolveActivity(getPackageManager()) != null) {
startActivity(browserIntent);
}
// Toast.makeText(getApplicationContext(),earthquakes.get(i).getUrl(), Toast.LENGTH_SHORT).show();
}
});
earthquakeAdapter = new EarthquakeAdapter(this, earthquakes);
// Set the adapter on the {@link ListView}
// so the list can be populated in the user interface
earthquakeListView.setAdapter(earthquakeAdapter);
}
}
| 38.409722 | 138 | 0.713976 |
ec105c7ae7d42cd585078f220343417df05950be | 1,262 | /*
* Copyright © 2017 camunda services GmbH ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.zeebe.util.collection;
import java.util.NoSuchElementException;
import org.agrona.collections.IntArrayList;
public class IntArrayListIterator implements IntIterator {
private IntArrayList list = null;
private int cursor = 0;
public void wrap(IntArrayList list) {
this.list = list;
cursor = 0;
}
@Override
public boolean hasNext() {
return list.size() - cursor > 0;
}
@Override
public int nextInt() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
return list.getInt(cursor++);
}
}
@Override
public Integer next() {
return nextInt();
}
}
| 25.755102 | 75 | 0.701268 |
bc42de81caee3c4d2728928df4d98745863c2859 | 1,592 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.criteria.nulliteral;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaUpdate;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
/**
* @author Andrea Boriero
*/
public class NullLiteralExpression extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {Person.class, Subject.class};
}
@Test
@TestForIssue( jiraKey = "HHH-11159")
public void testNullLiteralExpressionInCriteriaUpdate() {
EntityManager entityManager = getOrCreateEntityManager();
try {
entityManager.getTransaction().begin();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaUpdate<Person> criteriaUpdate = builder.createCriteriaUpdate( Person.class );
criteriaUpdate.from(Person.class);
criteriaUpdate.set( Person_.subject, builder.nullLiteral( Subject.class ) );
entityManager.createQuery( criteriaUpdate ).executeUpdate();
entityManager.getTransaction().commit();
}
catch (Exception e) {
if ( entityManager.getTransaction().isActive() ) {
entityManager.getTransaction().rollback();
}
throw e;
}
finally {
entityManager.close();
}
}
}
| 28.945455 | 94 | 0.758794 |
d800a99d76afccfb4c3b0dd59153fb0c688d1095 | 4,669 | package crazypants.enderio.machine.hypercube;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
import com.enderio.core.common.util.PlayerUtil;
import crazypants.enderio.Log;
public class HyperCubeConfig {
private static final String KEY_PUBLIC_CHANNELS = "public.chanels";
private static final String DELIM = "~";
private static final String DELIM_ESC = "/:/";
private static final String KEY_USERS = "users";
private static final String KEY_USER_CHANNEL = ".channels";
private final Properties props = new Properties();
private final List<Channel> publicChannels = new ArrayList<Channel>();
private final Map<UUID, List<Channel>> userChannels = new HashMap<UUID, List<Channel>>();
private final File file;
public HyperCubeConfig(File file) {
this.file = file;
if(file.exists()) {
load(file);
}
}
public List<Channel> getPublicChannels() {
return publicChannels;
}
public void setPublicChannels(Collection<Channel> chans) {
publicChannels.clear();
publicChannels.addAll(chans);
}
public Map<UUID, List<Channel>> getUserChannels() {
return userChannels;
}
public void setUserChannels(Map<UUID, List<Channel>> channels) {
userChannels.clear();
userChannels.putAll(channels);
}
public void save() {
props.clear();
setChannelListProperty(KEY_PUBLIC_CHANNELS, publicChannels);
StringBuilder userListStr = new StringBuilder();
Iterator<Entry<UUID, List<Channel>>> itr = userChannels.entrySet().iterator();
while (itr.hasNext()) {
Entry<UUID, List<Channel>> entry = itr.next();
UUID user = entry.getKey();
List<Channel> channels = entry.getValue();
if(user != null && channels != null && !channels.isEmpty()) {
userListStr.append(user.toString());
setChannelListProperty(user + KEY_USER_CHANNEL, channels);
}
if(itr.hasNext()) {
userListStr.append(DELIM);
}
}
if(userListStr.length() > 0) {
props.setProperty(KEY_USERS, userListStr.toString());
}
FileOutputStream fos = null;
try {
file.getParentFile().mkdirs();
fos = new FileOutputStream(file);
props.store(fos, null);
} catch (IOException ex) {
Log.warn("HyperCubeConfig: could not save hypercube config:" + ex);
} finally {
IOUtils.closeQuietly(fos);
}
}
private void setChannelListProperty(String key, List<Channel> channels) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < channels.size(); i++) {
//DELIM_ESC;
String name = channels.get(i).name;
if(name != null) {
name = name.trim();
name = name.replaceAll(DELIM, DELIM_ESC);
if(name.length() > 0) {
sb.append(name);
}
}
if(i != channels.size() - 1) {
sb.append(DELIM);
}
}
props.setProperty(key, sb.toString());
}
private void load(File file) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
props.load(fis);
} catch (Exception e) {
Log.error("HyperCubeConfig: Could not load config file: " + e);
return;
} finally {
IOUtils.closeQuietly(fis);
}
publicChannels.clear();
loadChannelList(KEY_PUBLIC_CHANNELS, null, publicChannels);
userChannels.clear();
List<String> users = new ArrayList<String>();
String usersStr = props.getProperty(KEY_USERS, "");
String[] usersSplit = usersStr.split(DELIM);
for (String user : usersSplit) {
if(user != null) {
users.add(user);
}
}
for (String user : users) {
List<Channel> channels = new ArrayList<Channel>();
UUID uuid=PlayerUtil.getPlayerUIDUnstable(user);
loadChannelList(user + KEY_USER_CHANNEL, uuid, channels);
if(!channels.isEmpty()) {
userChannels.put(uuid, channels);
}
}
}
private void loadChannelList(String key, UUID user, List<Channel> channels) {
String chans = props.getProperty(key, "");
//chans = chans.replaceAll(DELIM_ESC, DELIM);
String[] chanSplit = chans.split(DELIM);
for (String chan : chanSplit) {
if(chan != null) {
chan = chan.trim();
if(!chan.isEmpty()) {
channels.add(new Channel(chan.replaceAll(DELIM_ESC, DELIM), user));
}
}
}
}
}
| 26.988439 | 91 | 0.649604 |
7607f003fb7d4f79fc88a1d590ca0dcd64a7da70 | 6,828 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.arbiter.layers;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.deeplearning4j.arbiter.optimize.api.ParameterSpace;
import org.deeplearning4j.arbiter.optimize.parameter.FixedValue;
import org.deeplearning4j.arbiter.util.LeafUtils;
import org.deeplearning4j.nn.conf.ConvolutionMode;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
/**
* Layer hyperparameter configuration space for subsampling layers
*
* @author Alex Black
*/
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor(access = AccessLevel.PRIVATE) //For Jackson JSON/YAML deserialization
public class SubsamplingLayerSpace extends LayerSpace<SubsamplingLayer> {
protected ParameterSpace<ConvolutionMode> convolutionMode;
protected ParameterSpace<SubsamplingLayer.PoolingType> poolingType;
protected ParameterSpace<int[]> kernelSize;
protected ParameterSpace<int[]> stride;
protected ParameterSpace<int[]> padding;
protected ParameterSpace<Integer> pnorm;
protected ParameterSpace<Double> eps;
private SubsamplingLayerSpace(Builder builder) {
super(builder);
this.convolutionMode = builder.convolutionMode;
this.poolingType = builder.poolingType;
this.kernelSize = builder.kernelSize;
this.stride = builder.stride;
this.padding = builder.padding;
this.pnorm = builder.pnorm;
this.eps = builder.eps;
this.numParameters = LeafUtils.countUniqueParameters(collectLeaves());
}
@Override
public SubsamplingLayer getValue(double[] values) {
SubsamplingLayer.Builder b = new SubsamplingLayer.Builder();
setLayerOptionsBuilder(b, values);
return b.build();
}
protected void setLayerOptionsBuilder(SubsamplingLayer.Builder builder, double[] values) {
super.setLayerOptionsBuilder(builder, values);
if (convolutionMode != null)
builder.convolutionMode(convolutionMode.getValue(values));
if (poolingType != null)
builder.poolingType(poolingType.getValue(values));
if (kernelSize != null)
builder.kernelSize(kernelSize.getValue(values));
if (stride != null)
builder.stride(stride.getValue(values));
if (padding != null)
builder.padding(padding.getValue(values));
if(pnorm != null)
builder.pnorm(pnorm.getValue(values));
if(eps != null)
builder.eps(eps.getValue(values));
}
@Override
public String toString() {
return toString(", ");
}
@Override
public String toString(String delim) {
StringBuilder sb = new StringBuilder("SubsamplingLayerSpace(");
if (convolutionMode != null)
sb.append("convolutionMode: ").append(convolutionMode).append(delim);
if (poolingType != null)
sb.append("poolingType: ").append(poolingType).append(delim);
if (kernelSize != null)
sb.append("kernelSize: ").append(kernelSize).append(delim);
if (stride != null)
sb.append("stride: ").append(stride).append(delim);
if (padding != null)
sb.append("padding: ").append(padding).append(delim);
if (pnorm != null)
sb.append("pnorm: ").append(pnorm).append(delim);
if (eps != null)
sb.append("eps: ").append(eps).append(delim);
sb.append(super.toString(delim)).append(")");
return sb.toString();
}
public static class Builder extends FeedForwardLayerSpace.Builder<Builder> {
protected ParameterSpace<ConvolutionMode> convolutionMode;
protected ParameterSpace<SubsamplingLayer.PoolingType> poolingType;
protected ParameterSpace<int[]> kernelSize;
protected ParameterSpace<int[]> stride;
protected ParameterSpace<int[]> padding;
protected ParameterSpace<Integer> pnorm;
protected ParameterSpace<Double> eps;
public Builder convolutionMode(ConvolutionMode convolutionMode){
return convolutionMode(new FixedValue<>(convolutionMode));
}
public Builder convolutionMode(ParameterSpace<ConvolutionMode> convolutionMode){
this.convolutionMode = convolutionMode;
return this;
}
public Builder poolingType(SubsamplingLayer.PoolingType poolingType) {
return poolingType(new FixedValue<>(poolingType));
}
public Builder poolingType(ParameterSpace<SubsamplingLayer.PoolingType> poolingType) {
this.poolingType = poolingType;
return this;
}
public Builder kernelSize(int... kernelSize) {
return kernelSize(new FixedValue<>(kernelSize));
}
public Builder kernelSize(ParameterSpace<int[]> kernelSize) {
this.kernelSize = kernelSize;
return this;
}
public Builder stride(int... stride) {
return stride(new FixedValue<int[]>(stride));
}
public Builder stride(ParameterSpace<int[]> stride) {
this.stride = stride;
return this;
}
public Builder padding(int... padding) {
return padding(new FixedValue<int[]>(padding));
}
public Builder padding(ParameterSpace<int[]> padding) {
this.padding = padding;
return this;
}
public Builder pnorm(int pnorm){
return pnorm(new FixedValue<>(pnorm));
}
public Builder pnorm(ParameterSpace<Integer> pnorm){
this.pnorm = pnorm;
return this;
}
public Builder eps(double eps){
return eps(new FixedValue<>(eps));
}
public Builder eps(ParameterSpace<Double> eps){
this.eps = eps;
return this;
}
@SuppressWarnings("unchecked")
public SubsamplingLayerSpace build() {
return new SubsamplingLayerSpace(this);
}
}
}
| 35.378238 | 94 | 0.643527 |
a60b7c371b40a9c4bab86ce362ae599d48f14c7b | 281 | package br.com.zup.bootcamp.gateway.database.repository;
import br.com.zup.bootcamp.gateway.database.model.AdviseTripDBDomain;
import org.springframework.data.repository.CrudRepository;
public interface AdviseTripRepository extends CrudRepository<AdviseTripDBDomain, String> {
}
| 35.125 | 90 | 0.854093 |
663dfde3c02daa2f785f92c37a705e515157a965 | 974 | package com.dapidi.events.services;
import com.dapidi.events.models.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Created for K and M Consulting LLC.
* Created by Jose M Leon 2017
**/
public class CheckRules implements Runnable {
private static final Logger log = LoggerFactory.getLogger(CheckRules.class);
private List<Rule> rules;
public CheckRules(List<Rule> rules) {
this.rules = rules;
}
@Override
public void run() {
// Thread.currentThread().setName("StartJobs");
// log.info("Starting StartJobs thread");
// for (UUID id : this.map.keySet()) {
// StartJob startJob = new StartJob(
// id,
// this.map.get(id),
// map
// );
// Thread t1 = new Thread(startJob, id.toString());
// t1.start();
// }
// log.info("Ending StartJobs thread");
}
}
| 24.974359 | 80 | 0.579055 |
e00895f6838ca9fae3c992cb9eba139ad25f2e9b | 5,011 | /*******************************************************************************
* Copyright (c) 2011, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation
*
******************************************************************************/
package org.eclipse.persistence.jpa.tests.jpql;
import org.eclipse.persistence.jpa.jpql.EclipseLinkVersion;
import org.eclipse.persistence.jpa.jpql.JPAVersion;
import org.eclipse.persistence.jpa.jpql.parser.JPQLGrammar;
import org.eclipse.persistence.jpa.tests.jpql.parser.JPQLGrammarTestHelper;
import org.eclipse.persistence.jpa.tests.jpql.parser.JPQLGrammarTools;
import org.eclipse.persistence.jpa.tests.jpql.tools.DefaultSemanticValidatorTest2_0;
import org.eclipse.persistence.jpa.tests.jpql.tools.DefaultSemanticValidatorTest2_1;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;
/**
* @version 2.5
* @since 2.4
* @author Pascal Filion
*/
public final class AllSemanticValidatorTests {
private AllSemanticValidatorTests() {
super();
}
/**
* This test suite tests JPQL queries written following the grammar defined in the JPA 2.0 spec
* and makes sure the various JPQL grammars that support it parses them correctly.
*/
@SuiteClasses({
DefaultSemanticValidatorTest2_0.class,
})
@RunWith(JPQLTestRunner.class)
public static class AllDefaultSemanticValidatorTest2_0 {
private AllDefaultSemanticValidatorTest2_0() {
super();
}
@JPQLGrammarTestHelper
static JPQLGrammar[] buildJPQLGrammars() {
return JPQLGrammarTools.allJPQLGrammars(JPAVersion.VERSION_2_0);
}
}
/**
* This test suite tests JPQL queries written following the grammar defined in the JPA 2.1 spec
* and makes sure the various JPQL grammars that support it parses them correctly.
*/
@SuiteClasses({
DefaultSemanticValidatorTest2_1.class,
})
@RunWith(JPQLTestRunner.class)
public static class AllDefaultSemanticValidatorTest2_1 {
private AllDefaultSemanticValidatorTest2_1() {
super();
}
@JPQLGrammarTestHelper
static JPQLGrammar[] buildJPQLGrammars() {
return JPQLGrammarTools.allJPQLGrammars(JPAVersion.VERSION_2_1);
}
}
/**
* This test suite tests JPQL queries written following the grammar defined in the JPA 2.0 spec
* with the extension provided by EclipseLink 2.0, 2.1, 2.2 and 2.3 and makes sure the various
* JPQL grammars that support it parses them correctly.
*/
@SuiteClasses({
EclipseLinkSemanticValidatorTest.class,
})
@RunWith(JPQLTestRunner.class)
public static class AllEclipseLinkSemanticValidatorTest {
private AllEclipseLinkSemanticValidatorTest() {
super();
}
@JPQLGrammarTestHelper
static JPQLGrammar[] buildJPQLGrammars() {
return JPQLGrammarTools.allEclipseLinkJPQLGrammars(EclipseLinkVersion.VERSION_2_0);
}
}
/**
* This test suite tests JPQL queries written following the grammar defined in the JPA 2.1 spec
* with the extension provided by EclipseLink 2.4 and makes sure the various JPQL grammars that
* support it parses them correctly.
*/
@SuiteClasses({
EclipseLinkSemanticValidatorTest2_4.class,
EclipseLinkSemanticValidatorExtensionTest2_4.class
})
@RunWith(JPQLTestRunner.class)
public static class AllEclipseLinkSemanticValidatorTest2_4 {
private AllEclipseLinkSemanticValidatorTest2_4() {
super();
}
@JPQLGrammarTestHelper
static JPQLGrammar[] buildJPQLGrammars() {
return JPQLGrammarTools.allEclipseLinkJPQLGrammars(EclipseLinkVersion.VERSION_2_4);
}
}
/**
* This test suite tests JPQL queries written following the grammar defined in the JPA 2.1 spec
* with the extension provided by EclipseLink 2.5 and makes sure the various JPQL grammars that
* support it parses them correctly.
*/
@SuiteClasses({
EclipseLinkSemanticValidatorTest2_5.class,
})
@RunWith(JPQLTestRunner.class)
public static class AllEclipseLinkSemanticValidatorTest2_5 {
private AllEclipseLinkSemanticValidatorTest2_5() {
super();
}
@JPQLGrammarTestHelper
static JPQLGrammar[] buildJPQLGrammars() {
return JPQLGrammarTools.allEclipseLinkJPQLGrammars(EclipseLinkVersion.VERSION_2_5);
}
}
}
| 35.539007 | 99 | 0.687288 |
96fd3e51cdca49da9d7b2de64fe6681f3235cc42 | 8,193 | /*
* Copyright 2022 KCodeYT
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ms.kevi.skyblock.util;
import cn.nukkit.Player;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.level.Level;
import cn.nukkit.math.Vector3;
import ms.kevi.skyblock.SkyBlockPlugin;
import ms.kevi.skyblock.level.WorldConverter;
import ms.kevi.skyblock.level.schematic.Schematic;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class DefaultUtils {
private static final Map<Player, DoubleValue<Vector3, Vector3>> DEBUG_MAP = new HashMap<>();
private static final Map<Player, Schematic> DEBUG_MAP_2 = new HashMap<>();
public static void init(SkyBlockPlugin skyBlockPlugin) {
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("pos1") {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
DEBUG_MAP.putIfAbsent((Player) commandSender, new DoubleValue<>(null, null));
DEBUG_MAP.get(commandSender).setValue1(((Player) commandSender).asBlockVector3().asVector3());
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("pos2") {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
DEBUG_MAP.putIfAbsent((Player) commandSender, new DoubleValue<>(null, null));
DEBUG_MAP.get(commandSender).setValue2(((Player) commandSender).asBlockVector3().asVector3());
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("schem") {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
DEBUG_MAP.putIfAbsent((Player) commandSender, new DoubleValue<>(null, null));
createSchematic((Player) commandSender, DEBUG_MAP.get(commandSender).getValue1(), DEBUG_MAP.get(commandSender).getValue2(), ((Player) commandSender).asBlockVector3().asVector3());
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("place") {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
DEBUG_MAP_2.get(commandSender).buildInstant(((Player) commandSender).asBlockVector3().asVector3(), ((Player) commandSender).getLevel(), Boolean.parseBoolean(args[0]));
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("aniplace") {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
DEBUG_MAP_2.get(commandSender).buildAnimated(((Player) commandSender).asBlockVector3().asVector3(), ((Player) commandSender).getLevel(), Boolean.parseBoolean(args[0]));
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("save") {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
DEBUG_MAP_2.get(commandSender).save(new File("./" + String.join(" ", args) + ".schem"));
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("load") {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
DEBUG_MAP_2.put((Player) commandSender, new Schematic(new File("./" + String.join(" ", args) + ".schem")));
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("worldtp", "", "", new String[]{"wtp", "tpw"}) {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
((Player) commandSender).teleport(commandSender.getServer().getLevelByName(args[0]).getSpawnLocation());
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("loadworld", "", "", new String[]{"lw", "loadw"}) {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
commandSender.getServer().loadLevel(args[0]);
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("unloadworld", "", "", new String[]{"ulw", "unloadw"}) {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
commandSender.getServer().unloadLevel(commandSender.getServer().getLevelByName(args[0]));
return true;
}
});
skyBlockPlugin.getServer().getCommandMap().register("skyblock", new Command("convertworld", "", "", new String[]{"cw", "convertw"}) {
@Override
public boolean execute(CommandSender commandSender, String s, String[] args) {
WorldConverter.convert(commandSender.getServer().getLevelByName(args[0]), true);
return true;
}
});
}
private static void createSchematic(Player player, Vector3 vector3_1, Vector3 vector3_2, Vector3 vector3_3) {
int minX = (int) Math.floor(Math.min(vector3_1.x, vector3_2.x));
int maxX = (int) Math.floor(Math.max(vector3_1.x, vector3_2.x));
int minY = (int) Math.floor(Math.min(vector3_1.y, vector3_2.y));
int maxY = (int) Math.floor(Math.max(vector3_1.y, vector3_2.y));
int minZ = (int) Math.floor(Math.min(vector3_1.z, vector3_2.z));
int maxZ = (int) Math.floor(Math.max(vector3_1.z, vector3_2.z));
Schematic schematic = new Schematic();
Level level = player.getLevel();
for(int x = minX; x <= maxX; x++) {
for(int y = minY; y <= maxY; y++) {
for(int z = minZ; z <= maxZ; z++) {
Vector3 vector3 = new Vector3(x, y, z);
int xMinus = x - vector3_3.getFloorX();
int yMinus = y - vector3_3.getFloorY();
int zMinus = z - vector3_3.getFloorZ();
schematic.addBlock(new Vector3(xMinus, yMinus, zMinus), level.getBlock(vector3));
Arrays.stream(level.getEntities()).
filter(entity -> !(entity instanceof Player) && entity.getFloorX() == vector3.getFloorX() && entity.getFloorY() == vector3.getFloorY() && entity.getFloorZ() == vector3.getFloorZ()).
forEach(entity -> {
entity.saveNBT();
schematic.addEntity(entity.subtract(vector3_3.getFloorX(), vector3_3.getFloorY(), vector3_3.getFloorZ()), entity.getSaveId(), entity.namedTag.copy());
});
BlockEntity blockEntity = level.getBlockEntity(new Vector3(x, y, z));
if(blockEntity != null)
schematic.addBlockEntity(new Vector3(xMinus, yMinus, zMinus).asBlockVector3(), blockEntity.getSaveId(), blockEntity.getCleanedNBT().copy());
}
}
}
DEBUG_MAP_2.put(player, schematic);
}
}
| 48.767857 | 209 | 0.613451 |
dfa250b7c3373cbfc1ce23829ec76ad85a12ad7b | 2,678 | /*
The Command class checks given command is valid or not. And keeps the data is given by command.
*/
public class Command{
private String[] command;
//Patterns of all commands.
private static final Object[][] COMMAND_PATTERN = new Object[][]{
{2, "load", "load;file_name"},
{6, "addAgency", "addAgency;name;address;town;city;phone"},
{9, "addAgent", "addAgent;agency_id;name;birthdate;address;town;city;phone;gender"},
{9, "addRealEstate", "addRealEstate;type;status;address;town;city;surface_area;price;number_of_rooms"},
{8, "addCustomer", "addCustomer;name;birthdate;address;town;city;phone;gender"},
{5, "addContract", "addContract;real_estate_id;customer_id;agent_id;contract_date"},
{2, "deleteAgent", "deleteAgent;agent_id"},
{2, "deleteRealEstate", "deleteRealEstate;real_estate_id"},
{2, "deleteCustomer", "deleteCustomer;customer_id"},
{1, "displayAgencies", "displayAgencies"},
{1, "displayAgents", "displayAgents"},
{1, "displayRealEstates", "displayRealEstates"},
{1, "displayCustomers", "displayCustomers"},
{1, "displayContracts", "displayContracts"},
{8, "search", "search;type;status;town;city;min_surface_area-max_surface_area;min_price-max_price;min_number_of_rooms-max_number_of_rooms"},
{2, "calculateSalaries", "calculateSalaries;month/year"},
{2, "calculateTotalIncome", "calculateTotalIncome;month/year"},
{2, "mostProfitableAgency", "mostProfitableAgency;month/year"},
{2, "agentOfTheMonth", "agentOfTheMonth;month/year"},
{1, "clear", "clear"},
{1, "exit", "exit"},
};
//Constructor of command class. If it validates given command, creates object.
public Command(String command){
String[] args = trim(command.split(";", -1));
if(validate(args))
this.command = args;
else
throw new IllegalArgumentException("Unknown command: " + args[0]);
}
//Deletes white spaces from beginning and end of the parameters of command.
private String[] trim(String[] args){
for(int i = 0 ; i < args.length ; i++){
args[i] = args[i].trim();
}
return args;
}
//Checks given command is acceptible or not.
private boolean validate(String[] command){
for(int i = 0 ; i < COMMAND_PATTERN.length ; i++ ){
if(command[0].replaceAll("ı", "i").equalsIgnoreCase((String)COMMAND_PATTERN[i][1])){
if(command.length != (int)COMMAND_PATTERN[i][0])
throw new IllegalArgumentException("Wrong prototype!\n Expected: " + (String)COMMAND_PATTERN[i][2] + " ");
else
return true;
}
}
return false;
}
public String get(int index){
return command[index];
}
}
| 35.236842 | 144 | 0.67177 |
4f017b78fb871de18d9484bc657d8531e58f9475 | 6,335 | package seedu.scheduler.testutil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import seedu.scheduler.model.person.DefaultValues;
import seedu.scheduler.model.person.Department;
import seedu.scheduler.model.person.Email;
import seedu.scheduler.model.person.Interviewer;
import seedu.scheduler.model.person.Name;
import seedu.scheduler.model.person.Person;
import seedu.scheduler.model.person.Phone;
import seedu.scheduler.model.person.Slot;
import seedu.scheduler.model.tag.Tag;
/**
* A class which gives sample interviewers.
*/
public class SampleInterviewer {
private static String[] alphabets = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
public static Interviewer getInterviewerOneValidAvailability() {
String[] availabilities = new String[]{"10/09/2019 18:00-18:30"};
return getAlicePauline(availabilities);
}
public static Interviewer getInterviewerMultipleValidAvailabilities() {
String[] availabilities = new String[]{"10/09/2019 18:30-19:00", "10/09/2019 19:00-19:30",
"10/09/2019 20:00-20:30"};
return getAlicePauline(availabilities);
}
/**
* Invalid date and invalid time.
*/
public static Interviewer getInterviewerMultipleInvalidAvailabilities() {
String[] availabilities = new String[]{"20/09/2019 18:30-19:00", "10/09/2019 22:00-23:30"};
return getAlicePauline(availabilities);
}
public static Interviewer getInterviewerMultipleAvailabilitiesSomeInvalid() {
String[] availabilities = new String[]{"08/09/2019 18:30-19:00", "10/09/2019 19:00-19:30",
"10/09/2019 20:00-20:30", "10/09/2019 23:00-23:30"};
return getAlicePauline(availabilities);
}
private static Interviewer getAlicePauline(String[] availabilities) {
Person alice = TypicalPersons.ALICE;
Department department = new Department("Technical");
Name name = alice.getName();
Phone phone = alice.getPhone();
Email email = DefaultValues.DEFAULT_PERSONAL_EMAIL;
Set<Tag> tags = alice.getTags();
Interviewer alicePauline = new Interviewer.InterviewerBuilder(name, phone, tags)
.email(email)
.department(department)
.build();
alicePauline.setAvailabilities(
Arrays.stream(availabilities).map(Slot::fromString).collect(Collectors.toList()));
return alicePauline;
}
public static Interviewer getHazel() {
Interviewer hazel = getInterviewer("Hazel", "Welfare");
String[] availabilitiesAsArray = new String[]{"10/09/2019 18:30-19:00", "10/09/2019 19:00-19:30",
"10/09/2019 20:00-20:30", "10/09/2019 20:30-21:00"};
List<String> availabilities = Arrays.asList(availabilitiesAsArray);
hazel.setAvailabilities(availabilities.stream().map(Slot::fromString).collect(Collectors.toList()));
return hazel;
}
public static Interviewer getBernard() {
Interviewer bernard = getInterviewer("Bernard", "Presidential");
return bernard;
}
public static Interviewer getInterviewer(String nameString, String departmentString) {
Person alice = TypicalPersons.ALICE;
Department department = new Department(departmentString);
Name name = new Name(nameString);
Phone phone = alice.getPhone();
Email email = DefaultValues.DEFAULT_PERSONAL_EMAIL;
Set<Tag> tags = alice.getTags();
return new Interviewer.InterviewerBuilder(name, phone, tags)
.department(department)
.email(email)
.build();
}
/**
* Returns sample slots for the sample graph 1 in the sample graph data.
*/
public static List<Interviewer> getSampleInterviewersForGraph1() {
List<Slot> slots = SampleSlot.getSampleSlotsForGraph1();
List<Slot> slots1 = new LinkedList<>();
slots1.add(slots.get(0));
slots1.add(slots.get(1));
List<Slot> slots2 = new LinkedList<>();
slots2.add(slots.get(2));
slots2.add(slots.get(3));
List<Slot> slots3 = new LinkedList<>();
slots3.add(slots.get(4));
Interviewer interviewer1 = new Interviewer.InterviewerBuilder(new Name("Chris"), new Phone("12345678"),
new HashSet<>()).department(new Department("Technical")).availabilities(slots1).build();
Interviewer interviewer2 = new Interviewer.InterviewerBuilder(new Name("John"), new Phone("12345678"),
new HashSet<>()).department(new Department("Technical")).availabilities(slots2).build();
Interviewer interviewer3 = new Interviewer.InterviewerBuilder(new Name("Barry"), new Phone("12345678"),
new HashSet<>()).department(new Department("Technical")).availabilities(slots3).build();
Interviewer[] interviewersArr = new Interviewer[]{interviewer1, interviewer2, interviewer3};
return Arrays.asList(interviewersArr);
}
/**
* Helper method to get expected list of interviewers for testing.
* @return expected list of interviewers
*/
public static List<Interviewer> getSampleListOfInterviewers() {
ArrayList<Interviewer> expectedInterviewers = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Name interviewerName = new Name("Person " + alphabets[i]);
Department interviewerDepartment = new Department("Department " + alphabets[i]);
Interviewer.InterviewerBuilder interviewerBuilder =
new Interviewer.InterviewerBuilder(interviewerName,
DefaultValues.DEFAULT_PHONE, DefaultValues.DEFAULT_TAGS);
interviewerBuilder.department(interviewerDepartment);
if (i == 0) {
ArrayList<Slot> slots = new ArrayList<>();
slots.add(Slot.fromString("10/10/2019 18:00-18:30"));
interviewerBuilder.availabilities(slots);
} else {
interviewerBuilder.availabilities(new ArrayList<>());
}
expectedInterviewers.add(interviewerBuilder.build());
}
return expectedInterviewers;
}
}
| 41.677632 | 111 | 0.65809 |
75d0cf1631ced56bd01e54325c2db9750fd08fb5 | 5,133 | package com.mrh0.buildersaddition.gui;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mrh0.buildersaddition.BuildersAddition;
import com.mrh0.buildersaddition.config.Config;
import com.mrh0.buildersaddition.container.SpeakerContainer;
import com.mrh0.buildersaddition.midi.IMidiEvent;
import com.mrh0.buildersaddition.network.PlayNotePacket;
import com.mrh0.buildersaddition.network.UpdateDataPacket;
import com.mrh0.buildersaddition.tileentity.SpeakerTileEntity;
import com.mrh0.buildersaddition.util.Notes;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.widget.button.Button.IPressable;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TranslationTextComponent;
public class SpeakerGui extends ContainerScreen<SpeakerContainer> implements IMidiEvent {
private final SpeakerContainer screenContainer;
private final SpeakerTileEntity te;
private static final int SIZE = 16;
private Button connectBtn;
private Button[] btns;
public SpeakerGui(SpeakerContainer screenContainer, PlayerInventory inv, ITextComponent tc) {
super(screenContainer, inv, tc);
this.screenContainer = screenContainer;
this.te = (SpeakerTileEntity) Minecraft.getInstance().world.getTileEntity(screenContainer.pos);
this.xSize = 384;
this.ySize = 192;
if (BuildersAddition.midi != null)
BuildersAddition.midi.midiEvent = this;
}
protected void func_230451_b_(MatrixStack p_230451_1_, int p_230451_2_, int p_230451_3_) {
//this.field_230712_o_.func_238422_b_(p_230451_1_, this.field_230704_d_, (float) this.field_238742_p_,(float) this.field_238743_q_, 4210752);
}
// init
@Override
public void func_231158_b_(Minecraft p_231158_1_, int p_231158_2_, int p_231158_3_) {
super.func_231158_b_(p_231158_1_, p_231158_2_, p_231158_3_);
int x = this.field_230708_k_ / 2;// with
int y = this.field_230709_l_ / 2;// height
IPressable p = (b) -> {
};
connectBtn = new Button(x - 48, y + 24 * 4, 96, 20,
new TranslationTextComponent(BuildersAddition.midi == null ? "container.buildersaddition.speaker.connect" : "container.buildersaddition.speaker.disconnect"), (b) -> {
if (BuildersAddition.midi != null) {
if (BuildersAddition.midi.midiEvent == null)
BuildersAddition.midi.midiEvent = this;
else
BuildersAddition.midi.midiEvent = null;
connectBtn.func_238482_a_(new TranslationTextComponent(
BuildersAddition.midi.midiEvent == null ? "container.buildersaddition.speaker.connect" : "container.buildersaddition.speaker.disconnect"));// SetMessage
}
});
this.func_230480_a_(connectBtn);// addButton
btns = new Button[SIZE];
for (int i = 0; i < SIZE; i++) {
btns[i] = new Button(x + (i > 7 ? -100 : 4), y + (i % 8 * 24) - 4 * 24, 96, 20,
new TranslationTextComponent("note.buildersaddition." + Notes.instrumentNames[i]), p);
this.func_230480_a_(btns[i]);// addButton
btns[i].field_230693_o_ = te.isInstrumentActive(i);// active
}
}
// mouseClicked
@Override
public boolean func_231044_a_(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) {
for (int i = 0; i < SIZE; i++) {
if (btns[i].func_230449_g_())// isHovered
buttonClicked(btns[i], i);
}
return super.func_231044_a_(p_mouseClicked_1_, p_mouseClicked_3_, p_mouseClicked_5_);
}
private void buttonClicked(Button b, int id) {
b.field_230693_o_ = !b.field_230693_o_;// active
sendInstrumentUpdate(getEncoded());
}
private int getEncoded() {
int r = 0;
for (int i = 0; i < SIZE; i++) {
r += btns[i].field_230693_o_ ? Math.pow(2, i) : 0;
}
return r;
}
private void sendInstrumentUpdate(int data) {
if (getTE() != null)
BuildersAddition.Network.sendToServer(new UpdateDataPacket(this.getTE().getPos(), data));
}
// render
@Override
public void func_230430_a_(MatrixStack stack, int x, int y, float p_230430_4_) {
super.func_230430_a_(stack, x, y, p_230430_4_);
GlStateManager.disableLighting();
GlStateManager.disableBlend();
for (int i = 0; i < SIZE; i++) {
if (btns[i].func_230449_g_())// isHovered
func_238652_a_(stack, new StringTextComponent("F#" + Notes.octaveNames[i]), x, y);
}
this.func_230459_a_(stack, x, y);
}
public TileEntity getTE() {
return te;
}
private void sendNote(int note) {
if (getTE() != null)
BuildersAddition.Network.sendToServer(new PlayNotePacket(this.getTE().getPos(), note));
}
@Override
public void minecraftNote(int note, boolean on) {
note += 24;
if (note < 0)
return;
if (on)
sendNote(note);
}
// drawGuiContainerBackgroundLayer
@Override
protected void func_230450_a_(MatrixStack stack, float p_230450_2_, int p_230450_3_, int p_230450_4_) {
func_230446_a_(stack);//renderBackground
GlStateManager.color4f(1.0f, 1.0f, 1.0f, 1.0f);
}
} | 33.54902 | 170 | 0.742646 |
11b4093e78ea4e4e14da1911703bf57d27258f62 | 4,333 | /*
* VTrackGenerator_Test.java
*
* Created on July 24, 2007, 11:54 AM
*
* $Id: VTrackGenerator_Test.java,v 1.1.1.1 2010/04/08 20:38:00 jeremy Exp $
*/
package org.lcsim.recon.tracking.trfbase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.TestCase;
import org.lcsim.recon.tracking.trfutil.Assert;
/**
*
* @author Norman Graf
*/
public class VTrackGenerator_Test extends TestCase
{
private boolean debug;
/** Creates a new instance of VTrackGenerator_Test */
public void testVTrackGenerator()
{
String component = "VTrackGenerator";
String ok_prefix = component + " (I): ";
String error_prefix = component + " test (E): ";
if(debug) System.out.println( ok_prefix
+ "---------- Testing component " + component
+ ". ----------" );
//********************************************************************
// Verify that each generated track is different and is in range.
if(debug) System.out.println( ok_prefix + "Test default sequence." );
SurfTest stest = new SurfTest(1);
TrackVector min = new TrackVector();
TrackVector max = new TrackVector();
min.set(0, 0.0);
max.set(0, 1.0);
min.set(1, 1.0);
max.set(1, 2.0);
min.set(2, -3.0);
max.set(2, -2.0);
min.set(3, 3.0);
max.set(3, 4.0);
min.set(4, -4.0);
max.set(4, 5.0);
VTrackGenerator gen = new VTrackGenerator(stest,min,max);
if(debug) System.out.println( gen );
Assert.assertTrue( stest.pureEqual( gen.surface() ) );
int ntest = 20;
int itest;
List values = new ArrayList();
if(debug) System.out.println( "************" );
for ( itest=0; itest<ntest; ++itest )
{
VTrack trk = gen.newTrack();
if(debug) System.out.println( trk );
if(debug) System.out.println( "************" );
for ( Iterator ival=values.iterator(); ival.hasNext(); )
{
Assert.assertTrue( !trk.equals( (VTrack) ival.next()) );
}
Assert.assertTrue( stest.pureEqual( trk.surface() ) );
for ( int i=0; i<5; ++i )
{
Assert.assertTrue( trk.vector().get(i) >= min.get(i) );
Assert.assertTrue( trk.vector().get(i) <= max.get(i) );
}
values.add(trk);
}
//********************************************************************
// Verify that two generators starting with the same seed give the
// same values.
if(debug) System.out.println( ok_prefix + "Test sequence with seed." );
long seed = 246813579L;
gen.setSeed(seed);
VTrackGenerator gen2 = new VTrackGenerator(stest,min,max);
gen2.setSeed(seed);
for ( itest=0; itest<ntest; ++itest )
{
VTrack trk = gen.newTrack();
VTrack trk2 = gen2.newTrack();
if(debug) System.out.println( trk );
if(debug) System.out.println( "*****" );
if(debug) System.out.println( trk2 );
if(debug) System.out.println( "************" );
Assert.assertTrue( trk.equals(trk2) );
}
//********************************************************************
if(debug) System.out.println( ok_prefix + "Test copy constructor." );
VTrackGenerator gen3 = new VTrackGenerator(gen);
for ( itest=0; itest<ntest; ++itest )
{
VTrack trk = gen.newTrack();
VTrack trk2 = gen3.newTrack();
if(debug) System.out.println( trk );
if(debug) System.out.println( "*****" );
if(debug) System.out.println( trk2 );
if(debug) System.out.println( "************" );
Assert.assertTrue( trk.equals(trk2) );
}
//********************************************************************
if(debug) System.out.println( ok_prefix
+ "------------- All tests passed. -------------" );
//********************************************************************
}
}
| 35.809917 | 79 | 0.474267 |
e27bed4f31c698dbb1ee9e7f2f7a6119bf9f045c | 4,416 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.zxy.commons.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Spring工具类,用于从spring上下文中获取对象
*
* <p>
* 注意:
* 此类一般用于非依赖注入的方式调用spring对象,建议尽量通过spring的依赖注入加载对象
* <p>重要:
* <p>使用时,需在spring中加入以下配置,以xml为例:
* <p><bean id="springBeanUtils" class="com.zxy.commons.spring.SpringBeanUtils" />
* <p>或者引入该包中的配置:
* <p><import resource="classpath:spring_config/zxy_commons_spring.xml" />
* <p>
* <a href="SpringBeanUtils.java"><i>View Source</i></a>
*
* @author [email protected]
* @version 1.0
* @since 1.0
*/
public class SpringBeanUtils implements ApplicationContextAware {
private static ApplicationContext context;
/* (non-Javadoc)
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
if(context == null) {
context = appContext;
}
}
/**
* 通过beanName从spring上下文中获取对象
*
* @param beanName bean name
* @return spring上下文中引用的对象
*/
public static Object getBean(String beanName){
return context.getBean(beanName);
}
/**
* 通过beanClass从spring上下文中获取对象
*
* @param <T> This is the type parameter
* @param beanClass bean class
* @return spring上下文中引用的对象
*/
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
/**
* 通过beanClass从spring上下文中获取对象
*
* @param <T> This is the type parameter
* @param name the name of the bean to retrieve
* @param beanClass bean class
* @return spring上下文中引用的对象。
*/
public static <T> T getBean(String name, Class<T> beanClass) {
return context.getBean(name, beanClass);
}
/**
* 通过class type从spring上下文中获取对象
*
* @param <T> This is the type parameter
* @param type class type
* @return spring上下文中引用的对象
* @throws BeansException BeansException
*/
public static <T> Object getBeanOfType(Class<T> type) throws BeansException {
return BeanFactoryUtils.beanOfType(context, type);
}
/**
* 初始化spring配置
*
* @param applicationContextPaths Application context paths
* @return Application context
*/
public static ApplicationContext init(String... applicationContextPaths){
return new ClassPathXmlApplicationContext(applicationContextPaths);
}
/*public static ClassPathXmlApplicationContext init(String... applicationContextPaths){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
// context.setAllowBeanDefinitionOverriding(false);
context.setConfigLocations(applicationContextPaths);
context.refresh();
return context;
}*/
/*private final static class SpringBeanUtilsBuilder {
private final static SpringBeanUtils BUILDER = new SpringBeanUtils();
}
private SpringBeanUtils() {
super();
}
@Override
protected String getConfigLocation() {
return "classpath:applicationContext.xml";
}
public static ApplicationContext getContext() {
return SpringBeanUtilsBuilder.BUILDER.context;
}*/
}
| 31.542857 | 133 | 0.697917 |
ed624ea67add605e99b4801e70d1fc34c00af229 | 574 | package xyz.lgvalle.tddpersistence;
import java.util.Date;
public class TaskMapper {
public TaskDBModel fromDomain(Task task) {
Date expiration = task.getExpiration();
if (expiration == null) {
expiration = new Date();
}
return new TaskDBModel(
task.getName(),
expiration.getTime()
);
}
public Task toDomain(TaskDBModel taskDBModel) {
return new Task(
taskDBModel.getName(),
new Date(taskDBModel.getExpiration())
);
}
}
| 21.259259 | 53 | 0.555749 |
e114d7ad4ac92f854d4a91f19ce953e4668e435c | 1,277 | package com.bytesfly.jwt.component;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.bytesfly.jwt.model.CurrentUser;
import com.bytesfly.jwt.model.RequestContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 运行时上下文环境(从Spring容器中获取Bean,获取当前登录用户等)
*/
@Component
public class Context implements ApplicationContextAware {
public static final TransmittableThreadLocal<RequestContext> THREAD_LOCAL = new TransmittableThreadLocal<>();
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
Context.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
public static RequestContext ctx() {
return THREAD_LOCAL.get();
}
/**
* 返回当前请求的用户信息
*/
public static CurrentUser currentUser() {
RequestContext ctx = ctx();
return ctx != null ? ctx.getCurrentUser() : null;
}
}
| 28.377778 | 113 | 0.7361 |
d0d1c5848229f03f471d757115374b3f75ec5118 | 5,830 | /*----------------------------------------------------------------------------------------------------------------------
NumberUtil sınıfı
----------------------------------------------------------------------------------------------------------------------*/
package org.csystem.util;
import static java.lang.Math.*;
public class NumberUtil {
private static final String [] ONES;
private static final String [] TENS;
static {
ONES = new String[]{"", "bir", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz", "dokuz"};
TENS = new String[]{"", "on", "yürmi", "otuz", "kırk", "elli", "altmış", "yetmiş", "seksen", "doksan"};
}
private static String getTextByDigits(int a, int b, int c)
{
String result = "";
if (a != 0) {
if (a != 1)
result += ONES[a];
result += "yüz";
}
if (b != 0)
result += TENS[b];
if (c != 0)
result += ONES[c];
return result;
}
private static String numberToText3DigitsTR(int val)
{
if (val == 0)
return "sıfır";
String result = "";
val = Math.abs(val);
int a = val / 100;
int b = val / 10 % 10;
int c = val % 10;
return result + getTextByDigits(a, b, c);
}
public static int [] getDigits(long val, int n)
{
val = Math.abs(val);
int [] digits = new int[val == 0 ? 1 : (int)(Math.log10(val) / n) + 1];
int len = digits.length;
int powerOfTen = (int)Math.pow(10, n);
for (int i = 0; i < len; digits[len - 1 - i] = (int)(val % powerOfTen), val /= powerOfTen, ++i)
;
return digits;
}
private NumberUtil()
{
}
public static int countDigits(int val)
{
return val == 0 ? 1 : (int) log10(abs(val)) + 1;
}
public static long factorial(int n)
{
long result = 1;
for (int i = 2; i <= n; ++i)
result *= i;
return result;
}
public static int [] getDigits(long val)
{
return getDigits(val, 1);
}
public static int [] getDigits(int val)
{
return getDigits((long)val);
}
public static int [] getDigitsInTwos(long val)
{
return getDigits(val, 2);
}
public static int [] getDigitsInThrees(long val)
{
return getDigits(val, 3);
}
public static int getDigitsSum(int val)
{
int sum = 0;
while (val != 0) {
sum += val % 10;
val /= 10;
}
return sum;
}
public static int getFibonacciNumber(int n)
{
if (n <= 0)
return -1;
if (n <= 2)
return n - 1;
int prev1 = 1, prev2 = 0, val = 0;
for (int i = 2; i < n; ++i) {
val = prev1 + prev2;
prev2 = prev1;
prev1 = val;
}
return val;
}
public static int getNextFibonacciNumber(int val)
{
if (val < 0)
return 0;
int prev1 = 1, prev2 = 0, result;
for (;;) {
result = prev1 + prev2;
if (result > val)
return result;
prev2 = prev1;
prev1 = result;
}
}
public static boolean isPalindrome(int val)
{
return getReverse(val) == val;
}
public static int getPrime(int n)
{
if (n <= 0)
return -1;
int count = 0;
int val = 2;
for (;;) {
if (isPrime(val))
++count;
if (count == n)
return val;
++val;
}
}
public static int getPowSum(int val)
{
int n = countDigits(val);
int sum = 0;
while (val != 0) {
sum += pow(val % 10, n);
val /= 10;
}
return sum;
}
public static int getReverse(int val)
{
int reverse = 0;
while (val != 0) {
reverse = reverse * 10 + val % 10;
val /= 10;
}
return reverse;
}
public static boolean isArmstrong(int val)
{
return val >= 0 && getPowSum(val) == val;
}
public static boolean isEven(int val)
{
return val % 2 == 0;
}
public static boolean isHarshad(int val)
{
if (val <= 0)
return false;
return val % getDigitsSum(val) == 0;
}
public static boolean isPrime(int val)
{
if (val <= 1)
return false;
if (val % 2 == 0)
return val == 2;
if (val % 3 == 0)
return val == 3;
if (val % 5 == 0)
return val == 5;
if (val % 7 == 0)
return val == 7;
int sqrtIntValue = (int) sqrt(val);
for (int i = 11; i <= sqrtIntValue; i += 2)
if (val % i == 0)
return false;
return true;
}
public static boolean isOdd(int val)
{
return !isEven(val);
}
public static int max(int a, int b, int c)
{
return Math.max(Math.max(a, b), c);
}
public static int mid(int a, int b, int c)
{
if (a <= b && b <= c || c <= b && b <= a)
return b;
if (b <= a && a <= c || c <= a && a <= b)
return a;
return c;
}
public static int min(int a, int b, int c)
{
return Math.min(Math.min(a, b), c);
}
public static String numToStr(long val)
{
int [] digitsInThrees = getDigitsInThrees(val);
String result = val < 0 ? "eksi" : "";
val = Math.abs(val);
for (int d : digitsInThrees)
result += numberToText3DigitsTR(d) + ".....";
return result;
}
} | 20.45614 | 121 | 0.430532 |
937273169dfc9033777d3decbf428e0e88ee50d1 | 5,270 | import javax.swing.*;
import java.awt.*;
public class Buttons {
public static void createButtons(JFrame frame) {
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
JButton five = new JButton("5");
JButton six = new JButton("6");
JButton seven = new JButton("7");
JButton eight = new JButton("8");
JButton nine = new JButton("9");
JButton zero = new JButton("0");
JButton decimal = new JButton(".");
JButton equals = new JButton("=");
JButton divide = new JButton("÷");
JButton multiply = new JButton("×");
JButton subtract = new JButton("−");
JButton add = new JButton("+");
JButton sign = new JButton("+/-");
JButton ans = new JButton("ANS");
JButton clear = new JButton("CLEAR");
//--------------------------------------
//Button styles for all the buttons
buttonStyle(one, 10, 240, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(two, 80, 240, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(three, 150, 240, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(four, 10, 180, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(five, 80, 180, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(six, 150, 180, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(seven, 10, 120, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(eight, 80, 120, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(nine, 150, 120, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(zero, 10, 300, 50, 50, Color.BLACK, Color.WHITE);
buttonStyle(decimal, 80, 300, 50, 50, Color.GRAY, Color.WHITE);
buttonStyle(equals, 150, 300, 50, 50, Color.RED, Color.WHITE);
buttonStyle(divide, 230, 120, 50, 50, Color.GREEN, Color.BLACK);
buttonStyle(multiply, 230, 180, 50, 50, Color.GREEN, Color.BLACK);
buttonStyle(subtract, 230, 240, 50, 50, Color.GREEN, Color.BLACK);
buttonStyle(add, 230, 300, 50, 50, Color.GREEN, Color.BLACK);
buttonStyle(sign, 230, 90, 50, 20, Color.ORANGE, Color.BLACK);
buttonStyle(ans, 10, 90, 50, 20, Color.ORANGE, Color.BLACK);
buttonStyle(clear, 80, 90, 120, 20, Color.WHITE, Color.BLACK);
//--------------------------------------
//Button actions for each button
ButtonAction action = new ButtonAction(Components.getDisplayArea());
one.addActionListener(e -> ButtonAction.one());
two.addActionListener(e -> ButtonAction.two());
three.addActionListener(e -> ButtonAction.three());
four.addActionListener(e -> ButtonAction.four());
five.addActionListener(e -> ButtonAction.five());
six.addActionListener(e -> ButtonAction.six());
seven.addActionListener(e -> ButtonAction.seven());
eight.addActionListener(e -> ButtonAction.eight());
nine.addActionListener(e -> ButtonAction.nine());
zero.addActionListener(e -> ButtonAction.zero());
decimal.addActionListener(e -> ButtonAction.decimal());
equals.addActionListener(e -> ButtonAction.equals());
divide.addActionListener(e -> ButtonAction.divide());
multiply.addActionListener(e -> ButtonAction.multiply());
subtract.addActionListener(e -> ButtonAction.subtract());
add.addActionListener(e -> ButtonAction.add());
sign.addActionListener(e -> ButtonAction.sign());
ans.addActionListener(e -> ButtonAction.ans());
clear.addActionListener(e -> ButtonAction.clear());
//--------------------------------------
//Places all buttons on frame
placeButton(frame, one);
placeButton(frame, two);
placeButton(frame, three);
placeButton(frame, four);
placeButton(frame, five);
placeButton(frame, six);
placeButton(frame, seven);
placeButton(frame, eight);
placeButton(frame, nine);
placeButton(frame, zero);
placeButton(frame, decimal);
placeButton(frame, equals);
placeButton(frame, divide);
placeButton(frame, multiply);
placeButton(frame, subtract);
placeButton(frame, add);
placeButton(frame, sign);
changeButtonFont(sign, 13);
placeButton(frame, ans);
changeButtonFont(ans, 8);
placeButton(frame, clear);
changeButtonFont(clear, 16);
}
//Changes button position(x, y), width, height, background/foreground color, and the font
private static void buttonStyle(JButton button, int x, int y, int width, int height, Color Backgroundcolor, Color Foregroundcolor) {
button.setBounds(x, y, width, height);
button.setBackground(Backgroundcolor);
button.setForeground(Foregroundcolor);
button.setFont(new Font("Arial", Font.BOLD, 20));
}
//Places button on frame
private static void placeButton(JFrame frame, JButton button) {
frame.add(button);
}
//Changes button font and size
private static void changeButtonFont(JButton button, int font_size) {
button.setFont(new Font("Arial", Font.BOLD, font_size));
}
}
| 47.053571 | 136 | 0.613283 |
3b59ab312055420b5f6cd30aa544242d8d03474b | 2,343 | package seedu.address.model.task;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_TASK_DEADLINE_1;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TASK_DEADLINE_0;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TASK_DEADLINE_1;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TASK_DEADLINE_2;
import static seedu.address.testutil.Assert.assertThrows;
import org.junit.jupiter.api.Test;
class TaskDeadlineTest {
private final TaskDeadline taskDeadline1 = new TaskDeadline(VALID_TASK_DEADLINE_0);
private final TaskDeadline taskDeadline2 = new TaskDeadline(VALID_TASK_DEADLINE_1);
@Test
public void constructor_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new TaskDeadline(null));
}
@Test
public void constructor_invalidDeadline_throwsIllegalArgumentException() {
String invalidDeadline = "";
assertThrows(IllegalArgumentException.class, () -> new TaskDeadline(invalidDeadline));
}
@Test
void isValidTaskDeadline() {
// only contains alphanumeric characters -> returns true
assertTrue(TaskDeadline.isValidTaskDeadline(VALID_TASK_DEADLINE_0));
// only contains alphanumeric characters and dashes -> returns true
assertTrue(TaskDeadline.isValidTaskDeadline(VALID_TASK_DEADLINE_1));
// different time format -> returns true
assertTrue(TaskDeadline.isValidTaskDeadline(VALID_TASK_DEADLINE_2));
// contains others symbols -> returns false
assertFalse(TaskDeadline.isValidTaskDeadline(INVALID_TASK_DEADLINE_1));
}
@Test
void equals() {
// same object -> returns true
assertTrue(taskDeadline1.equals(taskDeadline1));
// not a TaskDeadline object -> returns false
assertFalse(taskDeadline1.equals(VALID_TASK_DEADLINE_0));
// same String -> returns true
assertTrue(taskDeadline1.equals(new TaskDeadline(VALID_TASK_DEADLINE_0)));
// null -> returns false
assertFalse(taskDeadline1.equals(null));
// different String -> returns false
assertFalse(taskDeadline1.equals(taskDeadline2));
}
}
| 37.190476 | 94 | 0.748186 |
aea4ff2b0b12cfda04d4520ceb62aa873d522176 | 19,415 | package controller;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.function.Predicate;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.util.Callback;
import model.Customer;
public class CustomersController implements Initializable {
@FXML
public TableView<Customer> table;
@FXML
public TableColumn<Customer, String> id;
@FXML
public TableColumn<Customer, String> surname;
@FXML
public TableColumn<Customer, String> name;
@FXML
public TableColumn<Customer, String> identity;
@FXML
public TableColumn<Customer, String> password;
@FXML
public TableColumn<Customer, String> number;
@FXML
public TableColumn<Customer, String> street;
@FXML
public TableColumn<Customer, String> postalcode;
@FXML
public TableColumn<Customer, String> city;
@FXML
public TableColumn<Customer, String> country;
@FXML
public TableColumn<Customer, Void> detail;
@FXML
public TableColumn<Customer, Void> remove;
@FXML
public Label displayCount;
@FXML
public ToggleButton filtersButton;
@FXML
public BorderPane mainPane;
@FXML
public VBox filterPanel;
@FXML
public VBox surnameVBox;
@FXML
public VBox nameVBox;
@FXML
public VBox identityVBox;
@FXML
public VBox postalcodeVBox;
@FXML
public VBox cityVBox;
@FXML
public VBox countryVBox;
@FXML
public CheckBox seePass;
private List<Predicate<Customer>> surnameFilters;
private List<Predicate<Customer>> nameFilters;
private List<Predicate<Customer>> identityFilters;
private List<Predicate<Customer>> postalcodeFilters;
private List<Predicate<Customer>> cityFilters;
private List<Predicate<Customer>> countryFilters;
private List<Customer> allItems;
private ObservableList<Customer> displayedItems;
public static Tab createControl() {
try {
URL fxmlURL = CustomersController.class.getResource("../view/Customers.fxml");
FXMLLoader fxmlLoader = new FXMLLoader(fxmlURL);
return fxmlLoader.<TabPane>load().getTabs().get(0);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
filtersButton.setOnAction((e) -> mainPane.setRight(filtersButton.isSelected() ? filterPanel : null));
mainPane.setRight(null);
surnameFilters = new LinkedList<Predicate<Customer>>();
nameFilters = new LinkedList<Predicate<Customer>>();
identityFilters = new LinkedList<Predicate<Customer>>();
postalcodeFilters = new LinkedList<Predicate<Customer>>();
cityFilters = new LinkedList<Predicate<Customer>>();
countryFilters = new LinkedList<Predicate<Customer>>();
seePass.setOnAction((e) -> table.refresh());
id.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(Integer.toString(arg0.getValue().getId()));
}
});
surname.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getSurname());
}
});
name.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getName());
}
});
identity.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getIdentifier());
}
});
password.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(seePass.isSelected() ? arg0.getValue().getPwd()
: Utilities.getHiddenString(arg0.getValue().getPwd()));
}
});
number.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getAddressNumber());
}
});
street.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getAddressStreet());
}
});
postalcode.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getAddressPostalCode());
}
});
city.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getAddressCity());
}
});
country.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Customer, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Customer, String> arg0) {
return new ReadOnlyStringWrapper(arg0.getValue().getAddressCountry());
}
});
detail.setCellFactory(new Callback<TableColumn<Customer, Void>, TableCell<Customer, Void>>() {
@Override
public TableCell<Customer, Void> call(TableColumn<Customer, Void> arg0) {
return new TableCell<Customer, Void>() {
private Button button = new Button();
{
var iv = new ImageView();
iv.setSmooth(false);
iv.setPreserveRatio(false);
iv.setImage(MainWindowController.detailImage);
button.setGraphic(iv);
alignmentProperty().set(Pos.BASELINE_CENTER);
button.setOnAction((ActionEvent event) -> {
MainWindowController.detailCustomer(table.getItems().get(getIndex()));
});
}
@Override
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(button);
}
}
};
};
});
remove.setCellFactory(new Callback<TableColumn<Customer, Void>, TableCell<Customer, Void>>() {
@Override
public TableCell<Customer, Void> call(TableColumn<Customer, Void> arg0) {
return new TableCell<Customer, Void>() {
private Button button = new Button();
{
var iv = new ImageView();
iv.setSmooth(false);
iv.setPreserveRatio(false);
iv.setImage(MainWindowController.removeImage);
button.setGraphic(iv);
alignmentProperty().set(Pos.BASELINE_CENTER);
button.setOnAction((ActionEvent event) -> {
var custo = table.getItems().get(getIndex());
MainWindowController.removeCustomer(custo, () -> {
allItems.remove(custo);
applyFilters();
}, null);
});
}
@Override
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(button);
}
}
};
};
});
displayedItems = FXCollections.observableList(new ArrayList<Customer>());
allItems = new LinkedList<Customer>();
table.setItems(displayedItems);
table.setOnKeyPressed((KeyEvent ev) -> {
if (ev.getCode() == KeyCode.DELETE) {
var custo = table.getSelectionModel().getSelectedItem();
if (custo != null) {
MainWindowController.removeCustomer(custo, () -> {
allItems.remove(custo);
applyFilters();
}, null);
}
}
});
addSurnameFilter();
addNameFilter();
addIdentityFilter();
addPostalcodeFilter();
addCityFilter();
addCountryFilter();
refresh();
}
public void refresh() {
MainWindowController.runAsynchronously(() -> {
allItems.clear();
for (Customer custo : MainWindowController.factory.getCustomerDAO().getAll())
allItems.add(custo);
}, () -> applyFilters());
}
public void filter() {
surnameFilters.clear();
nameFilters.clear();
identityFilters.clear();
postalcodeFilters.clear();
cityFilters.clear();
countryFilters.clear();
for (Node filter : surnameVBox.getChildren()) {
var field = (TextField) ((HBox) filter).getChildren().get(0);
var key = field.getText();
surnameFilters.add((custo) -> Utilities.compareStrings(key, custo.getSurname()));
}
for (Node filter : nameVBox.getChildren()) {
var field = (TextField) ((HBox) filter).getChildren().get(0);
var key = field.getText();
nameFilters.add((custo) -> Utilities.compareStrings(key, custo.getName()));
}
for (Node filter : identityVBox.getChildren()) {
var field = (TextField) ((HBox) filter).getChildren().get(0);
var key = field.getText();
identityFilters.add((custo) -> Utilities.compareStrings(key, custo.getIdentifier()));
}
for (Node filter : postalcodeVBox.getChildren()) {
var field = (TextField) ((HBox) filter).getChildren().get(0);
var key = field.getText();
postalcodeFilters.add((custo) -> Utilities.compareStrings(key, custo.getAddressPostalCode()));
}
for (Node filter : cityVBox.getChildren()) {
var field = (TextField) ((HBox) filter).getChildren().get(0);
var key = field.getText();
cityFilters.add((custo) -> Utilities.compareStrings(key, custo.getAddressCity()));
}
for (Node filter : countryVBox.getChildren()) {
var field = (TextField) ((HBox) filter).getChildren().get(0);
var key = field.getText();
countryFilters.add((custo) -> Utilities.compareStrings(key, custo.getAddressCountry()));
}
applyFilters();
}
public void applyFilters() {
displayedItems.clear();
for (Customer custo : allItems) {
if (Utilities.testAny(surnameFilters, (c) -> c.test(custo), true)
&& Utilities.testAny(nameFilters, (c) -> c.test(custo), true)
&& Utilities.testAny(identityFilters, (c) -> c.test(custo), true)
&& Utilities.testAny(postalcodeFilters, (c) -> c.test(custo), true)
&& Utilities.testAny(cityFilters, (c) -> c.test(custo), true)
&& Utilities.testAny(countryFilters, (c) -> c.test(custo), true))
displayedItems.add(custo);
}
displayCount.setText(displayedItems.size() + " / " + allItems.size() + " affiché"
+ (displayedItems.size() != 1 ? "s " : " "));
}
public void addSurnameFilter() {
var key = new TextField();
var deleteButton = new Button();
var img = new ImageView(MainWindowController.removeImage);
img.setPreserveRatio(false);
img.setSmooth(false);
img.setFitHeight(24);
img.setFitWidth(24);
deleteButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
deleteButton.setGraphic(img);
var box = new HBox();
deleteButton.setOnAction((e) -> surnameVBox.getChildren().remove(box));
box.setAlignment(Pos.CENTER_LEFT);
box.getChildren().addAll(key, deleteButton);
HBox.setMargin(key, new Insets(5));
HBox.setMargin(deleteButton, new Insets(5));
surnameVBox.getChildren().add(box);
}
public void addNameFilter() {
var key = new TextField();
var deleteButton = new Button();
var img = new ImageView(MainWindowController.removeImage);
img.setPreserveRatio(false);
img.setSmooth(false);
img.setFitHeight(24);
img.setFitWidth(24);
deleteButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
deleteButton.setGraphic(img);
var box = new HBox();
deleteButton.setOnAction((e) -> nameVBox.getChildren().remove(box));
box.setAlignment(Pos.CENTER_LEFT);
box.getChildren().addAll(key, deleteButton);
HBox.setMargin(key, new Insets(5));
HBox.setMargin(deleteButton, new Insets(5));
nameVBox.getChildren().add(box);
}
public void addIdentityFilter() {
var key = new TextField();
var deleteButton = new Button();
var img = new ImageView(MainWindowController.removeImage);
img.setPreserveRatio(false);
img.setSmooth(false);
img.setFitHeight(24);
img.setFitWidth(24);
deleteButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
deleteButton.setGraphic(img);
var box = new HBox();
deleteButton.setOnAction((e) -> identityVBox.getChildren().remove(box));
box.setAlignment(Pos.CENTER_LEFT);
box.getChildren().addAll(key, deleteButton);
HBox.setMargin(key, new Insets(5));
HBox.setMargin(deleteButton, new Insets(5));
identityVBox.getChildren().add(box);
}
public void addPostalcodeFilter() {
var key = new TextField();
var deleteButton = new Button();
var img = new ImageView(MainWindowController.removeImage);
img.setPreserveRatio(false);
img.setSmooth(false);
img.setFitHeight(24);
img.setFitWidth(24);
deleteButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
deleteButton.setGraphic(img);
var box = new HBox();
deleteButton.setOnAction((e) -> postalcodeVBox.getChildren().remove(box));
box.setAlignment(Pos.CENTER_LEFT);
box.getChildren().addAll(key, deleteButton);
HBox.setMargin(key, new Insets(5));
HBox.setMargin(deleteButton, new Insets(5));
postalcodeVBox.getChildren().add(box);
}
public void addCityFilter() {
var key = new TextField();
var deleteButton = new Button();
var img = new ImageView(MainWindowController.removeImage);
img.setPreserveRatio(false);
img.setSmooth(false);
img.setFitHeight(24);
img.setFitWidth(24);
deleteButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
deleteButton.setGraphic(img);
var box = new HBox();
deleteButton.setOnAction((e) -> cityVBox.getChildren().remove(box));
box.setAlignment(Pos.CENTER_LEFT);
box.getChildren().addAll(key, deleteButton);
HBox.setMargin(key, new Insets(5));
HBox.setMargin(deleteButton, new Insets(5));
cityVBox.getChildren().add(box);
}
public void addCountryFilter() {
var key = new TextField();
var deleteButton = new Button();
var img = new ImageView(MainWindowController.removeImage);
img.setPreserveRatio(false);
img.setSmooth(false);
img.setFitHeight(24);
img.setFitWidth(24);
deleteButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
deleteButton.setGraphic(img);
var box = new HBox();
deleteButton.setOnAction((e) -> countryVBox.getChildren().remove(box));
box.setAlignment(Pos.CENTER_LEFT);
box.getChildren().addAll(key, deleteButton);
HBox.setMargin(key, new Insets(5));
HBox.setMargin(deleteButton, new Insets(5));
countryVBox.getChildren().add(box);
}
} | 40.280083 | 120 | 0.591038 |
df10ea1f52d91980871c579a0f8151c0f34753c7 | 444 | package ch.uepaa.quickstart;
public class GlobalVar {
public String getGlobalVar1() {
return GlobalVar1;
}
public void setGlobalVar1(String GlobalVar1) {
this.GlobalVar1 = GlobalVar1;
}
private String GlobalVar1 = "";
private static final GlobalVar instance = new GlobalVar();
private GlobalVar() {
}
public static GlobalVar getInstance() {
return GlobalVar.instance;
}
}
| 17.76 | 62 | 0.650901 |
508d39217ce24dc1a07946bd9afaedeb02ce5fd0 | 3,104 | package com.github.pettyfer.caas.framework.core.restful;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pettyfer.caas.framework.biz.entity.BizSqlBuild;
import com.github.pettyfer.caas.framework.biz.entity.BizSqlBuildHistory;
import com.github.pettyfer.caas.framework.core.model.BuildStepView;
import com.github.pettyfer.caas.framework.core.model.SqlBuildHistorySelectView;
import com.github.pettyfer.caas.framework.core.model.SqlBuildListView;
import com.github.pettyfer.caas.framework.core.service.ISqlBuildCoreService;
import com.github.pettyfer.caas.global.constants.ApiConstant;
import com.github.pettyfer.caas.global.model.R;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* @author Pettyfer
*/
@RestController
@RequestMapping(ApiConstant.API_V1_PREFIX + "/core/sql-build")
public class SqlBuildApi {
private final ISqlBuildCoreService sqlBuildCoreService;
public SqlBuildApi(ISqlBuildCoreService sqlBuildCoreService) {
this.sqlBuildCoreService = sqlBuildCoreService;
}
@GetMapping("page")
public R<IPage<SqlBuildListView>> page(BizSqlBuild sqlBuild, Page<BizSqlBuild> page) {
return new R<IPage<SqlBuildListView>>(sqlBuildCoreService.page(sqlBuild, page));
}
@GetMapping("/{id}")
public R<BizSqlBuild> get(@PathVariable String id) {
return new R<BizSqlBuild>(sqlBuildCoreService.get(id));
}
@PutMapping
public R<Boolean> update(@Valid @RequestBody BizSqlBuild sqlBuild) {
return new R<Boolean>(sqlBuildCoreService.update(sqlBuild));
}
@PostMapping
public R<String> create(@Valid @RequestBody BizSqlBuild sqlBuild) {
return new R<String>(sqlBuildCoreService.create(sqlBuild));
}
@DeleteMapping("/{id}")
public R<Boolean> delete(@PathVariable String id) {
return new R<Boolean>(sqlBuildCoreService.delete(id));
}
@PostMapping("build/{id}")
public R<Boolean> build(@PathVariable String id) {
return new R<>(sqlBuildCoreService.startBuild(id));
}
@GetMapping("history/select/{id}")
public R<List<SqlBuildHistorySelectView>> historySelect(@PathVariable String id) {
return new R<List<SqlBuildHistorySelectView>>(sqlBuildCoreService.historySelect(id));
}
@GetMapping("page/history/{buildId}")
public R<IPage<BizSqlBuildHistory>> page(@PathVariable String buildId, BizSqlBuildHistory history, Page<BizSqlBuildHistory> page) {
return new R<IPage<BizSqlBuildHistory>>(sqlBuildCoreService.page(buildId, history, page));
}
@GetMapping("build/log/step/{buildId}/{jobId}")
public R<BuildStepView> logStep(@PathVariable String buildId, @PathVariable String jobId) {
return new R<BuildStepView>(sqlBuildCoreService.logStep(buildId, jobId));
}
@DeleteMapping("build/log/{historyId}")
public R<Boolean> deleteHistory(@PathVariable String historyId) {
return new R<Boolean>(sqlBuildCoreService.deleteHistory(historyId));
}
}
| 37.39759 | 135 | 0.746456 |
d63a87e3d33e827d51bb9377a568c64da5fd23bd | 1,613 | package com.xixi.approval.myapproval.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* @author xixi
*/
@Data
@TableName("APPROVAL_LOG")
public class ApprovalLogEntity extends BaseEntity implements Serializable {
@TableId(value = "ID", type = IdType.ID_WORKER_STR)
@TableField("ID")
private String id;
/**
* 回滚的原因
*/
@TableField("REASON")
private String reason;
/**
* 状态
*/
@TableField("STATUS")
private String status;
/**
* 关联id
*/
@TableField("RELATE_ID")
private String relateId;
/**
* 节点索引
*/
@TableField("NODE_INDEX")
private Integer nodeIndex;
/**
* 在多节点状态下,子索引数
*/
@TableField("CHILDREN_IDX")
private Integer childrenIdx;
/**
* 审批的用户id
*/
@TableField("USER_ID")
private String userId;
/**
* 审批类型
*/
@TableField("APPROVAL_TYPE")
private String approvalType;
public ApprovalLogEntity(String reason, String status, String relateId, Integer nodeIndex, Integer childrenIdx, String userId, String approvalType) {
this.reason = reason;
this.status = status;
this.relateId = relateId;
this.nodeIndex = nodeIndex;
this.childrenIdx = childrenIdx;
this.userId = userId;
this.approvalType = approvalType;
}
public ApprovalLogEntity() {
}
}
| 20.679487 | 153 | 0.645381 |
dbbf04e1634b0bd100c9986bb39b9ea4b75dded5 | 4,196 | package charistas.actibit;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.TextView;
/**
* This class is responsible for initializing and configuring the hour and minute picker.
*/
public class SetDurationDialogFragment extends DialogFragment {
/**
* Create a new instance of this fragment.
* @return A new instance of this fragment
*/
static SetDurationDialogFragment createFragment() {
return new SetDurationDialogFragment();
}
/**
* Responsible for initializing and configuring the dialog that lets the user set the total
* hours and minutes spent on the chosen Fitbit activity.
* @param savedInstanceState The state generated by a previous instance of this activity
* @return The newly created dialog
*/
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.fragment_duration_dialog, null);
// Configure the picker that lets the user set the hours
final NumberPicker hours = (NumberPicker) view.findViewById(R.id.hourPicker);
final String [] hourPossibleValues = new String[24];
hourPossibleValues[0] = "0";
for (int i = 1; i < hourPossibleValues.length; i++) {
hourPossibleValues[i] = Integer.toString(i);
}
hours.setMaxValue(23);
hours.setMinValue(0);
hours.setWrapSelectorWheel(false);
// Configure the picker that lets the user set the minutes
final NumberPicker minutes = (NumberPicker) view.findViewById(R.id.minutePicker);
final String [] minutePossibleValues = new String[13];
minutePossibleValues[0] = "0";
for (int i = 1; i < minutePossibleValues.length; i++) {
minutePossibleValues[i] = Integer.toString(5 * i);
}
minutes.setMinValue(0);
minutes.setMaxValue(11);
minutes.setDisplayedValues(minutePossibleValues);
minutes.setWrapSelectorWheel(false);
builder.setTitle(getString(R.string.set_duration));
// TODO: Ask on StackOverflow why the following TextViews stay invisible
TextView htv = (TextView)view.findViewById(R.id.hoursTextView);
htv.setEnabled(true);
TextView mtv = (TextView)view.findViewById(R.id.minutesTextView);
mtv.setEnabled(true);
builder.setView(view);
// Configure the OK and Cancel buttons
builder.setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
durationListener.onDone(hourPossibleValues[hours.getValue()], minutePossibleValues[minutes.getValue()]);
}
});
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog - do nothing
}
});
return builder.create();
}
/**
* Captures the Interface implementation
* @param context The active context
*/
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
this.durationListener = (OnDurationInputDoneListener)context;
}
catch (final ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnDurationInputDoneListener");
}
}
/**
* This listener is used to communicate with the LogFitbitActivity whenever the user chooses OK
* in the dialog.
*/
public interface OnDurationInputDoneListener {
void onDone(String hours, String minutes);
}
private OnDurationInputDoneListener durationListener;
} | 37.464286 | 120 | 0.679218 |
402a5dd3dc25dcd8ffdac5a070b9b8ea2360d26c | 4,668 | package net.npg.abattle.server.game.impl;
import java.util.Collection;
import java.util.List;
import net.npg.abattle.common.model.Board;
import net.npg.abattle.common.model.CellTypes;
import net.npg.abattle.common.model.Player;
import net.npg.abattle.common.utils.FieldLoop;
import net.npg.abattle.common.utils.SingleList;
import net.npg.abattle.common.utils.Validate;
import net.npg.abattle.communication.command.CommandQueueServer;
import net.npg.abattle.communication.command.CommandType;
import net.npg.abattle.communication.command.commands.InitBoardCommand;
import net.npg.abattle.communication.command.data.CellData;
import net.npg.abattle.communication.command.data.CellDataBuilder;
import net.npg.abattle.communication.command.data.InitBoardData;
import net.npg.abattle.server.game.GameEnvironment;
import net.npg.abattle.server.model.BoardInitializedNotifier;
import net.npg.abattle.server.model.ServerCell;
import net.npg.abattle.server.model.ServerGame;
import net.npg.abattle.server.model.ServerLinks;
import net.npg.abattle.server.model.ServerPlayer;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure2;
@SuppressWarnings("all")
public class InitGameSender implements BoardInitializedNotifier {
private GameEnvironment game;
private CommandQueueServer commandQueue;
public InitGameSender(final GameEnvironment game, final CommandQueueServer commandQueue) {
Validate.notNulls(game, commandQueue);
this.game = game;
this.commandQueue = commandQueue;
}
private void addCommandToQueue(final InitBoardData boardUpdate, final Player player) {
ServerGame _serverGame = this.game.getServerGame();
int _id = _serverGame.getId();
final InitBoardCommand command = new InitBoardCommand(boardUpdate, false, _id);
int _id_1 = player.getId();
List<Integer> _create = SingleList.<Integer>create(Integer.valueOf(_id_1));
this.commandQueue.addCommand(command, CommandType.TOCLIENT, _create);
}
private InitBoardData createBoardUpdate(final Board<ServerPlayer, ServerCell, ServerLinks> board, final ServerPlayer player) {
InitBoardData _xblockexpression = null;
{
final CellData[][] cellUpdates = this.fillCells(board);
_xblockexpression = new InitBoardData(cellUpdates);
}
return _xblockexpression;
}
private CellData[][] fillCells(final Board<ServerPlayer, ServerCell, ServerLinks> board) {
int _xSize = board.getXSize();
int _ySize = board.getYSize();
final CellData[][] cellUpdates = new CellData[_xSize][_ySize];
int _xSize_1 = board.getXSize();
int _ySize_1 = board.getYSize();
final Procedure2<Integer, Integer> _function = new Procedure2<Integer, Integer>() {
@Override
public void apply(final Integer x, final Integer y) {
final ServerCell originalCell = board.getCellAt((x).intValue(), (y).intValue());
CellData[] _get = cellUpdates[(x).intValue()];
CellData _buildCell = InitGameSender.this.buildCell(originalCell);
_get[(y).intValue()] = _buildCell;
}
};
FieldLoop.visitAllFields(_xSize_1, _ySize_1, _function);
return cellUpdates;
}
private CellData buildCell(final ServerCell originalCell) {
CellDataBuilder _cellDataBuilder = new CellDataBuilder();
int _id = originalCell.getId();
CellDataBuilder _id_1 = _cellDataBuilder.id(_id);
int _height = originalCell.getHeight();
CellDataBuilder _height_1 = _id_1.height(_height);
CellTypes _cellType = originalCell.getCellType();
int _ordinal = _cellType.ordinal();
CellDataBuilder _cellType_1 = _height_1.cellType(_ordinal);
return _cellType_1.build();
}
@Override
public void boardCreated(final Board<ServerPlayer, ServerCell, ServerLinks> board) {
ServerGame _serverGame = this.game.getServerGame();
Collection<ServerPlayer> _players = _serverGame.getPlayers();
final Function1<ServerPlayer, Boolean> _function = new Function1<ServerPlayer, Boolean>() {
@Override
public Boolean apply(final ServerPlayer it) {
boolean _isComputer = it.isComputer();
return Boolean.valueOf((!_isComputer));
}
};
Iterable<ServerPlayer> _filter = IterableExtensions.<ServerPlayer>filter(_players, _function);
for (final ServerPlayer player : _filter) {
{
final InitBoardData boardUpdate = this.createBoardUpdate(board, player);
this.addCommandToQueue(boardUpdate, player);
}
}
}
}
| 43.222222 | 129 | 0.734362 |
9cfc830c761300a134289087b72c7fb4a79ecba0 | 1,142 | package ru.job4j.controller.servlets;
import ru.job4j.model.entity.Item;
import ru.job4j.model.store.HibernateORM;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
/**
* Created by VLADIMIR on 15.02.2018.
*/
public class SaveOrUpdateItem extends HttpServlet {
/**
* Save or update item.
* @param req - req.
* @param resp - resp.
* @throws ServletException - exception.
* @throws IOException - exception.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final int id = Integer.parseInt(req.getParameter("item_id"));
final String desc = req.getParameter("item_description");
final Timestamp created = new Timestamp(System.currentTimeMillis());
final boolean done = Boolean.parseBoolean(req.getParameter("item_done"));
HibernateORM.getInstance().saveOrUpdate(new Item(id, desc, created, done));
}
}
| 31.722222 | 114 | 0.725044 |
4774fe258e95563ae5f82b48812c1f94ffb5d5ee | 1,745 | package com.github.seratch.jslack.api.methods.request.dnd;
import com.github.seratch.jslack.api.methods.SlackApiRequest;
public class DndSetSnoozeRequest implements SlackApiRequest {
/**
* Authentication token. Requires scope: `dnd:write`
*/
private String token;
/**
* Number of minutes, from now, to snooze until.
*/
private Integer numMinutes;
DndSetSnoozeRequest(String token, Integer numMinutes) {
this.token = token;
this.numMinutes = numMinutes;
}
public static DndSetSnoozeRequestBuilder builder() {
return new DndSetSnoozeRequestBuilder();
}
public String getToken() {
return this.token;
}
public Integer getNumMinutes() {
return this.numMinutes;
}
public void setToken(String token) {
this.token = token;
}
public void setNumMinutes(Integer numMinutes) {
this.numMinutes = numMinutes;
}
public static class DndSetSnoozeRequestBuilder {
private String token;
private Integer numMinutes;
DndSetSnoozeRequestBuilder() {
}
public DndSetSnoozeRequest.DndSetSnoozeRequestBuilder token(String token) {
this.token = token;
return this;
}
public DndSetSnoozeRequest.DndSetSnoozeRequestBuilder numMinutes(Integer numMinutes) {
this.numMinutes = numMinutes;
return this;
}
public DndSetSnoozeRequest build() {
return new DndSetSnoozeRequest(token, numMinutes);
}
public String toString() {
return "DndSetSnoozeRequest.DndSetSnoozeRequestBuilder(token=" + this.token + ", numMinutes=" + this.numMinutes + ")";
}
}
} | 26.044776 | 130 | 0.643553 |
09ad26c277c9cbc6b3d00cc708ec7f7c5681a8e1 | 7,213 | package com.blue.sky.mobile.manager.music.cache;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.blue.sky.common.db.DBHelper;
import com.blue.sky.common.utils.Strings;
import com.blue.sky.mobile.manager.music.module.network.entity.Song;
import com.blue.sky.mobile.manager.music.module.network.entity.SongExtend;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2010/10/11.
*/
public class MusicDBHelper {
private final static Object LOCK = new Object();
private final static String SKY_MUSIC = "sky_music";
private final static String SKY_MUSIC_FAVORITE = "sky_music_favorite";
public final static String[] SKY_MUSIC_FAVORITE_TAB_COLS = new String[]{
"id", "name", "thumbPath", "filePath", "sortOrder"
};
public static String createMusicTable() {
StringBuilder sb = new StringBuilder();
sb.append("CREATE TABLE IF NOT EXISTS sky_music(");
sb.append("id integer,");
sb.append("name nvarchar(128),");
sb.append("singerName nvarchar(64),");
sb.append("singerId nvarchar(16),");
sb.append("albumName nvarchar(64),");
sb.append("pickCount nvarchar(8),");
sb.append("duration nvarchar(8),");
sb.append("format nvarchar(8),");
sb.append("rate nvarchar(8),");
sb.append("size nvarchar(8),");
sb.append("type nvarchar(8),");
sb.append("url nvarchar(1024),");
sb.append("mv nvarchar(1024),");
sb.append("categoryId int default 0,");
sb.append("status integer default 1");
sb.append(")");
return sb.toString();
}
public static String createMusicFavoriteTable() {
StringBuilder sb = new StringBuilder();
sb.append("CREATE TABLE IF NOT EXISTS sky_music_favorite(");
sb.append("id integer primary key,");
sb.append("name nvarchar(64),");
sb.append("thumbPath nvarchar(256),");
sb.append("filePath nvarchar(256),");
sb.append("sortOrder integer default 1,");
sb.append("createDate datetime,");
sb.append("status integer default 1");
sb.append(")");
return sb.toString();
}
public static void addFavoriteMusic(Context context, ContentValues value) {
DBHelper.insert(context, SKY_MUSIC_FAVORITE, value);
}
public static void deleteFavorite(Context context, long id) {
DBHelper.delete(context, SKY_MUSIC_FAVORITE, "id=?", new String[]{id + ""});
}
public static List<Song> getFavoriteMusicList(Context context) {
List<Song> list = new ArrayList<Song>();
synchronized (LOCK) {
SQLiteDatabase db = DBHelper.getDB(context);
Cursor cursor = db.query(SKY_MUSIC_FAVORITE, SKY_MUSIC_FAVORITE_TAB_COLS, null, null, null, null, "createDate DESC");
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Song music = new Song();
music.setId(cursor.getInt(0)+"");
music.setName(cursor.getString(1));
music.setArtist(cursor.getString(2));
music.setSingleList(cursor.getString(3), "");
list.add(music);
cursor.moveToNext();
}
cursor.close();
}
return list;
}
public static void addMusic(Context context, List<Song> listSong, String categoryId){
for(Song s : listSong){
s.setCategoryId(Integer.valueOf(categoryId));
addMusic(context, s);
}
}
public static void addMusic(Context context, Song song){
ContentValues value = new ContentValues();
value.put("id", song.getId());
value.put("name", song.getName());
value.put("singerName", song.getSingerName());
value.put("singerId", song.getSingerId());
value.put("albumName", song.getAlbumName());
value.put("pickCount", song.getPickCount());
value.put("duration", song.getPlayInfo().getDuration());
value.put("format", song.getPlayInfo().getFormat());
value.put("rate", song.getPlayInfo().getRate());
value.put("size", song.getPlayInfo().getSize());
value.put("type", song.getPlayInfo().getType());
value.put("url", song.getPlayInfo().getUrl());
value.put("mv", song.getMv() == null ? "" : song.getMv().getUrl());
value.put("categoryId", song.getCategoryId());
DBHelper.safeInsert(context, SKY_MUSIC, value, "id=? AND categoryId=?", new String[]{song.getId(),song.getCategoryId()+""});
}
public static List<Song> getMusicList(Context context,int categoryId, int pageIndex, int pageSize) {
List<Song> list = new ArrayList<Song>();
synchronized (LOCK) {
SQLiteDatabase db = DBHelper.getDB(context);
Cursor cursor = db.query(SKY_MUSIC, null, "categoryId=? limit ?", new String[]{categoryId+"", pageSize+""}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Song song = new Song();
song.setId(cursor.getString(cursor.getColumnIndex("id")));
song.setName(cursor.getString(cursor.getColumnIndex("name")));
song.setSingerName(cursor.getString(cursor.getColumnIndex("singerName")));
song.setSingerId(cursor.getString(cursor.getColumnIndex("singerId")));
song.setAlbumName(cursor.getString(cursor.getColumnIndex("albumName")));
song.setPickCount(cursor.getString(cursor.getColumnIndex("pickCount")));
song.setCategoryId(cursor.getInt(cursor.getColumnIndex("categoryId")));
song.setUrlList(getSongExtendInfo(cursor, null));
String mvUrl = cursor.getString(cursor.getColumnIndex("mv"));
if(Strings.isNotEmpty(mvUrl)){
song.setMv(getSongExtendInfo(cursor,mvUrl));
}
list.add(song);
cursor.moveToNext();
}
cursor.close();
}
return list;
}
private static SongExtend getSongExtendInfo(Cursor cursor, String mvUrl){
SongExtend songExtend = new SongExtend();
songExtend.setUrl(cursor.getString(cursor.getColumnIndex("url")));
songExtend.setDuration(cursor.getString(cursor.getColumnIndex("duration")));
songExtend.setFormat(cursor.getString(cursor.getColumnIndex("format")));
songExtend.setRate(cursor.getString(cursor.getColumnIndex("rate")));
songExtend.setSize(cursor.getString(cursor.getColumnIndex("size")));
songExtend.setType(cursor.getString(cursor.getColumnIndex("type")));
if(Strings.isNotEmpty(mvUrl)){
songExtend.setUrl(mvUrl);
}else{
songExtend.setUrl(cursor.getString(cursor.getColumnIndex("url")));
}
return songExtend;
}
}
| 41.217143 | 139 | 0.608485 |
735e18318ec38c875d82e02f6d0b178273dcbafc | 1,716 | package com.h5190066.sumeyye_cakir_final.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import com.h5190066.sumeyye_cakir_final.R;
import com.h5190066.sumeyye_cakir_final.model.MakyajModel;
import com.h5190066.sumeyye_cakir_final.util.Constants;
import com.h5190066.sumeyye_cakir_final.util.GlideUtil;
import com.h5190066.sumeyye_cakir_final.util.ObjectUtil;
public class MakyajDetayActivity extends AppCompatActivity {
ImageView imgKapakAlani;
TextView txtBaslik,txtKullanimAlani,txtRenkSecenegi,txtAciklama;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_makyaj_detay);
init();
}
private void init(){
String tasinanMakyajString=getIntent().getStringExtra(Constants.TIKLANAN_MAKYAJ_TASINANIN_BASLIGI);
MakyajModel makyajModel= ObjectUtil.jsonStringToMakyaj(tasinanMakyajString);
imgKapakAlani=findViewById(R.id.imgKapakAlani);
txtBaslik=findViewById(R.id.txtBaslik);
txtAciklama=findViewById(R.id.txtAciklama);
txtKullanimAlani=findViewById(R.id.txtKullanimAlani);
txtRenkSecenegi=findViewById(R.id.txtRenkSecenegi);
txtBaslik.setText((makyajModel.getAdi()));
txtKullanimAlani.setText(makyajModel.getKullanimAlani());
txtAciklama.setText((makyajModel.getAciklama()));
txtRenkSecenegi.setText((makyajModel.getRenkSecenekleri()));
GlideUtil.resmiIndiripGoster(getApplicationContext(),makyajModel.getBannerUrl(),imgKapakAlani);
}
} | 31.2 | 107 | 0.77331 |
8e55fe71783e21b570bf5f2b29d289f1b8538b54 | 20,098 | class YgMn3 {
public static void t1VXbmeFK71om (String[] ad30rcQcCWhhd_) throws yMwHV {
{
void[] x3f2ME75;
{
;
}
return;
iwtAmsO6 qsMn_CSq87O8g2;
;
void cS1JO4qaw3cL;
boolean FvdolxbzIN;
void erp4C6;
;
boolean[][] a068;
void sQyXBS3;
void wB5X46EKg;
{
;
}
;
return;
{
return;
}
if ( IH9uszio.d3bxw_hc9) false[ !j().eAotA2cGYup()];
boolean MqDpZ8l;
while ( k.R9u4x5x()) return;
e69()[ true.BUgqbcxXv];
}
void yAVf4FNZ = !false._17q = !--null.Kwl();
qIeRYcl[] MFDRuMXvC4p3;
;
B_C[][] W4QC;
uR990evT1dv5[] JtgCFq = !RIdrajbfnU8Nn5().lH = !false.zRblRwF();
{
return;
;
void x;
return;
{
void V3Wk;
}
void DdTl1jy;
while ( Y0UZ.vgWbKeZgOLXn7()) ;
}
boolean[][] QBibVhyDFCCog;
int ZDexh;
-new VjB50Ign().m4cfZl8ZDkweRZ();
void[] HNa3 = Qc59vlw3RPq().S17KeELt0HZ_q() = !this._PXh();
false.XaSgY();
void evdwNr3MzYs;
int[][] Wmc7HAhgs = null.sDix() = !false.zQT18C;
while ( false[ new GpqYSLRAZd[ !new DdwmHQbMwrh().yDRzG9EF5mQKP3].p()]) if ( -null.aKqIGzZE()) ;
if ( rvIOeRwgtr.o()) while ( new zMuJAgqElNl().wkcsIlVlRBKa()) {
UovODmE1x[][] BT94Ja1E;
}else while ( -null[ ( --false[ !!new int[ true[ ----this[ this.aSA_E6kqL9p]]].PHZ3tr()])[ new e4rnVDFG1Wp().rsGiNfVTHbgqlm]]) !( this[ new L().UMOmohi]).d4Pax_Q;
!null.UFIvFeV;
( l[ ---!new D_Xzg6rDZ4E().RQF4RoPF]).R7F9s1O;
-!!!!!!saN808DT3Z()[ YpM2Jk().z2jgHVC4Lay];
}
public boolean VHutm9fMZ (yS0PPheIFl8[][][] MMCTYi, int FKMkkQ) {
;
boolean zi = -6646155.rnRSzU();
--!-( null[ false.J2KrJu_P()]).f8ScIk5U;
while ( new boolean[ ( !!this.DrNNhV8j)[ -yjJkGPh.l47JJpgJvT]].XML) {
if ( -new Tgi()[ !( false[ ( true.FKV()).zlqb6Erlyi5N])[ this[ JE()[ ( -( false.brjA())[ 70595496[ !q2hkEovlwfUGlE().pE()]]).KjyX25qQr()]]]]) -new zTDm_sX5jy().gzG85();
}
boolean Z6qtxrnHOcaAz = k().Ei5o2Iak_rrbRB = !-( f8eRCxXz6Ufs()[ new boolean[ !new R6W2sr().Cei8ps2bZwNO7X()].VCT()]).T8u0E_BD();
void HttUPz6 = !!new int[ ( null.Tpsc).VdQalP0]._yE;
tOO9GbgmeG3aH[][] zh_ESFqlpa = -this.cioFzRA6bd();
while ( -!this.eMC) return;
{
int[][] gbcU0CS;
if ( -!!!!new ZLrhn()[ ---!-869[ ( !-false.Ht9yJ).R]]) {
while ( new boolean[ !!03251[ false.Jzq()]].N1Sy) ;
}
while ( YdMgybq().eq2()) if ( 74658.Qlql) return;
}
boolean _ = !-!-new int[ LjEJ6wB7do.XHzooonLXaIW2][ !gnUOihc2Ho._z9fZzY0hd4()];
if ( new YCdLdkeTgKtHEv[ false.wDjgekJo].uSH9a5Lu1) --lPZNf[ false[ !false.R1MFHO9iAsfULD]];
return true[ false.b62cxSi3Hb()];
}
public int fydACpXdSh;
public static void RF_EHG9KZT (String[] W) {
void n3zA79fxFqi9LV = true.Fc() = !!-true.ktHpJeyp5WGZ();
if ( pS()[ ---!!!!-true.TxoryUGRen]) null.eVXSTvXpBaK;else while ( -JaKPd7YhQOJ().LLPG_zZpU9ksfx) return;
PQjU lokj1QrfRDKb;
!true.CAaLgv5xbjn2;
{
-null.o843ssQe();
while ( true.uEN_Vb) while ( tRuS.RWkmvppDez) if ( --false.sUcssR()) ;
int AYcZe;
boolean[][][] knPUJyxnEu9YbR;
-!false.zU8JlzfO5DRy();
{
;
}
boolean t;
if ( !yopVOFgwJ7vJNC.HAEvfel_()) while ( new ujCcBH().yrR()) ( 282449958.VgTj6jb8UHB())[ -!--!true[ --!-new void[ false.lUyAtKOOruAjx].ecrrgwUOB]];
LYfPr[][][][] zkQ9sh;
void Z3PEALMsAmmy;
void pvp;
ZTUNg8ng71LY0w[][][][] cW;
boolean sWXZslamOmUu7j;
}
{
!!!!new c4RYj4fpFHI5J()[ this.BYnVf3()];
return;
IrqR4cnrd()[ -370242270[ T9LviBGH()[ HH().aYleh()]]];
zE8Q[][][][] c5;
;
while ( !7459986.f_JO()) {
if ( -true.J()) new HSzS()[ false.zYL6f()];
}
if ( !true.CjaUtECMotJwo) ;
boolean[][] IrmHVL2;
!!!!-null.yRBki6pq();
return;
int[][][] caWSDiOxH0;
void yv2KRa9;
return;
boolean[] Rqt0U;
boolean[][] tWXAs1msFR9;
int F_hH_5t;
pLTMJNJN Aaci23m3c97;
boolean xx46zP;
}
{
while ( new dxa().D2V_iCAQkYx) ;
void l01tvDWbMYs;
true.AzWV76XQm;
int[][][][][] YACfebUF8cUZkF;
;
while ( -new z[ -true.rz1cTQkO()].BhNa7()) {
{
boolean J;
}
}
void vOxteuna1UE;
if ( !new HyWlYbdtukDRKQ()[ -69.zwDgBTlizwT]) this[ N8KyR71CI()[ -!B_LSgGJt3l.kYhE0py()]];
while ( true[ -false[ this[ -!Fiwx._4]]]) {
void[] OKpK429;
}
{
!!new void[ new c0n().qwrfsE3r6iadA][ -null.ZysIsAxMz()];
}
WpBefqxFk0X5i[][][] HwVe82;
MtTXecYaNkQrUT bQD;
if ( new boolean[ -!-Le1lLQkrHH48i.x4ZAPk4()].WoKlpoSjKG()) return;
boolean dwLBPMjq6ac;
boolean[][][] KV1BoUp7LoQ;
}
return --cLzROKGzk65Z[ --( -!R6y5kAweSYPug0[ !PTKs7b().bGQXZdASZVP])[ true[ --false[ true.zKZeHz3np]]]];
int JiXwed1uZwoD = !false[ -PeD[ 3064.quh3CULX]] = -null[ this.lL6C558DNSc];
}
public boolean dpsqFcb8aHmDgv (void UFf20z5xOP, Xy[] wd, void fwC3, boolean[] zl5QNhJO, void BWK) {
void[] UHhK;
int IKHlu;
false.rCR5tyh();
h6tui3[][] RcyVcFN7f0Pb8m = new int[ --new SfMELGOw1Jii().U2XE3jq7()].BDiydG_atnFF;
int[][] Cnpig = new RuEWyOj_()[ 48521774.WACvvh09nA] = new int[ null[ !false.JJV]].p8_hFMMwUcKLE();
LBWMIFuq[] _hgiCbqYk;
while ( --false.JBCQk_mA5bH()) !new chql8()[ FKyoi_WgZAy().VE84doAwVqlh];
}
public V[] jxIHl () throws no2tCux4xD20 {
boolean[][][][][] A_E;
;
boolean hrzbvkHfu = !!!69743659.S = 01894[ !!-true.fE4GxKJ()];
while ( true[ !!( Y9ncuqMMd2H0.m6Fs2pMiC)[ !new rKSlmfM6().e6n8()]]) !!!5077[ !-new boolean[ ( !-false[ -59[ 94975875[ -!--true.Z_pBgk()]]])[ -true.X770QitgB76()]].e0BFHTrns_a];
boolean[][][][][] sMHEOOpVOJfpv = -!!new SPiwK2vAk[ !!-( true.AFxX).qj1ujK0][ -( !--!1852.Nl9).cIC51wY] = true[ ( -!null.tAG6hV33TuIB())[ !----( new NJZ8n8Qv4d9oWw()[ !false[ new void[ null[ new void[ -( !!( 636715177.PfnnPa8S())[ -!false.XplWtWcAGb2_Ih()]).xt0xqKyX][ XZn6HIjLrw996a.xtIKJ]]].n8CyspvlT]])[ !----!true.j]]];
{
BKHZdR1JD[] YBr;
false[ new p[ true.w()][ -HUR.cU5HeXx]];
;
;
boolean[] yE;
RSMVwer6eGfK[] E;
{
void alo8n;
}
boolean[] K5v2k7;
if ( this.Mbh7KQlDJI0K9) ;
;
int[][] bjctfuZZn5atZp;
return;
ULqqU AtyfS5cjtlzdZB;
while ( !cCZxNB.G4()) while ( false.QV()) ;
}
boolean dZFFE = ( -( !!null.yf3AbT()).PuS())[ this[ new void[ -!-( false.b()).GkUuGEKm93][ new mcT_MQ6XTSsoj().Az4]]];
DAmEW[] C = !!!new gBz()[ !plZwB8WRL7RGW.XbAn_JVa()] = -false.X_;
boolean uXrjsTH;
boolean[] MBB7tn8F7p = new Lv0sAjaguB[ ( !true.jthCq9Z8ShIuh()).Cwga6tg][ this.fV4qLbelZsxUtw];
boolean[][] d3yqWs;
if ( !null.gsTj) return;
;
return;
void[] l99Cuf3Ydm;
boolean[] GB4FIig9;
;
if ( !-this.b()) while ( --true.WFgd4s) {
boolean Scy;
}else ;
!this.weqxG;
}
public void[] nU;
public void x9 (int[][][] zxJCU, int hTRseJ) {
void lWKV96 = cMbCd.TxGsVsLyvhjjll() = -JO1BrES4bcA9f().PjVw6;
new Grw9H_5C3loZl[ -new void[ -!-!this.qHIYSojn79Y].i2wxyWkZ0OA8q][ --!new boolean[ -!3407.D3jiPx6NtdUJop()][ _7AKYMCHEod().f3lm5o]];
{
int[] s;
{
rhQUcw[] LKIisRcRi1ST;
}
XudG4b[] X;
void[] piepx;
boolean KJ0lfh93JXS;
int[] Cqcvt5YN2;
boolean[][] aKZmtB_;
}
while ( -!---!4388325.y()) while ( this[ -null.AoQFN()]) while ( new boolean[ new boolean[ --( y2tZtgQ.VWkqKG1qb).BRJPxXwEJSFMVh()][ -new boolean[ false[ !9.cWGC4X()]][ false[ !!( new c49QAYrX4V9()[ null.T1xo2TXY]).HbMHpQ()]]]].WQYc()) if ( -new xVKQQ2yxdt[ !!true.b7OTCF2Qx][ -Aityc2GWwjVn.XgF5eZEYLfE9rW()]) return;
if ( -skjHedBBpklU().ePQlEDmbDzH) while ( 25.Nqd8Iov2OBP1US()) ;
UEHvDDk S3LN3z3tnuMkc = !!new boolean[ --new boolean[ ( false.oV).sqJ4YvOQrKT].CtCwx1][ 046120.RdKC_sjXXrm3Od];
new int[ -!--!( ( -false[ !this._]).IzmTcmRG())[ !-( new zP6Q1EZB709().W_()).YEvx]][ -!true[ ---!69819816.vupJU]];
!--!-!-!---i1o().wwRZ();
void OHHgMb;
UOFGdfB gxvh9axCVX = !!!3779116[ RfEY().LOsTjo0] = -false.wwBlVtb18GpE;
boolean rQ = LL_GDzH.dGb4Su6B7Rb6;
return;
( this[ !!a6u3F70vht9().mOrT8kv9t1a]).LXk;
while ( !SZm[ !null[ -null.Ap4cxG]]) ;
boolean[][] dMjrRwE;
RmvTJCZz4hhT79 ZhNo = new dEtgkHTUUj[ true.QL4Y].s07() = false.KLbuiuQOt6();
efyZIl[] R;
}
public static void CPnFMtnDcloa (String[] Mbuq) {
while ( ( !iGh0.RHAk_Jq()).aYXaQe()) ;
return;
return;
{
return;
if ( -false.ka1U) if ( !6.qYI04_3mD) if ( true[ ( false.LAe69pPosz)[ null[ true[ -dDwgj.q6DsNwmL4()]]]]) {
void[][][] OHZIIx;
}
}
{
;
if ( -( -!-false.c97X5m).sglkU40t()) while ( _Y2Mp6gG5ma().J) if ( -33524._qqSfU4) {
void[] P7tNMqlX0h0H;
}
if ( 773.YeojadHvkeT6W()) if ( this.ETCOTrI) return;
return;
}
return H9czFf8zYj.x_;
return;
while ( Vce2.HWUBzDxka70) null.c_29m0eCoa55pP;
while ( !( this.SIpOFukTomSyZO())[ ---true.tfzv()]) {
int[][] dQ51j6Ya1vWi;
}
boolean[][][] s3ALRPF9IXVHu;
;
boolean[] RpJxODDp = -false.R = !-917521307.E();
_ LTfG21B_b7Kag;
;
}
public boolean J6pbO3Fuf1DiWE () {
return new jX3pQj3o[ !-( --qErID_bqt().Mny)[ !!!( RniGzmsNdHLMF().Gb2DMWa()).J6n1LbV9pGg()]].fUuaSR3();
;
int cg9 = !!null.E() = new YMlNY().uRwI8sQpWjF();
if ( !this.zyklnlBa) return;else if ( ( !-null.REQRK_y4w1YyQv).rx9FyFPN()) return;
;
YrViwslS[][] ewHGRAa = --!--new QWCW()[ ------_k21w()[ new S0TOP266Gxw().cuF()]];
A V8Upf7STLUqGvf = -true.IqdCv5nwXLTeJ5() = !this.gVMaXbxXT();
while ( !null[ true.LdXFOVOn()]) 682.I;
while ( -new boolean[ -!( false[ !---this[ Yj9fuclxP.p5nmeN4uyFtfI()]]).Ura][ false[ cvwZWGfaPP5kBY.T()]]) if ( this[ true.FY7n()]) return;
int KbB_U = !--1985427.QnwXpc3L5WrSI = true.b4;
boolean[] BUa;
int mWFw_QSRHbep = -false.FqU0_RA8wy78S();
;
boolean[] MajZsB;
if ( this.CV1fFGb3ncV()) {
;
}
void[][] G;
void mejQX_;
( false[ -exWTqEU_3x9YtP.P()]).DlUYiYos7_CM();
!44.miQ2I_O;
}
public boolean Z (int oYzCQPG_, boolean vEVzEJyP, boolean[][][][][][][] hx0, int TCes) throws fGo88rswlGDY {
void[] Glaon0 = eeO0Ck03WKF()[ false.QnM1TbdzSJ] = -this[ --l3()[ OubkEgEWBY8uZ().J]];
while ( this.Fub) if ( -287387.kCGc1JWHkH0()) while ( -!oxpkQYEaXO2.gLF) {
while ( !this._u()) ;
}
int[][][][][][][][] qa15uI;
boolean[] OalvOsvBg = -!( !new boolean[ -new MWJY4LS4CuuJMf[ null.iy0jAAq3lK2B].FHRCLu()].TgWl4tygj()).ejN45WO;
int[][][] N;
int[][][][][] PH487vVTNCj3v = ( ( !!new Zs6zwg_N67FP().a).ouQNHc)[ true[ new boolean[ --!-true.Vhl][ --this[ null[ false.x2ybplmIRE7UsF]]]]] = -!0018249[ 06[ 1361597.GKx7Xw()]];
int WZfAvs;
void[][] Le9Y = false.XK_tAb8() = ---null.WD8UOmnex;
return !!( true.sTWwvW7c()).G1fS5fqk7Ei5P;
if ( new raL8P_03d[ !!new hEUXQ9laC_2L().TQj2AurATd][ new void[ -!!null.hFAfLh].HD8ImjrWZL()]) {
void kxSDtgfgnvO;
}else if ( SIH.pCcG7Ei) while ( !null[ 46113.X()]) {
return;
}
{
if ( false[ ( yb().v9zwy3lp)[ !S().mzn]]) while ( -true.FLX18dC1z) ;
void[] HCjQiLjZNOk;
int M_YDgk2OwrMww;
while ( SMB().mZEEB0MMb0dh()) if ( -!--Bk8Q9iq5mE[ new void[ -!false.OIz5SF7][ this[ !new uSgPJJ().DdLoM_PIch()]]]) return;
}
int _fEQKB = !new void[ !!null[ -false[ false.fMADfScr71ihr()]]].cMCMgljNC5() = --this.Jy;
if ( !--865.jNEmb8iC7()) while ( new Ez8()[ new SqM().P19WlifOPTH]) while ( --!A().t82wgi) {
;
}else while ( -new QSwJ1pAN().C49Ryf) !new Du().JYS30QXFruqb4;
;
int[] Gn;
int OgOPUo5nqT5f;
return -!!--false.vF43vexZVQt();
return true[ I.IBgl];
-null.dtMXkAkV;
SApsHnR2K[][][][][] VQIG = -false[ -new int[ new wK_lC()[ new boolean[ new FQNU1GXgi2()[ --this.MGvFy_Yyz7gJ()]].XTnEeDNefl()]][ -new void[ new m9NK2meZ().GUTt()][ !new int[ !-new a66uPIu5W().MT3ZqUccG_W()][ true.ogOlOTWCOu()]]]];
}
public static void JkpKAJuHvLTNn (String[] EoUOXeHN) {
sSuH3s q8pa9JgTtNwa = -QwB3().C1qahndsF;
while ( null.My2bp1) while ( -!-!!ZVAU_hT()[ -!B6TK9nVS().UZUNWpI]) if ( V3()[ Sdq.uXJpKK6CMj]) ( --!( -!-!baqY7SLv_UZ6().VijhgiDricd())[ null.V()]).RRK();
while ( 81717.n) while ( null.SQx8v8aOGw) return;
eUSLw P26Ybm2Ux9HU2w = null.cwPhPWT_JCpYOk();
return;
int[][] qopN;
;
!new boolean[ -new boolean[ --!15746[ -9337617[ -new Q().ts4OblitQK4Ve()]]][ rHLkX8o21RChQ.uXde()]].nL3w;
int igXRA7d9mY_R = -!-new HvHo_WkY[ !this[ ( -!( !!-Pn9Pqfym().pM6dMT4S()).P)[ new int[ _0P956PJo.NkzVLX].YOQZ0GpiaaGy()]]].H2sfWfAP();
boolean DK7bpl1xC86 = !!--!!-new f34f2G().Ge_J3X9W() = -( !Cduc7Qp()[ ( ( -new NWZRW[ !this[ !new VR6rK87FKTF[ new Az9qos00()[ QMqaLBvga6i[ true.S2Nbo9qY()]]].xk9CS()]].ZKgPLn)[ true.WuH4t1qDDAX()]).Pa0uj9TW_jK2hA()]).Z();
}
public static void e0eor6cp (String[] z) {
{
if ( ( -AoN7f9HzlK5D.qhSs).Tsh5wq) ;
while ( this[ new it9OphmHVtdkcG().Ku_B()]) while ( this[ !true.dQH80gsB]) if ( Q()[ false.H8mR()]) while ( -!GmkV1_T_ue().qhL7caP) {
;
}
QNTi6[][] LMV;
return;
return;
boolean[][][] xYxR;
boolean[][] AAQDi;
int KQUQsjuTtAl4;
null.w70DdGvjS();
while ( this[ !new odQY3baj5sN7L().DmL()]) true.r;
true.Up3cP8OI();
if ( -BjD_jrNeWBnNh()[ !RRUoLj()[ !true.iEOA7o9qOmPF0]]) !!Mz()[ ( this[ !this[ this.AGZMRspXk]])[ !( 89687809[ -( -R()[ -!DoMuhGgosJY()[ --true.hid()]]).aHj])[ !true.mQT1B]]];
void WfxsH0coko;
}
int[] XVb_DvC;
JJ QAyhIMowMV08 = 52721.p9NK5m6Bm0U7n = new int[ ---!-new u().DJXkif()][ false.PhoU_xTpdYg()];
{
ckX[] ihzf;
while ( Mc09TVUmecL().iOWe5Toi28HEQ7) 60095991.tUt2VYm;
;
boolean UvaO40RO;
{
{
{
void[][] z;
}
}
}
;
void[][][][] gl;
boolean VOZJ;
J7BvVOJxw6[][][] X22b90yajqDGe;
int AluP_RFC4r;
while ( --_aqb5Z2sqygxc().JvWlN8wy9()) if ( !( new void[ UOoRFmmtU9kC5k()[ null.oOgBzfaSU3oCYF]][ wGd4lB34.sbVQlA()])[ false[ -new iG().xVn41__zip()]]) ;
}
( -!!this.bGrr9Tvx7).eUbG1OkfSoc9;
int[] dMimTRXZ = new int[ 685103.kEBXIb()][ PT.zFIAuKk] = false.YnQz7Q4uz8();
( null[ !!-!-402.iO()]).kHr4A;
{
gL PDhUjyosuSM;
int[] XDJEB;
!c.dYGqrINYqMeS;
K5 kqFJc;
while ( -new void[ ---2[ -rvO6jS.Cz9R21Uq]][ !this.aCnUHSZT2_TtL]) return;
{
int nH6qus;
}
--T().SzY3Zv;
;
}
if ( --!C8TCG7().imWVWcnF0m) ;
if ( ( 19146.lYkv8otupAkonh()).UTiq30v92nVYy) if ( 391[ !-!false.VzlsgVDl()]) return;
int[] QMTFKYR_;
boolean LKjI39wAJ;
{
boolean q8Qs6l78QX1ig;
void[][] GK9WfXIEz5;
void H39txc;
while ( -true.E5vV) if ( this.Ec2T40sBoWOXvN) ;
return;
return;
if ( new fNXyIFb().WHm()) !!!-!-this[ OR[ this.yR3xYzhJL8b3mV()]];
while ( -!!LuVcdsgRvdSs1().uJqK()) !false[ !-( !-!!!-!new y().wuFkdsc6xL()).EdZDx5XAjCN];
return;
k5eK_HrU5BdIs[] Voywry;
return;
;
if ( -Ajd6ZJHvn0.rPOksnITnZs()) ;
boolean jlEibKC;
}
if ( ( --!335906.br2ecy()).Gu) return;
while ( 20547146.z) return;
if ( -this.wAfqQUL4Rje9p9()) if ( Wq9od503JPU()[ !tHJmHnWtLumN().rMwBuFVdvj8zjo]) if ( !GnG().ZK) return;else return;
OAr3f0BVQJ Gt9vMe1kR = xtSGbn().sl();
if ( CB3Ar3z().y()) if ( false[ !this.jiFOdEa]) ;
}
public ajdhYTC kJRL3yDCq () throws pppx {
boolean[] fK = 3121.E = !( -this.R)[ ---new D2gow6G1k()[ !RUIasCri1.A_tVW4B]];
int[] JClKrHQz = !-( false.LjMypPCtx5Qr())[ new eTboriTJREY().XO7vzGQlIqmYqh()];
;
void[][] f9Lvf2v5gO63e;
int[] G2YdTMvV;
}
public static void u4UL1F82a4ZKI (String[] W3l1) throws VBpS3KIS_PCWu {
return;
{
void[] JV;
boolean ejCz8;
{
void GhE73XyLC;
}
{
void V9Ldtr;
}
{
int[][] JJUCG;
}
l2h16s weekkB2oPCu;
int[] pE6_Xu;
return;
cA iXRQmQmweNKOJm;
int[][][] F2RLb7P8veU;
r6V[][] MT;
;
int v0vAbA0i9P;
while ( -!false[ -------!sLb()[ 4694.WGBS_0K()]]) {
while ( !!!new MV30qP7().FDQcGCm) ;
}
boolean V6bhg;
{
;
}
boolean[] WZaqe1;
;
if ( --!-!!!!null.UOc2CYMw()) {
{
boolean[] pFA_ly9VL;
}
}
}
jJnsx[][][] gJ_D0Glw;
int[][][] EpZWW_fwmzQcTQ;
boolean[] QdCc3BE;
if ( 160._rSn) {
boolean[][] UH0JxAITIoJX;
}else true.obBKnzviAUu;
while ( qW.qK8Fk0NI) return;
return null.keDgyw62QdiG();
boolean[][] LofL5NWSom = -this[ !( ( !-!HKGileS0d4C[ !!954539[ -this[ 2427909.YRj()]]]).qdS_eZ_)[ -true.oWP_erL6hWu]];
{
boolean zmN2I;
return;
int[] gox1qAiGR0v;
return;
int[][] sB;
boolean fFZW_xDd5m2Vb;
boolean BXU8n;
;
c9xhPp mbD;
GrpbfXPHNaGWQB[][][] Ux;
while ( -s56gqhA[ Np1J[ -true[ !null.LzAT2WfSH]]]) {
void[] wmKb;
}
void UCJ0oZrJ_;
-new boolean[ true[ -8.TsW]][ this[ -null.gbLy8()]];
}
ya AEUx;
return -JnflHYhp1c0()[ !null.Ljbj2Bproiat()];
{
;
int lwdSL293zZRpTL;
}
}
}
class HZv {
}
| 40.35743 | 333 | 0.488705 |
d0d9f8103ca993d811bba51a8578b0a88ac28e9f | 2,489 | /*
* Copyright 2017-2018 Frederic Thevenet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.binjr.core.preferences;
import javafx.util.Duration;
import java.util.Arrays;
/**
* Choices for the notification popup duration preference
*
* @author Frederic Thevenet
*/
public enum NotificationDurationChoices {
FIVE_SECONDS("5 seconds", Duration.seconds(5)),
TEN_SECONDS("10 seconds", Duration.seconds(10)),
THIRTY_SECONDS("30 seconds", Duration.seconds(30)),
NEVER("Never", Duration.INDEFINITE);
private final String name;
private final Duration duration;
NotificationDurationChoices(String name, Duration duration) {
this.name = name;
this.duration = duration;
}
/**
* Returns the name for the enum entry.
*
* @return the name for the enum entry.
*/
public String getName() {
return name;
}
/**
* Returns the {@link Duration} value for the enum entry.
*
* @return the {@link Duration} value for the enum entry.
*/
public Duration getDuration() {
return duration;
}
@Override
public String toString() {
return name;
}
/**
* Returns the {@link NotificationDurationChoices} value corresponding to the provided duration or {@code NotificationDurationChoices.NEVER} if there isn't one.
*
* @param duration the {@link Duration} corresponding to a {@link NotificationDurationChoices} entry.
* @return the {@link NotificationDurationChoices} value corresponding to the provided duration or {@code NotificationDurationChoices.NEVER} if there isn't one.
*/
public static NotificationDurationChoices valueOf(Duration duration) {
return Arrays.stream(values())
.filter(notificationDurationChoices -> notificationDurationChoices.getDuration().equals(duration))
.findFirst()
.orElse(NEVER);
}
}
| 31.910256 | 164 | 0.676979 |
8cad03ae4a2916760a266feb1de98727fdcc9607 | 1,790 | public boolean performFinish() {
try {
IJavaProject javaProject = JavaCore.create(getProject());
final IProjectDescription projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectPage.getProjectName());
projectDescription.setLocation(null);
getProject().create(projectDescription, null);
List<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>();
projectDescription.setNatureIds(getNatures());
List<String> builderIDs = new ArrayList<String>();
addBuilders(builderIDs);
ICommand[] buildCMDS = new ICommand[builderIDs.size()];
int i = 0;
for (String builderID : builderIDs) {
ICommand build = projectDescription.newCommand();
build.setBuilderName(builderID);
buildCMDS[i++] = build;
}
projectDescription.setBuildSpec(buildCMDS);
getProject().open(null);
getProject().setDescription(projectDescription, null);
addClasspaths(classpathEntries, getProject());
javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), null);
javaProject.setOutputLocation(new Path("/" + projectPage.getProjectName() + "/bin"), null);
createFiles();
return true;
} catch (Exception exception) {
StatusManager.getManager().handle(new Status(IStatus.ERROR, getPluginID(), "Problem creating " + getProjectTypeName() + " project. Ignoring.", exception));
try {
getProject().delete(true, null);
} catch (Exception e) {
}
return false;
}
}
| 51.142857 | 167 | 0.612849 |
00f80b5ad46bda36f1692fa2e8ec6fd37cf12a2f | 320 | package com.example.deneme123;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Deneme123Application {
public static void main(String[] args) {
SpringApplication.run(Deneme123Application.class, args);
}
}
| 22.857143 | 68 | 0.825 |
60e0eaa4d1de50c968158f78ebeae4625077c784 | 3,751 | /**
* Copyright (C) 2011 Pierre-Yves Ricau (py.ricau at gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed To in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package info.piwai.toohardforyou.core.paddle;
import info.piwai.toohardforyou.core.Constants;
import info.piwai.toohardforyou.core.NewGameListener;
import info.piwai.toohardforyou.core.TooHardForYouEngine;
import info.piwai.toohardforyou.core.entity.DynamicPhysicsEntity;
import info.piwai.toohardforyou.core.entity.PhysicsEntity;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import org.jbox2d.dynamics.contacts.Contact;
public abstract class TouchPaddleEntity extends DynamicPhysicsEntity implements PhysicsEntity.HasContactListener, PhysicsEntity.HasPresolveListener, NewGameListener {
private static final float RADIUS = 10 * Constants.PHYS_UNIT_PER_SCREEN_UNIT;
private static final float MAX_POS_Y = Constants.BOARD_BOTTOM + RADIUS;
private static final float DIAMETER = 2 * RADIUS;
private final TooHardForYouEngine engine;
public TouchPaddleEntity(TooHardForYouEngine engine, String image, float x, float y) {
super(engine.getEntityEngine(), image, x, y - RADIUS, 0);
this.engine = engine;
engine.addNewGameListener(this);
}
@Override
protected Body initPhysicsBody(World world, Body groundBody, float x, float y, float angle) {
FixtureDef fixtureDef = new FixtureDef();
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position = new Vec2(0, 0);
Body body = world.createBody(bodyDef);
CircleShape circleShape = new CircleShape();
circleShape.m_radius = getRadius();
fixtureDef.shape = circleShape;
fixtureDef.density = 0.1f;
fixtureDef.friction = 0f;
fixtureDef.restitution = 1.00f;
circleShape.m_p.set(0, 0);
body.createFixture(fixtureDef);
body.setLinearDamping(0f);
body.setTransform(new Vec2(x, y), angle);
return body;
}
@Override
public void update(float delta) {
super.update(delta);
if (getPosY() > MAX_POS_Y) {
destroy();
outOfGame();
}
}
public void destroy() {
engine.removeNewGameListener(this);
engine.getEntityEngine().remove(this);
}
protected abstract void outOfGame();
@Override
public void contact(PhysicsEntity other) {
if (other instanceof Paddle) {
destroy();
touchedPaddle();
}
}
protected abstract void touchedPaddle();
@Override
public float getWidth() {
return DIAMETER;
}
@Override
public float getHeight() {
return DIAMETER;
}
private float getRadius() {
return RADIUS;
}
@Override
public boolean onNewGame() {
destroy();
return true;
}
@Override
public void presolve(Contact contact, PhysicsEntity other) {
if (!(other instanceof Paddle)) {
contact.setEnabled(false);
}
}
}
| 30.25 | 166 | 0.684617 |
04a8ff21aca3b93f176b506e40fadf83be8ae718 | 18,681 | package org.xcolab.service.members.domain.member;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Record1;
import org.jooq.SelectQuery;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.xcolab.client.user.pojo.wrapper.UserWrapper;
import org.xcolab.commons.SortColumn;
import org.xcolab.model.tables.MemberCategoryTable;
import org.xcolab.model.tables.UserRoleTable;
import org.xcolab.model.tables.UserTable;
import org.xcolab.model.tables.records.UserRecord;
import org.xcolab.service.utils.PaginationHelper;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
import static org.jooq.impl.DSL.coalesce;
import static org.jooq.impl.DSL.concat;
import static org.jooq.impl.DSL.countDistinct;
import static org.jooq.impl.DSL.ltrim;
import static org.jooq.impl.DSL.max;
import static org.jooq.impl.DSL.nullif;
import static org.jooq.impl.DSL.sum;
import static org.jooq.impl.DSL.val;
import static org.xcolab.model.Tables.ACTIVITY_ENTRY;
import static org.xcolab.model.Tables.LOGIN_LOG;
import static org.xcolab.model.Tables.MEMBER_CATEGORY;
import static org.xcolab.model.Tables.POINTS;
import static org.xcolab.model.Tables.USER;
import static org.xcolab.model.Tables.USER_ROLE;
@Repository
public class UserDaoImpl implements UserDao {
private final DSLContext dslContext;
@Autowired
public UserDaoImpl(DSLContext dslContext) {
this.dslContext = dslContext;
}
@Override
public List<UserWrapper> findByGiven(PaginationHelper paginationHelper, String partialName,
String partialEmail, String roleName, String email, String screenName, Long facebookId,
String googleId, String colabSsoId, String climateXId, List<Long> roleIds) {
final UserTable member = USER.as("member");
final UserRoleTable usersRoles = USER_ROLE.as("userRole");
final MemberCategoryTable memberCategory = MEMBER_CATEGORY.as("memberCategory");
final SelectQuery<Record> query = dslContext.selectDistinct(member.fields())
.from(member)
.where(member.STATUS.eq(0))
.getQuery();
if (roleName != null || roleIds != null) {
query.addJoin(usersRoles, member.ID.equal(usersRoles.USER_ID));
}
if (roleName != null) {
query.addJoin(memberCategory, memberCategory.ROLE_ID.equal(usersRoles.ROLE_ID));
}
if (partialName != null || partialEmail != null) {
addSearchCondition(partialName, partialEmail, query,member);
}
if (roleName != null) {
query.addConditions(memberCategory.DISPLAY_NAME.eq(roleName));
}
if (roleIds != null) {
query.addConditions(usersRoles.ROLE_ID.in(roleIds));
}
if (screenName != null) {
query.addConditions(member.SCREEN_NAME.eq(screenName));
}
if (email != null) {
query.addConditions(member.EMAIL_ADDRESS.eq(email));
}
if (facebookId != null) {
query.addConditions(member.FACEBOOK_ID.eq(facebookId));
}
if (googleId != null) {
query.addConditions(member.GOOGLE_ID.eq(googleId));
}
if (colabSsoId != null) {
query.addConditions(member.COLAB_SSO_ID.eq(colabSsoId));
}
if (climateXId != null) {
query.addConditions(member.CLIMATE_X_ID.eq(climateXId));
}
if (roleName != null) {
UserRoleTable userRoleInner = USER_ROLE.as("userRoleInner");
MemberCategoryTable memberCategoryInner = MEMBER_CATEGORY.as("memberCategoryInner");
query.addConditions(usersRoles.ROLE_ID.eq(
dslContext.select(userRoleInner.ROLE_ID)
.from(userRoleInner)
.innerJoin(memberCategoryInner).on(userRoleInner.ROLE_ID.eq(memberCategoryInner.ROLE_ID))
.where(userRoleInner.USER_ID.eq(member.ID))
.orderBy(memberCategoryInner.SORT_ORDER.desc())
.limit(0,1)
));
}
for (SortColumn sortColumn : paginationHelper.getSortColumns()) {
switch (sortColumn.getColumnName()) {
case "createdAt":
query.addOrderBy(sortColumn.isAscending()
? member.CREATED_AT.asc() : member.CREATED_AT.desc());
break;
case "screenName":
query.addOrderBy(sortColumn.isAscending()
? member.SCREEN_NAME.asc() : member.SCREEN_NAME.desc());
break;
case "displayName":
Field<String> displayName = getDisplayName(member);
query.addOrderBy(sortColumn.isAscending()
? displayName.asc() : displayName.desc());
break;
case "activityCount":
//TODO COLAB-2608: this property is owned by the activity-service
Field<Object> activityCount = this.dslContext.selectCount()
.from(ACTIVITY_ENTRY)
.where(ACTIVITY_ENTRY.USER_ID.equal(member.ID))
.asField("activityCount");
query.addSelect(activityCount);
query.addSelect(member.fields());
query.addOrderBy(sortColumn.isAscending()
? activityCount.asc() : activityCount.desc());
break;
//TODO COLAB-2607: this sorting doesn't work
case "roleName":
Field<Object> roleNameField = dslContext.select(max(MEMBER_CATEGORY.SORT_ORDER))
.from(MEMBER_CATEGORY)
.join(USER_ROLE).on(USER_ROLE.ROLE_ID.eq(MEMBER_CATEGORY.ROLE_ID))
.where(USER_ROLE.USER_ID.eq(member.ID))
.asField("roleName");
query.addSelect(roleNameField);
query.addOrderBy(sortColumn.isAscending()
? roleNameField.asc()
: roleNameField.desc());
break;
case "points":
Field<Object> points =
this.dslContext.select(sum(POINTS.MATERIALIZED_POINTS))
.from(POINTS)
.where(POINTS.USER_ID.equal(member.ID))
.asField("points");
query.addSelect(points);
query.addOrderBy(sortColumn.isAscending()
? points.asc() : points.desc());
break;
default:
}
}
query.addLimit(paginationHelper.getStartRecord(), paginationHelper.getCount());
return query.fetchInto(UserWrapper.class);
}
private Field<String> getDisplayName(UserTable member) {
// Concatenate first name and last name to full name. If the full name is more than just a
// space, return the full name. Else, return the screen name.
Field<String> firstName = coalesce(ltrim(member.FIRST_NAME), "");
Field<String> lastName = coalesce(ltrim(member.LAST_NAME), "");
Field<String> fullName = ltrim(concat(firstName, val(" "), lastName));
fullName = nullif(fullName, " ");
Field<String> screenName = member.SCREEN_NAME;
return coalesce(fullName, screenName);
}
private void addSearchCondition(String partialName, String partialEmail,
SelectQuery<?> query, UserTable memberTable) {
Condition searchCondition = DSL.falseCondition();
if (partialName != null) {
String[] searchTerms = partialName.split("\\s");
for (String searchTerm : searchTerms) {
searchCondition = searchCondition
.or(memberTable.SCREEN_NAME.contains(searchTerm))
.or(memberTable.FIRST_NAME.contains(searchTerm))
.or(memberTable.LAST_NAME.contains(searchTerm));
}
}
if (partialEmail != null) {
searchCondition = searchCondition.or(memberTable.EMAIL_ADDRESS.contains(partialEmail));
}
query.addConditions(searchCondition);
}
@Override
public List<UserWrapper> findByIp(String ip) {
final SelectQuery<Record> query = dslContext
.selectDistinct(USER.fields())
.from(USER)
.join(LOGIN_LOG).on(LOGIN_LOG.USER_ID.equal(USER.ID))
.where(LOGIN_LOG.IP_ADDRESS.eq(ip))
.getQuery();
return query.fetchInto(UserWrapper.class);
}
@Override
public List<UserWrapper> findByScreenNameName(String name) {
final SelectQuery<Record> query = dslContext.select()
.from(USER)
.where(USER.SCREEN_NAME.like("%"+name+"%"))
.or(USER.FIRST_NAME.like("%"+name+"%"))
.and(USER.STATUS.eq(0))
.orderBy(USER.SCREEN_NAME)
.getQuery();
return query.fetchInto(UserWrapper.class);
}
@Override
public int countByGiven(String partialName, String partialEmail, String roleName) {
final UserTable memberTable = USER.as("member");
final UserRoleTable usersRoles = USER_ROLE.as("usersRoles");
final MemberCategoryTable memberCategory = MEMBER_CATEGORY.as("memberCategory");
final SelectQuery<Record1<Integer>> query = dslContext.select(countDistinct(memberTable.ID))
.from(memberTable)
.join(usersRoles).on(memberTable.ID.equal(usersRoles.USER_ID))
.join(memberCategory).on(memberCategory.ROLE_ID.equal(usersRoles.ROLE_ID))
.where(memberTable.STATUS.eq(0))
.getQuery();
if (partialName != null || partialEmail != null) {
addSearchCondition(partialName, partialEmail, query,memberTable);
}
if (roleName != null) {
query.addConditions(memberCategory.DISPLAY_NAME.eq(roleName));
}
return query.fetchOne().into(Integer.class);
}
@Override
public Optional<UserWrapper> getUser(long userId) {
final Record memberRecord = dslContext.select()
.from(USER)
.where(USER.ID.eq(userId))
.fetchOne();
if (memberRecord == null) {
return Optional.empty();
}
return Optional.of(memberRecord.into(UserWrapper.class));
}
@Override
public boolean updatePassword(long userId, String hashedPassword) {
return dslContext.update(USER)
.set(USER.HASHED_PASSWORD, hashedPassword)
.set(USER.PASSWORD_UPDATED_AT, DSL.currentTimestamp())
.set(USER.UPDATED_AT, DSL.currentTimestamp())
.set(USER.FORGOT_PASSWORD_TOKEN, (String) null)
.set(USER.FORGOT_PASSWORD_TOKEN_EXPIRE_TIME, (Timestamp) null)
.where(USER.ID.eq(userId))
.execute() > 0;
}
@Override
public boolean isScreenNameTaken(String screenName) {
return dslContext.selectCount()
.from(USER)
.where(USER.SCREEN_NAME.eq(screenName))
.fetchOne(0, Integer.class) > 0;
}
@Override
public boolean isEmailUsed(String email) {
return dslContext.selectCount()
.from(USER)
.where(USER.EMAIL_ADDRESS.eq(email))
.fetchOne(0, Integer.class) > 0;
}
@Override
public Optional<UserWrapper> findOneByScreenName(String screenName) {
final Record record = dslContext.select()
.from(USER)
.where(USER.SCREEN_NAME.eq(screenName))
.fetchOne();
if (record == null) {
return Optional.empty();
}
return Optional.of(record.into(UserWrapper.class));
}
@Override
public Optional<UserWrapper> findOneByEmail(String email) {
final Record record = dslContext.select()
.from(USER)
.where(USER.EMAIL_ADDRESS.eq(email))
.fetchOne();
if (record == null) {
return Optional.empty();
}
return Optional.of(record.into(UserWrapper.class));
}
@Override
public Optional<UserWrapper> findOneByLoginTokenId(String loginTokenId) {
final Record record = dslContext.select()
.from(USER)
.where(USER.LOGIN_TOKEN_ID.eq(loginTokenId))
.fetchOne();
if (record == null) {
return Optional.empty();
}
return Optional.of(record.into(UserWrapper.class));
}
@Override
public Optional<UserWrapper> findOneByForgotPasswordHash(String newPasswordToken) {
final Record record = dslContext.select()
.from(USER)
.where(USER.FORGOT_PASSWORD_TOKEN.eq(newPasswordToken))
.fetchOne();
if (record == null) {
return Optional.empty();
}
return Optional.of(record.into(UserWrapper.class));
}
@Override
public boolean updateUser(UserWrapper member) {
return this.dslContext.update(USER)
.set(USER.UUID, member.getUuid())
.set(USER.UPDATED_AT, DSL.currentTimestamp())
.set(USER.SCREEN_NAME, member.getScreenName())
.set(USER.EMAIL_ADDRESS, member.getEmailAddress())
.set(USER.IS_EMAIL_CONFIRMED, member.isIsEmailConfirmed())
.set(USER.IS_EMAIL_BOUNCED, member.isIsEmailBounced())
.set(USER.OPEN_ID, member.getOpenId())
.set(USER.DEFAULT_LOCALE, member.getDefaultLocale())
.set(USER.FIRST_NAME, member.getFirstName())
.set(USER.LAST_NAME, member.getLastName())
.set(USER.LOGIN_DATE, member.getLoginDate())
.set(USER.LOGIN_IP, member.getLoginIp())
.set(USER.FACEBOOK_ID, member.getFacebookId())
.set(USER.GOOGLE_ID, member.getGoogleId())
.set(USER.COLAB_SSO_ID, member.getColabSsoId())
.set(USER.CLIMATE_X_ID, member.getClimateXId())
.set(USER.SHORT_BIO, member.getShortBio())
.set(USER.AUTO_REGISTERED_MEMBER_STATUS, member.getAutoRegisteredMemberStatus())
.set(USER.DEFAULT_LOCALE, member.getDefaultLocale())
.set(USER.COUNTRY, member.getCountry())
.set(USER.STATUS, member.getStatus())
.set(USER.PORTRAIT_FILE_ENTRY_ID, member.getPortraitFileEntryId())
.set(USER.FORGOT_PASSWORD_TOKEN, member.getForgotPasswordToken())
.set(USER.FORGOT_PASSWORD_TOKEN_EXPIRE_TIME, member.getForgotPasswordTokenExpireTime())
.set(USER.LOGIN_TOKEN_ID, member.getLoginTokenId())
.set(USER.LOGIN_TOKEN_KEY, member.getLoginTokenKey())
.set(USER.LOGIN_TOKEN_EXPIRATION_DATE, member.getLoginTokenExpirationDate())
.where(USER.ID.equal(member.getId()))
.execute() > 0;
}
@Override
public UserWrapper createUser(UserWrapper member) {
final Optional<UserRecord> memberRecord =
dslContext.insertInto(USER)
.set(USER.UUID, member.getUuid())
.set(USER.SCREEN_NAME, member.getScreenName())
.set(USER.EMAIL_ADDRESS, member.getEmailAddress())
.set(USER.IS_EMAIL_CONFIRMED, member.isIsEmailConfirmed())
.set(USER.IS_EMAIL_BOUNCED, member.isIsEmailBounced())
.set(USER.OPEN_ID, member.getOpenId())
.set(USER.DEFAULT_LOCALE, member.getDefaultLocale())
.set(USER.FIRST_NAME, member.getFirstName())
.set(USER.LAST_NAME, member.getLastName())
.set(USER.LOGIN_DATE, member.getLoginDate())
.set(USER.LOGIN_IP, member.getLoginIp())
.set(USER.HASHED_PASSWORD, member.getHashedPassword())
.set(USER.FACEBOOK_ID, member.getFacebookId())
.set(USER.GOOGLE_ID, member.getGoogleId())
.set(USER.COLAB_SSO_ID, member.getColabSsoId())
.set(USER.CLIMATE_X_ID, member.getClimateXId())
.set(USER.SHORT_BIO, member.getShortBio())
.set(USER.AUTO_REGISTERED_MEMBER_STATUS, member.getAutoRegisteredMemberStatus())
.set(USER.DEFAULT_LOCALE, member.getDefaultLocale())
.set(USER.COUNTRY, member.getCountry())
.set(USER.STATUS, member.getStatus())
.set(USER.PORTRAIT_FILE_ENTRY_ID, member.getPortraitFileEntryId())
.set(USER.FORGOT_PASSWORD_TOKEN, member.getForgotPasswordToken())
.set(USER.FORGOT_PASSWORD_TOKEN_EXPIRE_TIME, member.getForgotPasswordTokenExpireTime())
.set(USER.LOGIN_TOKEN_ID, member.getLoginTokenId())
.set(USER.LOGIN_TOKEN_KEY, member.getLoginTokenKey())
.set(USER.LOGIN_TOKEN_EXPIRATION_DATE, member.getLoginTokenExpirationDate())
.set(USER.CREATED_AT, DSL.currentTimestamp())
.set(USER.UPDATED_AT, DSL.currentTimestamp())
.returning(USER.ID)
.fetchOptional();
if (!memberRecord.isPresent()) {
throw new IllegalStateException("Could not fetch generated ID");
}
member.setId(memberRecord.get().getValue(USER.ID));
return member;
}
@Override
public Integer getUserMaterializedPoints(Long userId) {
return this.dslContext.select(sum(POINTS.MATERIALIZED_POINTS))
.from(POINTS).where(POINTS.USER_ID.equal(userId)).fetchOne(0, Integer.class);
}
@Override
public Integer getUserHypotheticalPoints(Long userId) {
return dslContext.select(sum(POINTS.HYPOTHETICAL_POINTS))
.from(POINTS).where(POINTS.USER_ID.eq(userId)).fetchOne(0, Integer.class);
}
}
| 44.691388 | 111 | 0.592955 |
e44825709816e8f2a9b086a9b5c92a79c1f8442d | 2,094 | package cz.hartrik.common.reflect;
/**
* Jednoduché stopky, které slouží hlavně k testování.
*
* @version 2015-07-25
* @author Patrik Harag
*/
public class StopWatch {
// --- statické metody ---
/**
* Vytvoří stopky, spustí metodu {@link Runnable#run()} a vrátí stopky s
* výsledným časem.
*
* @param runnable instance s metodou <code>run</code>
* @return stopky s časem
*/
public static final StopWatch measure(Runnable runnable) {
StopWatch watch = new StopWatch();
watch.start();
runnable.run();
watch.stop();
return watch;
}
/**
* Spustí metodu {@link Runnable#run()} a výsledný čas v milisekundách
* vypíše na standardní výstup v určitém formátu. <p>
* Ukázka:
* <pre>{@code
* StopWatch.measureAndPrint("Načtení: %d ms", () -> {
* ...
* });}</pre>
*
* @param format formát, ve kterém bude výsledný čas zapsán
* @param runnable instance s metodou <code>run</code>
* @see String#format(String, Object...)
*/
public static final void measureAndPrint(String format, Runnable runnable) {
String text = String.format(format, measure(runnable).getMillis());
System.out.println(text);
}
// --- třída ---
private boolean running = false;
private long start = 0;
private long stop = 0;
/** Spustí stopky */
public void start() {
if (!running) {
running = true;
start = System.currentTimeMillis();
}
}
/** Zastaví stopky. */
public void stop() {
stop = System.currentTimeMillis();
running = false;
}
public long getMillis() {
return (running ? System.currentTimeMillis() : stop) - start;
}
public long getSec() { return getMillis() / 1000; }
public long getMin() { return getSec() / 60; }
public long getHour() { return getMin() / 60; }
public long getDay() { return getHour() / 24; }
} | 27.194805 | 81 | 0.557307 |
85806e03601c6e9f7feb11610a19996b0a9254ee | 232 | package edu.njnu.reproducibility.domain.method.support;
import lombok.Data;
/**
* @Author :Zhiyi
* @Date :2021/3/31 16:46
* @modified By:
* @version: 1.0.0
*/
@Data
public class Authorship {
String name;
String id;
}
| 14.5 | 55 | 0.659483 |
d5d0e5f7c16639a90727649b8601c269206ae884 | 247 | package com.globant.bootcamp.patterns.factory;
import java.util.Properties;
import com.globant.bootcamp.repository.Connection;
public abstract class ConnectionAbstractFactory {
public abstract Connection getConnection(Properties properties);
} | 27.444444 | 65 | 0.846154 |
616322d02f737ca99cae9df76757d586e5964340 | 420 | package com.github.soniex2.notebetter.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author soniex2
*/
public class StreamHelper {
public static void copy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[4096];
int l;
while ((l = is.read(bytes)) != -1) {
os.write(bytes, 0, l);
}
}
}
| 22.105263 | 81 | 0.62619 |
f8143a03e8d86c23c7d4061be55970577a146dd3 | 2,385 | package crazypants.enderzoo.entity.ai;
import java.util.List;
import crazypants.enderzoo.entity.EntityUtil;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.util.math.BlockPos;
public class EntityAIFlyingFindPerch extends EntityAIBase {
private EntityCreature entity;
private double xPosition;
private double yPosition;
private double zPosition;
private double speed;
private int executionChance;
private int searchRange = 6;
private int searchAttempts = 30;
public EntityAIFlyingFindPerch(EntityCreature creatureIn, double speedIn) {
this(creatureIn, speedIn, 120);
}
public EntityAIFlyingFindPerch(EntityCreature creatureIn, double speedIn, int chance) {
entity = creatureIn;
speed = speedIn;
executionChance = chance;
setMutexBits(1);
}
@Override
public boolean shouldExecute() {
int chance = executionChance;
if (isOnLeaves()) { // if we are already on leaves, don't look for a new perch so often
chance *= 10;
}
// chance = 5;
if (entity.getRNG().nextInt(chance) != 0) {
return false;
}
BlockPos targetPos = EntityUtil.findRandomLandingSurface(entity, searchRange, entity.getPosition().getY() + 1, 250, searchAttempts);
if (targetPos != null) {
List<EntityCreature> others = entity.getEntityWorld().getEntitiesWithinAABB(entity.getClass(), EntityUtil.getBoundsAround(targetPos, 4));
if (others != null && others.size() > 1) {
return false;
}
xPosition = targetPos.getX() + 0.5;
yPosition = targetPos.getY();
zPosition = targetPos.getZ() + 0.5;
return true;
}
return false;
}
private boolean isOnLeaves() {
IBlockState bs = entity.getEntityWorld().getBlockState(entity.getPosition().down());
return bs.getMaterial() == Material.LEAVES;
}
@Override
public boolean shouldContinueExecuting() {
return !entity.getNavigator().noPath();
}
@Override
public void startExecuting() {
if (!entity.getNavigator().tryMoveToXYZ(xPosition, yPosition, zPosition, speed)) {
// System.out.println("EntityAIFlyingFindPerch.startExecuting: No path");
}
}
public void setExecutionChance(int newchance) {
executionChance = newchance;
}
} | 30.189873 | 143 | 0.710273 |
a6f909384ccb69e4fdcd9fa94e01f361675abdba | 4,818 | package gamesoftitalia.bizbong;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import gamesoftitalia.bizbong.connessione.CreaProfiloAsync;
import gamesoftitalia.bizbong.connessione.LoginAsync;
import gamesoftitalia.bizbong.entity.Impostazioni;
import gamesoftitalia.bizbong.service.MusicServiceBase;
public class LoginActivity extends AppCompatActivity {
private EditText nicknameEdit, passwordEdit;
private TextView login;
private ImageButton backButton;
private String nickname, password;
private Impostazioni entity;
private Intent music=new Intent();
private boolean audioAssociato;
private MusicServiceBase mServ;
ServiceConnection Scon =new ServiceConnection(){
/*implementazione metodi astratti*/
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicServiceBase.ServiceBinder)binder).getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
entity= (Impostazioni) getIntent().getSerializableExtra("Impostazioni"); //ricevitore oggetto Impostazioni
//Music
audioAssociato=entity.getAudio();
if (audioAssociato){
music.setClass(this, MusicServiceBase.class);
bindService(music, Scon, Context.BIND_AUTO_CREATE); //legare il servizio al contesto
startService(music);
}
//EditText
nicknameEdit = (EditText) findViewById(R.id.nicknameEdit);
passwordEdit = (EditText) findViewById(R.id.passwordEdit);
//Button
backButton = (ImageButton) findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(entity.getEffetti()==true) {
MediaPlayer mp = MediaPlayer.create(LoginActivity.this, R.raw.bottoni);
mp.start();
}
if(entity.getVibrazione()){
Vibrator g = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
g.vibrate(100);
}
LoginActivity.super.onBackPressed();
}
});
login = (TextView) findViewById(R.id.registrazioneButton);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(entity.getEffetti()==true) {
MediaPlayer mp = MediaPlayer.create(LoginActivity.this, R.raw.bottoni);
mp.start();
}
if(entity.getVibrazione()){
Vibrator g = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
g.vibrate(100);
}
nickname = nicknameEdit.getText().toString();
password = passwordEdit.getText().toString();
if(nickname.length() > 0 && password.length() > 0) {
new LoginAsync(LoginActivity.this).execute(nickname, password);
}
}
});
}
@Override
protected void onResume() { /*quando l'app viene riattivata*/
super.onResume();
if (audioAssociato==true)
if(mServ!=null) {
bindService(music, Scon, Context.BIND_AUTO_CREATE);
mServ.resumeMusic();
}
};
@Override
protected void onPause() { /*quando l'app va in background viene stoppato*/
if (audioAssociato==true)
if(mServ!=null){
mServ.pauseMusic();
unbindService(Scon);
}
super.onPause();
}
@Override
protected void onDestroy() {
try {
audioAssociato = entity.getAudio();
if (audioAssociato) {
mServ.stopMusic();
stopService(music);
unbindService(Scon); //togliere il contesto al servizio
}
} catch (NullPointerException | IllegalArgumentException e){}
super.onDestroy();
}
}
| 33.929577 | 118 | 0.617891 |
1018d138a14ed92b109a14239e11e9e3cf1823a9 | 1,570 | package gr.uom.java.xmi;
import java.io.Serializable;
public class UMLAnonymousClass extends UMLAbstractClass implements Comparable<UMLAnonymousClass>, Serializable, LocationInfoProvider {
private String codePath;
public UMLAnonymousClass(String packageName, String name, String codePath, LocationInfo locationInfo) {
super();
this.packageName = packageName;
this.name = name;
this.locationInfo = locationInfo;
this.codePath = codePath;
}
public boolean isDirectlyNested() {
return !name.contains(".");
}
public String getCodePath() {
if(packageName.equals(""))
return codePath;
else
return packageName + "." + codePath;
}
public String getName() {
if(packageName.equals(""))
return name;
else
return packageName + "." + name;
}
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(o instanceof UMLAnonymousClass) {
UMLAnonymousClass umlClass = (UMLAnonymousClass)o;
return this.packageName.equals(umlClass.packageName) && this.attributes.equals(umlClass.attributes) &&
this.operations.equals(umlClass.operations) && this.getSourceFile().equals(umlClass.getSourceFile());
}
return false;
}
public String toString() {
return getName();
}
public int compareTo(UMLAnonymousClass umlClass) {
return this.toString().compareTo(umlClass.toString());
}
public boolean isSingleAbstractMethodInterface() {
return false;
}
public boolean isInterface() {
return false;
}
}
| 24.920635 | 134 | 0.681529 |
ebbff9bb8d82063830e0484686d8a9433af9fdc3 | 2,528 | package com.whyn.asm.recorders.interfaces.impl;
import com.whyn.bean.element.FieldBean;
import com.whyn.bean.element.InnerClassBean;
import com.whyn.bean.element.MethodBean;
import com.whyn.asm.recorders.interfaces.IClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import java.util.LinkedList;
import java.util.List;
public class ClassReaderDispatcher implements IClassReader {
private List<IClassReader> mViewRecorders = new LinkedList<>();
public boolean register(IClassReader reader) {
if (reader == null)
return false;
return mViewRecorders.add(reader);
}
public boolean unregister(IClassReader reader) {
if (reader == null)
return true;
return mViewRecorders.remove(reader);
}
@Override
public void visitVersion(int version) {
for (IClassReader reader : mViewRecorders) {
reader.visitVersion(version);
}
}
@Override
public void visitClass(int access, String name, String signature, String superName, String[] interfaces) {
for (IClassReader reader : mViewRecorders) {
reader.visitClass(access, name, signature, superName, interfaces);
}
}
@Override
public void visitInnerClass(InnerClassBean bean) {
for (IClassReader reader : mViewRecorders) {
reader.visitInnerClass(bean);
}
}
@Override
public void visitField(FieldBean bean) {
for (IClassReader reader : mViewRecorders) {
reader.visitField(bean);
}
}
@Override
public void visitMethod(MethodBean bean) {
for (IClassReader reader : mViewRecorders) {
reader.visitMethod(bean);
}
}
@Override
public MethodVisitor injectMethod(MethodVisitor mv, int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor methodVisitor = mv;
MethodVisitor tempMethodVisitor;
for (IClassReader reader : mViewRecorders) {
tempMethodVisitor = reader.injectMethod(methodVisitor, access, name, desc, signature, exceptions);
//ignnore those who don't wanna inject
if (tempMethodVisitor != methodVisitor)
methodVisitor = tempMethodVisitor;
}
return methodVisitor;
}
@Override
public void visitEnd(ClassVisitor cv) {
for (IClassReader reader : mViewRecorders) {
reader.visitEnd(cv);
}
}
}
| 29.741176 | 134 | 0.660206 |
a078c619c54926314421c150f7cefa8ddd6d48bd | 279 | // It is not allowed to static-import a package-private type from another package.
// https://bitbucket.org/extendj/extendj/issues/289/illegal-static-type-import-is-allowed
// .result: COMPILE_FAIL
import static my.thing.A.Thing; // Error: illegal import.
public class Test { }
| 39.857143 | 89 | 0.763441 |
95b4f262f470dcd7ba66c930092259ada1fea7e4 | 2,835 | /*
* Copyright (C) 2013 Guillaume Lesniak
* Copyright (C) 2012 Paul Lawitzki
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.cyanogenmod.focal.picsphere;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import java.util.Timer;
import java.util.TimerTask;
public class SensorFusion implements SensorEventListener {
private SensorManager mSensorManager = null;
float[] mOrientation = new float[3];
float[] mRotationMatrix;
public SensorFusion(Context context) {
// get sensorManager and initialise sensor listeners
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
initListeners();
}
public void onPauseOrStop() {
mSensorManager.unregisterListener(this);
}
public void onResume() {
// restore the sensor listeners when user resumes the application.
initListeners();
}
// This function registers sensor listeners for the accelerometer, magnetometer and gyroscope.
public void initListeners(){
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
20000);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (mRotationMatrix == null) {
mRotationMatrix = new float[16];
}
// Get rotation matrix from angles
SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
// Remap the axes
SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_Z,
SensorManager.AXIS_X, mRotationMatrix);
// Get back a remapped orientation vector
SensorManager.getOrientation(mRotationMatrix, mOrientation);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
public float[] getFusedOrientation() {
return mOrientation;
}
public float[] getRotationMatrix() {
return mRotationMatrix;
}
}
| 31.853933 | 98 | 0.711111 |
1289b52d3a9f8c6c4f0afb2823c268e0bba9c6eb | 4,682 | package com.mercadopago.resources;
import com.mercadopago.core.MPBase;
import com.mercadopago.core.MPRequestOptions;
import com.mercadopago.core.MPResourceArray;
import com.mercadopago.core.annotations.rest.GET;
import com.mercadopago.core.annotations.rest.POST;
import com.mercadopago.exceptions.MPException;
import com.mercadopago.resources.datastructures.advancedpayment.Source;
import java.util.*;
public class DisbursementRefund extends MPBase {
private Integer id;
private Integer paymentId;
private Float amount;
private Source source;
private Date dateCreated;
private String status;
private transient Integer advancedPaymentId;
private transient Long disbursementId;
public Integer getAdvancedPaymentId() {
return advancedPaymentId;
}
public DisbursementRefund setAdvancedPaymentId(Integer advancedPaymentId) {
this.advancedPaymentId = advancedPaymentId;
return this;
}
public Long getDisbursementId() {
return disbursementId;
}
public DisbursementRefund setDisbursementId(Long disbursementId) {
this.disbursementId = disbursementId;
return this;
}
public Integer getId() {
return id;
}
public DisbursementRefund setId(Integer id) {
this.id = id;
return this;
}
public Integer getPaymentId() {
return paymentId;
}
public DisbursementRefund setPaymentId(Integer paymentId) {
this.paymentId = paymentId;
return this;
}
public Float getAmount() {
return amount;
}
public DisbursementRefund setAmount(Float amount) {
this.amount = amount;
return this;
}
public Source getSource() {
return source;
}
public DisbursementRefund setSource(Source source) {
this.source = source;
return this;
}
public Date getDateCreated() {
return dateCreated;
}
public DisbursementRefund setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
return this;
}
public String getStatus() {
return status;
}
public DisbursementRefund setStatus(String status) {
this.status = status;
return this;
}
public static MPResourceArray all(String advancedPaymentId, Boolean useCache) throws MPException {
return all(advancedPaymentId, useCache, MPRequestOptions.createDefault());
}
@GET(path="/v1/advanced_payments/:advanced_payment_id/refunds")
public static MPResourceArray all(String advancedPaymentId, Boolean useCache, MPRequestOptions requestOptions) throws MPException {
return processMethodBulk(Refund.class, "all", useCache, requestOptions, advancedPaymentId);
}
public DisbursementRefund save(float amount) throws MPException {
return save(amount, MPRequestOptions.createDefault());
}
public DisbursementRefund save(float amount, MPRequestOptions requestOptions) throws MPException {
if (amount > 0) {
this.amount = amount;
}
return save(requestOptions);
}
public DisbursementRefund save() throws MPException {
return save(MPRequestOptions.createDefault());
}
@POST(path="/v1/advanced_payments/:advanced_payment_id/disbursements/:disbursement_id/refunds")
public DisbursementRefund save(MPRequestOptions requestOptions) throws MPException {
return processMethod("save", WITHOUT_CACHE, requestOptions);
}
@POST(path="/v1/advanced_payments/:advanced_payment_id/refunds")
protected static MPResourceArray createAll(Long advancedPaymentId,MPRequestOptions requestOptions) throws MPException {
Map<String, String> pathParams = new HashMap<String, String>();
pathParams.put("advanced_payment_id", advancedPaymentId.toString());
return processMethodBulk(DisbursementRefund.class, "createAll", pathParams, WITHOUT_CACHE, requestOptions);
}
@POST(path="/v1/advanced_payments/:advanced_payment_id/disbursements/:disbursement_id/refunds")
protected static DisbursementRefund create(Long advancedPaymentId, Long disbursementId, float amount, MPRequestOptions requestOptions) throws MPException {
Map<String,String> pathParams = new HashMap<String, String>();
pathParams.put("advanced_payment_id", advancedPaymentId.toString());
pathParams.put("disbursement_id", disbursementId.toString());
DisbursementRefund refund = new DisbursementRefund()
.setAmount(amount);
return processMethod(DisbursementRefund.class, refund, "create", pathParams,WITHOUT_CACHE, requestOptions);
}
}
| 31.006623 | 159 | 0.71273 |
c90877e8a89c520d978f7bceaf0c34daca4314e1 | 553 | package org.kyojo.schemaorg.m3n5.doma.core.container;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaorg.m3n5.core.impl.ICAO_CODE;
import org.kyojo.schemaorg.m3n5.core.Container.IcaoCode;
@ExternalDomain
public class IcaoCodeConverter implements DomainConverter<IcaoCode, String> {
@Override
public String fromDomainToValue(IcaoCode domain) {
return domain.getNativeValue();
}
@Override
public IcaoCode fromValueToDomain(String value) {
return new ICAO_CODE(value);
}
}
| 24.043478 | 77 | 0.804702 |
eddfe3dca15def447dacee06d699a5f0d85ced24 | 71 | package com.blamejared.mas.events;
public class CommonEvents {
}
| 11.833333 | 34 | 0.732394 |
3cb5f33233d7e9da560c184dcdf7cb6a120fd37d | 12,244 | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.uikit;
import apple.NSObject;
import apple.coregraphics.struct.CGRect;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.uikit.protocol.UIPopoverBackgroundViewMethods;
import apple.uikit.struct.UIEdgeInsets;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
@Generated
@Library("UIKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class UIPopoverPresentationController extends UIPresentationController {
static {
NatJ.register();
}
@Generated
protected UIPopoverPresentationController(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native UIPopoverPresentationController alloc();
@Generated
@Selector("allocWithZone:")
@MappedReturn(ObjCObjectMapper.class)
public static native Object allocWithZone(VoidPtr zone);
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
@Generated
@Owned
@Selector("new")
@MappedReturn(ObjCObjectMapper.class)
public static native Object new_objc();
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("version")
@NInt
public static native long version_static();
/**
* Returns the direction the arrow is pointing on a presented popover. Before presentation, this returns UIPopoverArrowDirectionUnknown.
*/
@Generated
@Selector("arrowDirection")
@NUInt
public native long arrowDirection();
/**
* Set popover background color. Set to nil to use default background color. Default is nil.
*/
@Generated
@Selector("backgroundColor")
public native UIColor backgroundColor();
@Generated
@Selector("barButtonItem")
public native UIBarButtonItem barButtonItem();
/**
* By default, a popover is not allowed to overlap its source view rect.
* When this is set to YES, popovers with more content than available space are allowed to overlap the source view rect in order to accommodate the content.
*/
@Generated
@Selector("canOverlapSourceViewRect")
public native boolean canOverlapSourceViewRect();
@Generated
@Selector("delegate")
@MappedReturn(ObjCObjectMapper.class)
public native Object delegate();
@Generated
@Selector("init")
public native UIPopoverPresentationController init();
@Generated
@Selector("initWithPresentedViewController:presentingViewController:")
public native UIPopoverPresentationController initWithPresentedViewControllerPresentingViewController(
UIViewController presentedViewController, UIViewController presentingViewController);
/**
* By default, a popover disallows interaction with any view outside of the popover while the popover is presented.
* This property allows the specification of an array of UIView instances which the user is allowed to interact with
* while the popover is up.
*/
@Generated
@Selector("passthroughViews")
public native NSArray<? extends UIView> passthroughViews();
@Generated
@Selector("permittedArrowDirections")
@NUInt
public native long permittedArrowDirections();
/**
* Clients may customize the popover background chrome by providing a class which subclasses `UIPopoverBackgroundView`
* and which implements the required instance and class methods on that class.
*/
@Generated
@Selector("popoverBackgroundViewClass")
@MappedReturn(ObjCObjectMapper.class)
public native UIPopoverBackgroundViewMethods popoverBackgroundViewClass();
/**
* Clients may wish to change the available area for popover display. The default implementation of this method always
* returns a system defined inset from the edges of the display, and presentation of popovers always accounts
* for the status bar. The rectangle being inset is always expressed in terms of the current device orientation; (0, 0)
* is always in the upper-left of the device. This may require insets to change on device rotation.
*/
@Generated
@Selector("popoverLayoutMargins")
@ByValue
public native UIEdgeInsets popoverLayoutMargins();
/**
* Set popover background color. Set to nil to use default background color. Default is nil.
*/
@Generated
@Selector("setBackgroundColor:")
public native void setBackgroundColor(UIColor value);
@Generated
@Selector("setBarButtonItem:")
public native void setBarButtonItem(UIBarButtonItem value);
/**
* By default, a popover is not allowed to overlap its source view rect.
* When this is set to YES, popovers with more content than available space are allowed to overlap the source view rect in order to accommodate the content.
*/
@Generated
@Selector("setCanOverlapSourceViewRect:")
public native void setCanOverlapSourceViewRect(boolean value);
@Generated
@Selector("setDelegate:")
public native void setDelegate_unsafe(@Mapped(ObjCObjectMapper.class) Object value);
@Generated
public void setDelegate(@Mapped(ObjCObjectMapper.class) Object value) {
Object __old = delegate();
if (value != null) {
org.moe.natj.objc.ObjCRuntime.associateObjCObject(this, value);
}
setDelegate_unsafe(value);
if (__old != null) {
org.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this, __old);
}
}
/**
* By default, a popover disallows interaction with any view outside of the popover while the popover is presented.
* This property allows the specification of an array of UIView instances which the user is allowed to interact with
* while the popover is up.
*/
@Generated
@Selector("setPassthroughViews:")
public native void setPassthroughViews(NSArray<? extends UIView> value);
@Generated
@Selector("setPermittedArrowDirections:")
public native void setPermittedArrowDirections(@NUInt long value);
/**
* Clients may customize the popover background chrome by providing a class which subclasses `UIPopoverBackgroundView`
* and which implements the required instance and class methods on that class.
*/
@Generated
@Selector("setPopoverBackgroundViewClass:")
public native void setPopoverBackgroundViewClass(
@Mapped(ObjCObjectMapper.class) UIPopoverBackgroundViewMethods value);
/**
* Clients may wish to change the available area for popover display. The default implementation of this method always
* returns a system defined inset from the edges of the display, and presentation of popovers always accounts
* for the status bar. The rectangle being inset is always expressed in terms of the current device orientation; (0, 0)
* is always in the upper-left of the device. This may require insets to change on device rotation.
*/
@Generated
@Selector("setPopoverLayoutMargins:")
public native void setPopoverLayoutMargins(@ByValue UIEdgeInsets value);
/**
* The rectangle in the coordinate space of sourceView that the popover should point at. This property is ignored if a barButtonItem is set.
* Starting in iOS 13.2, a value of CGRectNull will cause the popover to point at the current frame of sourceView and automatically update when the size of sourceView changes. Prior to iOS 13.2, a null rectangle was not supported.
* The default value in iOS 13.2 is CGRectNull. Prior to iOS 13.2, the default value was CGRectZero.
*/
@Generated
@Selector("setSourceRect:")
public native void setSourceRect(@ByValue CGRect value);
@Generated
@Selector("setSourceView:")
public native void setSourceView(UIView value);
/**
* The rectangle in the coordinate space of sourceView that the popover should point at. This property is ignored if a barButtonItem is set.
* Starting in iOS 13.2, a value of CGRectNull will cause the popover to point at the current frame of sourceView and automatically update when the size of sourceView changes. Prior to iOS 13.2, a null rectangle was not supported.
* The default value in iOS 13.2 is CGRectNull. Prior to iOS 13.2, the default value was CGRectZero.
*/
@Generated
@Selector("sourceRect")
@ByValue
public native CGRect sourceRect();
@Generated
@Selector("sourceView")
public native UIView sourceView();
}
| 37.558282 | 234 | 0.742159 |
16f809ce01f959fce620c3f73ca585c610459995 | 1,621 | package io.conceptive.quarkus.plugin.runconfig.executionfacade;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.process.ProcessHandler;
import io.conceptive.quarkus.plugin.runconfig.options.IQuarkusRunConfigurationOptions;
import org.jetbrains.annotations.*;
import java.util.function.Consumer;
/**
* @author w.glanzer, 23.05.2020
*/
public interface IInternalRunConfigs
{
interface IDebugRunConfig extends RunConfiguration
{
/**
* Reinitializes this RunConfig with new settings
*
* @param pBuildProcessHandler ProcessHandler for the build Process
* @param pPort Debug-Port
* @param pOnRestart Runnable that gets called, if this runconfig gets restartet
*/
void reinit(@Nullable ProcessHandler pBuildProcessHandler, int pPort, @Nullable Runnable pOnRestart);
/**
* Enables the message cache on the given process handler, so that all messages that appear in the given handler
* will be cached and will retain in memory to process afterwards
*
* @param pBuildProcessHandler Handler to attach to
*/
void enableMessageCache(@NotNull ProcessHandler pBuildProcessHandler);
}
interface IBuildRunConfig extends RunConfiguration
{
/**
* Reinitializes this RunConfig with new settings
*
* @param pPort Debug-Port
* @param pOnRdy Consumer which handles ready-Events
*/
void reinit(@Nullable Integer pPort, @NotNull IQuarkusRunConfigurationOptions pOptions, @Nullable Consumer<ProcessHandler> pOnRdy, @Nullable Runnable pOnRestart);
}
}
| 33.770833 | 166 | 0.740901 |
74556470159205e9cd737542923c1e403ae35be7 | 1,694 | package atomicStuff;
/**
* Run the main method of this class and you will see Runners in different threads get the same value
*/
public class UnsafeCounter {
private int count;
public int increment() {
return ++count;
}
public static void main(String[] args) {
UnsafeCounter counter = new UnsafeCounter();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
System.out.println("Runner got: " + counter.increment());
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
System.out.println("Runner got: " + counter.increment());
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
System.out.println("Runner got: " + counter.increment());
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
| 27.770492 | 101 | 0.411452 |
9161ae09034ef55b20d1e8280f84b348d7845a89 | 2,940 | /*
* Copyright 2017 ~ 2050 the original author or authors <[email protected], [email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.dopaas.uci.pipeline.provider;
import com.wl4g.component.common.annotation.Stable;
import com.wl4g.dopaas.uci.core.context.PipelineContext;
/**
* Pipeline provider SPI.
*
* @author vjay
* @author Wangl.sir <[email protected]>
* @date 2019-05-05 17:17:00
*/
@Stable
public interface PipelineProvider {
/**
* Execution pipeline with provider process.
*
* @throws Exception
*/
default void execute() throws Exception {
throw new UnsupportedOperationException();
}
/**
* Roll-back with provider process.
*
* @throws Exception
*/
default void rollback() throws Exception {
throw new UnsupportedOperationException();
}
/**
* Get pipeline information.
*
* @return
*/
PipelineContext getContext();
/**
* Invoke remote commands.
*
* @param remoteHost
* @param user
* @param command
* @param sshkey
* @throws Exception
*/
void doRemoteCommand(String remoteHost, String user, String command, String sshkey) throws Exception;
char[] getUsableCipherSshKey(String sshkey) throws Exception;
String getAssetsFingerprint();
String getSourceFingerprint();
/**
* Pipeline type definition.
*
* @author Wangl.sir
* @version v1.0 2019年8月29日
* @since
*/
public static abstract class PipelineKind {
/**
* MAVEN assemble tar provider alias.
*/
final public static String MVN_ASSEMBLE_TAR = "MvnAssTar";
/**
* Spring boot executable jar provider alias.
*/
final public static String SPRING_EXECUTABLE_JAR = "SpringExecJar";
/**
* War tomcat pipeline provider alias.
*/
final public static String WAR_TOMCAT = "warTomcat";
/**
* NPM provider alias.
*/
final public static String NPM_VIEW = "NpmTar";
/**
* view native ,needn't build
*/
final public static String VIEW_NATIVE = "ViewNative";
/**
* Python3 standard provider alias.
*/
final public static String PYTHON3_STANDARD = "Python3";
/**
* GOLANG standard mod provider alias.
*/
final public static String GOLANG_STANDARD = "Golang";
/**
* Docker native provider alias.
*/
final public static String DOCKER_NATIVE = "DockerNative";
/**
* CoreOS(Red hat) RKT native provider alias.
*/
final public static String RKT_NATIVE = "RktNative";
}
} | 22.790698 | 102 | 0.695578 |
e2c2b2badc5898433188506d31837e39c5105eff | 28,812 | package com.econtabil.integration.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.econtabil.api.APIResponse;
import com.econtabil.integration.domain.Jogo;
import com.econtabil.integration.domain.Jogo.Dias;
import com.econtabil.integration.domain.Jogo.Status;
import com.econtabil.integration.domain.JogoPorData;
import com.econtabil.integration.domain.JogoPorData.StatusJogoPorData;
import com.econtabil.integration.domain.Notificacoes;
import com.econtabil.integration.domain.Notificacoes.NotificacoesStatus;
import com.econtabil.integration.domain.Quadra;
import com.econtabil.integration.domain.User;
import com.econtabil.integration.domain.UserJogo2;
import com.econtabil.integration.domain.UserJogo2.Admin;
import com.econtabil.integration.domain.UserJogo2.StatusUser;
import com.econtabil.integration.service.JogoService;
import com.econtabil.integration.service.JogoUserService;
import com.econtabil.integration.service.NotificacoesService;
import com.econtabil.integration.service.QuadraService;
import com.econtabil.integration.service.UserService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
public class JogoController {
@Autowired
private JogoService jogoService;
@Autowired
private QuadraService quadraService;
@Autowired
private UserService userService;
@Autowired
private NotificacoesService notificacoesService;
@Autowired
private JogoUserService jogoUserService;
@CrossOrigin(origins = "*")
@RequestMapping(value = "/jogo/update", method = RequestMethod.POST)
public @ResponseBody APIResponse createNewMensagem(@RequestBody String users)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
Jogo user = mapper.readValue(users, Jogo.class);
ModelAndView modelAndView = new ModelAndView();
List<String> erros = new ArrayList<String>();
Notificacoes notificacoes = new Notificacoes();
Quadra quadra = new Quadra();
User userss = new User();
Jogo jogo = new Jogo();
String noticicacaoText = "";//+ quadra.getNome() + " " + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + " " + "" + userss.getEmail() + " " + userss.getLastName();
switch (user.getStatus()) {
case DISPONIVEL:
jogoService.saveUpdateJogo(user);
notificacoes = new Notificacoes("DISPONIVEL", new Date(), "Titulo DISPONIVEL", NotificacoesStatus.NAOLIDO, 10, 8);
break;
case ACONFIRMAR:
quadra = quadraService.findAllQuadraById(user.getQuadraId());
userss = userService.findUserById(user.getUser_id());
jogo = jogoService.findJogoById(user.getId());
jogoService.saveUpdateJogo(user);
List<UserJogo2> userJogos = new ArrayList<UserJogo2>();
userJogos.add(new UserJogo2(user.getUser_id(),user.getId(),StatusUser.CONFIRMADO,Admin.SIM));
jogoUserService.saveUserJogo(userJogos);
noticicacaoText = "Acabo de ser solicitado na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Solicitado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("ACONFIRMAR", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getId(), 82);
notificacoes.setParaJogoId(user.getId());
notificacoes.setParaEmprId(82);
break;
case OCUPADO:
jogoService.saveUpdateJogo(user);
notificacoes = new Notificacoes("OCUPADO", new Date(), "Titulo OCUPADO", NotificacoesStatus.NAOLIDO, 10,8);
break;
case INDISPONIVEL:
Jogo jogoa = jogoService.findJogoById(user.getId());
// jogoService.updateStatus(Status.INDISPONIVEL,user.getId());
jogoa.setStatus(Status.INDISPONIVEL);
jogoService.saveUpdateJogo(jogoa);
quadra = quadraService.findAllQuadraById(user.getQuadraId());
userss = userService.findUserById(user.getUser_id());
user.setUsersJogo2(jogoUserService.findJogoUserByJogoId(user.getId()));
for (UserJogo2 userJogo2 : user.getUsersJogo2()) {
if(Admin.SIM.equals(userJogo2.getAdmin())) {
noticicacaoText = "Foi Aprovado na quadra : " + quadra.getNome() + " dia: " +jogoa.getDia().name().toLowerCase() + " horario (" + jogoa.getHoraInicial() + " - " + jogoa.getHoraFinal() + "). " + "Aprovado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 0,0);
notificacoes.setParaJogoId(jogoa.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
}
// notificacoes = new Notificacoes("INDISPONIVEL", new Date(), "Titulo INDISPONIVEL", NotificacoesStatus.NAOLIDO, 10,8);
// notificacoes.setParaJogoId(user.getId());
break;
case CONFIRMAR:
jogoService.saveUpdateJogo(user);
notificacoes = new Notificacoes("CONFIRMAR", new Date(), "Titulo CONFIRMAR", NotificacoesStatus.NAOLIDO, 10,8);
break;
case DESMARCAR:
notificacoes = new Notificacoes("DESMARCAR", new Date(), "Titulo DESMARCAR", NotificacoesStatus.NAOLIDO, 10,8);
break;
case SOLICITAR:
List<UserJogo2> userJogos1 = new ArrayList<UserJogo2>();
userJogos1.add(new UserJogo2(user.getUser_id(),user.getId(),StatusUser.SOLICITADO,Admin.NAO));
jogoUserService.saveUserJogo(userJogos1);
notificacoes = new Notificacoes("SOLICITAR", new Date(), "Titulo SOLICITAR", NotificacoesStatus.NAOLIDO, 10,8);
break;
default:
break;
}
notificacoesService.insertNotificacoes(notificacoes);
HashMap<String, Object> authResp = new HashMap<String, Object>();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object token = auth.getCredentials();
authResp.put("token", token);
authResp.put("user", user);
authResp.put("Error", erros);
return APIResponse.toOkResponse(authResp);
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/jogo/updateJogoPorData", method = RequestMethod.POST)
public @ResponseBody APIResponse updateJogoPorData(@RequestBody String users)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
JogoPorData user = mapper.readValue(users, JogoPorData.class);
ModelAndView modelAndView = new ModelAndView();
List<String> erros = new ArrayList<String>();
Jogo jogo = jogoService.findJogoById(user.getJogoId());
Quadra quadra = quadraService.findAllQuadraById(jogo.getQuadraId());
User userss = userService.findUserById(user.getUser_id());
String noticicacaoText = "";
Notificacoes notificacoes = new Notificacoes();
switch (user.getStatus()) {
case CONFIRMADO:
jogoService.saveJogoPorData(user);
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
noticicacaoText = userss.getEmail() + " " + userss.getLastName() +" foi aprovado e participara do racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + ")." + "Solicitado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
noticicacaoText = "Parabens foi APROVADA sua solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Solicitado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("TALVEZ", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogoId());
//notificacoes = new Notificacoes("CONFIRMADO", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
break;
case NAOVO:
jogoService.saveJogoPorData(user);
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
if(Admin.SIM.equals(userJogo2.getAdmin())) {
noticicacaoText = "Foi Recusado solicitação de "+ userss.getEmail() + " " + userss.getLastName() +" na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Solicitado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
}
noticicacaoText = "Infelizmente solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Não foi aprovado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("TALVEZ", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogoId());
break;
case TALVEZ:
jogoService.saveJogoPorData(user);
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
if(Admin.SIM.equals(userJogo2.getAdmin())) {
noticicacaoText = "Foi Recusado solicitação de "+ userss.getEmail() + " " + userss.getLastName() +" na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Solicitado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
}
noticicacaoText = "Infelizmente solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Não foi aprovado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("TALVEZ", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogoId());
break;
default:
break;
}
notificacoesService.insertNotificacoes(notificacoes);
HashMap<String, Object> authResp = new HashMap<String, Object>();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object token = auth.getCredentials();
authResp.put("token", token);
authResp.put("user", user);
authResp.put("Error", erros);
return APIResponse.toOkResponse(authResp);
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/jogo/aprovarJogador", method = RequestMethod.POST)
public @ResponseBody APIResponse aprovarJogador(@RequestBody String users)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
UserJogo2 user = mapper.readValue(users, UserJogo2.class);
ModelAndView modelAndView = new ModelAndView();
List<String> erros = new ArrayList<String>();
Jogo jogo = jogoService.findJogoById(user.getJogo_id());
Quadra quadra = quadraService.findAllQuadraById(jogo.getQuadraId());
User userss = userService.findUserById(user.getUser_id());
User userAprov = userService.findUserById(user.getAprovadoPor());
String noticicacaoText = "";
Notificacoes notificacoes = new Notificacoes();
switch (user.getStatus_user()) {
case CONFIRMADO:
jogoUserService.saveUserJogo(Arrays.asList(user));
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
noticicacaoText = userss.getEmail() + " " + userss.getLastName() +" foi aprovado e participara do racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + ")." + "Aprovado por : " + userAprov.getEmail() + " " + userAprov.getLastName();
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
noticicacaoText = "Parabens foi APROVADA sua solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Aprovado por : " + userAprov.getEmail() + " " + userAprov.getLastName();
notificacoes = new Notificacoes("TALVEZ", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
//notificacoes = new Notificacoes("CONFIRMADO", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
break;
case RECUSADO:
jogoUserService.saveUserJogo(Arrays.asList(user));
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
if(Admin.SIM.equals(userJogo2.getAdmin())) {
noticicacaoText = "Foi Recusado solicitação de "+ userss.getEmail() + " " + userss.getLastName() +" na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Recusado por : " + userAprov.getEmail() + " " + userAprov.getLastName();
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
}
noticicacaoText = "Infelizmente solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Não foi aprovado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("TALVEZ", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
break;
default:
break;
}
user.setAprovadoDate(new Date());
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(user.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
HashMap<String, Object> authResp = new HashMap<String, Object>();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object token = auth.getCredentials();
authResp.put("token", token);
authResp.put("user", user);
authResp.put("Error", erros);
return APIResponse.toOkResponse(authResp);
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/jogo/insertUserJogo", method = RequestMethod.POST)
public @ResponseBody APIResponse insertJogoPorData(@RequestBody String users)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
UserJogo2 user = mapper.readValue(users, UserJogo2.class);
ModelAndView modelAndView = new ModelAndView();
List<String> erros = new ArrayList<String>();
Jogo jogo = jogoService.findJogoById(user.getJogo_id());
Quadra quadra = quadraService.findAllQuadraById(jogo.getQuadraId());
User userss = userService.findUserById(user.getUser_id());
Notificacoes notificacoes = new Notificacoes();
String noticicacaoText = "";
switch (user.getStatus_user()) {
case CONFIRMADO:
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
noticicacaoText = userss.getEmail() + " " + userss.getLastName() +" foi aprovado e participara do racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). ";
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
noticicacaoText = "Parabens foi APROVADA sua solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Aprovado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("TALVEZ", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
//notificacoes = new Notificacoes("CONFIRMADO", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
break;
case SOLICITADO:
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
if(Admin.SIM.equals(userJogo2.getAdmin())) {
noticicacaoText = "Tem uma nova solicitação("+ userss.getEmail() + " " + userss.getLastName() +") para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). ";
notificacoes = new Notificacoes("SOLICITADO", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
}
noticicacaoText = "Sua solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "foi enviado para o administrador do racha ";
notificacoes = new Notificacoes("SOLICITADO", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
break;
case RECUSADO:
for (UserJogo2 userJogo2 : jogo.getUsersJogo2()) {
if(Admin.SIM.equals(userJogo2.getAdmin())) {
noticicacaoText = "Foi Aprovado na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Aprovado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("INDISPONIVEL", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, 10,8);
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(userJogo2.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
}
}
noticicacaoText = "Infelizmente solicitação para o racha na quadra : " + quadra.getNome() + " dia: " +jogo.getDia().name().toLowerCase() + " horario (" + jogo.getHoraInicial() + " - " + jogo.getHoraFinal() + "). " + "Não foi aprovado por : " + userss.getEmail() + " " + userss.getLastName();
notificacoes = new Notificacoes("TALVEZ", new Date(), noticicacaoText, NotificacoesStatus.NAOLIDO, user.getUser_id(),user.getJogo_id());
break;
default:
break;
}
user.setAprovadoDate(new Date());
notificacoes.setParaJogoId(jogo.getId());
notificacoes.setParaUserId(user.getUser_id());
notificacoesService.insertNotificacoes(notificacoes);
jogoUserService.saveUserJogo(Arrays.asList(user));
HashMap<String, Object> authResp = new HashMap<String, Object>();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object token = auth.getCredentials();
authResp.put("token", token);
authResp.put("userJogo", user);
authResp.put("Error", erros);
return APIResponse.toOkResponse(authResp);
}
@CrossOrigin(origins = "*")
@RequestMapping(value = "/jogo/createNovo", method = RequestMethod.POST)
public @ResponseBody APIResponse createNovo(@RequestBody String jog)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
// Jogo user = mapper.readValue(jog, Jogo.class);
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm"); // você pode usar outras máscaras
Jogo jogo = jogoService.findJogoById(Integer.parseInt(jog));
List<JogoPorData> jogosData = new ArrayList<JogoPorData>();
for (UserJogo2 user : jogo.getUsersJogo2()) {
if(user.getStatus_user().equals(StatusUser.CONFIRMADO))
{
GregorianCalendar gc = new GregorianCalendar();
jogosData.add(new JogoPorData(shouldDownloadFile2(jogo.getDia(),gc,jogo.getHoraInicial()).getTime(),shouldDownloadFile2(jogo.getDia(),gc,jogo.getHoraFinal()).getTime(), jogo.getId(), user.getUser_id(), StatusJogoPorData.ACONFIRMAR, 0, 0,
jogo.getQuadraId()));
}
}
// List<Jogo> jogos = jogoService.findAllJogo();
// List<JogoPorData> jogosData = new ArrayList<JogoPorData>();
// for (Jogo jogo : jogos) {
// System.out.println(jogo.getStatus());
// if(jogo.getStatus().equals(Status.INDISPONIVEL))
// {
// for (UserJogo2 user : jogo.getUsersJogo2()) {
// if(user.getStatus_user().equals(StatusUser.CONFIRMADO))
// {
// GregorianCalendar gc = new GregorianCalendar();
// jogosData.add(new JogoPorData(shouldDownloadFile2(jogo.getDia(),gc,jogo.getHoraInicial()).getTime(),shouldDownloadFile2(jogo.getDia(),gc,jogo.getHoraFinal()).getTime(), jogo.getId(), user.getUser_id(), StatusJogoPorData.ACONFIRMAR, 0, 0,
// jogo.getQuadraId()));
// }
// }
// }
// }
jogoService.saveJogoPorData(jogosData);
HashMap<String, Object> authResp = new HashMap<String, Object>();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object token = auth.getCredentials();
authResp.put("token", token);
authResp.put("jogo", jogo);
authResp.put("Error", "");
return APIResponse.toOkResponse(authResp);
}
//
// //@CrossOrigin(origins = "*")
// @RequestMapping(value = "/raxa/delete", method = RequestMethod.POST)
// public @ResponseBody APIResponse deleteMensagem(@Valid User user,
// BindingResult bindingResult) {
// ModelAndView modelAndView = new ModelAndView();
// List<String> erros = new ArrayList<String>();
// User userExists = userService.findUserByEmail(user.getEmail());
// if (userExists != null) {
// erros.add("There is already a user registered with the email provided");
// }
//
// userService.saveUser(user);
// modelAndView.addObject("successMessage", "User has been registered
// successfully");
// modelAndView.addObject("user", new User());
// modelAndView.setViewName("registration");
//
//
// HashMap<String, Object> authResp = new HashMap<String, Object>();
// Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//
// Object token = auth.getCredentials();
// authResp.put("token", token);
// authResp.put("user", user);
// authResp.put("Error", erros);
//
//
// return APIResponse.toOkResponse(authResp);
// }
//
// //@CrossOrigin(origins = "*")
// @RequestMapping(value = "/raxa/fetchByUser", method = RequestMethod.POST)
// public @ResponseBody APIResponse fetchByUser(@Valid User user, BindingResult
// bindingResult) {
// ModelAndView modelAndView = new ModelAndView();
// List<String> erros = new ArrayList<String>();
// User userExists = userService.findUserByEmail(user.getEmail());
// if (userExists != null) {
// erros.add("There is already a user registered with the email provided");
// }
//
// userService.saveUser(user);
// modelAndView.addObject("successMessage", "User has been registered
// successfully");
// modelAndView.addObject("user", new User());
// modelAndView.setViewName("registration");
//
//
// HashMap<String, Object> authResp = new HashMap<String, Object>();
// Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//
// Object token = auth.getCredentials();
// authResp.put("token", token);
// authResp.put("user", user);
// authResp.put("Error", erros);
//
//
// return APIResponse.toOkResponse(authResp);
// }
//
// private void createAuthResponse(User user, HashMap<String, Object>
// authResp,ArrayList<String> erros) {
// String token = "";
// //Jwts.builder().setSubject(user.getEmail())
// // .claim("role", user.getRole().name()).setIssuedAt(new Date())
// // .signWith(SignatureAlgorithm.HS256, JWTTokenAuthFilter.JWT_KEY).compact();
// authResp.put("token", token);
// authResp.put("user", user);
// authResp.put("Error", erros);
// }
@CrossOrigin(origins = "*")
@RequestMapping(value = "/jogo/findJogoByUser", method = RequestMethod.POST)
public ResponseEntity<List<Jogo>> findAllQuadraById(@RequestBody String users)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(users, User.class);
List<Jogo> quadra = jogoService.findJogoByUser(user);
return new ResponseEntity<List<Jogo>>(quadra, HttpStatus.OK);
}
public GregorianCalendar shouldDownloadFile2(Dias dia,GregorianCalendar gc,String hInc)
{
Integer a= 0;
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == gc.SUNDAY) {
switch (dia) {
case DOMINGO:
a = 0;
break;
case SEGUNDA:
a = 1;
break;
case TERCA:
a = 2;
break;
case QUARTA:
a = 3;
break;
case QUINTA:
a = 4;
break;
case SEXTA:
a = 5;
break;
case SABADO:
a = 6;
break;
}
}else
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == gc.MONDAY) {
switch (dia) {
case DOMINGO:
a = 6;
break;
case SEGUNDA:
a = 0;
break;
case TERCA:
a = 1;
break;
case QUARTA:
a = 2;
break;
case QUINTA:
a = 3;
break;
case SEXTA:
a = 4;
break;
case SABADO:
a = 5;
break;
}
}else
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == gc.TUESDAY) {
switch (dia) {
case DOMINGO:
a = 5;
break;
case SEGUNDA:
a = 6;
break;
case TERCA:
a = 0;
break;
case QUARTA:
a = 1;
break;
case QUINTA:
a = 2;
break;
case SEXTA:
a = 3;
break;
case SABADO:
a = 4;
break;
}
}else
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == gc.WEDNESDAY) {
switch (dia) {
case DOMINGO:
a = 4;
break;
case SEGUNDA:
a = 5;
break;
case TERCA:
a = 6;
break;
case QUARTA:
a = 0;
break;
case QUINTA:
a = 1;
break;
case SEXTA:
a = 2;
break;
case SABADO:
a = 3;
break;
}
}else
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == gc.THURSDAY) {
switch (dia) {
case DOMINGO:
a = 3;
break;
case SEGUNDA:
a = 4;
break;
case TERCA:
a = 5;
break;
case QUARTA:
a = 6;
break;
case QUINTA:
a = 0;
break;
case SEXTA:
a = 1;
break;
case SABADO:
a = 2;
break;
}
}else
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == gc.FRIDAY) {
switch (dia) {
case DOMINGO:
a = 2;
break;
case SEGUNDA:
a = 3;
break;
case TERCA:
a = 4;
break;
case QUARTA:
a = 5;
break;
case QUINTA:
a = 6;
break;
case SEXTA:
a = 1;
break;
case SABADO:
a = 2;
break;
}
}else
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == gc.SATURDAY) {
switch (dia) {
case DOMINGO:
a = 1;
break;
case SEGUNDA:
a = 2;
break;
case TERCA:
a = 3;
break;
case QUARTA:
a = 4;
break;
case QUINTA:
a = 5;
break;
case SEXTA:
a = 6;
break;
case SABADO:
a = 7;
break;
}
}
gc.add(gc.DATE, a);
String[] rabbitmqUserInfo = hInc.split(":");
gc.set(GregorianCalendar.HOUR_OF_DAY,Integer.parseInt(rabbitmqUserInfo[0]));
gc.set(GregorianCalendar.MINUTE,Integer.parseInt(rabbitmqUserInfo[1]));
//gc.add(gc.HOUR, Integer.parseInt(rabbitmqUserInfo[0]));
// gc.add(gc.MINUTE, Integer.parseInt(rabbitmqUserInfo[0]));
return gc;
}
}
| 42.246334 | 340 | 0.700715 |
7e13096d923125a401efeb6295ab487a32072301 | 360 | package com.atguigu.gmall.wms.dao;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品库存
*
* @author zhangkai
* @email [email protected]
* @date 2019-10-28 22:34:33
*/
@Mapper
public interface WareSkuDao extends BaseMapper<WareSkuEntity> {
}
| 20 | 63 | 0.755556 |
1d8b35342f5be1c535df7496b44ba057959e8431 | 215 | package ch.the.force.server;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
@Data
@AllArgsConstructor
public class Event {
private final Long id;
private final Date when;
}
| 14.333333 | 33 | 0.75814 |
f42971f555daee055bb02ba54a8592a07c12abc0 | 387 | package com.gb.ir;
public class Constant {
private static final String MESSAGE_HEAD = "=====MessageHead=====";
public static final byte[] MESSAGE_HEAD_BYTES = MESSAGE_HEAD.getBytes();
private static final String MESSAGE_END = "=====MessageEND=====";
public static final byte[] MESSAGE_END_BYTES = MESSAGE_END.getBytes();
public static int BUFFER_BYTE_SIZE = 1024;
}
| 38.7 | 76 | 0.713178 |
abf052001ea2ad4a537a4cbced44528cb57cf15f | 2,084 | package me.gookven.swingx.generictable;
import me.gookven.swingx.generictable.api.ColumnDescriptor;
import me.gookven.swingx.generictable.api.ColumnDescriptorFactory;
import me.gookven.swingx.generictable.api.GenericTableColumn;
import java.beans.PropertyDescriptor;
public class DefaultColumnDescriptorFactory implements ColumnDescriptorFactory {
@Override
public ColumnDescriptor createColumnDescriptor(PropertyDescriptor property) {
GenericTableColumn column = property.getReadMethod().getAnnotation(GenericTableColumn.class);
if (column == null) {
return new DefaultColumnDescriptor(
capitalize(property.getDisplayName()),
property.getReadMethod() != null,
property.getWriteMethod() != null
);
}
return new DefaultColumnDescriptor(
column.value().length() > 0 ? column.value() : capitalize(property.getDisplayName()),
column.visible(),
column.editable()
);
}
private String capitalize(String string) {
if (isEmpty(string)) {
return string;
}
return string.substring(0, 1).toUpperCase() + string.substring(1);
}
private boolean isEmpty(String string) {
return string == null || string.length() == 0;
}
private static class DefaultColumnDescriptor implements ColumnDescriptor {
private final String displayName;
private final boolean visible;
private final boolean editable;
private DefaultColumnDescriptor(String displayName, boolean visible, boolean editable) {
this.displayName = displayName;
this.visible = visible;
this.editable = editable;
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public boolean isVisible() {
return visible;
}
@Override
public boolean isEditable() {
return editable;
}
}
}
| 30.647059 | 101 | 0.630518 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.