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
|
---|---|---|---|---|---|
9ad19f8e79c85419409460c1fe2b7d22b6acd3f5 | 1,448 | package com.androidstarterkit.tool;
import com.androidstarterkit.android.api.resource.ResourceType;
import com.androidstarterkit.android.api.resource.ValueType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class ResourceMatcher {
private final Matcher matcher;
public interface Handler {
void handle(String type, String name);
}
public ResourceMatcher(String input, MatchType matchType) {
this.matcher = matchType.getMatchPattern().matcher(input);
}
public void match(Handler handler) {
matcher.reset();
while (matcher.find()) {
handler.handle(matcher.group(1), matcher.group(2));
}
}
public enum MatchType {
RES_FILE_IN_JAVA("R.("
+ ResourceType.LAYOUT
+ "|" + ResourceType.MENU
+ "|" + ResourceType.DRAWABLE
+ ").([\\w_]*)"),
RES_VALUE_IN_JAVA("R.("
+ ValueType.STRING
+ "|" + ValueType.DIMEN
+ ").([\\w_.]*)"),
RES_FILE_IN_XML("@("
+ ResourceType.LAYOUT
+ "|" + ResourceType.MENU
+ "|" + ResourceType.DRAWABLE
+ ")/([\\w_]*)"),
RES_VALUE_IN_XML("@("
+ ValueType.STYLE
+ "|" + ValueType.DIMEN
+ "|" + ValueType.STRING
+ ")/([\\w_.]*)");
private Pattern matchPattern;
MatchType(String regex) {
this.matchPattern = Pattern.compile(regex);
}
public Pattern getMatchPattern() {
return matchPattern;
}
}
}
| 22.984127 | 63 | 0.609807 |
a75a628cc9d8cf4f7edd2f1f9559e687710260e8 | 4,916 | package com.tinkerpop.gremlin.driver;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import com.tinkerpop.gremlin.util.StreamFactory;
import io.netty.channel.Channel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* A {@code ResultSet} is returned from the submission of a Gremlin script to the server and represents the
* results provided by the server. The results from the server are streamed into the {@code ResultSet} and
* therefore may not be available immediately. As such, {@code ResultSet} provides access to a a number
* of functions that help to work with the asynchronous nature of the data streaming back. Data from results
* is stored in an {@link Result} which can be used to retrieve the item once it is on the client side.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class ResultSet implements Iterable<Result> {
private final ResponseQueue responseQueue;
private final ExecutorService executor;
private final Channel channel;
private final Supplier<Void> onChannelError;
public ResultSet(final ResponseQueue responseQueue, final ExecutorService executor,
final Channel channel, final Supplier<Void> onChannelError) {
this.executor = executor;
this.responseQueue = responseQueue;
this.channel = channel;
this.onChannelError = onChannelError;
}
/**
* Determines if all items have been returned to the client.
*/
public boolean allItemsAvailable() {
return responseQueue.getStatus() == ResponseQueue.Status.COMPLETE;
}
/**
* Gets the number of items available on the client.
*/
public int getAvailableItemCount() {
return responseQueue.size();
}
/**
* Determines if there are any remaining items being streamed to the client.
*/
public boolean isExhausted() {
if (!responseQueue.isEmpty())
return false;
awaitItems(1).join();
assert !responseQueue.isEmpty() || allItemsAvailable();
return responseQueue.isEmpty();
}
/**
* Get the next {@link Result} from the stream, blocking until one is available.
*/
public Result one() {
ResponseMessage msg = responseQueue.poll();
if (msg != null)
return new Result(msg);
awaitItems(1).join();
msg = responseQueue.poll();
if (msg != null)
return new Result(msg);
else
return null;
}
/**
* Wait for some number of items to be available on the client. The future will contain the number of items
* available which may or may not be the number the caller was waiting for.
*/
public CompletableFuture<Integer> awaitItems(final int items) {
if (allItemsAvailable())
CompletableFuture.completedFuture(getAvailableItemCount());
return CompletableFuture.supplyAsync(() -> {
while (!allItemsAvailable() && getAvailableItemCount() < items) {
if (!channel.isOpen()) {
onChannelError.get();
throw new RuntimeException("Error while processing results from channel - check client and server logs for more information");
}
try {
// small delay between checks for available items
Thread.sleep(10);
} catch (Exception ex) {
return null;
}
}
return getAvailableItemCount();
}, executor);
}
/**
* Wait for all items to be available on the client exhausting the stream.
*/
public CompletableFuture<List<Result>> all() {
return CompletableFuture.supplyAsync(() -> {
final List<Result> list = new ArrayList<>();
while (!isExhausted()) {
final ResponseMessage msg = responseQueue.poll();
if (msg != null)
list.add(new Result(msg));
}
return list;
}, executor);
}
/**
* Stream items with a blocking iterator.
*/
public Stream<Result> stream() {
return StreamFactory.stream(iterator());
}
@Override
public Iterator<Result> iterator() {
return new Iterator<Result>() {
@Override
public boolean hasNext() {
return !isExhausted();
}
@Override
public Result next() {
return ResultSet.this.one();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
| 32.342105 | 146 | 0.613303 |
a6490ee1154287e7aa997c415fd6808b254641db | 3,680 | package controller.ui.ui.components;
import common.TotalScaleLayout;
import controller.action.ActionBoard;
import controller.ui.localization.LocalizationManager;
import data.Rules;
import data.states.AdvancedData;
import data.values.GameStates;
import data.values.Side;
import javax.swing.*;
/**
* Created by rkessler on 2017-03-29.
*/
public class TeamActions extends AbstractComponent {
private static final int TIMEOUT_HIGHLIGHT_SECONDS = 10;
protected static final String OUT = "Out";
protected static final String STUCK = "Global <br/> Game <br/> Stuck";
protected Side side;
protected JButton timeOut;
protected JButton stuck;
protected JButton out;
protected JPanel container;
public TeamActions(Side side) {
this.side = side;
defineLayout();
}
public void defineLayout() {
container = new JPanel();
container.setVisible(true);
TotalScaleLayout layout = new TotalScaleLayout(container);
container.setLayout(layout);
timeOut = new JButton(LocalizationManager.getLocalization().TAKE_TIMEOUT);
out = new JButton(OUT);
stuck = new JButton(STUCK);
layout.add(0, 0, 0.33, 1, timeOut);
layout.add(0.33, 0, 0.33, 1, out);
layout.add(0.66, 0, 0.34, 1, stuck);
out.setVisible(false);
stuck.setVisible(false);
timeOut.setVisible(false);
timeOut.setVisible(true);
out.setVisible(true);
timeOut.addActionListener(ActionBoard.timeOut[side.value()]);
out.addActionListener(ActionBoard.out[side.value()]);
this.setLayout(new TotalScaleLayout(this));
((TotalScaleLayout) this.getLayout()).add(0, 0, 1, 1, container);
this.setVisible(true);
}
@Override
public void update(AdvancedData data) {
updateTimeOut(data);
if (out != null) {
updateOut(data);
}
}
/**
* Updates the time-out.
*
* @param data The current data (model) the GUI should view.
*/
protected void updateTimeOut(AdvancedData data) {
if (data.timeOutActive[side.value()]) {
timeOut.setText(LocalizationManager.getLocalization().END_TIMEOUT);
} else {
timeOut.setText(LocalizationManager.getLocalization().TAKE_TIMEOUT);
}
if (!data.timeOutActive[side.value()]) {
timeOut.setSelected(false);
resetHighlighting(timeOut);
} else {
if (data.isSecondaryClockLowerThan(TIMEOUT_HIGHLIGHT_SECONDS)) {
highlight(timeOut);
}
}
timeOut.setEnabled(ActionBoard.timeOut[side.value()].isLegal(data));
}
/**
* Updates the global game stuck.
*
* @param data The current data (model) the GUI should view.
*/
protected void updateGlobalStuck(AdvancedData data) {
if (data.gameState == GameStates.PLAYING
&& data.getRemainingSeconds(data.whenCurrentGameStateBegan, Rules.league.kickoffTime + Rules.league.minDurationBeforeStuck) > 0) {
stuck.setEnabled(false);
stuck.setText("<font color=#808080>" + STUCK);
} else {
stuck.setEnabled(ActionBoard.stuck[side.value()].isLegal(data));
stuck.setText((ActionBoard.stuck[side.value()].isLegal(data) ? "<font color=#000000>" : "<font color=#808080>") + STUCK);
}
}
/**
* Updates the out.
*
* @param data The current data (model) the GUI should view.
*/
protected void updateOut(AdvancedData data) {
out.setEnabled(ActionBoard.out[side.value()].isLegal(data));
}
}
| 28.091603 | 146 | 0.630163 |
3efb5ae04a685301bcb50590608f77099f8a2fb8 | 1,206 | //package com.example.demo;
//
//import org.apache.juli.logging.Log;
//import org.apache.juli.logging.LogFactory;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.springframework.stereotype.Component;
//
//import java.time.LocalDateTime;
//
//@Component
//@Aspect
//public class LoggingAroundAspect {
// private Log log = LogFactory.getLog(getClass());
//
// @Around("execution(* com.example.demo.CustomerService.*(..))")
// public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
// LocalDateTime start = LocalDateTime.now();
// Throwable toThrow = null;
// Object returnValue = null;
//
// try {
// returnValue = joinPoint.proceed();
// } catch (Throwable t) {
// toThrow = t;
// }
//
// LocalDateTime stop = LocalDateTime.now();
// log.info("Starting @ " + start.toString());
// log.info("Finishing @ " + stop.toString() + " with duration " + stop.minusNanos(start.getNano()).getNano());
//
// if (null != toThrow)
// throw toThrow;
//
// return returnValue;
// }
//}
| 30.923077 | 118 | 0.626036 |
a69caa4fa28690abcb3594fbcfff48e4d224a843 | 1,823 | package marubinotto.piggydb.impl.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import marubinotto.piggydb.model.entity.RawEntityFactory;
import marubinotto.piggydb.model.entity.RawTag;
import marubinotto.piggydb.model.exception.BaseDataObsoleteException;
import marubinotto.util.Assert;
import org.springframework.jdbc.core.JdbcTemplate;
public class TagRowMapper extends EntityRowMapper<RawTag> {
private static final EntityTable TABLE =
new EntityTable("tag", "tag_id")
.defColumn("tag_name")
.defColumn("fragment_id");
private static Object[] toValues(RawTag tag) {
return new Object[]{
tag.getName(),
tag.getFragmentId()
};
}
public static void insert(RawTag tag, JdbcTemplate jdbcTemplate) {
Assert.Arg.notNull(tag, "tag");
Assert.Arg.notNull(jdbcTemplate, "jdbcTemplate");
TABLE.insert(tag, toValues(tag), jdbcTemplate);
}
public static void update(RawTag tag, JdbcTemplate jdbcTemplate)
throws BaseDataObsoleteException {
Assert.Arg.notNull(tag, "tag");
Assert.Arg.notNull(jdbcTemplate, "jdbcTemplate");
TABLE.update(tag, toValues(tag), true, jdbcTemplate);
}
public TagRowMapper(RawEntityFactory<RawTag> factory, String prefix) {
super(factory, prefix);
}
@Override
protected EntityTable getEntityTable() {
return TABLE;
}
public RawTag mapRow(ResultSet rs, int rowNum) throws SQLException {
RawTag tag = createEntityWithCommonColumns(rs);
// ResultSet.getLong
// if the value is SQL NULL, the value returned is 0
Iterator<String> columns = properColumns();
tag.setName(rs.getString(columns.next()));
Long fragmentId = rs.getLong(columns.next());
if (fragmentId != 0) tag.setFragmentId(fragmentId);
return tag;
}
} | 27.621212 | 72 | 0.725727 |
f527987d1e6d03f1e2a4e9622a98be9e0fa69225 | 1,623 | package com.duy.imageoverlay.views;
import android.graphics.Bitmap;
import java.nio.ByteBuffer;
/**
* Created by Duy on 19-Feb-17.
*/
public class ImageUtils {
public static byte[] bitmapToByteArray(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
return byteBuffer.array();
}
public static Bitmap createBlackAndWhite(Bitmap src) {
int width = src.getWidth();
int height = src.getHeight();
Bitmap bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final float factor = 255f;
final float redBri = 0.2126f;
final float greenBri = 0.2126f;
final float blueBri = 0.0722f;
int length = width * height;
int[] inpixels = new int[length];
int[] oupixels = new int[length];
src.getPixels(inpixels, 0, width, 0, 0, width, height);
int point = 0;
for(int pix: inpixels){
int R = (pix >> 16) & 0xFF;
int G = (pix >> 8) & 0xFF;
int B = pix & 0xFF;
float lum = (redBri * R / factor) + (greenBri * G / factor) + (blueBri * B / factor);
if (lum > 0.4) {
oupixels[point] = 0xFFFFFFFF;
}else{
oupixels[point] = 0xFF000000;
}
point++;
}
bmOut.setPixels(oupixels, 0, width, 0, 0, width, height);
return bmOut;
}
}
| 27.982759 | 97 | 0.564387 |
f70be66076190df05a980e5b1123e7ee6410ae14 | 634 | package net.neoremind.fountain.producer.dispatch.misc;
import java.util.Iterator;
/**
* 只有一个元素的迭代器
*
* @author hexiufeng
*/
public class SingleIterator implements Iterator<Object> {
private int count = 1;
private final Object message;
/**
* 构造器
*
* @param message 消息
*/
public SingleIterator(Object message) {
this.message = message;
}
@Override
public boolean hasNext() {
return count > 0;
}
@Override
public Object next() {
count--;
return message;
}
@Override
public void remove() {
// don't support
}
}
| 15.85 | 57 | 0.582019 |
20865e09e68a0ac06084736b35c2739e0c65f4b6 | 3,907 | package xreliquary.items;
import net.minecraft.block.Blocks;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.FireballEntity;
import net.minecraft.entity.projectile.SmallFireballEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Rarity;
import net.minecraft.particles.RedstoneParticleData;
import net.minecraft.util.DamageSource;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import xreliquary.util.RandHelper;
import java.util.List;
public class SalamanderEyeItem extends ItemBase {
public SalamanderEyeItem() {
super("salamander_eye", new Properties().maxStackSize(1));
}
@Override
public Rarity getRarity(ItemStack stack) {
return Rarity.EPIC;
}
@Override
@OnlyIn(Dist.CLIENT)
public boolean hasEffect(ItemStack stack) {
return true;
}
@Override
public void inventoryTick(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected) {
if(world.isRemote || !(entity instanceof PlayerEntity)) {
return;
}
PlayerEntity player = (PlayerEntity) entity;
if(player.getHeldItem(Hand.MAIN_HAND).getItem() == this || player.getHeldItem(Hand.OFF_HAND).getItem() == this) {
doFireballEffect(player);
doExtinguishEffect(player);
}
}
private void doExtinguishEffect(PlayerEntity player) {
if(player.isBurning()) {
player.extinguish();
}
int x = (int) Math.floor(player.getPosX());
int y = (int) Math.floor(player.getPosY());
int z = (int) Math.floor(player.getPosZ());
for(int xOff = -3; xOff <= 3; xOff++) {
for(int yOff = -3; yOff <= 3; yOff++) {
for(int zOff = -3; zOff <= 3; zOff++) {
if(player.world.getBlockState(new BlockPos(x + xOff, y + yOff, z + zOff)).getBlock() == Blocks.FIRE) {
player.world.setBlockState(new BlockPos(x + xOff, y + yOff, z + zOff), Blocks.AIR.getDefaultState());
player.world.playSound(x + xOff + 0.5D, y + yOff + 0.5D, z + zOff + 0.5D, SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.NEUTRAL, 0.5F, 2.6F + RandHelper.getRandomMinusOneToOne(player.world.rand) * 0.8F, false);
}
}
}
}
}
private void doFireballEffect(PlayerEntity player) {
List<FireballEntity> ghastFireballs = player.world.getEntitiesWithinAABB(FireballEntity.class, new AxisAlignedBB(player.getPosX() - 5, player.getPosY() - 5, player.getPosZ() - 5, player.getPosX() + 5, player.getPosY() + 5, player.getPosZ() + 5));
for(FireballEntity fireball : ghastFireballs) {
if(player.getDistance(fireball) < 4) {
fireball.remove();
}
fireball.attackEntityFrom(DamageSource.causePlayerDamage(player), 1);
player.world.playSound(fireball.getPosX(), fireball.getPosY(), fireball.getPosZ(), SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.NEUTRAL, 0.5F, 2.6F + RandHelper.getRandomMinusOneToOne(player.world.rand) * 0.8F, false);
}
List<SmallFireballEntity> blazeFireballs = player.world.getEntitiesWithinAABB(SmallFireballEntity.class, new AxisAlignedBB(player.getPosX() - 3, player.getPosY() - 3, player.getPosZ() - 3, player.getPosX() + 3, player.getPosY() + 3, player.getPosZ() + 3));
for(SmallFireballEntity fireball : blazeFireballs) {
for(int particles = 0; particles < 4; particles++) {
player.world.addParticle(RedstoneParticleData.REDSTONE_DUST, fireball.getPosX(), fireball.getPosY(), fireball.getPosZ(), 0.0D, 1.0D, 1.0D);
}
player.world.playSound(fireball.getPosX(), fireball.getPosY(), fireball.getPosZ(), SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.NEUTRAL, 0.5F, 2.6F + RandHelper.getRandomMinusOneToOne(player.world.rand) * 0.8F, false);
fireball.remove();
}
}
}
| 42.467391 | 258 | 0.738674 |
56fad7a7245ebe0b7a917813c3755a32b8b8e176 | 6,766 | /******************************************************************************
* Copyright (C) 2019 by the ARA Contributors *
* *
* 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.decathlon.ara.domain;
import com.decathlon.ara.domain.enumeration.Handling;
import com.querydsl.core.annotations.QueryInit;
import lombok.*;
import org.hibernate.annotations.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
import static java.util.Comparator.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@With
@Entity
// Keep business key in sync with compareTo(): see https://developer.jboss.org/wiki/EqualsAndHashCode
@EqualsAndHashCode(of = { "runId", "featureFile", "name", "line" })
@Table(indexes = @Index(columnList = "run_id"))
public class ExecutedScenario implements Comparable<ExecutedScenario>, Serializable {
public static final int CUCUMBER_ID_MAX_SIZE = 640;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "executed_scenario_id")
@SequenceGenerator(name = "executed_scenario_id", sequenceName = "executed_scenario_id", allocationSize = 1)
private Long id;
// 1/2 for @EqualsAndHashCode to work: used when an entity is fetched by JPA
@Column(name = "run_id", insertable = false, updatable = false)
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private Long runId;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "run_id")
@QueryInit("*.*") // Requires Q* class regeneration https://github.com/querydsl/querydsl/issues/255
private Run run;
private String featureFile;
private String featureName;
private String featureTags;
private String tags;
@Column(length = 32)
private String severity;
@Column(length = 512)
private String name;
@Column(length = 640)
private String cucumberId;
private int line;
@Lob
@org.hibernate.annotations.Type(type = "org.hibernate.type.TextType")
private String content;
@Column(name = "start_date_time")
@Temporal(TemporalType.TIMESTAMP)
private Date startDateTime;
@Column(length = 512)
private String screenshotUrl;
@Column(length = 512)
private String videoUrl;
@Column(length = 512)
private String logsUrl;
@Column(length = 512)
private String httpRequestsUrl;
@Column(length = 512)
private String javaScriptErrorsUrl;
@Column(length = 512)
private String diffReportUrl;
@Column(length = 512)
private String cucumberReportUrl;
@Column(length = 16)
private String apiServer;
@Column(length = 128)
private String seleniumNode;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "executedScenario", orphanRemoval = true)
@OnDelete(action = OnDeleteAction.CASCADE)
@SortNatural
@Fetch(FetchMode.SUBSELECT)
private Set<Error> errors = new TreeSet<>();
// 2/2 for @EqualsAndHashCode to work: used for entities created outside of JPA
public void setRun(Run run) {
this.run = run;
this.runId = (run == null ? null : run.getId());
}
public void addError(Error error) {
// Set the child-entity's foreign-key BEFORE adding the child-entity to the TreeSet,
// as the foreign-key is required to place the child-entity in the right order (with child-entity's compareTo)
// and is required not to change while the child-entity is in the TreeSet
error.setExecutedScenario(this);
this.errors.add(error);
}
public void addErrors(Iterable<? extends Error> errorsToAdd) {
for (Error error : errorsToAdd) {
addError(error);
}
}
public void removeError(Error error) {
this.errors.remove(error);
error.setExecutedScenario(null);
}
/**
* @return SUCCESS if the scenario has no error, HANDLED if at least one error has at least one problem that is open
* or did not reappear after closing date, UNHANDLED otherwise (has errors with only open or reappeared problems)
*/
public Handling getHandling() {
if (getErrors().isEmpty()) {
return Handling.SUCCESS;
}
for (Error error : getErrors()) {
for (ProblemOccurrence problemOccurrence : error.getProblemOccurrences()) {
var problemPattern = problemOccurrence.getProblemPattern();
if (problemPattern.getProblem().isHandled()) {
return Handling.HANDLED;
}
}
}
return Handling.UNHANDLED;
}
@Override
public int compareTo(ExecutedScenario other) {
// Keep business key in sync with @EqualsAndHashCode
Comparator<ExecutedScenario> runIdComparator = comparing(e -> e.runId, nullsFirst(naturalOrder()));
Comparator<ExecutedScenario> featureFileComparator = comparing(ExecutedScenario::getFeatureFile, nullsFirst(naturalOrder()));
Comparator<ExecutedScenario> nameComparator = comparing(ExecutedScenario::getName, nullsFirst(naturalOrder()));
Comparator<ExecutedScenario> lineComparator = comparing(e -> Long.valueOf(e.getLine()), nullsFirst(naturalOrder()));
return nullsFirst(runIdComparator
.thenComparing(featureFileComparator)
.thenComparing(nameComparator)
.thenComparing(lineComparator)).compare(this, other);
}
}
| 36.376344 | 133 | 0.625185 |
c77faba335b3a3d6bd681666c733ab0e77b6f244 | 1,600 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([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 org.jkiss.dbeaver.ui.editors.sql.log;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.jkiss.dbeaver.ui.controls.querylog.QueryLogViewer;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditor;
/**
* ResultSetViewer
*/
public class SQLLogPanel extends Composite
{
private QueryLogViewer queryLogViewer;
public SQLLogPanel(Composite parent, SQLEditor editor)
{
super(parent, SWT.NONE);
GridLayout gl = new GridLayout(1, true);
gl.marginHeight = 0;
gl.marginWidth = 0;
gl.verticalSpacing = 0;
gl.horizontalSpacing = 0;
setLayout(gl);
queryLogViewer = new QueryLogViewer(this, editor.getSite(), new SQLLogFilter(editor), false, true);
}
public QueryLogViewer getQueryLogViewer()
{
return queryLogViewer;
}
} | 32 | 108 | 0.6925 |
421b9ed47e415a445bada03daf938b9cc3a5138c | 1,786 | /*
* MatchFunction.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2020 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apple.foundationdb.record.query.plan.temp.matching;
import com.apple.foundationdb.record.query.plan.temp.AliasMap;
import javax.annotation.Nonnull;
/**
* An functional interface for a match function that computes a match result (an {@link Iterable} of type {@code M}.
*
* @param <T> element type
* @param <M> type of intermediate result
*/
@FunctionalInterface
public interface MatchFunction<T, M> {
/**
* Compute a match result.
* @param element element on this side
* @param otherElement element on the other side
* @param aliasMap bindings that already have been established
* @return an {@link Iterable} of type {@code M}. The matching logic interprets the resulting {@link Iterable}.
* A non-empty {@link Iterable} is considered a successful match attempt; an empty {@link Iterable} is
* considered a failed match attempt.
*/
Iterable<M> apply(@Nonnull T element,
@Nonnull T otherElement,
@Nonnull AliasMap aliasMap);
}
| 37.208333 | 116 | 0.704367 |
2fc34a5151ad9497fd03edf7cb290e04df8619f0 | 1,377 | package fr.insee.arc.batch;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurableEnvironment;
import fr.insee.arc.utils.ressourceUtils.PropertySourcesHelper;
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class BatchConfig {
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(ConfigurableEnvironment env) throws IOException {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
PropertySourcesHelper fetcher = new PropertySourcesHelper();
List<String> expectedPaths = new ArrayList<>();
String propertyPathVar = System.getProperty("properties.path");
if (propertyPathVar != null) {
expectedPaths.add("file:" + propertyPathVar + "/*.properties");
}
expectedPaths.add("classpath*:fr/insee/config/*.properties");
fetcher.configure(configurer, env, expectedPaths.toArray(new String[0]));
configurer.setIgnoreUnresolvablePlaceholders(true);
configurer.setIgnoreResourceNotFound(true);
return configurer;
}
}
| 36.236842 | 131 | 0.818446 |
ce3ad5dd5a9be759e7a01e5c8c6bbf18a30f3492 | 265 | package com.heynchy.baiduocr.resultInterface;
import com.heynchy.baiduocr.event.ResultEvent;
/**
* @author CHY
* Create at 2017/12/12 14:23.
*/
public interface ResultListener {
void onResult(ResultEvent result);
void onError(String error);
}
| 18.928571 | 46 | 0.713208 |
f86f4cf85562fb0ae1d557619b388bd74aa5a307 | 5,131 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.common.collect;
import com.carrotsearch.ant.tasks.junit4.dependencies.com.google.common.collect.ImmutableMap;
import org.elasticsearch.test.ElasticsearchTestCase;
import java.util.HashMap;
import java.util.Map;
public class CopyOnWriteHashMapTests extends ElasticsearchTestCase {
private static class O {
private final int value, hashCode;
O(int value, int hashCode) {
super();
this.value = value;
this.hashCode = hashCode;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof O)) {
return false;
}
return value == ((O) obj).value;
}
}
public void testDuel() {
final int iters = scaledRandomIntBetween(2, 5);
for (int iter = 0; iter < iters; ++iter) {
final int valueBits = randomIntBetween(1, 30);
final int hashBits = randomInt(valueBits);
// we compute the total number of ops based on the bits of the hash
// since the test is much heavier when few bits are used for the hash
final int numOps = randomInt(10 + hashBits * 100);
Map<O, Integer> ref = new HashMap<>();
CopyOnWriteHashMap<O, Integer> map = new CopyOnWriteHashMap<>();
assertEquals(ref, map);
final int hashBase = randomInt();
for (int i = 0; i < numOps; ++i) {
final int v = randomInt(1 << valueBits);
final int h = (v & ((1 << hashBits) - 1)) ^ hashBase;
O key = new O(v, h);
Map<O, Integer> newRef = new HashMap<>(ref);
final CopyOnWriteHashMap<O, Integer> newMap;
if (randomBoolean()) {
// ADD
Integer value = v;
newRef.put(key, value);
newMap = map.copyAndPut(key, value);
} else {
// REMOVE
final Integer removed = newRef.remove(key);
newMap = map.copyAndRemove(key);
if (removed == null) {
assertSame(map, newMap);
}
}
assertEquals(ref, map); // make sure that the old copy has not been modified
assertEquals(newRef, newMap);
assertEquals(newMap, newRef);
ref = newRef;
map = newMap;
}
assertEquals(ref, CopyOnWriteHashMap.copyOf(ref));
assertEquals(ImmutableMap.of(), CopyOnWriteHashMap.copyOf(ref).copyAndRemoveAll(ref.keySet()));
}
}
public void testCollision() {
CopyOnWriteHashMap<O, Integer> map = new CopyOnWriteHashMap<>();
map = map.copyAndPut(new O(3, 0), 2);
assertEquals((Integer) 2, map.get(new O(3, 0)));
assertNull(map.get(new O(5, 0)));
map = map.copyAndPut(new O(5, 0), 5);
assertEquals((Integer) 2, map.get(new O(3, 0)));
assertEquals((Integer) 5, map.get(new O(5, 0)));
map = map.copyAndRemove(new O(3, 0));
assertNull(map.get(new O(3, 0)));
assertEquals((Integer) 5, map.get(new O(5, 0)));
map = map.copyAndRemove(new O(5, 0));
assertNull(map.get(new O(3, 0)));
assertNull(map.get(new O(5, 0)));
}
public void testUnsupportedAPIs() {
try {
new CopyOnWriteHashMap<>().put("a", "b");
fail();
} catch (UnsupportedOperationException e) {
// expected
}
try {
new CopyOnWriteHashMap<>().copyAndPut("a", "b").remove("a");
fail();
} catch (UnsupportedOperationException e) {
// expected
}
}
public void testUnsupportedValues() {
try {
new CopyOnWriteHashMap<>().copyAndPut("a", null);
fail();
} catch (IllegalArgumentException e) {
// expected
}
try {
new CopyOnWriteHashMap<>().copyAndPut(null, "b");
fail();
} catch (IllegalArgumentException e) {
// expected
}
}
}
| 33.535948 | 107 | 0.554278 |
d0015e66c674ee73495c95d0366a58c5c21a6b48 | 2,589 | package com.s4game.server.public_.nodecontrol.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.s4game.core.data.accessor.cache.manager.CacheManager;
import com.s4game.core.event.IEventService;
import com.s4game.core.sync.annotation.Sync;
import com.s4game.server.bus.init.export.InitExportService;
import com.s4game.server.bus.role.service.IUserRoleService;
import com.s4game.server.public_.nodecontrol.event.publish.RoleLogoutEvent;
import com.s4game.server.public_.nodecontrol.service.INodeControlService;
import com.s4game.server.public_.share.service.IPublicRoleStateService;
@Component
public class NodeControlServiceImpl implements INodeControlService {
private boolean usecache = true;
@Autowired
private IPublicRoleStateService publicRoleStateService;
@Autowired
private InitExportService initExportService;
@Autowired
private IEventService eventService;
@Autowired
private IUserRoleService roleService;
@Autowired
@Qualifier("publicCacheManager")
private CacheManager publicCacheManager;
public NodeControlServiceImpl() {
}
public void change2online(String roleId) {
this.publicRoleStateService.change2PublicOnline(roleId);
}
public void change2offline(String roleId) {
this.publicRoleStateService.change2PublicOffline(roleId);
}
public void nodeLogin(String roleId, String ip) {
if (this.usecache) {
this.publicCacheManager.activateRoleCache(roleId);
}
this.initExportService.roleIn(roleId, ip);
}
public void nodeExit(String roleId, String paramString2) {
if (this.publicRoleStateService.isPublicOnline(roleId)) {
this.eventService.publish(new RoleLogoutEvent(roleId, paramString2,
this.roleService.getRole(roleId).getOnlineTime()));
}
if (this.usecache) {
try {
this.publicCacheManager.freezeRoleCache(roleId);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
this.initExportService.roleOut(roleId);
} catch (Exception e) {
e.printStackTrace();
}
change2offline(roleId);
}
@Sync(component = "public", indexes = { 0 })
public void nodeExitOnServerClose(String paramString) {
nodeExit(paramString, null);
}
} | 31.573171 | 79 | 0.696022 |
40b043ce83385a25b19bb90a45549fd884a4f83e | 708 | package io.demo;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 简单的测试
*
* @author Ecloss
*/
public class FileTest01 {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("F:\\Workspace\\file\\001.txt");
String s = "";
String temp = "";
char[] buf = new char[3];
int num = 0;
// 把0到3的长度存到buf中
while ((num = fr.read(buf, 0, 3)) != -1) {
temp = new String(buf, 0, num);
System.out.println(temp + " ");
s += temp;
}
System.out.println();
System.out.println(s);
fr.close();
}
}
| 20.228571 | 71 | 0.533898 |
a7bbba3696e822b1b0723a3536999323bbbd593c | 1,198 | /* Challenge Activity 2
*
* When I was in college my MET100 Professor only gave us 3 exams.
* There were 150 questions on each exam.
* Your final grade in the course was the sum of the number of questions
* you got right on each of exam1, exam2 and exam3 divided by 450 (the
* maximum possible points)
*
* Write a program which given 3 exam scores displays your total of all 3
* exam scores and percentage (as a whole number)
*
* SAMPLE RUN:
* Exam 1 Score : 120
* Exam 2 Score : 135
* Exam 3 Score : 130
* Total points : 385
* Percentage : 85
*
*/
package finalgradeinmet100;
import java.util.Scanner;
public class Grade
{
public static void main(String[] args)
{
int e1, e2, e3, total, perc;
Scanner sc = new Scanner(System.in);
System.out.print("Exam 1 Score= ");
e1 = sc.nextInt();
System.out.print("Exam 2 Score= ");
e2 = sc.nextInt();
System.out.print("Exam 3 Score= ");
e3 = sc.nextInt();
total = e1 + e2 + e3;
perc = 100 * total / 450;
System.out.println("Total points ="+total);
System.out.println("Percentage ="+perc);
}
}
| 26.043478 | 73 | 0.60601 |
f5a86614671da1127af97d40d2423192ea471acc | 3,128 | /**
* 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.activemq.tool.reports;
import java.util.Iterator;
import java.util.List;
public final class PerformanceStatisticsUtil {
private PerformanceStatisticsUtil() {
}
public static long getSum(List numList) {
long sum = 0;
if (numList != null) {
for (Iterator i = numList.iterator(); i.hasNext();) {
sum += ((Long)i.next()).longValue();
}
} else {
sum = -1;
}
return sum;
}
public static long getMin(List numList) {
long min = Long.MAX_VALUE;
if (numList != null) {
for (Iterator i = numList.iterator(); i.hasNext();) {
min = Math.min(((Long)i.next()).longValue(), min);
}
} else {
min = -1;
}
return min;
}
public static long getMax(List numList) {
long max = Long.MIN_VALUE;
if (numList != null) {
for (Iterator i = numList.iterator(); i.hasNext();) {
max = Math.max(((Long)i.next()).longValue(), max);
}
} else {
max = -1;
}
return max;
}
public static double getAve(List numList) {
double ave;
if (numList != null) {
int sampleCount = 0;
long totalTP = 0;
for (Iterator i = numList.iterator(); i.hasNext();) {
sampleCount++;
totalTP += ((Long)i.next()).longValue();
}
return (double)totalTP / (double)sampleCount;
} else {
ave = -1;
}
return ave;
}
public static double getAveEx(List numList) {
double ave;
long minTP = getMin(numList);
long maxTP = getMax(numList);
if (numList != null) {
int sampleCount = 0;
long totalTP = 0;
long sampleTP;
for (Iterator i = numList.iterator(); i.hasNext();) {
sampleCount++;
sampleTP = ((Long)i.next()).longValue();
if (sampleTP != minTP && sampleTP != maxTP) {
totalTP += sampleTP;
}
}
return (double)totalTP / (double)sampleCount;
} else {
ave = -1;
}
return ave;
}
}
| 30.970297 | 75 | 0.542839 |
fd33445d5332a11e4483a6ace360d2c5ac5c5889 | 742 | package brandonmilan.tonglaicha.ambiwidget.objects;
import java.io.Serializable;
public class ApplianceStateObject implements Serializable {
private String fan;
private String acMode;
private String power;
private String swing;
private String temperature;
public String getFan() {
return fan;
}
public String getAcMode() {
return acMode;
}
public String getPower() {
return power;
}
public String getSwing() {
return swing;
}
public String getTemperature() {
return temperature;
}
public ApplianceStateObject (String fan, String acMode, String power, String swing, String temperature) {
this.fan = fan;
this.acMode = acMode;
this.power = power;
this.swing = swing;
this.temperature = temperature;
}
}
| 20.611111 | 106 | 0.739892 |
30aa437863d29328f2114a5a477c7cd123fecf70 | 676 | package com.mentor4you.repository;
import com.mentor4you.model.Categories;
import com.mentor4you.model.Mentees;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface CategoriesRepository extends JpaRepository<Categories,Integer> {
Optional<Categories> findById(int id);
@Query("Select a from Categories a")
List<Categories> findAllCategory();
@Query("Select a.name from Categories a")
List<String> findAllCategoryName();
void deleteByName(String name);
} | 28.166667 | 81 | 0.789941 |
3914cd9e8a3d6abc219463d9924fff4bd31c2ade | 3,100 | package thewrestler.cards.skill;
import basemod.abstracts.CustomCard;
import com.badlogic.gdx.graphics.Color;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import thewrestler.WrestlerMod;
import thewrestler.actions.power.ApplyGrappledAction;
import thewrestler.enums.AbstractCardEnum;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static thewrestler.WrestlerMod.getCardResourcePath;
public class SleeperHold extends CustomCard {
public static final String ID = WrestlerMod.makeID("SleeperHold");
public static final String NAME;
public static final String DESCRIPTION;
public static final String[] EXTENDED_DESCRIPTION;
public static final String IMG_PATH = "sleeperhold.png";
private static final CardStrings cardStrings;
private static final CardType TYPE = CardType.SKILL;
private static final CardRarity RARITY = CardRarity.UNCOMMON;
private static final CardTarget TARGET = CardTarget.ENEMY;
private static final int COST = 2;
private static final int NUM_CARDS = 1;
private static final int NUM_CARDS_UPGRADE = 1;
private static final int COST_REDUCTION = 1;
public SleeperHold() {
super(ID, NAME, getCardResourcePath(IMG_PATH), COST, getDescription(NUM_CARDS), TYPE,
AbstractCardEnum.THE_WRESTLER_ORANGE, RARITY, TARGET);
this.magicNumber = this.baseMagicNumber = COST_REDUCTION;
}
@Override
public void use(AbstractPlayer p, AbstractMonster m) {
AbstractDungeon.actionManager.addToBottom(new ApplyGrappledAction(m, p));
List<AbstractCard> eligibleCards = AbstractDungeon.player.hand.group.stream()
.filter(c -> c.type != CardType.ATTACK && c.costForTurn > 0 && c.uuid != this.uuid)
.collect(Collectors.toList());
if (!eligibleCards.isEmpty()) {
Collections.shuffle(eligibleCards);
eligibleCards.stream()
.limit(this.magicNumber)
.forEach(c -> {
c.setCostForTurn(c.cost - COST_REDUCTION);
c.superFlash(Color.TEAL);
});
}
}
@Override
public AbstractCard makeCopy() {
return new SleeperHold();
}
@Override
public void upgrade() {
if (!this.upgraded) {
this.upgradeName();
this.upgradeMagicNumber(NUM_CARDS_UPGRADE);
this.rawDescription = getDescription(this.magicNumber);
initializeDescription();
}
}
public static String getDescription(int numCards) {
return DESCRIPTION
+ (numCards == 1 ? EXTENDED_DESCRIPTION[0] : EXTENDED_DESCRIPTION[1])
+ EXTENDED_DESCRIPTION[2] + COST_REDUCTION + EXTENDED_DESCRIPTION[3];
}
static {
cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
NAME = cardStrings.NAME;
DESCRIPTION = cardStrings.DESCRIPTION;
EXTENDED_DESCRIPTION = cardStrings.EXTENDED_DESCRIPTION;
}
} | 33.695652 | 91 | 0.743871 |
30d3f862533e40b53f4fcef2b8cca0b112caa5cb | 4,393 | package com.vaadin.flow.component.charts.model;
/*-
* #%L
* Vaadin Charts for Flow
* %%
* Copyright (C) 2014 - 2020 Vaadin Ltd
* %%
* This program is available under Commercial Vaadin Add-On License 3.0
* (CVALv3).
*
* See the file licensing.txt distributed with this software for more
* information about licensing.
*
* You should have received a copy of the CVALv3 along with this program.
* If not, see <https://vaadin.com/license/cval-3>.
* #L%
*/
import java.time.Instant;
import com.vaadin.flow.component.charts.model.style.Color;
import com.vaadin.flow.component.charts.util.Util;
/**
* DataSeriesItem that can hold also x2 and partialFill amount and color. Used
* in e.g. xrange series.
* <p>
* To change partial fill amount or color use {@link #getPartialFill()} to get
* the configuration object.
*/
public class DataSeriesItemXrange extends DataSeriesItem {
private Number x2;
private ItemPartialFill partialFill;
/**
* Constructs an empty item
*/
public DataSeriesItemXrange() {
super();
}
/**
* Constructs an item with X, X2 and Y
*
* @param x
* @param x2
* @param y
*/
public DataSeriesItemXrange(Number x, Number x2, Number y) {
super(x, y);
setX2(x2);
}
/**
* Constructs an item with X, X2 and Y
*
* @param x
* @param x2
* @param y
*/
public DataSeriesItemXrange(Instant x, Instant x2, Number y) {
super(x, y);
setX2(x2);
}
/**
* Constructs an item with X, X2, Y and partialFillAmount.
*
* @param x
* @param x2
* @param y
* @param partialFillAmount
*/
public DataSeriesItemXrange(Number x, Number x2, Number y,
Number partialFillAmount) {
this(x, x2, y);
setPartialFill(new ItemPartialFill(partialFillAmount));
}
/**
* Constructs an item with X, X2, Y and partialFillAmount.
*
* @param x
* @param x2
* @param y
* @param partialFillAmount
*/
public DataSeriesItemXrange(Instant x, Instant x2, Number y,
Number partialFillAmount) {
this(x, x2, y);
setPartialFill(new ItemPartialFill(partialFillAmount));
}
/**
* Constructs an item with X, X2, Y, partialFillAmount and partialFillColor.
*
* @param x
* @param x2
* @param y
* @param partialFillAmount
* @param partialFillColor
*/
public DataSeriesItemXrange(Number x, Number x2, Number y,
Number partialFillAmount, Color partialFillColor) {
this(x, x2, y);
setPartialFill(
new ItemPartialFill(partialFillAmount, partialFillColor));
}
/**
* Constructs an item with X, X2, Y, partialFillAmount and partialFillColor.
*
* @param x
* @param x2
* @param y
* @param partialFillAmount
* @param partialFillColor
*/
public DataSeriesItemXrange(Instant x, Instant x2, Number y,
Number partialFillAmount, Color partialFillColor) {
this(x, x2, y);
setPartialFill(
new ItemPartialFill(partialFillAmount, partialFillColor));
}
/**
* Returns the X2-value of the item.
*
* @see #setX2(Number)
* @return The X2 value of this data item.
*/
public Number getX2() {
return x2;
}
/**
* Sets the X2 value of this data item. Defaults to null.
*
* @param x
* X-value of the item.
*/
public void setX2(Number x2) {
this.x2 = x2;
makeCustomized();
}
/**
* Sets the given instant as the x2 value.
*
* @param instant
* Instant to set.
*/
public void setX2(Instant instant) {
setX2(Util.toHighchartsTS(instant));
}
/**
* @see #setPartialFill(ItemPartialFill)
*/
public ItemPartialFill getPartialFill() {
if (partialFill == null) {
partialFill = new ItemPartialFill();
makeCustomized();
}
return partialFill;
}
/**
* Partial fill configuration for series points, typically used to visualize
* how much of a task is performed.
*/
public void setPartialFill(ItemPartialFill partialFill) {
this.partialFill = partialFill;
makeCustomized();
}
}
| 24.405556 | 80 | 0.593672 |
6ad9ffd727f0a0f6d1dc93f69cc821c52602c159 | 883 | package leandro.soares.quevedo.scheduller.model;
import com.google.gson.annotations.SerializedName;
public class AlarmInfo {
@SerializedName("startHours")
private String startHours;
@SerializedName("endHours")
private String endHours;
@SerializedName("dayLength")
private String dayLength;
public AlarmInfo (String startours, String endHours, String dayLength) {
this.startHours = startours;
this.endHours = endHours;
this.dayLength = dayLength;
}
public String getStartHours () {
return startHours;
}
public void setStartHours (String startHours) {
this.startHours = startHours;
}
public String getEndHours () {
return endHours;
}
public void setEndHours (String endHours) {
this.endHours = endHours;
}
public String getDayLength () {
return dayLength;
}
public void setDayLength (String dayLength) {
this.dayLength = dayLength;
}
}
| 19.622222 | 73 | 0.746319 |
7202f500003628af26495e3635ba6397d22fb687 | 3,417 | /*
*
* Copyright 2020. Explore in HMS. 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.genar.hmssandbox.huawei.feature_gameservice.fragments;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.genar.hmssandbox.huawei.feature_gameservice.databinding.FragmentGameServicesFloatingWindowBinding;
import com.huawei.hms.android.HwBuildEx;
import com.huawei.hms.jos.games.Games;
import com.huawei.hms.jos.games.buoy.BuoyClient;
import java.lang.reflect.Field;
import java.util.Objects;
public class GameServicesFloatingWindowFragment extends BaseFragmentGameServices<FragmentGameServicesFloatingWindowBinding> {
private static final String TAG = "GameServicesFloatingWindowFragment";
@Override
FragmentGameServicesFloatingWindowBinding bindView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return FragmentGameServicesFloatingWindowBinding.inflate(inflater, container, false);
}
@Override
void initializeUI() {
setTitle("Floating Window");
int emuiVersion = getEmuiVersion();
if (emuiVersion < HwBuildEx.VersionCodes.EMUI_10_0) {
Toast.makeText(requireContext(), "Your EMUI Version is not enough to support floating window functions", Toast.LENGTH_SHORT).show();
}
BuoyClient buoyClient = Games.getBuoyClient(requireActivity());
view.btnShowFWGameservices.setOnClickListener(view1 -> buoyClient.showFloatWindow());
view.btnHideFWGameservices.setOnClickListener(view1 -> buoyClient.hideFloatWindow());
}
private int getEmuiVersion() {
Object returnObj = null;
int emuiVersionCode = 0;
try {
Class<?> targetClass = Class.forName("com.huawei.android.os.BuildEx$VERSION");
Field field = targetClass.getDeclaredField("EMUI_SDK_INT");
returnObj = field.get(targetClass);
if (null != returnObj) {
emuiVersionCode = (Integer) returnObj;
}
} catch (ClassNotFoundException e) {
Log.e(TAG, "ClassNotFoundException: ");
} catch (NoSuchFieldException e) {
Log.e(TAG, "NoSuchFieldException: ");
} catch (IllegalAccessException e) {
Log.e(TAG, "IllegalAccessException: ");
} catch (ClassCastException e) {
Log.e(TAG, "ClassCastException: getEMUIVersionCode is not a number" + Objects.requireNonNull(returnObj).toString());
}catch (SecurityException e) {
Log.e(TAG, e.getLocalizedMessage());
}
Log.i(TAG, "emuiVersionCodeValue: " + emuiVersionCode);
return emuiVersionCode;
}
} | 36.351064 | 158 | 0.708224 |
d51a802adea5abff58fae52b662e0b6cfdcc5d28 | 2,022 | /*
* 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 edu.ucsb.cs.eager.dao;
import edu.ucsb.cs.eager.models.APIInfo;
import edu.ucsb.cs.eager.models.ApplicationInfo;
import edu.ucsb.cs.eager.models.DependencyInfo;
import edu.ucsb.cs.eager.models.EagerException;
public class CachedEagerDependencyMgtDAO extends EagerDependencyMgtDAO {
private LRUCache<String,DependencyInfo[]> cache = new LRUCache<String, DependencyInfo[]>(1000);
@Override
public DependencyInfo[] getDependencies(String name, String version) throws EagerException {
String key = getCacheKey(name, version);
synchronized (key.intern()) {
DependencyInfo[] results = cache.get(key);
if (results == null) {
results = super.getDependencies(name, version);
cache.put(key, results);
}
return results;
}
}
@Override
public boolean recordDependencies(ApplicationInfo app) throws EagerException {
String key = getCacheKey(app.getName(), app.getVersion());
cache.remove(key);
return super.recordDependencies(app);
}
private String getCacheKey(String name, String version) {
return name + ":" + version;
}
}
| 36.763636 | 99 | 0.69634 |
bb7d595914812b5c37e9e4d1b8d4b3b3967184f9 | 697 | package com.github.baeconboy.magicstuff.block;
import com.github.baeconboy.magicstuff.base.BlockBase;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.block.Material;
public class BlockTest extends BlockBase {
public static String blockName = "test";
public static FabricBlockSettings settings = FabricBlockSettings
.of(Material.GLASS)
.breakByTool(FabricToolTags.PICKAXES, 2)
.requiresTool()
.luminance(50)
.strength(5.0F, 30.0F);
public BlockTest() {
super(BlockTest.settings, blockName);
}
} | 30.304348 | 75 | 0.711621 |
82e45655bee19d365a386ccbe98696635a6459f2 | 5,982 | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
//----------------------------------------------------
// THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST.
//----------------------------------------------------
package co.elastic.clients.elasticsearch.security;
import co.elastic.clients.elasticsearch._types.ErrorResponse;
import co.elastic.clients.elasticsearch._types.RequestBase;
import co.elastic.clients.json.JsonpDeserializable;
import co.elastic.clients.json.JsonpDeserializer;
import co.elastic.clients.json.ObjectBuilderDeserializer;
import co.elastic.clients.json.ObjectDeserializer;
import co.elastic.clients.transport.Endpoint;
import co.elastic.clients.transport.SimpleEndpoint;
import co.elastic.clients.util.ObjectBuilder;
import jakarta.json.stream.JsonGenerator;
import java.lang.Boolean;
import java.lang.String;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import javax.annotation.Nullable;
// typedef: security.get_api_key.Request
public final class GetApiKeyRequest extends RequestBase {
@Nullable
private final String id;
@Nullable
private final String name;
@Nullable
private final Boolean owner;
@Nullable
private final String realmName;
@Nullable
private final String username;
// ---------------------------------------------------------------------------------------------
public GetApiKeyRequest(Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.owner = builder.owner;
this.realmName = builder.realmName;
this.username = builder.username;
}
public GetApiKeyRequest(Function<Builder, Builder> fn) {
this(fn.apply(new Builder()));
}
/**
* API key id of the API key to be retrieved
* <p>
* API name: {@code id}
*/
@Nullable
public String id() {
return this.id;
}
/**
* API key name of the API key to be retrieved
* <p>
* API name: {@code name}
*/
@Nullable
public String name() {
return this.name;
}
/**
* flag to query API keys owned by the currently authenticated user
* <p>
* API name: {@code owner}
*/
@Nullable
public Boolean owner() {
return this.owner;
}
/**
* realm name of the user who created this API key to be retrieved
* <p>
* API name: {@code realm_name}
*/
@Nullable
public String realmName() {
return this.realmName;
}
/**
* user name of the user who created this API key to be retrieved
* <p>
* API name: {@code username}
*/
@Nullable
public String username() {
return this.username;
}
// ---------------------------------------------------------------------------------------------
/**
* Builder for {@link GetApiKeyRequest}.
*/
public static class Builder implements ObjectBuilder<GetApiKeyRequest> {
@Nullable
private String id;
@Nullable
private String name;
@Nullable
private Boolean owner;
@Nullable
private String realmName;
@Nullable
private String username;
/**
* API key id of the API key to be retrieved
* <p>
* API name: {@code id}
*/
public Builder id(@Nullable String value) {
this.id = value;
return this;
}
/**
* API key name of the API key to be retrieved
* <p>
* API name: {@code name}
*/
public Builder name(@Nullable String value) {
this.name = value;
return this;
}
/**
* flag to query API keys owned by the currently authenticated user
* <p>
* API name: {@code owner}
*/
public Builder owner(@Nullable Boolean value) {
this.owner = value;
return this;
}
/**
* realm name of the user who created this API key to be retrieved
* <p>
* API name: {@code realm_name}
*/
public Builder realmName(@Nullable String value) {
this.realmName = value;
return this;
}
/**
* user name of the user who created this API key to be retrieved
* <p>
* API name: {@code username}
*/
public Builder username(@Nullable String value) {
this.username = value;
return this;
}
/**
* Builds a {@link GetApiKeyRequest}.
*
* @throws NullPointerException
* if some of the required fields are null.
*/
public GetApiKeyRequest build() {
return new GetApiKeyRequest(this);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Endpoint "{@code security.get_api_key}".
*/
public static final Endpoint<GetApiKeyRequest, GetApiKeyResponse, ErrorResponse> ENDPOINT = new SimpleEndpoint<>(
// Request method
request -> {
return "GET";
},
// Request path
request -> {
return "/_security/api_key";
},
// Request parameters
request -> {
Map<String, String> params = new HashMap<>();
if (request.owner != null) {
params.put("owner", String.valueOf(request.owner));
}
if (request.name != null) {
params.put("name", request.name);
}
if (request.id != null) {
params.put("id", request.id);
}
if (request.realmName != null) {
params.put("realm_name", request.realmName);
}
if (request.username != null) {
params.put("username", request.username);
}
return params;
}, SimpleEndpoint.emptyMap(), false, GetApiKeyResponse._DESERIALIZER);
}
| 23.832669 | 114 | 0.638248 |
f43e25825d5c1438fa57d95d63285e4a6045c53f | 1,093 | package back_end.model.command;
import back_end.model.node.IReadableInput;
import back_end.model.robot.IRobot;
import back_end.model.states.IModifiableEnvironmentState;
import back_end.model.exception.InvalidInputNumberException;
import back_end.model.exception.InvalidNodeUsageException;
public class IfElseCommand extends IfCommand {
private boolean myExecuteMethod;
public IfElseCommand(IRobot aRobot, IModifiableEnvironmentState aEnvironment, String aCommandName) {
super(aRobot, aEnvironment, aCommandName);
myExecuteMethod = true;
}
@Override
protected int evalConditionInNode(IReadableInput... aList) throws InvalidNodeUsageException, InvalidInputNumberException {
errorCheckForTooManyInputs(aList.length, 2);
if (myExecuteMethod) {
int returnVal = (super.evalCondition(aList) == 0) ? 0 : 1;
myExecuteMethod = false;
return returnVal;
}
return -1;
}
@Override
public double eval (IReadableInput ... aList) throws InvalidNodeUsageException {
return super.eval(aList);
}
}
| 32.147059 | 126 | 0.74108 |
9ce0f45798c7409763f94bf25b9a8720ce777707 | 616 | package tp.p2.logic.objects.zombies;
import tp.p2.logic.objects.Zombie;
public class Deportista extends Zombie{
public static final int VELOCIDAD = 1;
public static final int CICLOS = 1;
public static final int RESISTENCIA = 2 ;
public static final int DANYO = 1;
public static final String NAME = "Deportista";
public static final String SHORT_NAME = "X";
public Deportista() {
super(RESISTENCIA, DANYO, CICLOS, NAME, SHORT_NAME);
}
public Zombie clone() {
Deportista depor = new Deportista();
depor.setResistance(getResistance());
depor.setRemaining(getRemaining());
return depor;
}
}
| 24.64 | 54 | 0.732143 |
30c10e32a5a61985a4040c1fd0924d19ee99109c | 3,487 | package com.example.android.newsfeedapp.Activities;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.example.android.newsfeedapp.Helpers.BottomNavigationViewHelper;
import com.example.android.newsfeedapp.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity{
@BindView(R.id.bottomNavigationView) BottomNavigationView bottomNavMenu; //Bottom Navigation View Menu
@BindView(R.id.all_news) TextView viewAllNews; // View All TextView
@BindView(R.id.read_more_news) Button readMoreNews; // READ MORE Button
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Sets the screen to fullscreen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView); //Disables the default transaction in the bottom navigation view
//Sets onClick listeners on the buttons on the bottom navigation view
bottomNavMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
YoYo.with(Techniques.Tada)
.duration(700)
.playOn(findViewById(R.id.home));
break;
case R.id.headline:
Intent playListIntent = new Intent(MainActivity.this, HeadlinesActivity.class);
startActivity(playListIntent);
break;
case R.id.favourites:
Intent favourtieIntent = new Intent(MainActivity.this, FavouritesActivity.class);
startActivity(favourtieIntent);
break;
case R.id.trending:
Intent trendingIntent = new Intent(MainActivity.this, TrendingNewsActivity.class);
startActivity(trendingIntent);
break;
}
return false;
}
});
}
// Sets onClick listener on View All TextView
@OnClick(R.id.all_news)
public void viewNews(View view) {
Intent intent = new Intent(MainActivity.this, HeadlinesActivity.class);
startActivity(intent);
}
// Sets onClick listener on READ MORE Button
@OnClick(R.id.read_more_news)
public void submit(View view) {
Intent intent = new Intent(MainActivity.this, HeadlinesActivity.class);
startActivity(intent);
}
}
| 37.902174 | 139 | 0.67049 |
677f3f7d83be1934c21f29f42c9e2b549efbbd40 | 1,819 | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
package ru.arsmagna.infrastructure;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import ru.arsmagna.Utility;
import static ru.arsmagna.Utility.nullToEmpty;
/**
* INI-file line with key and value.
*/
public final class IniLine {
/**
* Key (case insensitive).
*/
public String key;
/**
* Value (may be null).
*/
public String value;
//=========================================================================
/**
* Default constructor.
*/
public IniLine() {
}
/**
* Initializing constructor.
*
* @param key The key (can't be null).
* @param value Value (can be null).
*/
public IniLine (@NotNull String key, @Nullable String value) {
if (key == null) {
throw new IllegalArgumentException();
}
this.key = key;
this.value = value;
}
//=========================================================================
/**
* Whether two given keys are the same?
* @param first First key.
* @param second Second key.
* @return true for same keys.
*/
public static boolean sameKey(@NotNull String first, @NotNull String second) {
if (first == null || second == null) throw new IllegalArgumentException();
return first.equalsIgnoreCase(second);
}
//=========================================================================
@Override
@Contract(pure = true)
public String toString() {
return Utility.toVisible(key) + "=" + nullToEmpty(value);
}
}
| 24.581081 | 83 | 0.53326 |
a70cd6c16503407fa6477eb2108874b9f4fd5acc | 8,677 | /******************************************************************************
* Product: iDempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2012 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.idempiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.idempiere.common.util.KeyNamePair;
/** Generated Interface for C_TaxDeclarationLine
* @author iDempiere (generated)
* @version Release 5.1
*/
public interface I_C_TaxDeclarationLine
{
/** TableName=C_TaxDeclarationLine */
public static final String Table_Name = "C_TaxDeclarationLine";
/** AD_Table_ID=819 */
public static final int Table_ID = 819;
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 3 - Client - Org
*/
BigDecimal accessLevel = BigDecimal.valueOf(3);
/** Load Meta Data */
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name C_AllocationLine_ID */
public static final String COLUMNNAME_C_AllocationLine_ID = "C_AllocationLine_ID";
/** Set Allocation Line.
* Allocation Line
*/
public void setC_AllocationLine_ID (int C_AllocationLine_ID);
/** Get Allocation Line.
* Allocation Line
*/
public int getC_AllocationLine_ID();
public I_C_AllocationLine getC_AllocationLine() throws RuntimeException;
/** Column name C_BPartner_ID */
public static final String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID";
/** Set Business Partner .
* Identifies a Business Partner
*/
public void setC_BPartner_ID (int C_BPartner_ID);
/** Get Business Partner .
* Identifies a Business Partner
*/
public int getC_BPartner_ID();
public I_C_BPartner getC_BPartner() throws RuntimeException;
/** Column name C_Currency_ID */
public static final String COLUMNNAME_C_Currency_ID = "C_Currency_ID";
/** Set Currency.
* The Currency for this record
*/
public void setC_Currency_ID (int C_Currency_ID);
/** Get Currency.
* The Currency for this record
*/
public int getC_Currency_ID();
public I_C_Currency getC_Currency() throws RuntimeException;
/** Column name C_Invoice_ID */
public static final String COLUMNNAME_C_Invoice_ID = "C_Invoice_ID";
/** Set Invoice.
* Invoice Identifier
*/
public void setC_Invoice_ID (int C_Invoice_ID);
/** Get Invoice.
* Invoice Identifier
*/
public int getC_Invoice_ID();
public I_C_Invoice getC_Invoice() throws RuntimeException;
/** Column name C_InvoiceLine_ID */
public static final String COLUMNNAME_C_InvoiceLine_ID = "C_InvoiceLine_ID";
/** Set Invoice Line.
* Invoice Detail Line
*/
public void setC_InvoiceLine_ID (int C_InvoiceLine_ID);
/** Get Invoice Line.
* Invoice Detail Line
*/
public int getC_InvoiceLine_ID();
public I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException;
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name C_TaxDeclaration_ID */
public static final String COLUMNNAME_C_TaxDeclaration_ID = "C_TaxDeclaration_ID";
/** Set Tax Declaration.
* Define the declaration to the tax authorities
*/
public void setC_TaxDeclaration_ID (int C_TaxDeclaration_ID);
/** Get Tax Declaration.
* Define the declaration to the tax authorities
*/
public int getC_TaxDeclaration_ID();
public I_C_TaxDeclaration getC_TaxDeclaration() throws RuntimeException;
/** Column name C_TaxDeclarationLine_ID */
public static final String COLUMNNAME_C_TaxDeclarationLine_ID = "C_TaxDeclarationLine_ID";
/** Set Tax Declaration Line.
* Tax Declaration Document Information
*/
public void setC_TaxDeclarationLine_ID (int C_TaxDeclarationLine_ID);
/** Get Tax Declaration Line.
* Tax Declaration Document Information
*/
public int getC_TaxDeclarationLine_ID();
/** Column name C_TaxDeclarationLine_UU */
public static final String COLUMNNAME_C_TaxDeclarationLine_UU = "C_TaxDeclarationLine_UU";
/** Set C_TaxDeclarationLine_UU */
public void setC_TaxDeclarationLine_UU (String C_TaxDeclarationLine_UU);
/** Get C_TaxDeclarationLine_UU */
public String getC_TaxDeclarationLine_UU();
/** Column name C_Tax_ID */
public static final String COLUMNNAME_C_Tax_ID = "C_Tax_ID";
/** Set Tax.
* Tax identifier
*/
public void setC_Tax_ID (int C_Tax_ID);
/** Get Tax.
* Tax identifier
*/
public int getC_Tax_ID();
public I_C_Tax getC_Tax() throws RuntimeException;
/** Column name DateAcct */
public static final String COLUMNNAME_DateAcct = "DateAcct";
/** Set Account Date.
* Accounting Date
*/
public void setDateAcct (Timestamp DateAcct);
/** Get Account Date.
* Accounting Date
*/
public Timestamp getDateAcct();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name IsManual */
public static final String COLUMNNAME_IsManual = "IsManual";
/** Set Manual.
* This is a manual process
*/
public void setIsManual (boolean IsManual);
/** Get Manual.
* This is a manual process
*/
public boolean isManual();
/** Column name Line */
public static final String COLUMNNAME_Line = "Line";
/** Set Line No.
* Unique line for this document
*/
public void setLine (int Line);
/** Get Line No.
* Unique line for this document
*/
public int getLine();
/** Column name TaxAmt */
public static final String COLUMNNAME_TaxAmt = "TaxAmt";
/** Set Tax Amount.
* Tax Amount for a document
*/
public void setTaxAmt (BigDecimal TaxAmt);
/** Get Tax Amount.
* Tax Amount for a document
*/
public BigDecimal getTaxAmt();
/** Column name TaxBaseAmt */
public static final String COLUMNNAME_TaxBaseAmt = "TaxBaseAmt";
/** Set Tax base Amount.
* Base for calculating the tax amount
*/
public void setTaxBaseAmt (BigDecimal TaxBaseAmt);
/** Get Tax base Amount.
* Base for calculating the tax amount
*/
public BigDecimal getTaxBaseAmt();
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
}
| 27.546032 | 94 | 0.687795 |
bdece09b943daceae54405a4d8a55f7a51cfff7d | 519 | package net.minecraft.server;
import com.google.common.base.Predicate;
final class BlockSkullInnerClass1 implements Predicate {
BlockSkullInnerClass1() {}
public boolean a(ShapeDetectorBlock shapedetectorblock) {
return shapedetectorblock.a().getBlock() == Blocks.SKULL && shapedetectorblock.b() instanceof TileEntitySkull && ((TileEntitySkull) shapedetectorblock.b()).getSkullType() == 1;
}
public boolean apply(Object object) {
return this.a((ShapeDetectorBlock) object);
}
}
| 30.529412 | 184 | 0.732177 |
c50255e980d75346a0af1cd6efa284cd7a81a96c | 11,214 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.authority.scheme;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.cocoon.environment.Request;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.aspect.administrative.FlowResult;
import org.dspace.app.xmlui.aspect.authority.AuthorityUtils;
import org.dspace.app.xmlui.aspect.authority.FlowAuthorityMetadataValueUtils;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.authority.Concept;
import org.dspace.content.authority.Scheme;
import org.dspace.content.authority.Scheme2Concept;
import org.dspace.core.Constants;
import org.dspace.core.Context;
/**
* Utility methods to processes actions on EPeople. These methods are used
* exclusively from the administrative flow scripts.
*
* @author Scott Phillips
*/
public class FlowSchemeUtils {
/** log4j category */
private static final Logger log = Logger.getLogger(FlowSchemeUtils.class);
/** Language Strings */
private static final Message T_add_Scheme_success_notice =
new Message("default","xmlui.administrative.FlowSchemeUtils.add_Scheme_success_notice");
private static final Message T_edit_Scheme_success_notice =
new Message("default","xmlui.administrative.FlowSchemeUtils.edit_Scheme_success_notice");
private static final Message T_reset_password_success_notice =
new Message("default","xmlui.administrative.FlowSchemeUtils.reset_password_success_notice");
private static final Message t_delete_Scheme_success_notice =
new Message("default","xmlui.administrative.FlowSchemeUtils.delete_Scheme_success_notice");
private static final Message t_delete_Scheme_failed_notice =
new Message("default","xmlui.administrative.FlowSchemeUtils.delete_Scheme_failed_notice");
private static final Message t_delete_Term_success_notice =
new Message("default","xmlui.administrative.FlowTermUtils.delete_Term_success_notice");
private static final Message t_delete_Term_failed_notice =
new Message("default","xmlui.administrative.FlowTermUtils.delete_Term_failed_notice");
private static final Message t_delete_identifier_exists_notice =
new Message("default","xmlui.administrative.FlowTermUtils.identifier_exists_notice");
/**
* Add a new Scheme. This method will not set metadata on scheme
*
* @param context The current DSpace context
* @param request The HTTP request parameters
* @param objectModel Cocoon's object model
* @return A process result's object.
*/
public static FlowResult processAddScheme(Context context, Request request, Map objectModel) throws SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
result.setContinue(false); // default to no continue
String language = request.getParameter("language");
String status = request.getParameter("status");
if (result.getErrors() == null)
{
Scheme newScheme = AuthorityUtils.createNewScheme(objectModel, status, language);
context.commit();
// success
result.setContinue(true);
result.setOutcome(true);
result.setMessage(T_add_Scheme_success_notice);
result.setParameter("SchemeID", newScheme.getID());
}
return result;
}
/**
* Edit an Scheme's metadata and concept
* @return A process result's object.
*/
public static FlowResult processEditScheme(Context context,
Request request, Map ObjectModel, int schemeID)
throws SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
result.setContinue(false); // default to failure
// Get all our request parameters
String status = request.getParameter("status");
String identifier = request.getParameter("identifier");
String language = request.getParameter("lang");
//boolean certificate = (request.getParameter("certificate") != null) ? true : false;
// No errors, so we edit the Scheme with the data provided
if (result.getErrors() == null)
{
// Grab the person in question
Scheme schemeModified = Scheme.find(context, schemeID);
String originalStatus = schemeModified.getStatus();
if (originalStatus == null || !originalStatus.equals(status)) {
schemeModified.setStatus(status);
}
String originalLang = schemeModified.getLang();
if (originalLang == null || !originalLang.equals(language)) {
schemeModified.setLang(language);
}
schemeModified.update();
context.commit();
result.setContinue(true);
result.setOutcome(true);
// FIXME: rename this message
result.setMessage(T_edit_Scheme_success_notice);
}
// Everything was fine
return result;
}
/**
* Detele scheme
* todo:need delete concept ?
*/
public static FlowResult processDeleteScheme(Context context, String[] schemeIds) throws NumberFormatException, SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
List<String> unableList = new ArrayList<String>();
for (String id : schemeIds)
{
Scheme schemeDeleted = Scheme.find(context, Integer.valueOf(id));
try {
schemeDeleted.delete();
}
catch (Exception epde)
{
int schemeDeletedId = schemeDeleted.getID();
unableList.add(Integer.toString(schemeDeletedId));
}
}
if (unableList.size() > 0)
{
result.setOutcome(false);
result.setMessage(t_delete_Scheme_failed_notice);
String characters = null;
for(String unable : unableList )
{
if (characters == null)
{
characters = unable;
}
else
{
characters += ", " + unable;
}
}
result.setCharacters(characters);
}
else
{
result.setOutcome(true);
result.setMessage(t_delete_Scheme_success_notice);
}
return result;
}
/*
remove the concept from scheme
*/
public static FlowResult doDeleteConceptFromScheme(Context context,String schemeIds, String[] conceptIds) throws NumberFormatException, SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
Scheme schemeDeleted = Scheme.find(context, Integer.valueOf(schemeIds));
List<String> unableList = new ArrayList<String>();
for (String id : conceptIds)
{
Concept concept = Concept.find(context, Integer.valueOf(id));
try {
schemeDeleted.removeConcept(concept);
}
catch (Exception epde)
{
int schemeDeletedId = schemeDeleted.getID();
unableList.add(Integer.toString(schemeDeletedId));
}
}
if (unableList.size() > 0)
{
result.setOutcome(false);
result.setMessage(t_delete_Scheme_failed_notice);
String characters = null;
for(String unable : unableList )
{
if (characters == null)
{
characters = unable;
}
else
{
characters += ", " + unable;
}
}
result.setCharacters(characters);
}
else
{
schemeDeleted.update();
context.commit();
result.setOutcome(true);
result.setMessage(t_delete_Scheme_success_notice);
}
return result;
}
/*
remove the concept from scheme
*/
public static void addConcept2Scheme(Context context,String schemeId, String conceptId) throws NumberFormatException, SQLException, AuthorizeException
{
Scheme scheme = Scheme.find(context, Integer.parseInt(schemeId));
Concept concept = Concept.find(context, Integer.parseInt(conceptId));
scheme.addConcept(concept);
scheme.update();
context.commit();
}
public static FlowResult processEditSchemeMetadata(Context context, String schemeId,Request request){
return FlowAuthorityMetadataValueUtils.processEditMetadata(context, Constants.SCHEME, schemeId, request);
}
public static FlowResult doDeleteMetadataFromScheme(Context context, String schemeId,Request request)throws SQLException, AuthorizeException, UIException, IOException {
return FlowAuthorityMetadataValueUtils.doDeleteMetadata(context, Constants.SCHEME,schemeId, request);
}
public static FlowResult doAddMetadataToScheme(Context context, int schemeId, Request request) throws SQLException, AuthorizeException, UIException, IOException
{
return FlowAuthorityMetadataValueUtils.doAddMetadata(context, Constants.SCHEME,schemeId, request);
}
public static FlowResult processDeleteConcept(Context context,String schemeid, String[] conceptIds) throws NumberFormatException, SQLException, AuthorizeException
{
FlowResult result = new FlowResult();
List<String> unableList = new ArrayList<String>();
for (String id : conceptIds)
{
Scheme2Concept relationDeleted = Scheme2Concept.findBySchemeAndConcept(context, Integer.parseInt(schemeid), Integer.valueOf(id));
try {
relationDeleted.delete(context);
}
catch (Exception epde)
{
int termDeletedId = relationDeleted.getRelationID();
unableList.add(Integer.toString(termDeletedId));
}
}
if (unableList.size() > 0)
{
result.setOutcome(false);
result.setMessage(t_delete_Term_failed_notice);
String characters = null;
for(String unable : unableList )
{
if (characters == null)
{
characters = unable;
}
else
{
characters += ", " + unable;
}
}
result.setCharacters(characters);
}
else
{
result.setOutcome(true);
result.setMessage(t_delete_Term_success_notice);
}
return result;
}
}
| 34.718266 | 172 | 0.62957 |
f7bd47021a6dab6a3a64db2e9607dfec1911c902 | 884 | package io.dkozak.sfc.proj.services;
import io.dkozak.sfc.proj.fuzzy.FuzzySet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.toList;
public class FuzzySetService {
private Map<String, FuzzySet> sets = new HashMap<>();
public void addSet(FuzzySet set) {
sets.put(set.getName(), set);
}
public List<FuzzySet> getSets() {
return sets.entrySet()
.stream()
.map(Map.Entry::getValue)
.collect(toList());
}
public FuzzySet getSet(String name) {
FuzzySet fuzzySet = sets.get(name);
return fuzzySet != null ? fuzzySet : FuzzySet.NULL;
}
public void removeSet(String name) {
if (sets.remove(name) == null)
throw new RuntimeException("Set " + name + " does not exist");
}
}
| 24.555556 | 74 | 0.611991 |
353e5a9c1959f7b723d95514209772c2fad42de8 | 1,338 | /*
* Copyright(c) 2016 - Heliosphere Corp.
* ---------------------------------------------------------------------------
* This file is part of the Heliosphere's project which is licensed under the
* Apache license version 2 and use is subject to license terms.
* You should have received a copy of the license with the project's artifact
* binaries and/or sources.
*
* License can be consulted at http://www.apache.org/licenses/LICENSE-2.0
* ---------------------------------------------------------------------------
*/
package com.heliosphere.icare.model.entity.person;
import com.heliosphere.demeter2.base.annotation.Copyright;
import com.heliosphere.demeter2.base.annotation.License;
import com.heliosphere.icare.model.entity.person.type.ContactType;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Represents a contact information.
* <hr>
* @author <a href="mailto:[email protected]">Resse Christophe - Heliosphere</a>
* @version 1.0.0
*/
@Copyright(company="Heliosphere Corp.", year=2016, author="Resse Christophe")
@License(license="Apache", version="2.0", url="http://www.apache.org/licenses/LICENSE-2.0")
@EqualsAndHashCode
@ToString
public class Contact
{
/**
* Type of the contact.
*/
@Getter
@Setter
private ContactType type;
}
| 31.116279 | 91 | 0.663677 |
096bcd98b9462c9406348ff921f535d76e9c0ab3 | 3,477 | /*
* 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.uima.ducc.sm;
import java.io.File;
import java.io.FileInputStream;
import java.util.NavigableSet;
import java.util.Properties;
import org.apache.uima.ducc.common.persistence.services.IStateServices;
import org.apache.uima.ducc.common.persistence.services.StateServicesDirectory;
import org.apache.uima.ducc.common.persistence.services.StateServicesFactory;
import org.apache.uima.ducc.common.utils.DuccLogger;
import org.apache.uima.ducc.common.utils.DuccProperties;
import org.apache.uima.ducc.common.utils.id.DuccId;
import org.apache.uima.ducc.common.utils.id.DuccIdFactory;
import org.apache.uima.ducc.common.utils.id.IDuccIdFactory;
public class ServiceManagerHelper {
private static DuccLogger logger = DuccLogger.getLogger(ServiceManagerHelper.class.getName(), SmConstants.COMPONENT_NAME);
private static DuccId jobid = null;
private static String service_seqno = IStateServices.sequenceKey;
/**
* construct DuccIdFactory for services registry
*/
public static IDuccIdFactory getDuccIdFactory() {
String location = "getDuccIdFactory";
long fileSeqNo = getFileSeqNo()+1;
long dbSeqNo = getDbSeqNo()+1;
long seqNo = 0;
if(fileSeqNo > seqNo) {
seqNo = fileSeqNo;
}
if(dbSeqNo > seqNo) {
seqNo = dbSeqNo;
}
logger.info(location, jobid, "seqNo:", seqNo, "dbSeqNo:", dbSeqNo, "fileSeqNo:", fileSeqNo);
IDuccIdFactory duccIdFactory = new DuccIdFactory(seqNo);
return duccIdFactory;
}
private static long getFileSeqNo() {
String location = "getFileSeqNo";
long seqNo = -1;
try {
String state_dir = System.getProperty("DUCC_HOME") + "/state";
String state_file = state_dir + "/sm.properties";
Properties sm_props = new DuccProperties();
File sf = new File(state_file);
FileInputStream fos;
if (sf.exists()) {
fos = new FileInputStream(state_file);
try {
sm_props.load(fos);
String s = sm_props.getProperty(service_seqno);
seqNo = Integer.parseInt(s) + 1;
} finally {
fos.close();
}
}
}
catch(Exception e) {
logger.error(location, jobid, e);
}
return seqNo;
}
/**
* fetch largest service sequence number from database
*/
public static long getDbSeqNo() {
String location = "getDbSeqNo";
long seqno = -1;
try {
IStateServices iss = StateServicesFactory.getInstance(
ServiceManagerHelper.class.getName(),
SmConstants.COMPONENT_NAME);
StateServicesDirectory ssd = iss.getStateServicesDirectory();
NavigableSet<Long> keys = ssd.getDescendingKeySet();
if (!keys.isEmpty()) {
seqno = keys.first();
}
} catch (Exception e) {
logger.error(location, jobid, e);
}
return seqno;
}
}
| 31.899083 | 123 | 0.72994 |
c3fa1cb30a20976ee5b410e36f29d107920edc4f | 8,514 | /**
* ReportColumn.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.sforce.soap._2006._04.metadata;
public class ReportColumn implements java.io.Serializable {
private com.sforce.soap._2006._04.metadata.ReportSummaryType[] aggregateTypes;
private java.lang.String field;
private java.lang.Boolean reverseColors;
private java.lang.Boolean showChanges;
public ReportColumn() {
}
public ReportColumn(
com.sforce.soap._2006._04.metadata.ReportSummaryType[] aggregateTypes,
java.lang.String field,
java.lang.Boolean reverseColors,
java.lang.Boolean showChanges) {
this.aggregateTypes = aggregateTypes;
this.field = field;
this.reverseColors = reverseColors;
this.showChanges = showChanges;
}
/**
* Gets the aggregateTypes value for this ReportColumn.
*
* @return aggregateTypes
*/
public com.sforce.soap._2006._04.metadata.ReportSummaryType[] getAggregateTypes() {
return aggregateTypes;
}
/**
* Sets the aggregateTypes value for this ReportColumn.
*
* @param aggregateTypes
*/
public void setAggregateTypes(com.sforce.soap._2006._04.metadata.ReportSummaryType[] aggregateTypes) {
this.aggregateTypes = aggregateTypes;
}
public com.sforce.soap._2006._04.metadata.ReportSummaryType getAggregateTypes(int i) {
return this.aggregateTypes[i];
}
public void setAggregateTypes(int i, com.sforce.soap._2006._04.metadata.ReportSummaryType _value) {
this.aggregateTypes[i] = _value;
}
/**
* Gets the field value for this ReportColumn.
*
* @return field
*/
public java.lang.String getField() {
return field;
}
/**
* Sets the field value for this ReportColumn.
*
* @param field
*/
public void setField(java.lang.String field) {
this.field = field;
}
/**
* Gets the reverseColors value for this ReportColumn.
*
* @return reverseColors
*/
public java.lang.Boolean getReverseColors() {
return reverseColors;
}
/**
* Sets the reverseColors value for this ReportColumn.
*
* @param reverseColors
*/
public void setReverseColors(java.lang.Boolean reverseColors) {
this.reverseColors = reverseColors;
}
/**
* Gets the showChanges value for this ReportColumn.
*
* @return showChanges
*/
public java.lang.Boolean getShowChanges() {
return showChanges;
}
/**
* Sets the showChanges value for this ReportColumn.
*
* @param showChanges
*/
public void setShowChanges(java.lang.Boolean showChanges) {
this.showChanges = showChanges;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ReportColumn)) return false;
ReportColumn other = (ReportColumn) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.aggregateTypes==null && other.getAggregateTypes()==null) ||
(this.aggregateTypes!=null &&
java.util.Arrays.equals(this.aggregateTypes, other.getAggregateTypes()))) &&
((this.field==null && other.getField()==null) ||
(this.field!=null &&
this.field.equals(other.getField()))) &&
((this.reverseColors==null && other.getReverseColors()==null) ||
(this.reverseColors!=null &&
this.reverseColors.equals(other.getReverseColors()))) &&
((this.showChanges==null && other.getShowChanges()==null) ||
(this.showChanges!=null &&
this.showChanges.equals(other.getShowChanges())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getAggregateTypes() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getAggregateTypes());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getAggregateTypes(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getField() != null) {
_hashCode += getField().hashCode();
}
if (getReverseColors() != null) {
_hashCode += getReverseColors().hashCode();
}
if (getShowChanges() != null) {
_hashCode += getShowChanges().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ReportColumn.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "ReportColumn"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("aggregateTypes");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "aggregateTypes"));
elemField.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "ReportSummaryType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("field");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "field"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reverseColors");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "reverseColors"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("showChanges");
elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "showChanges"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| 34.330645 | 125 | 0.602772 |
ebfc084191c19a0692fc1449a662e2f479e58f10 | 864 | package team.gif.robot.commands.collector;
import edu.wpi.first.wpilibj2.command.CommandBase;
import team.gif.robot.Robot;
public class CollectorReverse extends CommandBase {
public CollectorReverse() {
super();
addRequirements(Robot.collector);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
Robot.collector.setSpeedPercentCollector(-0.5);
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return false;
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
Robot.collector.setSpeedPercentCollector(0);
}
}
| 23.351351 | 75 | 0.678241 |
64e423bbe9ab579311846b663c3b33a636c2ad0b | 4,422 | package openanonymizer.core.dict;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
/**
* This class allows to get value from dictionary file.
* Dictionary files, that are represented by {@link Dictionary} class,
* are loaded into memory, for faster value generation.
*
* Dictionary files could loaded from any storage, but must follow next format: name_locale.dict,
* where 'name' is a dictionary name, 'locale' is a dictionary locale and 'dict' is a file format.
* Files could be normal text files, with content separated by new line. For separating content in
* single line use delimiter ';'.
*
* Use static methods of this class. Do not use constructor.
*
* @version 0.1
* @since Open Anonymizer 1.0.0
*/
public final class DictionaryService {
private static final Logger logger = Logger.getLogger(DictionaryService.class);
private static final String DELIMITER = ";";
private static final String FILENAME = "%s/%s.dict";
private static Map<String, Dictionary> loadedDictionaries = new HashMap<>();
/**
* Get dictionary value using default locale
*
* @param path to the dictionaries directory
* @param name of the dictionary file
* @return {@link Optional} with dictionary value
*/
public static Optional<String> getDictionaryValue(final String path, final String name) {
return getDictionaryValue(path, name, null);
}
/**
* Get dictionary value using specific locale.
* If locale is set to null, dictionary file with 'def' ending will be used.
*
* @param path to the dictionaries directory
* @param name of the dictionary file
* @param locale dictionary locale
* @return {@link Optional} with dictionary value
*/
public static Optional<String> getDictionaryValue(final String path, final String name, final Locale locale) {
Validate.notEmpty(path, "Dictionaries path must be not null and not empty.");
Validate.notEmpty(name, "File name must be not null and not empty.");
String key = name + "_" + (locale == null ? "def" : locale.getLanguage());
if (loadedDictionaries.containsKey(key)) {
return Optional.ofNullable(loadedDictionaries.get(key).nextValue());
}
Dictionary dictionary = loadDictionary(String.format(FILENAME, path, key));
loadedDictionaries.put(key, dictionary);
return Optional.ofNullable(dictionary.nextValue());
}
/**
* Load dictionary file into memory
*
* @param filename name of file in local storage
* @return {@link Dictionary} class with loaded content from dictionary file
*/
private static Dictionary loadDictionary(final String filename) {
logger.info("Loading new dictionary from file [ " + filename + " ].");
try(BufferedReader reader = new BufferedReader(new FileReader(filename))) {
List<String> wordList = new ArrayList<>();
reader.lines().forEach(line -> wordList.addAll(Arrays.asList(line.split(DELIMITER))));
logger.info("Loaded " + wordList.size() + " new terms.");
return new Dictionary(wordList);
} catch (IOException e) {
logger.warn("Could not load dictionary from file [ " + filename + " ]. Dictionary will be empty." );
return new Dictionary(Collections.emptyList());
}
}
private DictionaryService() {
throw new IllegalStateException();
}
/**
* This class is a container for dictionary values. It allows reading values in cycle.
*/
private static class Dictionary {
private final List<String> iterable;
private Iterator<String> iterator;
Dictionary(List<String> iterable) {
this.iterable = iterable;
this.iterator = iterable.iterator();
}
/**
* Return next value from values collection.
* When iterator points to last element of collection,
* it is set to the collection first element.
*/
String nextValue() {
if (iterable.isEmpty()) {
return null;
} else if (!iterator.hasNext()) {
iterator = iterable.iterator();
}
return iterator.next();
}
}
}
| 38.12069 | 114 | 0.652872 |
2c58a9b7a8f314437fa65e12c33f07f90e470343 | 7,225 | package com.vmware.avi.vro.model;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.vmware.avi.vro.model.AttackMitigationAction;
import com.vmware.o11n.plugin.sdk.annotation.VsoFinder;
import com.vmware.o11n.plugin.sdk.annotation.VsoMethod;
import com.vmware.o11n.plugin.sdk.annotation.VsoObject;
import com.vmware.avi.vro.Constants;
import org.springframework.stereotype.Service;
/**
* The DnsAttack is a POJO class extends AviRestResource that used for creating
* DnsAttack.
*
* @version 1.0
* @since
*
*/
@VsoObject(create = false, name = "DnsAttack")
@VsoFinder(name = Constants.FINDER_VRO_DNSATTACK)
@JsonIgnoreProperties(ignoreUnknown = true)
@Service
public class DnsAttack extends AviRestResource {
@JsonProperty("attack_vector")
@JsonInclude(Include.NON_NULL)
private String attackVector = null;
@JsonProperty("enabled")
@JsonInclude(Include.NON_NULL)
private Boolean enabled = true;
@JsonProperty("max_mitigation_age")
@JsonInclude(Include.NON_NULL)
private Integer maxMitigationAge = 60;
@JsonProperty("mitigation_action")
@JsonInclude(Include.NON_NULL)
private AttackMitigationAction mitigationAction = null;
@JsonProperty("threshold")
@JsonInclude(Include.NON_NULL)
private Integer threshold = null;
/**
* This is the getter method this will return the attribute value.
* The dns attack vector.
* Enum options - DNS_REFLECTION, DNS_NXDOMAIN, DNS_AMPLIFICATION_EGRESS.
* Field introduced in 18.2.1.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return attackVector
*/
@VsoMethod
public String getAttackVector() {
return attackVector;
}
/**
* This is the setter method to the attribute.
* The dns attack vector.
* Enum options - DNS_REFLECTION, DNS_NXDOMAIN, DNS_AMPLIFICATION_EGRESS.
* Field introduced in 18.2.1.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param attackVector set the attackVector.
*/
@VsoMethod
public void setAttackVector(String attackVector) {
this.attackVector = attackVector;
}
/**
* This is the getter method this will return the attribute value.
* Enable or disable the mitigation of the attack vector.
* Field introduced in 18.2.1.
* Default value when not specified in API or module is interpreted by Avi Controller as true.
* @return enabled
*/
@VsoMethod
public Boolean getEnabled() {
return enabled;
}
/**
* This is the setter method to the attribute.
* Enable or disable the mitigation of the attack vector.
* Field introduced in 18.2.1.
* Default value when not specified in API or module is interpreted by Avi Controller as true.
* @param enabled set the enabled.
*/
@VsoMethod
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
/**
* This is the getter method this will return the attribute value.
* Time in minutes after which mitigation will be deactivated.
* Allowed values are 1-4294967295.
* Special values are 0- 'blocked for ever'.
* Field introduced in 18.2.1.
* Unit is min.
* Default value when not specified in API or module is interpreted by Avi Controller as 60.
* @return maxMitigationAge
*/
@VsoMethod
public Integer getMaxMitigationAge() {
return maxMitigationAge;
}
/**
* This is the setter method to the attribute.
* Time in minutes after which mitigation will be deactivated.
* Allowed values are 1-4294967295.
* Special values are 0- 'blocked for ever'.
* Field introduced in 18.2.1.
* Unit is min.
* Default value when not specified in API or module is interpreted by Avi Controller as 60.
* @param maxMitigationAge set the maxMitigationAge.
*/
@VsoMethod
public void setMaxMitigationAge(Integer maxMitigationAge) {
this.maxMitigationAge = maxMitigationAge;
}
/**
* This is the getter method this will return the attribute value.
* Mitigation action to perform for this dns attack vector.
* Field introduced in 18.2.1.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return mitigationAction
*/
@VsoMethod
public AttackMitigationAction getMitigationAction() {
return mitigationAction;
}
/**
* This is the setter method to the attribute.
* Mitigation action to perform for this dns attack vector.
* Field introduced in 18.2.1.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param mitigationAction set the mitigationAction.
*/
@VsoMethod
public void setMitigationAction(AttackMitigationAction mitigationAction) {
this.mitigationAction = mitigationAction;
}
/**
* This is the getter method this will return the attribute value.
* Threshold, in terms of dns packet per second, for the dns attack vector.
* Field introduced in 18.2.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return threshold
*/
@VsoMethod
public Integer getThreshold() {
return threshold;
}
/**
* This is the setter method to the attribute.
* Threshold, in terms of dns packet per second, for the dns attack vector.
* Field introduced in 18.2.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param threshold set the threshold.
*/
@VsoMethod
public void setThreshold(Integer threshold) {
this.threshold = threshold;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DnsAttack objDnsAttack = (DnsAttack) o;
return Objects.equals(this.attackVector, objDnsAttack.attackVector)&&
Objects.equals(this.mitigationAction, objDnsAttack.mitigationAction)&&
Objects.equals(this.enabled, objDnsAttack.enabled)&&
Objects.equals(this.maxMitigationAge, objDnsAttack.maxMitigationAge)&&
Objects.equals(this.threshold, objDnsAttack.threshold);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DnsAttack {\n");
sb.append(" attackVector: ").append(toIndentedString(attackVector)).append("\n");
sb.append(" enabled: ").append(toIndentedString(enabled)).append("\n");
sb.append(" maxMitigationAge: ").append(toIndentedString(maxMitigationAge)).append("\n");
sb.append(" mitigationAction: ").append(toIndentedString(mitigationAction)).append("\n");
sb.append(" threshold: ").append(toIndentedString(threshold)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 32.692308 | 100 | 0.718201 |
4276a88af428968ad6150e54189a932605cc044c | 4,994 | package com.gyangod.model;
import com.gyangod.embeddedentity.PackageOccurrences;
import org.springframework.data.geo.Point;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class Pack {
private String id;
private List<String> standards;
private String name;
private String description;
private Date courseEndDate;
private Customer createdBy;
private Customer teacher;
private String teacherName;
private Boolean anyoneCanAddBatch;
private Boolean refundable;
private Double costPerHour;
private Double courseDiscount;
private Double weeklyCost;
private Double totalWeekHours;
private Double totalMonthHours;
private Double monthlyCost;
private Double courseDuration;
private Boolean fixedCourse;
private Point location;
private Map<String,List<PackageOccurrences>> mapOccurrences;
private List<String> subjects;
private Boolean visibility;
private Boolean active;
public String getPackageId() {
return id;
}
public void setPackageId(String id) {
this.id = id;
}
public List<String> getStandards() {
return standards;
}
public void setStandards(List<String> standards) {
this.standards = standards;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCourseEndDate() {
return courseEndDate;
}
public void setCourseEndDate(Date courseEndDate) {
this.courseEndDate = courseEndDate;
}
public Customer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Customer createdBy) {
this.createdBy = createdBy;
}
public Customer getTeacher() {
return teacher;
}
public void setTeacher(Customer teacher) {
this.teacher = teacher;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public Boolean getAnyoneCanAddBatch() {
return anyoneCanAddBatch;
}
public void setAnyoneCanAddBatch(Boolean anyoneCanAddBatch) {
this.anyoneCanAddBatch = anyoneCanAddBatch;
}
public Boolean getRefundable() {
return refundable;
}
public void setRefundable(Boolean refundable) {
this.refundable = refundable;
}
public Double getCostPerHour() {
return costPerHour;
}
public void setCostPerHour(Double costPerHour) {
this.costPerHour = costPerHour;
}
public Double getCourseDiscount() {
return courseDiscount;
}
public void setCourseDiscount(Double courseDiscount) {
this.courseDiscount = courseDiscount;
}
public Double getWeeklyCost() {
return weeklyCost;
}
public void setWeeklyCost(Double weeklyCost) {
this.weeklyCost = weeklyCost;
}
public Double getTotalWeekHours() {
return totalWeekHours;
}
public void setTotalWeekHours(Double totalWeekHours) {
this.totalWeekHours = totalWeekHours;
}
public Double getTotalMonthHours() {
return totalMonthHours;
}
public void setTotalMonthHours(Double totalMonthHours) {
this.totalMonthHours = totalMonthHours;
}
public Double getMonthlyCost() {
return monthlyCost;
}
public void setMonthlyCost(Double monthlyCost) {
this.monthlyCost = monthlyCost;
}
public Double getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(Double courseDuration) {
this.courseDuration = courseDuration;
}
public Boolean getFixedCourse() {
return fixedCourse;
}
public void setFixedCourse(Boolean fixedCourse) {
this.fixedCourse = fixedCourse;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public Map<String, List<PackageOccurrences>> getMapOccurrences() {
return mapOccurrences;
}
public void setMapOccurrences(Map<String, List<PackageOccurrences>> mapOccurrences) {
this.mapOccurrences = mapOccurrences;
}
public List<String> getSubjects() {
return subjects;
}
public void setSubjects(List<String> subjects) {
this.subjects = subjects;
}
public Boolean getVisibility() {
return visibility;
}
public void setVisibility(Boolean visibility) {
this.visibility = visibility;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
| 20.636364 | 89 | 0.65859 |
904e429c6d932176187f4e873fe4654ac2f10b38 | 241 | package org.apache.log4j.or;
class DefaultRenderer implements ObjectRenderer {
public String doRender(Object o) {
try {
return o.toString();
} catch (Exception var3) {
return var3.toString();
}
}
}
| 20.083333 | 49 | 0.614108 |
20645e5c3a84cf3600964e2802967e9d408f2385 | 480 | package com.github.alanger.shiroext.servlets;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
public class MultiReadRequestFilter extends MutableRequestFilter {
@Override
protected ServletRequest getRequestWrapper(ServletRequest request) {
if (request instanceof HttpServletRequest) {
return new MultiReadRequestWrapper((HttpServletRequest) request);
} else {
return request;
}
}
}
| 28.235294 | 77 | 0.73125 |
f0e3d02dfd8b31f124ed10f17989fe331d81d65f | 1,664 | package com.example.demo.service.impl;
import com.example.demo.service.AbstractZookeeperLock;
import org.I0Itec.zkclient.IZkDataListener;
import org.springframework.stereotype.Service;
import java.util.concurrent.CountDownLatch;
/**
* zk分布式锁实现类
*/
@Service
public class ZookeeperLockImpl extends AbstractZookeeperLock {
private CountDownLatch countDownLatch = null;
@Override
protected boolean tryLock() {
try {
//创建临时节点
client.createEphemeral(PATH);
return true;
} catch (Exception e) {
return false;
}
}
@Override
protected void waitLock() {
//创建监听类
IZkDataListener zkDataListener = new IZkDataListener() {
/**
* 节点删除时
*
* @param s path
* @param o data
* @throws Exception
*/
@Override
public void handleDataChange(String s, Object o) throws Exception {
//唤醒
countDownLatch.countDown();
}
@Override
public void handleDataDeleted(String s) throws Exception {
}
};
//开启监听
client.subscribeDataChanges(PATH, zkDataListener);
//检查节点是否存在
if (client.exists(PATH)) {
countDownLatch = new CountDownLatch(1);
try {
//存在,等待
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//上面的countdownLatch放行,取消订阅
client.unsubscribeDataChanges(PATH, zkDataListener);
}
}
| 24.835821 | 79 | 0.551683 |
76eb9ead4ba57370f2d1826ee3cbf1e3d1bbef28 | 847 | package fw.jbiz.ext.verifycode.interfaces;
import java.util.List;
import javax.persistence.EntityManager;
import fw.jbiz.ext.verifycode.bean.ZVerifyCodeBean;
public interface IVerifyCodeProvider {
// 账号有效性
public boolean isValidAccount(String destAddress, EntityManager em);
// 当天发送次数
public int getSendTimes(String destAddress, EntityManager em);
// 保存code到db
void saveCode(ZVerifyCodeBean verifyCodeBean, EntityManager em);
// 获取所有有效的code
List<ZVerifyCodeBean> getAllCodes(String sessionKey, EntityManager em);
// 无效化sessionKey
void invalidSessionKey(String sessionKey, EntityManager em);
// 发送sms
boolean sendCodeBySms(String mobileNumber, String code, int validMinutes, String signature, String smsTemplateId);
// 发送email
boolean sendCodeByEmail(String emailAddress, String code, int validMinutes, String signature);
}
| 30.25 | 115 | 0.804014 |
68a2688124bb11263b90f8c0f31866a96e078ebf | 2,405 | /*
* Copyright (c) 2020-2030 ZHENGGENGWEI(码匠君)<[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.
*
* Eurynome Cloud 采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改 Eurynome Cloud 源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/herodotus/eurynome-cloud
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/herodotus/eurynome-cloud
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.herodotus.engine.web.configuration;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* <p>Description: Undertow 配置解决 启动的一个WARN问题 </p>
*
* @author : gengwei.zheng
* @date : 2019/11/17 16:07
*/
@Component
public class UndertowWebServerFactoryCustomizer implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
private static final Logger log = LoggerFactory.getLogger(UndertowWebServerFactoryCustomizer.class);
@PostConstruct
public void postConstruct() {
log.debug("[Herodotus] |- Plugin [Undertow WebServer Factory Customizer] Auto Configure.");
}
@Override
public void customize(UndertowServletWebServerFactory factory) {
factory.addDeploymentInfoCustomizers(deploymentInfo -> {
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, 1024));
deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo);
});
}
}
| 37.578125 | 120 | 0.772557 |
f8a0957443ac4f5777399798f037a827b7ae4250 | 3,119 | package com.appdevgenie.shuttleservice.fragments;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.appdevgenie.shuttleservice.R;
import com.appdevgenie.shuttleservice.adapters.RouteListAdapter;
import com.appdevgenie.shuttleservice.model.RouteStops;
import com.appdevgenie.shuttleservice.utils.CreateRouteStopArrayList;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import static com.appdevgenie.shuttleservice.utils.Constants.UPDATE_INTERVAL;
public class MainRouteStopsFragment extends Fragment {
private Handler handler = new Handler();
private Runnable runnable;
private RouteListAdapter routeListAdapter;
@BindView(R.id.recyclerViewDefault)
RecyclerView rvRoute;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_default_recyclerview, container, false);
ButterKnife.bind(this, view);
setupVariables();
return view;
}
private void setupVariables() {
Context context = getActivity();
AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
if (appCompatActivity != null) {
appCompatActivity.getSupportActionBar().setTitle(R.string.route_and_stops);
}
ArrayList<RouteStops> route = null;
//DividerItemDecoration dividerItemDecoration = null;
if (context != null) {
//dividerItemDecoration = new DividerItemDecoration(context, VERTICAL);
//dividerItemDecoration.setDrawable(context.getResources().getDrawable(R.drawable.line_divider));
route = CreateRouteStopArrayList.createArrayList(context);
}
//RecyclerView rvRoute = view.findViewById(R.id.recyclerViewDefault);
routeListAdapter = new RouteListAdapter(context, route);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
//rvRoute.addItemDecoration(dividerItemDecoration);
rvRoute.setLayoutManager(linearLayoutManager);
rvRoute.setHasFixedSize(true);
rvRoute.setAdapter(routeListAdapter);
}
@Override
public void onResume() {
super.onResume();
handler.postDelayed(runnable = new Runnable() {
@Override
public void run() {
routeListAdapter.notifyDataSetChanged();
handler.postDelayed(runnable, UPDATE_INTERVAL);
}
}, UPDATE_INTERVAL);
}
@Override
public void onStop() {
super.onStop();
handler.removeCallbacks(runnable);
}
}
| 34.274725 | 132 | 0.726836 |
4b447943cab49d19ac2881bd8880e675ac2f3b72 | 2,078 | package fundamental.sort.test;
import fundamental.sort.impl.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@SuppressWarnings("all")
class SortTest {
@Test
public void test_sort() {
String alg1 = "Bubble";
String alg2 = "Insertion";
int N = 10;
int T = 1;
// 算法 1 的总时间
double t1 = timeRandomInput(alg1, N, T);
// 算法 2 的总时间
double t2 = timeRandomInput(alg2, N, T);
System.out.println(String.format("For %d random Doubles\n %s is", N, alg1));
System.out.print(String.format(" %.1f times faster than %s\n",t2 / t1, alg2));
}
/**
*使用算法 alg 将 T 个长度为 N 的数组排序
*/
public static double timeRandomInput(String alg, int N, int T) {
double total = 0.0;
Double[] a = new Double[N];
// 进行一次测试(生成一个数组并排序)
for (int t = 0; t < T; t++) {
for (int i = 0; i < N; i++) {
a[i] = Math.random();
}
total += time(alg, a);
//断言数组是否有序
Assertions.assertTrue(Util.isSorted(a));
}
return total;
}
public static double time(String alg, Double[] a) {
Stopwatch timer = new Stopwatch();
if (alg.equals("Insertion")) {
Insertion.sort(a);
}
if (alg.equals("Selection")) {
Selection.sort(a);
}
if (alg.equals("Shell")) {
Shell.sort(a);
}
if (alg.equals("Merge")) {
Merge.sort(a);
}
if (alg.equals("Bubble")) {
Bubble.sort(a);
}
if (alg.equals("Quick")) {
Quick.sort(a);
}
if (alg.equals("Heap")) {
Heap.sort(a);
}
return timer.elapsedTime();
}
}
/**
* 程序运行时间计时类
*/
class Stopwatch {
private final long start;
public Stopwatch() {
start = System.currentTimeMillis();
}
public double elapsedTime() {
long now = System.currentTimeMillis();
return (now - start) / 1000.0;
}
}
| 25.036145 | 86 | 0.504812 |
c603b489ef331422bfbc6615b4caf503aea35a9e | 4,377 | /*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.world.sun;
import com.google.common.math.LongMath;
import org.terasology.context.Context;
import org.terasology.entitySystem.entity.EntityManager;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.UpdateSubscriberSystem;
import org.terasology.world.WorldComponent;
import org.terasology.world.WorldProvider;
import org.terasology.world.time.WorldTime;
import java.math.RoundingMode;
import static org.terasology.world.time.WorldTime.DAY_LENGTH;
/**
* A base class that fires events at different times of the day.
*/
public class DefaultCelestialSystem extends BaseComponentSystem implements CelestialSystem, UpdateSubscriberSystem {
private final WorldTime worldTime;
private long lastUpdate;
private final CelestialModel model;
private final EntityManager entityManager;
private boolean haltSunPosition = false;
private float haltedTime = 0f;
public DefaultCelestialSystem(CelestialModel model, Context context) {
WorldProvider worldProvider = context.get(WorldProvider.class);
entityManager = context.get(EntityManager.class);
worldTime = worldProvider.getTime();
lastUpdate = worldTime.getMilliseconds();
this.model = model;
}
@Override
public void update(float delta) {
fireEvents();
}
@Override
public float getSunPosAngle() {
float days;
if (isSunHalted()) {
days = haltedTime;
} else {
days = getWorldTime().getDays();
}
return model.getSunPosAngle(days);
}
@Override
public boolean isSunHalted() {
return haltSunPosition;
}
@Override
public void toggleSunHalting (float timeInDays) {
haltSunPosition = !haltSunPosition;
haltedTime = timeInDays;
}
/**
* Updates the game perception of the time of day via launching a new OnMiddayEvent(),
* OnDuskEvent(), OnMidnightEvent(), or OnDawnEvent() based on the time of day when
* this method is called upon.
*/
protected void fireEvents() {
long startTime = worldTime.getMilliseconds();
long delta = startTime - lastUpdate;
if (delta > 0) {
long timeInDay = LongMath.mod(startTime, DAY_LENGTH);
long day = LongMath.divide(startTime, DAY_LENGTH, RoundingMode.FLOOR);
long dawn = model.getDawn(day);
long midday = model.getMidday(day);
long dusk = model.getDusk(day);
long midnight = model.getMidnight(day);
if (timeInDay - delta < midday && timeInDay >= midday) {
long tick = day * DAY_LENGTH + midday;
getWorldEntity().send(new OnMiddayEvent(tick));
}
if (timeInDay - delta < dusk && timeInDay >= dusk) {
long tick = day * DAY_LENGTH + dusk;
getWorldEntity().send(new OnDuskEvent(tick));
}
if (timeInDay - delta < midnight && timeInDay >= midnight) {
long tick = day * DAY_LENGTH + midnight;
getWorldEntity().send(new OnMidnightEvent(tick));
}
if (timeInDay - delta < dawn && timeInDay >= dawn) {
long tick = day * DAY_LENGTH + dawn;
getWorldEntity().send(new OnDawnEvent(tick));
}
}
lastUpdate = startTime;
}
protected WorldTime getWorldTime() {
return worldTime;
}
protected EntityRef getWorldEntity() {
for (EntityRef entity : entityManager.getEntitiesWith(WorldComponent.class)) {
return entity;
}
return EntityRef.NULL;
}
}
| 32.183824 | 116 | 0.655472 |
63208c7444ccd89bea3e7dbbe3e30f5e20bb2c6f | 3,943 | package com.rc.gcmhelper;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.rc.gcmhelper.storage.StorageHelper;
import java.io.IOException;
/**
* Helper for mGCM registration
* Created by akshay on 19/08/14.
*/
public final class GCMRegistrar {
private static final String TAG = "###GCMRegistrar###";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private String mSenderId;
private Context mContext;
private GoogleCloudMessaging mGCM;
private String mRegId;
private GCMRegistrarListener mListener;
public interface GCMRegistrarListener {
void registrationDone(final String regId);
void registering();
void errorWhileRegistering(final Throwable exception);
}
private GCMRegistrar(final Context context, final String senderId,
final GCMRegistrarListener listener) {
mContext = context;
mSenderId = senderId;
mGCM = GoogleCloudMessaging.getInstance(context);
mRegId = StorageHelper.get(context.getApplicationContext()).getGCMRegistrationId();
mListener = listener;
}
public static void RegisterIfNotRegistered(final Context context,
final String senderId,
final GCMRegistrarListener listener) {
final String regId = StorageHelper.get(context.getApplicationContext()).getGCMRegistrationId();
if (!regId.isEmpty()) {
listener.registrationDone(regId);
return;
}
final GCMRegistrar gcmRegistrar = new GCMRegistrar(context, senderId, listener);
if (gcmRegistrar.checkPlayServices()) {
gcmRegistrar.register();
}
}
private void register() {
mListener.registering();
new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object[] objects) {
Log.d(TAG, "Registering with Google Servers");
String msg = "";
try {
if (mGCM == null) {
mGCM = GoogleCloudMessaging.getInstance(mContext.getApplicationContext());
}
mRegId = mGCM.register(mSenderId);
Log.d(TAG, "Registration is successful " + mRegId);
msg = "Device registered, registration ID=" + mRegId;
StorageHelper.get(mContext.getApplicationContext()).saveGCMRegistrationId(mRegId);
mListener.registrationDone(mRegId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
mListener.errorWhileRegistering(ex);
}
return msg;
}
}.execute(null, null, null);
}
private boolean checkPlayServices() {
Activity activity;
try {
activity = (Activity) mContext;
} catch (Exception e) {
return true;
}
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, activity,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
mListener.errorWhileRegistering(new IllegalStateException("This device is not supported for GCM"));
}
return false;
}
return true;
}
}
| 34.893805 | 115 | 0.610449 |
a0f71afd12e99ea4a7ad57e5cf4f6c54096df971 | 6,437 | package com.old.time.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.text.TextUtils;
import com.old.time.R;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类
* Created by huan on 2017/10/20.
*/
public class StringUtils {
private static final String TAG = "StringUtils";
public static String getLastPathSegment(String content) {
if (content == null || content.length() == 0) {
return "";
}
String[] segments = content.split("/");
if (segments.length > 0) {
return segments[segments.length - 1];
}
return "";
}
/**
* 判断手机格式是否正确
*
* @param mobiles 手机号
*/
public static boolean isMobileNO(String mobiles) {
if (TextUtils.isEmpty(mobiles)) {
return false;
}
String regExp = "^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|17[0-9]|14[0-9])\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(mobiles);
return m.matches();
}
// 验证邮箱地址是否正确
public static boolean checkEmail(String email) {
Pattern pattern = Pattern.compile("^[A-Za-z0-9][\\w\\._]*[a-zA-Z0-9]+@[A-Za-z0-9-_]+\\.([A-Za-z]{2,4})");
Matcher mc = pattern.matcher(email);
return mc.matches();
}
/**
* 获取当前应用程序的版本号
*/
public static String getVersion(Context context) {
String st = context.getResources().getString(R.string.Version_number_is_wrong);
PackageManager pm = context.getPackageManager();
try {
PackageInfo packinfo = pm.getPackageInfo(context.getPackageName(), 0);
String version = packinfo.versionName;
return version;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return st;
}
}
/**
* 读取本地json
*
* @param fileName
* @param context
* @return
*/
public static String getJson(String fileName, Context context) {
//将json数据变成字符串
StringBuilder stringBuilder = new StringBuilder();
try {
//获取assets资源管理器
AssetManager assetManager = context.getAssets();
//通过管理器打开文件并读取
BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
/**
* 十六进制下数字到字符的映射数组
*/
private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
/**
* 对字符串进行MD5编码
*
* @param originString
* @return
*/
public static String encodeByMD5(String originString) {
if (originString != null) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] results = md.digest(originString.getBytes());
String resultString = byteArrayToHexString(results);
return resultString.toUpperCase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 转换字节数组为16进制字串
*
* @param b 字节数组
* @return 十六进制字串
*/
private static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
/**
* 将一个字节转化成16进制形式的字符串
*
* @param b
* @return
*/
private static String byteToHexString(byte b) {
int n = b;
if (n < 0) n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
/**
* 转化分钟
*
* @param duration
* @return
*/
public static String getDurationStr(int duration) {
if (duration == 0) {
return "00:00";
}
String durationStr;
durationStr = duration / 60 > 9 ? "" + duration / 60 : "0" + duration / 60;
durationStr += duration % 60 > 9 ? ":" + duration % 60 : ":0" + duration % 60;
return durationStr;
}
private static final String[] letters = new String[]{"u", "kf", "av", "mwg", "h", "xn", "yi", "pjz", "b", "qrc"};
private static final String[] numbers = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
/**
* 获取加密手机号
*
* @return
*/
public static String getPhoneMobilePassWord(String mobile) {
if (TextUtils.isEmpty(mobile)) {
return "";
}
String[] mMobileChars = mobile.split("");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 1; i < mMobileChars.length; i++) {
stringBuffer.append(letters[Integer.parseInt(mMobileChars[i])]);
}
String newMobile = "Mi" + stringBuffer.toString() + "U";
return newMobile;
}
/**
* 获取解密后的手机号
*
* @param mobilePassWord
* @return
*/
public static String getPhoneMobile(String mobilePassWord) {
mobilePassWord = mobilePassWord.replace("Mi", "").replace("U", "");
for (int i = 0; i < 10; i++) {
mobilePassWord = mobilePassWord.replace(letters[i], numbers[i]);
}
return mobilePassWord;
}
/**
* 转化时间
*
* @param timeStr 2019-03-08 17:34:45
* @return 19/3/8 17:34
*/
public static String getCreateTime(String timeStr) {
if (TextUtils.isEmpty(timeStr) || timeStr.length() != 19) {
return timeStr;
}
return timeStr.replace("-", "/").substring(5, 16);
}
public static String subString(String text, int num) {
String content = "";
if (text.length() > num) {
content = text.substring(0, num - 1) + "...";
} else {
content = text;
}
return content;
}
}
| 26.599174 | 127 | 0.542799 |
426fa47628185a2164f3fc118f924f9fdcebcc5d | 16,937 | package org.jordon.security.core.crypto.symmetry;
import org.jordon.security.constant.DESConstants;
import org.jordon.security.core.crypto.CipherService;
import org.jordon.security.util.ArrayUtil;
import org.jordon.security.util.Base64Util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class DESCipherService implements CipherService {
private boolean printMsg;
private List<String> messages;
private String workingMode;
private char[] IV;
private char[][] counters;
public List<String> getMessages() {
return messages;
}
public void clearMessages() {
messages.clear();
}
public DESCipherService(boolean printMsg) {
this.printMsg = printMsg;
this.messages = new ArrayList<>();
}
public void setWorkingMode(String workingMode) {
this.workingMode = workingMode;
}
/**
* 明文填充,最后一组的最后8位表示填充长度
*/
public char[][] padPlaintext(char[] plaintextBytes) {
System.out.println("填充前的比特串: " + String.valueOf(plaintextBytes));
int length = plaintextBytes.length;
int lastBlockBits = length % 64;
// 现有块数
int blockCount = length / 64;
// 待伪随机填充位数
int randPadCount = 64 - lastBlockBits - 8;
char[] padded = new char[(blockCount + 1) * 64];
System.arraycopy(plaintextBytes, 0, padded, 0, length);
// 伪随机填充
for (int i = length; i < padded.length - 8; i++) {
padded[i] = new Random().nextBoolean() ? '1' : '0';
}
// 填充最后一个字节比特串
char[] padCountVal = Integer.toBinaryString(
(randPadCount & 0xff) + 0x0100).substring(1).toCharArray();
System.arraycopy(padCountVal, 0, padded, padded.length - 8, 8);
System.out.println("填充后的比特串: " + String.valueOf(padded));
// 将填充完比特穿分组
char[][] blocks = new char[blockCount + 1][64];
for (int i = 0; i < blockCount + 1; i++) {
System.arraycopy(padded, i * 64, blocks[i], 0, 64);
}
return blocks;
}
/**
* encrypt plaintext with key
* @param plaintext text to be encrypted
* @param key key
* @return encrypted text
* @throws UnsupportedEncodingException caused by String.getBytes()
*/
@Override
public String encrypt(String plaintext, String key) throws UnsupportedEncodingException {
if (printMsg) {
messages.add(ArrayUtil.printInfo("plaintext", plaintext, false));
messages.add(ArrayUtil.printInfo("keyText", key, true));
}
char[] keyBytes = ArrayUtil.bytesToChars(key.getBytes("UTF-8"));
// 获取填充后的所有分组
char[] plaintextBytes = ArrayUtil.bytesToChars(plaintext.getBytes());
return encrypt(plaintextBytes, keyBytes);
}
/**
* 对文件进行加密
* @param file 文件
* @param key 密钥
* @return 加密结果
*/
public String encryptFile(File file, String key) throws UnsupportedEncodingException, FileNotFoundException {
if (printMsg) {
messages.add(ArrayUtil.printInfo("fileName", file.getName(), false));
messages.add(ArrayUtil.printInfo("keyText", key, true));
}
char[] keyBytes = ArrayUtil.bytesToChars(key.getBytes("UTF-8"));
// 获取填充后的所有分组
char[] plaintextBytes = ArrayUtil.bytesToChars(ArrayUtil.getBytes(file));
return encrypt(plaintextBytes, keyBytes);
}
public String encrypt(char[] plaintextBytes, char[] keyBytes) {
// 填充、分组
char[][] blocks = padPlaintext(plaintextBytes);
int blockCount = blocks.length;
char[] cipherVal = new char[blocks.length * 64];
switch (workingMode) {
case "ECB":
// 对一块进行加密
for (int i = 0; i < blockCount; i++) {
char[] aCipher = encryptABlock(blocks[i], keyBytes);
System.arraycopy(aCipher, 0, cipherVal, i * 64, 64);
}
break;
case "CBC":
// 初始向量IV
char[] IV = ranBlock();
this.IV = IV;
char[] input;
for (int i = 0; i < blocks.length; i++) {
input = ArrayUtil.xor(IV, blocks[i], 64);
char[] aCipher = encryptABlock(input, keyBytes);
IV = aCipher;
System.arraycopy(aCipher, 0, cipherVal, i * 64, 64);
}
break;
case "CTR":
// 初始化blockCount个计数器
counters = new char[blockCount][64];
for (int i = 0; i < blockCount; i++) {
counters[i] = ranBlock();
}
// 加密过程
for (int i = 0; i < blocks.length; i++) {
char[] aCipher = ArrayUtil.xor(blocks[i], encryptABlock(counters[i], keyBytes), 64);
System.arraycopy(aCipher, 0, cipherVal, i * 64, 64);
}
break;
}
if (printMsg) {
messages.add(ArrayUtil.printBitChars("cipher blocks bits", cipherVal));
}
ArrayUtil.printBitChars("cipherVal", cipherVal);
return Base64Util.encode(cipherVal);
}
/**
* 产生随机64位比特串
* @return 64位比特串
*/
private char[] ranBlock() {
char[] result = new char[64];
for (int i = 0; i < 64; i++) {
result[i] = new Random().nextBoolean() ? '1' : '0';
}
return result;
}
/**
* 单块加密
* @param plaintextBytes 明文分组(64位)
* @param keyBytes 密钥串
* @return 加密结果
*/
private char[] encryptABlock(char[] plaintextBytes, char[] keyBytes) {
if (printMsg) {
messages.add(ArrayUtil.printBitChars("plaintext bits", plaintextBytes));
messages.add(ArrayUtil.printBitChars("key bits", keyBytes));
}
char[][] subKeys = generateSubKeys(keyBytes);
char[] result = encode(plaintextBytes, subKeys);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("encryptedText bits", result));
}
return result;
}
/**
* main encryption logic
* @param plaintextBytes plaintext bits in chars format
* @param subKeys subKeys bits in chars format
* @return encryption result bits in chars format
*/
public char[] encode(char[] plaintextBytes, char[][] subKeys) {
System.out.println(plaintextBytes.length);
// initial permutation, get 64 bit disrupted array
char[] chars = ArrayUtil.disruptArray(plaintextBytes, DESConstants.IP);
if (printMsg) {
ArrayUtil.printBitChars("plaintext after ip", chars);
}
int length = chars.length;
String binaryArrayStr = String.valueOf(chars);
char[] left = binaryArrayStr.substring(0, length / 2).toCharArray();
char[] right = binaryArrayStr.substring(length / 2).toCharArray();
char[] coreEncrypted, xorResult;
if (printMsg) {
messages.add(ArrayUtil.printBitChars("L0", left));
messages.add(ArrayUtil.printBitChars("R0", right));
}
for (int i = 0; i < 16; i++) {
if (printMsg) {
System.out.println();
messages.add("\n");
}
coreEncrypted = coreEncrypt(right, subKeys[i]);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("[f] " +
"P Replacement", coreEncrypted));
}
// get 32-bit array
xorResult = String.valueOf(ArrayUtil.xor(left, coreEncrypted, 48))
.substring(16).toCharArray();
left = right;
right = xorResult;
if (printMsg){
messages.add(ArrayUtil.printBitChars("[" + (i + 1) + "] " + "left", left));
messages.add(ArrayUtil.printBitChars("[" + (i + 1) + "] " + "right", right));
}
}
if (printMsg) {
messages.add("\n");
System.out.println();
}
char[] calResult = ArrayUtil.concat(right, left);
return ArrayUtil.disruptArray(calResult, DESConstants.inverseIP);
}
/**
* decrypt encrypted text with key
* @param encryptedText encrypted text
* @param key key
* @return decrypted origin plaintext
* @throws UnsupportedEncodingException caused by String.getBytes()
*/
@Override
public String decrypt(String encryptedText, String key) throws UnsupportedEncodingException {
if (printMsg) {
messages.add(ArrayUtil.printInfo("encryptedText", encryptedText, false));
messages.add(ArrayUtil.printInfo("key", key, true));
}
// 密文串
char[] encryptedTextBytes = Base64Util.decodeToChars(encryptedText);
// 密文分组
char[][] cipherBlocks = new char[encryptedTextBytes.length / 64][64];
char[] keyBytes = ArrayUtil.bytesToChars(key.getBytes("UTF-8"));
char[] decryptBytes = new char[cipherBlocks.length * 64];
// 处理工作模式
switch (workingMode) {
case "ECB":
for (int i = 0; i < cipherBlocks.length; i++) {
// 将密文串分组
System.arraycopy(encryptedTextBytes, i * 64, cipherBlocks[i], 0, 64);
// 单块解密
char[] aBlockResult = decryptABlock(cipherBlocks[i], keyBytes);
// 解密结果串成一串
System.arraycopy(aBlockResult, 0, decryptBytes, i * 64, 64);
}
break;
case "CBC":
char[] input = IV;
for (int i = 0; i < cipherBlocks.length; i++) {
// 将密文串分组
System.arraycopy(encryptedTextBytes, i * 64, cipherBlocks[i], 0, 64);
// 单块解密
char[] aBlockResult = ArrayUtil.xor(input, decryptABlock(cipherBlocks[i], keyBytes), 64);
// 下一个异或输入为当前密文块
input = cipherBlocks[i];
// 解密结果串成一串
System.arraycopy(aBlockResult, 0, decryptBytes, i * 64, 64);
}
break;
case "CTR":
for (int i = 0; i < cipherBlocks.length; i++) {
System.arraycopy(encryptedTextBytes, i * 64, cipherBlocks[i], 0, 64);
char[] aBlockResult = ArrayUtil.xor(cipherBlocks[i], encryptABlock(counters[i], keyBytes), 64);
// 解密结果串成一串
System.arraycopy(aBlockResult, 0, decryptBytes, i * 64, 64);
}
break;
}
// 处理填充
// 1. 抽出最后一个字节
String decryptBytesStr = String.valueOf(decryptBytes);
int paddedBits = Integer.parseInt(decryptBytesStr.substring(decryptBytes.length - 8), 2);
System.out.println("pad " + paddedBits);
char[] origin = decryptBytesStr.substring(0, decryptBytes.length - 8 - paddedBits).toCharArray();
String plaintext = ArrayUtil.segmentAndPrintChars(origin);
// 2. 去掉填充信息
if (printMsg) {
messages.add(ArrayUtil.printBitChars("plaintext bits", origin));
messages.add(ArrayUtil.printInfo("plaintext", plaintext, false));
}
return plaintext;
}
private char[] decryptABlock(char[] encryptedTextBlock, char[] keyBytes) {
char[][] inverseKeys = inverseSubKeys(generateSubKeys(keyBytes));
char[] result = encode(encryptedTextBlock, inverseKeys);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("encryptedBlock bits", encryptedTextBlock));
messages.add(ArrayUtil.printBitChars("key bits", keyBytes));
messages.add(ArrayUtil.printBitChars("decryptedText bits", result));
}
return result;
}
/**
* change over the sub keys for reusing the encode function
* @param subKeys origin subKeys
* @return inverse subKeys
*/
private char[][] inverseSubKeys(char[][] subKeys) {
char[][] inverseKeys = new char[subKeys.length][];
for (int i = 0; i < subKeys.length; i++) {
inverseKeys[i] = subKeys[subKeys.length - 1 - i];
}
return inverseKeys;
}
/**
* core function of DES,
* disruption and confusion most because of
* substituting and selecting operation
* @param right the right split of plaintext of xor result of last calculation
* @param subKey subKey in round i
* @return result after P Replacement
*/
private char[] coreEncrypt(char[] right, char[] subKey) {
// 1. do selection for 32-bit right disrupted info
// get 48-bit extended array
if (printMsg) {
messages.add(ArrayUtil.printBitChars("[f] 32-bit input", right));
}
char[] extendedRight = ArrayUtil.disruptArray(right, DESConstants.E);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("[f] Selection", extendedRight));
messages.add(ArrayUtil.printBitChars("[f] subKey", subKey));
}
// 2. xor 48-bit extendedRight and 48-bit subKey
char[] xorResult = ArrayUtil.xor(extendedRight, subKey, 48);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("[f] xor", xorResult));
}
// 3. substitute box mixing and confusing
// (1) format 1x48 matrix into an 8x6 matrix
char[][] twoDimensionArray = ArrayUtil.segmentDimension(xorResult, 8, 6);
StringBuilder outputBuilder = new StringBuilder();
for (int i = 0; i < twoDimensionArray.length; i++) {
char[] rowBits = {
twoDimensionArray[i][0],
twoDimensionArray[i][5]
};
char[] columnBits = {
twoDimensionArray[i][1], twoDimensionArray[i][2],
twoDimensionArray[i][3], twoDimensionArray[i][4]
};
// (2) obtain the index of output value in SUBSTITUTE_BOX[i]
int rowIndex = Integer.parseInt(String.valueOf(rowBits), 2);
int columnIndex = Integer.parseInt(String.valueOf(columnBits), 2);
// (3) obtain output of Si
short output = DESConstants.SUBSTITUTE_BOX[i][rowIndex][columnIndex];
outputBuilder.append(Integer.toBinaryString((output & 0x0f) + 0x10).substring(1));
}
char[] substitutedResult = outputBuilder.toString().toCharArray();
if (printMsg) {
messages.add(ArrayUtil.printBitChars("[F] SBox", substitutedResult));
}
// 4. replacement P, returns 28-bit array
return ArrayUtil.disruptArray(substitutedResult, DESConstants.P);
}
/**
* generate 16 48-bit sub keys
* @param keyBytes origin key bits in chars format
* @return 16-elements subKey array
*/
public char[][] generateSubKeys(char[] keyBytes) {
char[][] subKeys = new char[16][48];
// Replacement and selection 1
char[] c = ArrayUtil.disruptArray(keyBytes, DESConstants.PERMUTED_CHOICE_1_C0);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("Permuted Choice 1 C0", c));
}
char[] d = ArrayUtil.disruptArray(keyBytes, DESConstants.PERMUTED_CHOICE_1_D0);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("Permuted Choice 1 D0", d));
messages.add("\nStart to generate sub keys......");
System.out.println("\nStart to generate sub keys......");
}
// loop left shifting
for (int i = 0; i < 16; i++) {
c = ArrayUtil.leftShift(c, DESConstants.moveBit[i]);
d = ArrayUtil.leftShift(d, DESConstants.moveBit[i]);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("[" + (i + 1) + "]" + " leftShifting C", c));
messages.add(ArrayUtil.printBitChars("[" + (i + 1) + "]" + " leftShifting D", d));
}
// 56 bit concat
char[] concatChars = ArrayUtil.concat(c, d);
if (printMsg) {
messages.add(ArrayUtil.printBitChars("[" + (i + 1) + "]" + " concatChars", concatChars));
}
// Replacement and selection 2, get 48 bit array
char[] key = ArrayUtil.disruptArray(concatChars, DESConstants.replace2);
subKeys[i] = key;
if (printMsg) {
String prefix = "[" + (i + 1) + "] subKey";
messages.add(ArrayUtil.printBitChars(prefix, key));
messages.add("\n");
System.out.println();
}
}
return subKeys;
}
}
| 36.580994 | 115 | 0.563205 |
b7d3f0f6e787d040405d5c0b3adf6ea513e7aa71 | 309 | package com.neusoft;
/**
* @author liuboting
* @date 2020/7/23 21:52
*/
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
} | 13.434783 | 38 | 0.530744 |
509c1e0dce3e4704b1d0d9780e1ea72a97fbb2fe | 4,330 | package jp.go.ndl.lab.back.batch;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import jp.go.ndl.lab.back.Application;
import jp.go.ndl.lab.back.infra.EsDataStoreFactory;
import jp.go.ndl.lab.back.tools.GenericEsClient;
import jp.go.ndl.lab.common.utils.LabFileUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* ElasticSearchの全データをダンプするバッチ。version情報は失われる。
*/
@Slf4j
@Component("dump-data")
@Profile({Application.MODE_BATCH})
@Lazy
public class DumpAllDataBatch extends AbstractBatch {
public static void main(String[] args) throws Throwable {
Application.main(Application.MODE_BATCH, "dump-data", "ignore\\dump0814", "nonitem");
}
@Autowired
GenericEsClient esClient;
private ObjectMapper mapper = new ObjectMapper();
private Path outputDir;
@Override
public void run(String[] params) {
outputDir = Paths.get(params[0]);
if (!Files.exists(outputDir)) {
try {
Files.createDirectories(outputDir);
} catch (IOException ex) {
log.error("出力ディレクトリ作成失敗", ex);
}
}
String index = params[1];
try {
if (index.equals("all")) {
dumpAll();
} else {
dump(index);
}
} catch (Exception e) {
log.error("{}", e);
}
}
private void dumpAll() throws Exception {
dump("jd_book");
dump("jd_illustration");
dump("jd_page");
}
private void dump(String indexName) throws IOException {
log.info("start dump index {}", indexName);
int count = 0;
Path outputFile = outputDir.resolve(indexName + ".jsonl.gz");
final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.scroll(scroll);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = esClient.highClient.search(searchRequest, RequestOptions.DEFAULT);
String scrollId = searchResponse.getScrollId();
SearchHit[] searchHits = searchResponse.getHits().getHits();
try (LabFileUtils.Writer bw = LabFileUtils.gWriter(outputFile)) {
//1回目書き出し
for (SearchHit hit : searchHits) {
bw.writeDataV(hit.getId(), hit.getSourceAsString());
count++;
}
//継続
while (searchHits != null && searchHits.length > 0) {
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
searchResponse = esClient.highClient.scroll(scrollRequest, RequestOptions.DEFAULT);
scrollId = searchResponse.getScrollId();
searchHits = searchResponse.getHits().getHits();
for (SearchHit hit : searchHits) {
bw.writeDataV(hit.getId(), hit.getSourceAsString());
if (++count % 100000 == 0) {
log.info(" count {}", count);
}
}
}
} catch (Exception e) {
log.error("書き込み失敗", e);
}
log.info(" total {}", count);
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(scrollId);
ClearScrollResponse clearScrollResponse = esClient.highClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
}
}
| 35.785124 | 126 | 0.644573 |
2fa9cf279d4a49e3521519648abe3b2973436307 | 9,065 | /*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.ui.panel;
//~--- non-JDK imports --------------------------------------------------------
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.track.Track;
import org.broad.igv.track.TrackClickEvent;
import org.broad.igv.track.TrackMenuUtils;
import org.broad.igv.ui.IGV;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author eflakes
*/
abstract public class TrackPanelComponent extends JPanel {
private static Logger log = Logger.getLogger(TrackPanelComponent.class);
List<MouseableRegion> mouseRegions;
private TrackPanel trackPanel;
/**
* A scheduler is used to distinguish a click from a double click.
*/
protected ClickTaskScheduler clickScheduler = new ClickTaskScheduler();
public TrackPanelComponent(TrackPanel trackPanel) {
this.trackPanel = trackPanel;
setFocusable(true);
mouseRegions = new ArrayList();
initKeyDispatcher();
}
private void initKeyDispatcher() {
final Action delTracksAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
TrackMenuUtils.removeTracksAction(IGV.getInstance().getSelectedTracks());
}
};
if (Globals.isDevelopment()) {
final KeyStroke delKey = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false);
final KeyStroke backspaceKey = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0, false);
getInputMap().put(delKey, "deleteTracks");
getInputMap().put(backspaceKey, "deleteTracks");
getActionMap().put("deleteTracks", delTracksAction);
}
}
public TrackPanel getTrackPanel() {
if (trackPanel == null) {
trackPanel = (TrackPanel) getParent();
}
return trackPanel;
}
public String getTrackSetID() {
return getTrackPanel().getName();
}
protected void addMousableRegion(MouseableRegion region) {
mouseRegions.add(region);
}
protected void removeMousableRegions() {
mouseRegions.clear();
}
protected List<MouseableRegion> getMouseRegions() {
return mouseRegions;
}
public boolean scrollTo(String trackName) {
Track t = findNextTrackMatching(trackName);
if (t != null) {
IGV.getInstance().clearSelections();
t.setSelected(true);
if (trackPanel.getScrollPane().getVerticalScrollBar().isShowing()) {
trackPanel.getScrollPane().getVerticalScrollBar().setValue(t.getY());
}
return true;
}
return false;
}
int searchIdx = 0;
private synchronized Track findNextTrackMatching(String trackName) {
List<Track> tracks = getAllTracks();
searchIdx = Math.min(searchIdx, tracks.size());
for (int i = searchIdx; i < tracks.size(); i++) {
Track t = tracks.get(i);
if (t.getName().toUpperCase().contains(trackName.toUpperCase())) {
searchIdx = i + 1;
return t;
}
}
for (int i = 0; i < searchIdx; i++) {
Track t = tracks.get(i);
if (t.getName().toUpperCase().contains(trackName.toUpperCase())) {
searchIdx = i + 1;
return t;
}
}
return null;
}
public String getPopupMenuTitle(int x, int y) {
Collection<Track> tracks = getSelectedTracks();
String popupTitle;
if (tracks.size() == 1) {
popupTitle = tracks.iterator().next().getName();
} else {
popupTitle = "Total Tracks Selected: " + tracks.size();
}
return popupTitle;
}
protected Collection<Track> getSelectedTracks() {
return IGV.getInstance().getSelectedTracks();
}
public List<Track> getAllTracks() {
TrackPanel dataTrackView = (TrackPanel) getParent();
return dataTrackView.getTracks();
}
protected void openPopupMenu(TrackClickEvent te) {
openPopupMenu(te, null);
}
protected void openPopupMenu(TrackClickEvent te, List<Component> extraItems) {
MouseEvent e = te.getMouseEvent();
final Collection<Track> selectedTracks = getSelectedTracks();
if (selectedTracks.size() == 0) {
return;
}
IGVPopupMenu menu = null;
// If a single track is selected, give it an opportunity to provide the popup menu
if (selectedTracks.size() == 1) {
Track track = selectedTracks.iterator().next();
menu = track.getPopupMenu(te);
}
// If still no menu, create a generic one with common items
if (menu == null) {
String title = getPopupMenuTitle(e.getX(), e.getY());
menu = TrackMenuUtils.getPopupMenu(selectedTracks, title, te);
}
// Add additional items, if any
if (extraItems != null) {
menu.addSeparator();
for (Component item : extraItems) {
menu.add(item);
}
}
if (menu.includeStandardItems()) {
TrackMenuUtils.addPluginItems(menu, selectedTracks, te);
// Add saveImage items
menu.addSeparator();
JMenuItem savePng = new JMenuItem("Save PNG image...");
savePng.addActionListener(e1 -> saveImage("png"));
menu.add(savePng);
JMenuItem saveSvg = new JMenuItem("Save SVG image...");
saveSvg.addActionListener(e1 -> saveImage("svg"));
menu.add(saveSvg);
// Add export features
ReferenceFrame frame = FrameManager.getDefaultFrame();
JMenuItem exportFeats = TrackMenuUtils.getExportFeatures(selectedTracks, frame);
if (exportFeats != null) menu.add(exportFeats);
JMenuItem exportNames = new JMenuItem("Export track names...");
exportNames.addActionListener(e12 -> TrackMenuUtils.exportTrackNames(selectedTracks));
menu.add(exportNames);
menu.addSeparator();
menu.add(TrackMenuUtils.getRemoveMenuItem(selectedTracks));
}
menu.show(e.getComponent(), e.getX(), e.getY());
}
protected void toggleTrackSelections(MouseEvent e) {
for (MouseableRegion mouseRegion : mouseRegions) {
if (mouseRegion.containsPoint(e.getX(), e.getY())) {
IGV.getInstance().toggleTrackSelections(mouseRegion.getTracks());
return;
}
}
}
protected void clearTrackSelections() {
IGV.getInstance().clearSelections();
IGV.getMainFrame().repaint();
}
protected void selectTracks(MouseEvent e) {
for (MouseableRegion mouseRegion : mouseRegions) {
if (mouseRegion.containsPoint(e.getX(), e.getY())) {
IGV.getInstance().setTrackSelections(mouseRegion.getTracks());
return;
}
}
}
protected boolean isTrackSelected(MouseEvent e) {
for (MouseableRegion mouseRegion : mouseRegions) {
if (mouseRegion.containsPoint(e.getX(), e.getY())) {
for (Track t : mouseRegion.getTracks()) {
if (t.isSelected()) {
return true;
}
}
}
}
return false;
}
public void saveImage(String extension) {
IGV.getInstance().saveImage(getTrackPanel().getScrollPane(), "igv_panel", extension);
}
}
| 31.807018 | 100 | 0.61401 |
357e9bfef078f0764091c03e4cf0b56f324a1c1c | 8,136 | package com.github.jordanpottruff.jgml;
/**
* A matrix of dimensions 3x3.
*/
public class Mat3 extends MatN {
/**
* Constructs a Mat3 from a two-dimensional array of elements. The outer-array must contain
* three inner-arrays, with each being of length three. The order of the 2D array is preserved.
*
* @param array the 2D array of elements.
* @throws IllegalArgumentException if the outer-array does not contain three inner-arrays.
* @throws IllegalArgumentException if the inner-arrays are not all of length three.
*/
public Mat3(double[][] array) {
super(array);
Util.verifyExactDimension(array, 3, 3);
}
/**
* Constructs a Mat3 from a matrix object. The matrix must contain three rows and three columns.
* The order of the elements will be preserved.
*
* @param mat the matrix object.
* @throws IllegalArgumentException if the matrix object is not of dimension 3x3.
*/
public Mat3(Mat mat) {
super(mat);
Util.verifyExactDimension(mat.toArray(), 3, 3);
}
/**
* Constructs a Mat3 from three Vec3 objects. The vectors will create the column vectors of the
* new matrix.
*
* @param vec1 the first column vector.
* @param vec2 the second column vector.
* @param vec3 the third column vector.
*/
public Mat3(Vec3 vec1, Vec3 vec2, Vec3 vec3) {
super(new double[][]{vec1.toArray(), vec2.toArray(), vec3.toArray()});
}
/**
* Creates a 3x3 identity matrix.
*
* @return the identity matrix.
*/
public static Mat3 createIdentityMatrix() {
return new Mat3(Util.identity(3));
}
/**
* Returns the product of multiplying a series of 3x3 matrices together. The order of the
* arguments represents the order of multiplications such that A*B*C is equivalent to {@code
* chain(A, B, C)}.
*
* @param mat the first matrix of the product chain.
* @param matrices the rest of the matrices of the product chain.
* @return the product of the series of matrices.
*/
public static Mat3 chain(Mat3 mat, Mat3... matrices) {
return new Mat3(MatMN.chain(mat, matrices));
}
/**
* {@inheritDoc}
*/
@Override
public Mat3 invert() {
return new Mat3(super.invert());
}
/**
* {@inheritDoc}
*/
@Override
public Mat3 add(Mat mat) {
return new Mat3(super.add(mat));
}
/**
* {@inheritDoc}
*/
@Override
public Mat3 subtract(Mat mat) {
return new Mat3(super.subtract(mat));
}
/**
* {@inheritDoc}
*/
@Override
public Mat3 scale(double scalar) {
return new Mat3(super.scale(scalar));
}
/**
* {@inheritDoc}
*/
@Override
public Mat3 multiply(MatN mat) {
return new Mat3(super.multiply(mat));
}
/**
* Calculates the multiplication of this 3x3 matrix with the passed 3-dimensional vector.
*
* @param vec the 3-dimensional vector to multiply by.
* @return the product, always a 3-dimensional vector.
*/
public Vec3 multiply(Vec3 vec) {
return new Vec3(super.multiply(vec));
}
/**
* {@inheritDoc}
*/
@Override
public Mat3 inverse() {
return new Mat3(super.inverse());
}
/**
* A Mat3 builder that provides methods to construct an affine transformation. The order of
* execution of operations follows the order that the methods were called on the builder object.
*/
public static class TransformBuilder {
private Mat3 matrix;
/**
* Creates a new transformation.
*/
public TransformBuilder() {
matrix = createIdentityMatrix();
}
/**
* Scales in both axes.
*
* @param x how much to scale in the x-axis.
* @param y how much to scale in the y-axis.
* @return the transformed builder.
*/
public TransformBuilder scale(double x, double y) {
double[][] operation = createIdentityMatrix().toArray();
operation[0][0] = x;
operation[1][1] = y;
applyOperation(operation);
return this;
}
/**
* Scales along the x-axis.
*
* @param factor how much to scale in the x-axis.
* @return the transformed builder.
*/
public TransformBuilder scaleX(double factor) {
return scale(factor, 1.0);
}
/**
* Scales along the y-axis.
*
* @param factor how much to scale in the y-axis.
* @return the transformed builder.
*/
public TransformBuilder scaleY(double factor) {
return scale(1.0, factor);
}
/**
* Translates in both axes.
*
* @param x how much to translate along the x-axis.
* @param y how much to translate along the y-axis.
* @return the transformed builder.
*/
public TransformBuilder translate(double x, double y) {
double[][] operation = createIdentityMatrix().toArray();
operation[2][0] = x;
operation[2][1] = y;
applyOperation(operation);
return this;
}
/**
* Translates in both axes.
*
* @param amounts how much to translate along each axis, represented as a Vec2.
* @return the transformed builder.
*/
public TransformBuilder translate(Vec2 amounts) {
return translate(amounts.x(), amounts.y());
}
/**
* Translates along the x-axis.
*
* @param factor how much to translate along the x-axis.
* @return the transformed builder.
*/
public TransformBuilder translateX(double factor) {
return translate(factor, 0.0);
}
/**
* Translates along the y-axis.
*
* @param factor how much to translate along the y-axis.
* @return the transformed builder.
*/
public TransformBuilder translateY(double factor) {
return translate(0.0, factor);
}
/**
* Rotates (along the invisible third axis perpendicular to the view plane).
*
* @param radians the amount to rotate by, in radians.
* @return the transformed builder.
*/
public TransformBuilder rotate(double radians) {
double cos = Math.cos(radians);
double sin = Math.sin(radians);
double[][] operation = createIdentityMatrix().toArray();
operation[0][0] = cos;
operation[1][0] = -sin;
operation[0][1] = sin;
operation[1][1] = cos;
applyOperation(operation);
return this;
}
/**
* Shears the x-axis based on the y factor.
*
* @param y shear factor for y-axis.
* @return the transformed builder.
*/
public TransformBuilder shearX(double y) {
double[][] operation = createIdentityMatrix().toArray();
operation[1][0] = y;
applyOperation(operation);
return this;
}
/**
* Shears the y-axis based on x factor.
*
* @param x shear factor for x-axis.
* @return the transformed builder.
*/
public TransformBuilder shearY(double x) {
double[][] operation = createIdentityMatrix().toArray();
operation[0][1] = x;
applyOperation(operation);
return this;
}
/**
* Creates the transformation matrix.
*
* @return the transformation matrix.
*/
public Mat3 build() {
return new Mat3(matrix);
}
private void applyOperation(double[][] operation) {
Mat3 operationMat = new Mat3(operation);
matrix = operationMat.multiply(matrix);
}
}
}
| 29.057143 | 100 | 0.55998 |
5686af5e3dfa2fcd7a248f4e0275ce77e6d6416b | 340 | package br.com.zup.estacionamento;
public class EstacionamentoException extends Exception {
private static final long serialVersionUID = 7377982967933273901L;
private String mensagem;
public EstacionamentoException(String mensagem) {
super();
this.mensagem = mensagem;
}
public String getMensagem() {
return mensagem;
}
}
| 17.894737 | 67 | 0.773529 |
909a97e8b49bd85bba634a91c05a19f64d8a98de | 26,855 | /*
* Copyright 2015 Gregory Graham
*
* 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 nz.co.gregs.dbvolution.expressions;
import nz.co.gregs.dbvolution.results.RangeComparable;
import nz.co.gregs.dbvolution.results.DateRepeatResult;
import java.util.HashSet;
import java.util.Set;
import nz.co.gregs.dbvolution.DBDatabase;
import nz.co.gregs.dbvolution.DBRow;
import nz.co.gregs.dbvolution.databases.supports.SupportsDateRepeatDatatypeFunctions;
import nz.co.gregs.dbvolution.datatypes.DBBoolean;
import nz.co.gregs.dbvolution.datatypes.DBDateRepeat;
import org.joda.time.Period;
/**
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @author gregory.graham
*/
public class DateRepeatExpression implements DateRepeatResult, RangeComparable<DateRepeatResult>, ExpressionColumn<DBDateRepeat> {
DateRepeatResult innerDateRepeatResult = null;
private boolean nullProtectionRequired = false;
/**
* DateRepeat values are often stored as Strings of the format
* P2015Y12M30D23h59n59.0s
*/
public static final String INTERVAL_PREFIX = "P";
/**
* DateRepeat values are often stored as Strings of the format
* P2015Y12M30D23h59n59.0s
*/
public static final String YEAR_SUFFIX = "Y";
/**
* DateRepeat values are often stored as Strings of the format
* P2015Y12M30D23h59n59.0s
*/
public static final String MONTH_SUFFIX = "M";
/**
* DateRepeat values are often stored as Strings of the format
* P2015Y12M30D23h59n59.0s
*/
public static final String DAY_SUFFIX = "D";
/**
* DateRepeat values are often stored as Strings of the format
* P2015Y12M30D23h59n59.0s
*/
public static final String HOUR_SUFFIX = "h";
/**
* DateRepeat values are often stored as Strings of the format
* P2015Y12M30D23h59n59.0s
*/
public static final String MINUTE_SUFFIX = "n";
/**
* DateRepeat values are often stored as Strings of the format
* P2015Y12M30D23h59n59.0s
*/
public static final String SECOND_SUFFIX = "s";
/**
* Default constructor
*
*/
protected DateRepeatExpression() {
}
/**
* Creates a new DateRepeatExression that represents the value supplied.
*
* @param interval
*/
public DateRepeatExpression(Period interval) {
innerDateRepeatResult = new DBDateRepeat(interval);
if (interval == null || innerDateRepeatResult.getIncludesNull()) {
nullProtectionRequired = true;
}
}
/**
* Creates a new DateRepeatExression that represents the DateRepeat value
* supplied.
*
* @param interval the time period from which to create a DateRepeat value
*/
public DateRepeatExpression(DateRepeatResult interval) {
innerDateRepeatResult = interval;
if (interval == null || innerDateRepeatResult.getIncludesNull()) {
nullProtectionRequired = true;
}
}
/**
* Creates a new DateRepeatExression that represents the value supplied.
*
* <p>
* Equivalent to {@code new DateRepeatExpression(period)}
*
* @param period the time period from which to create a DateRepeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a DateRepeat expression representing the value supplied.
*/
public static DateRepeatExpression value(Period period) {
return new DateRepeatExpression(period);
}
/**
* Creates a new DateRepeatExpression that represents the value supplied.
*
* <p>
* Equivalent to {@code new DateRepeatExpression(period)}
*
* @param period the time period from which to create a DateRepeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a DateRepeat expression representing the value supplied.
*/
public static DateRepeatExpression value(DateRepeatResult period) {
return new DateRepeatExpression(period);
}
@Override
public DateRepeatExpression copy() {
return new DateRepeatExpression(innerDateRepeatResult);
}
@Override
public DBDateRepeat getQueryableDatatypeForExpressionValue() {
return new DBDateRepeat();
}
@Override
public String toSQLString(DBDatabase db) {
return innerDateRepeatResult.toSQLString(db);
}
@Override
public boolean isAggregator() {
return innerDateRepeatResult.isAggregator();
}
@Override
public Set<DBRow> getTablesInvolved() {
return innerDateRepeatResult.getTablesInvolved();
}
@Override
public boolean isPurelyFunctional() {
return innerDateRepeatResult == null ? true : innerDateRepeatResult.isPurelyFunctional();
}
@Override
public boolean getIncludesNull() {
return nullProtectionRequired || innerDateRepeatResult.getIncludesNull();
}
/**
* Returns TRUE if this expression evaluates to NULL, otherwise FALSE.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression isNull() {
return BooleanExpression.isNull(this);
}
/**
* Returns TRUE if this expression evaluates to a smaller or more negative
* offset than the provided value, otherwise FALSE.
*
* @param period the time period that might be greater in duration than this expression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression isLessThan(Period period) {
return this.isLessThan(value(period));
}
/**
* Returns TRUE if this expression evaluates to a smaller or more negative
* offset than the provided value, otherwise FALSE.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression isLessThan(DateRepeatResult anotherInstance) {
return new BooleanExpression(new DateRepeatDateRepeatWithBooleanResult(this, anotherInstance) {
@Override
protected String doExpressionTransform(DBDatabase db) {
return db.getDefinition().doDateRepeatLessThanTransform(getFirst().toSQLString(db), getSecond().toSQLString(db));
}
});
}
/**
* Returns TRUE if this expression evaluates to a greater or less negative
* offset than the provided value, otherwise FALSE.
*
* @param period the time period that might be lesser in duration than this expression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression isGreaterThan(Period period) {
return this.isGreaterThan(value(period));
}
/**
* Returns TRUE if this expression evaluates to a smaller or more negative
* offset than the provided value, otherwise FALSE.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression isGreaterThan(DateRepeatResult anotherInstance) {
return new BooleanExpression(new DateRepeatDateRepeatWithBooleanResult(this, anotherInstance) {
@Override
protected String doExpressionTransform(DBDatabase db) {
return db.getDefinition().doDateRepeatGreaterThanTransform(getFirst().toSQLString(db), getSecond().toSQLString(db));
}
});
}
/**
* Returns TRUE if this expression evaluates to an equal or smaller offset
* than the provided value, otherwise FALSE.
*
* @param period the time period that might be greater in duration than this expression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression isLessThanOrEqual(Period period) {
return this.isLessThanOrEqual(value(period));
}
/**
* Returns TRUE if this expression evaluates to an equal or smaller offset
* than the provided value, otherwise FALSE.
*
* @param anotherInstance the time period that might be greater in duration than this expression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression isLessThanOrEqual(DateRepeatResult anotherInstance) {
return new BooleanExpression(new DateRepeatDateRepeatWithBooleanResult(this, anotherInstance) {
@Override
protected String doExpressionTransform(DBDatabase db) {
return db.getDefinition().doDateRepeatLessThanEqualsTransform(getFirst().toSQLString(db), getSecond().toSQLString(db));
}
});
}
/**
* Returns TRUE if this expression evaluates to an equal or greater offset
* than the provided value, otherwise FALSE.
*
* @param period the time period that might be lesser in duration than this expression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression isGreaterThanOrEqual(Period period) {
return this.isGreaterThanOrEqual(value(period));
}
/**
* Returns TRUE if this expression evaluates to an equal or greater offset
* than the provided value, otherwise FALSE.
*
* @param anotherInstance the time period that might be lesser in duration than this expression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression isGreaterThanOrEqual(DateRepeatResult anotherInstance) {
return new BooleanExpression(new DateRepeatDateRepeatWithBooleanResult(this, anotherInstance) {
@Override
protected String doExpressionTransform(DBDatabase db) {
return db.getDefinition().doDateRepeatGreaterThanEqualsTransform(getFirst().toSQLString(db), getSecond().toSQLString(db));
}
});
}
/**
* Returns TRUE if this expression evaluates to an smaller offset than the
* provided value, FALSE when it is greater than the provided value, and
* the value of the fallBackWhenEqual parameter when the 2 values are the
* same.
*
* @param period the time period that might be greater in duration than this expression
* @param fallBackWhenEqual the expression to be evaluated when the DateRepeat values are equal
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression isLessThan(Period period, BooleanExpression fallBackWhenEqual) {
return this.isLessThan(value(period), fallBackWhenEqual);
}
/**
* Returns TRUE if this expression evaluates to an smaller offset than the
* provided value, FALSE when the it is greater than the provided value, and
* the value of the fallBackWhenEqual parameter when the 2 values are the
* same.
*
* @param anotherInstance the time period that might be greater in duration than this expression
* @param fallBackWhenEqual the expression to be evaluated when the values are equal
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression isLessThan(DateRepeatResult anotherInstance, BooleanExpression fallBackWhenEqual) {
return this.isLessThan(anotherInstance).or(this.is(anotherInstance).and(fallBackWhenEqual));
}
/**
* Returns TRUE if this expression evaluates to an greater offset than the
* provided value, FALSE when the it is smaller than the provided value, and
* the value of the fallBackWhenEqual parameter when the 2 values are the
* same.
*
* @param period the time period that might be lesser in duration than this expression.
* @param fallBackWhenEqual the expression to be evaluated when the values are equal.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression isGreaterThan(Period period, BooleanExpression fallBackWhenEqual) {
return this.isGreaterThan(value(period), fallBackWhenEqual);
}
/**
* Returns TRUE if this expression evaluates to an greater offset than the
* provided value, FALSE when the it is smaller than the provided value, and
* the value of the fallBackWhenEqual parameter when the 2 values are the
* same.
*
* @param anotherInstance the time period that might be lesser in duration than this expression.
* @param fallBackWhenEqual the expression to be evaluated when the values are equal.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression isGreaterThan(DateRepeatResult anotherInstance, BooleanExpression fallBackWhenEqual) {
return this.isGreaterThan(anotherInstance).or(this.is(anotherInstance).and(fallBackWhenEqual));
}
/**
* Returns TRUE if this expression and the provided value are the same.
*
* @param period the required value of the DateRepeat
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
public BooleanExpression is(Period period) {
return this.is(value(period));
}
/**
* Returns TRUE if this expression and the provided value are the same.
*
* @param anotherInstance the value that is to be found.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression is(DateRepeatResult anotherInstance) {
return new BooleanExpression(new DateRepeatDateRepeatWithBooleanResult(this, anotherInstance) {
@Override
protected String doExpressionTransform(DBDatabase db) {
return db.getDefinition().doDateRepeatEqualsTransform(getFirst().toSQLString(db), getSecond().toSQLString(db));
}
});
}
/**
* Returns FALSE if this expression and the provided value are the same.
*
* @param anotherInstance a value that the expression should not match.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a BooleanExpression
*/
@Override
public BooleanExpression isNot(DateRepeatResult anotherInstance) {
return is(anotherInstance).not();
}
/**
* Returns the YEARS part of this DateRepeat value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a number expression
*/
public NumberExpression getYears() {
return new NumberExpression(new DateRepeatWithNumberResult(this) {
@Override
protected String doExpressionTransform(DBDatabase db) {
if (db instanceof SupportsDateRepeatDatatypeFunctions) {
return db.getDefinition().doDateRepeatGetYearsTransform(getFirst().toSQLString(db));
} else {
return BooleanExpression.isNull(getFirst()).ifThenElse(
NumberExpression.nullExpression(),
getFirst().stringResult().substringBefore(YEAR_SUFFIX).substringAfter(INTERVAL_PREFIX).numberResult()
).toSQLString(db);
}
}
}
);
}
/**
* Returns the MONTHS part of this DateRepeat value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a number expression
*/
public NumberExpression getMonths() {
return new NumberExpression(new DateRepeatWithNumberResult(this) {
@Override
protected String doExpressionTransform(DBDatabase db) {
if (db instanceof SupportsDateRepeatDatatypeFunctions) {
return db.getDefinition().doDateRepeatGetMonthsTransform(getFirst().toSQLString(db));
} else {
return BooleanExpression.isNull(getFirst()).ifThenElse(
NumberExpression.nullExpression(),
getFirst().stringResult().substringBefore(MONTH_SUFFIX).substringAfter(YEAR_SUFFIX).numberResult()
).toSQLString(db);
}
}
}
);
}
/**
* Returns the DAYS part of this DateRepeat value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a number expression
*/
public NumberExpression getDays() {
return new NumberExpression(new DateRepeatWithNumberResult(this) {
@Override
protected String doExpressionTransform(DBDatabase db) {
if (db instanceof SupportsDateRepeatDatatypeFunctions) {
return db.getDefinition().doDateRepeatGetDaysTransform(getFirst().toSQLString(db));
} else {
return BooleanExpression.isNull(getFirst()).ifThenElse(
NumberExpression.nullExpression(),
getFirst().stringResult().substringBefore(DAY_SUFFIX).substringAfter(MONTH_SUFFIX).numberResult()
).toSQLString(db);
}
}
}
);
}
/**
* Returns the HOURS part of this DateRepeat value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a number expression
*/
public NumberExpression getHours() {
return new NumberExpression(new DateRepeatWithNumberResult(this) {
@Override
protected String doExpressionTransform(DBDatabase db) {
if (db instanceof SupportsDateRepeatDatatypeFunctions) {
return db.getDefinition().doDateRepeatGetHoursTransform(getFirst().toSQLString(db));
} else {
return BooleanExpression.isNull(getFirst()).ifThenElse(
NumberExpression.nullExpression(),
getFirst().stringResult().substringBefore(HOUR_SUFFIX).substringAfter(DAY_SUFFIX).numberResult()
).toSQLString(db);
}
}
}
);
}
/**
* Returns the MINUTES part of this DateRepeat value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a number expression
*/
public NumberExpression getMinutes() {
return new NumberExpression(new DateRepeatWithNumberResult(this) {
@Override
protected String doExpressionTransform(DBDatabase db) {
if (db instanceof SupportsDateRepeatDatatypeFunctions) {
return db.getDefinition().doDateRepeatGetMinutesTransform(getFirst().toSQLString(db));
} else {
return BooleanExpression.isNull(getFirst()).ifThenElse(
NumberExpression.nullExpression(),
getFirst().stringResult().substringBefore(MINUTE_SUFFIX).substringAfter(HOUR_SUFFIX).numberResult()
).toSQLString(db);
}
}
}
);
}
/**
* Returns the SECONDS part of this DateRepeat value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a number expression
*/
public NumberExpression getSeconds() {
return new NumberExpression(new DateRepeatWithNumberResult(this) {
@Override
protected String doExpressionTransform(DBDatabase db) {
if (db instanceof SupportsDateRepeatDatatypeFunctions) {
return db.getDefinition().doDateRepeatGetSecondsTransform(getFirst().toSQLString(db));
} else {
return BooleanExpression.isNull(getFirst()).ifThenElse(
NumberExpression.nullExpression(),
getFirst().stringResult().substringBefore(SECOND_SUFFIX).substringAfter(MINUTE_SUFFIX).numberResult()
).toSQLString(db);
}
}
}
);
}
/**
* Converts the interval expression into a string/character expression.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a StringExpression of the interval expression.
*/
@Override
public StringExpression stringResult() {
return new StringExpression(new DateRepeatWithStringResult(this) {
@Override
protected String doExpressionTransform(DBDatabase db) {
return db.getDefinition().doDateRepeatToStringTransform(getFirst().toSQLString(db));
}
});
}
@Override
public DBDateRepeat asExpressionColumn() {
return new DBDateRepeat(this);
}
private static abstract class DateRepeatDateRepeatWithBooleanResult extends BooleanExpression {
private DateRepeatExpression first;
private DateRepeatResult second;
private boolean requiresNullProtection;
DateRepeatDateRepeatWithBooleanResult(DateRepeatExpression first, DateRepeatResult second) {
this.first = first;
this.second = second;
if (this.second == null || this.second.getIncludesNull()) {
this.requiresNullProtection = true;
}
}
DateRepeatExpression getFirst() {
return first;
}
DateRepeatResult getSecond() {
return second;
}
@Override
public DBBoolean getQueryableDatatypeForExpressionValue() {
return new DBBoolean();
}
@Override
public String toSQLString(DBDatabase db) {
if (this.getIncludesNull()) {
return BooleanExpression.isNull(first).toSQLString(db);
} else {
return doExpressionTransform(db);
}
}
@Override
public DateRepeatDateRepeatWithBooleanResult copy() {
DateRepeatDateRepeatWithBooleanResult newInstance;
try {
newInstance = getClass().newInstance();
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
newInstance.first = first.copy();
newInstance.second = second.copy();
return newInstance;
}
protected abstract String doExpressionTransform(DBDatabase db);
@Override
public Set<DBRow> getTablesInvolved() {
HashSet<DBRow> hashSet = new HashSet<DBRow>();
if (first != null) {
hashSet.addAll(first.getTablesInvolved());
}
if (second != null) {
hashSet.addAll(second.getTablesInvolved());
}
return hashSet;
}
@Override
public boolean isAggregator() {
return first.isAggregator() || second.isAggregator();
}
@Override
public boolean getIncludesNull() {
return requiresNullProtection;
}
}
private static abstract class DateRepeatWithNumberResult extends NumberExpression {
private DateRepeatExpression first;
// private DateRepeatResult second;
private boolean requiresNullProtection;
DateRepeatWithNumberResult(DateRepeatExpression first) {
this.first = first;
// this.second = second;
// if (this.second == null || this.second.getIncludesNull()) {
// this.requiresNullProtection = true;
// }
}
protected abstract String doExpressionTransform(DBDatabase db);
DateRepeatExpression getFirst() {
return first;
}
// DateRepeatResult getSecond() {
// return second;
// }
@Override
public String toSQLString(DBDatabase db) {
if (this.getIncludesNull()) {
return BooleanExpression.isNull(first).toSQLString(db);
} else {
return doExpressionTransform(db);
}
}
@Override
public DateRepeatWithNumberResult copy() {
DateRepeatWithNumberResult newInstance;
try {
newInstance = getClass().newInstance();
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
newInstance.first = first.copy();
// newInstance.second = second.copy();
return newInstance;
}
@Override
public Set<DBRow> getTablesInvolved() {
HashSet<DBRow> hashSet = new HashSet<DBRow>();
if (first != null) {
hashSet.addAll(first.getTablesInvolved());
}
// if (second != null) {
// hashSet.addAll(second.getTablesInvolved());
// }
return hashSet;
}
@Override
public boolean isAggregator() {
return first.isAggregator();//|| second.isAggregator();
}
@Override
public boolean getIncludesNull() {
return requiresNullProtection;
}
}
private static abstract class DateRepeatWithStringResult extends StringExpression {
private DateRepeatExpression first;
// private DateRepeatResult second;
private boolean requiresNullProtection;
DateRepeatWithStringResult(DateRepeatExpression first) {
this.first = first;
// this.second = second;
// if (this.second == null || this.second.getIncludesNull()) {
// this.requiresNullProtection = true;
// }
}
protected abstract String doExpressionTransform(DBDatabase db);
DateRepeatExpression getFirst() {
return first;
}
// DateRepeatResult getSecond() {
// return second;
// }
@Override
public String toSQLString(DBDatabase db) {
if (this.getIncludesNull()) {
return BooleanExpression.isNull(first).toSQLString(db);
} else {
return doExpressionTransform(db);
}
}
@Override
public DateRepeatWithStringResult copy() {
DateRepeatWithStringResult newInstance;
try {
newInstance = getClass().newInstance();
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
newInstance.first = first.copy();
// newInstance.second = second.copy();
return newInstance;
}
@Override
public Set<DBRow> getTablesInvolved() {
HashSet<DBRow> hashSet = new HashSet<DBRow>();
if (first != null) {
hashSet.addAll(first.getTablesInvolved());
}
// if (second != null) {
// hashSet.addAll(second.getTablesInvolved());
// }
return hashSet;
}
@Override
public boolean isAggregator() {
return first.isAggregator();//|| second.isAggregator();
}
@Override
public boolean getIncludesNull() {
return requiresNullProtection;
}
}
}
| 31.970238 | 131 | 0.706349 |
230b71a118900c4b066b7396e4cde7a3ccea4357 | 308 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.blog.util;
/**
*
* @author dev-pai-20
*/
public class ExcepcionNegocio extends Exception {
public ExcepcionNegocio(String message) {
super(message);
}
}
| 17.111111 | 53 | 0.62013 |
40fee32316266fd810c59e155c10ed8e7e5d10d7 | 4,432 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.30 at 08:24:17 PM JST
//
package uk.org.ifopt.ifopt;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AbstractProjection complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AbstractProjection">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Features" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="GisFeatureRef" type="{http://www.ifopt.org.uk/ifopt}FeatureRefStructure" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AbstractProjection", propOrder = {
"features"
})
@XmlSeeAlso({
ZoneProjectionStructure.class,
PointProjectionStructure.class,
LinkProjectionStructure.class
})
public class AbstractProjection {
@XmlElement(name = "Features")
protected AbstractProjection.Features features;
/**
* Gets the value of the features property.
*
* @return
* possible object is
* {@link AbstractProjection.Features }
*
*/
public AbstractProjection.Features getFeatures() {
return features;
}
/**
* Sets the value of the features property.
*
* @param value
* allowed object is
* {@link AbstractProjection.Features }
*
*/
public void setFeatures(AbstractProjection.Features value) {
this.features = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="GisFeatureRef" type="{http://www.ifopt.org.uk/ifopt}FeatureRefStructure" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"gisFeatureRef"
})
public static class Features {
@XmlElement(name = "GisFeatureRef", required = true)
protected List<FeatureRefStructure> gisFeatureRef;
/**
* Gets the value of the gisFeatureRef property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the gisFeatureRef property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGisFeatureRef().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FeatureRefStructure }
*
*
*/
public List<FeatureRefStructure> getGisFeatureRef() {
if (gisFeatureRef == null) {
gisFeatureRef = new ArrayList<FeatureRefStructure>();
}
return this.gisFeatureRef;
}
}
}
| 29.945946 | 135 | 0.601083 |
49eca5cc2990131571ac04878b2b860bd2a76fb6 | 1,244 | package org.openntf.domino.exceptions;
public class Domino32KLimitException extends Exception {
private static final long serialVersionUID = 1L;
public Domino32KLimitException() {
super();
}
/**
* @param message
* the detail message. The detail message is saved for later retrieval by the Throwable.getMessage() method.
*/
public Domino32KLimitException(final String message) {
super(message);
}
/**
* @param cause
* the cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value is permitted, and
* indicates that the cause is nonexistent or unknown.)
*/
public Domino32KLimitException(final Throwable cause) {
super(cause);
}
/**
* @param message
* the detail message. The detail message is saved for later retrieval by the Throwable.getMessage() method.
* @param cause
* the cause (which is saved for later retrieval by the Throwable.getCause() method). (A null value is permitted, and
* indicates that the cause is nonexistent or unknown.)
*/
public Domino32KLimitException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 31.1 | 130 | 0.67283 |
9356eb06e21cc52887b2404bea9904efb5d6a592 | 1,922 | package nl.marcvanandel.logging.example;
import nl.marcvanandel.logging.Slf4jLoggingDelegate;
/**
* Example business service implementation only as example for application of the {@link LoggingDelegate} pattern.
* <p>
* See blog post: <a href="http://marcvanandel.nl/logging-delegate/">http://marcvanandel.nl/logging-delegate/</a>
*
* @author marc-va
* @since 1.0 on 12/02/2017
*/
public class BusinessServiceImpl {
private LoggingDelegate logger;
private BusinessServiceImpl otherBusinessService;
public BusinessServiceImpl() {
super();
logger = new LoggingDelegate();
}
/**
* Do some logic in this business service. Because this method is public this is exposed logic outside of the
* business service, probably the reason of this business service.
*
* @param input
* @return the result
*/
public String doSomething(final String input) {
logger.logDoSomethingStart(input);
String result = otherBusinessService.executeLogic(input);
logger.logDoSomethingFinish(input, result);
return result;
}
/**
* Example method to execute some logic. In the real world this would be real functional logic (of course ;-)
*
* @param input
* @return the result
*/
String executeLogic(String input) {
return "the result";
}
public void setOtherBusinessService(BusinessServiceImpl otherBusinessService) {
this.otherBusinessService = otherBusinessService;
}
private static class LoggingDelegate extends Slf4jLoggingDelegate {
public void logDoSomethingStart(final String input) {
logger.debug("doSomething START with [{}]", input);
}
public void logDoSomethingFinish(final String input, final String result) {
logger.info("doSomething FINISH with [{}], result: [{}]", input, result);
}
}
}
| 29.569231 | 114 | 0.675858 |
b01c9f42cec1c6a0de2b680d8384dc92dedae9ab | 4,975 | package com.wgs.kafka.consumer.v2.config;
import com.wgs.kafka.consumer.v2.KafkaMessageConsumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.KafkaMessageListenerContainer;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableKafka
public class KafkaConsumerConfig {
@Value("${spring.kafka.bootstrap-servers}")
private String servers;
@Value("${spring.kafka.consumer.group-id}")
private String groupId;
/**
* 是否自动提交
*/
@Value("${spring.kafka.consumer.enable-auto-commit}")
private boolean enableAutoCommit;
/**
* 执行超时时间
*/
@Value("${spring.kafka.consumer.properties.session.timeout}")
private String sessionTimeout;
/**
* 向zookeeper提交offset的频率,默认:5000
*/
@Value("${spring.kafka.consumer.properties.auto.commit.interval}")
private String autoCommitInterval;
/**
* 表示自动将偏移重置为最新的偏移量
*/
@Value("${spring.kafka.consumer.properties.auto.offset.reset}")
private String autoOffsetReset;
/**
* KafkaMessageListenerContainer监听器容器中启动的consumer个数
*/
@Value("${spring.kafka.consumer.properties.concurrency}")
private int concurrency;
/**
* consumer连接超时时间
* 在该时间段内consumer未发送心跳消息认为宕机
*/
@Value("${spring.kafka.consumer.properties.pollTimeout}")
private int pollTimeout;
@Resource
private KafkaMessageConsumer kafkaMessageConsumer;
/*
* The KafkaMessageListenerContainer receives all message from all topics or partitions on a single thread.
* The ConcurrentMessageListenerContainer delegates to one or more KafkaMessageListenerContainer instances
* to provide multi-threaded consumption.
*
* @return
*/
@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
// 使用ConcurrentKafkaListenerContainerFactory, 指定线程数量(concurrency), 并发消费
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
// 创建多个KafkaListenerContainer实例
factory.setConcurrency(concurrency);
factory.getContainerProperties().setPollTimeout(pollTimeout);
return factory;
}
@Bean
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> propsMap = new HashMap<>();
propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitInterval);
propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout);
propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
return propsMap;
}
/**
* Start a listener
*
* Each KafkaMessageListenerContainer gets one Consumer (and one thread).
* The thread continually poll()s the consumer, with the specified pollTimeout.
*
* @return
*/
@Bean(initMethod = "doStart")
public KafkaMessageListenerContainer kafkaMessageListenerContainer() {
return new KafkaMessageListenerContainer(consumerFactory(), containerProperties());
}
@Bean
public ContainerProperties containerProperties() {
String[] topics = new String[kafkaMessageConsumer.listTopics().size()];
kafkaMessageConsumer.listTopics().toArray(topics);
ContainerProperties containerProperties = new ContainerProperties(topics);
containerProperties.setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
containerProperties.setMessageListener(kafkaMessageConsumer);
return containerProperties;
}
}
| 35.283688 | 126 | 0.74794 |
551c8528e8462499b01235c7f8a6f795c7423f59 | 4,376 | import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Esta clase sirve para crear la interfaz de cliente
* @author Sebastián
*
*/
public class Cliente extends JFrame implements Runnable{
private JTextField textField1;
private JButton enviarButton;
private JPanel Principal;
private JTextArea textArea2;
private JTextField usuario;
private JTextField text1;
private JTextField text2;
private JTextField text3;
private JButton calcularButton;
public Cliente() {
setContentPane(Principal);//Se seleccion la interfaz creada en suing
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);//Se establece que la ventana no cambie su tamaño
setSize(500, 500);
setTitle("Chat");//Titulo de la ventana
Envia_texto mievento=new Envia_texto();//Se establece la funcion del boton
enviarButton.addActionListener(mievento);//Se establece la que el boton tenga una accion al tocar
Thread hilo=new Thread(this);//Hilo para que la interfaz funcione en todo momento
hilo.start();
calcularButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String Porcentaje= new String();
Porcentaje=text1.getText();
double P = Double.parseDouble(Porcentaje);
String Producto= new String();
Producto=text2.getText();
double Pro = Double.parseDouble(Producto);
String Peso= new String();
Peso=text3.getText();
double Pes = Double.parseDouble(Peso);
double R= (Pro*P/100)+(Pes*0.15);
System.out.println(R);
textArea2.append(String.valueOf(R));
}
});
}
/**
* Este parametro sirve para que el cliente reciba los mensajes que llegan al servidor
* @param "run"
*/
@Override
public void run() {
try{
ServerSocket servidor_Cliente=new ServerSocket(9090);// Socket que permite la conexion del servidor
Socket cliente;
Paquete_Cliente paquete_recibido;
while (true){
cliente=servidor_Cliente.accept();
ObjectInputStream flujoentrada=new ObjectInputStream(cliente.getInputStream());
paquete_recibido= (Paquete_Cliente) flujoentrada.readObject();
textArea2.append("\n"+paquete_recibido.getNick()+": "+paquete_recibido.getMensaje());
}
}catch (Exception ex){
System.out.println(ex.getMessage());// se imprime el mensaje del servidor
}
}
private class Envia_texto implements ActionListener{//funcion para enviar los mensajes dandole el click al boton
/**
* Este parametro sirve para que el clienete envie los mensajes al servirdor lo cual agarra los datos de la clase "Paquete_Cliente"
* @param "run"
*/
@Override//ENVIA
public void actionPerformed(ActionEvent e) {
try {
Socket misocket=new Socket("LocalHost",8080);
Paquete_Cliente datos=new Paquete_Cliente();
datos.setNick(usuario.getText());
datos.setMensaje(textField1.getText());
ObjectOutputStream paquete_datos=new ObjectOutputStream(misocket.getOutputStream());
paquete_datos.writeObject(datos);
misocket.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
Cliente Service = new Cliente();
}
}
/**
* Guarda los datos de la interfaz y la envia al servidor
* @author Sebas
*/
class Paquete_Cliente implements Serializable {
private String usuario,mensaje;
public String getNick() {
return usuario;
}
public void setNick(String nick) {
this.usuario = nick;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
}
| 29.768707 | 139 | 0.618144 |
541290ced931eeb2e137dac346c3980070286327 | 24,660 | package org.pushingpixels.demo.flamingo.svg.filetypes.transcoded;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.plaf.UIResource;
import org.pushingpixels.neon.icon.IsHiDpiAware;
import org.pushingpixels.neon.icon.ResizableIcon;
import org.pushingpixels.neon.icon.NeonIcon;
import org.pushingpixels.neon.icon.NeonIconUIResource;
/**
* This class has been automatically generated using <a
* href="https://github.com/kirill-grouchnikov/radiance">Ibis SVG transcoder</a>.
*/
public class ext_csproj implements ResizableIcon, IsHiDpiAware {
@SuppressWarnings("unused")
private void innerPaint(Graphics2D g) {
Shape shape = null;
Paint paint = null;
Stroke stroke = null;
float origAlpha = 1.0f;
Composite origComposite = g.getComposite();
if (origComposite instanceof AlphaComposite) {
AlphaComposite origAlphaComposite =
(AlphaComposite)origComposite;
if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) {
origAlpha = origAlphaComposite.getAlpha();
}
}
AffineTransform defaultTransform_ = g.getTransform();
//
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0 = g.getTransform();
g.transform(new AffineTransform(0.009999999776482582f, 0.0f, 0.0f, 0.009999999776482582f, 0.13999999687075615f, -0.0f));
// _0
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_0_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0_0
paint = new LinearGradientPaint(new Point2D.Double(36.0, 2.2646000385284424), new Point2D.Double(36.0, 100.25), new float[] {0.0f,0.139f,0.359f,0.617f,1.0f}, new Color[] {new Color(200, 212, 219, 255),new Color(216, 225, 230, 255),new Color(235, 240, 243, 255),new Color(249, 250, 251, 255),new Color(255, 255, 255, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 101.0f));
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.0, 0.8);
((GeneralPath)shape).lineTo(72.0, 27.5);
((GeneralPath)shape).lineTo(72.0, 98.8);
((GeneralPath)shape).lineTo(0.0, 98.8);
((GeneralPath)shape).lineTo(0.0, 0.80000305);
((GeneralPath)shape).lineTo(45.0, 0.80000305);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_0_0);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_0_1 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0_1
paint = new Color(0, 0, 0, 0);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.0, 0.8);
((GeneralPath)shape).lineTo(72.0, 27.5);
((GeneralPath)shape).lineTo(72.0, 98.8);
((GeneralPath)shape).lineTo(0.0, 98.8);
((GeneralPath)shape).lineTo(0.0, 0.80000305);
((GeneralPath)shape).lineTo(45.0, 0.80000305);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
paint = new Color(113, 145, 161, 255);
stroke = new BasicStroke(2.0f,0,0,4.0f,null,0.0f);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.0, 0.8);
((GeneralPath)shape).lineTo(72.0, 27.5);
((GeneralPath)shape).lineTo(72.0, 98.8);
((GeneralPath)shape).lineTo(0.0, 98.8);
((GeneralPath)shape).lineTo(0.0, 0.80000305);
((GeneralPath)shape).lineTo(45.0, 0.80000305);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(defaultTransform__0_0_1);
g.setTransform(defaultTransform__0_0);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1_0
paint = new Color(76, 108, 123, 255);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(13.0, 85.9);
((GeneralPath)shape).lineTo(15.1, 86.6);
((GeneralPath)shape).curveTo(14.8, 87.799995, 14.200001, 88.6, 13.5, 89.2);
((GeneralPath)shape).curveTo(12.7, 89.799995, 11.8, 90.1, 10.6, 90.1);
((GeneralPath)shape).curveTo(9.1, 90.0, 8.0, 89.5, 7.0, 88.5);
((GeneralPath)shape).curveTo(6.1, 87.5, 5.6, 86.2, 5.6, 84.5);
((GeneralPath)shape).curveTo(5.6, 82.7, 6.1, 81.3, 7.0, 80.3);
((GeneralPath)shape).curveTo(7.9, 79.3, 9.2, 78.8, 10.7, 78.8);
((GeneralPath)shape).curveTo(12.0, 78.8, 13.1, 79.200005, 13.9, 80.0);
((GeneralPath)shape).curveTo(14.4, 80.5, 14.799999, 81.1, 15.0, 82.0);
((GeneralPath)shape).lineTo(12.8, 82.5);
((GeneralPath)shape).curveTo(12.7, 81.9, 12.400001, 81.5, 12.0, 81.2);
((GeneralPath)shape).curveTo(11.6, 80.899994, 11.1, 80.7, 10.5, 80.7);
((GeneralPath)shape).curveTo(9.7, 80.7, 9.0, 81.0, 8.5, 81.6);
((GeneralPath)shape).curveTo(8.0, 82.2, 7.7, 83.1, 7.7, 84.4);
((GeneralPath)shape).curveTo(7.7, 85.8, 7.8999996, 86.700005, 8.4, 87.3);
((GeneralPath)shape).curveTo(8.9, 87.9, 9.5, 88.200005, 10.299999, 88.200005);
((GeneralPath)shape).curveTo(10.9, 88.200005, 11.4, 88.00001, 11.799999, 87.700005);
((GeneralPath)shape).curveTo(12.5, 87.2, 12.8, 86.7, 13.0, 85.9);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_1_0);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1_1 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1_1
paint = new Color(76, 108, 123, 255);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(16.4, 86.3);
((GeneralPath)shape).lineTo(18.5, 86.100006);
((GeneralPath)shape).curveTo(18.6, 86.8, 18.9, 87.3, 19.3, 87.700005);
((GeneralPath)shape).curveTo(19.699999, 88.100006, 20.199999, 88.200005, 20.9, 88.200005);
((GeneralPath)shape).curveTo(21.6, 88.200005, 22.1, 88.100006, 22.5, 87.8);
((GeneralPath)shape).curveTo(22.9, 87.5, 23.0, 87.200005, 23.0, 86.8);
((GeneralPath)shape).curveTo(23.0, 86.5, 22.9, 86.3, 22.8, 86.200005);
((GeneralPath)shape).curveTo(22.599998, 86.00001, 22.4, 85.9, 22.0, 85.700005);
((GeneralPath)shape).curveTo(21.7, 85.600006, 21.2, 85.50001, 20.2, 85.200005);
((GeneralPath)shape).curveTo(19.0, 84.9, 18.2, 84.600006, 17.7, 84.100006);
((GeneralPath)shape).curveTo(17.0, 83.50001, 16.7, 82.8, 16.7, 81.90001);
((GeneralPath)shape).curveTo(16.7, 81.40001, 16.900002, 80.80001, 17.2, 80.40001);
((GeneralPath)shape).curveTo(17.5, 79.90001, 18.0, 79.600006, 18.6, 79.30001);
((GeneralPath)shape).curveTo(19.2, 79.10001, 19.9, 78.90001, 20.7, 78.90001);
((GeneralPath)shape).curveTo(22.1, 78.90001, 23.1, 79.20001, 23.800001, 79.80001);
((GeneralPath)shape).curveTo(24.500002, 80.40001, 24.800001, 81.20001, 24.900002, 82.20001);
((GeneralPath)shape).lineTo(22.7, 82.30001);
((GeneralPath)shape).curveTo(22.6, 81.70001, 22.400002, 81.40001, 22.1, 81.10001);
((GeneralPath)shape).curveTo(21.800001, 80.90002, 21.300001, 80.70001, 20.7, 80.70001);
((GeneralPath)shape).curveTo(20.1, 80.70001, 19.6, 80.80001, 19.2, 81.10001);
((GeneralPath)shape).curveTo(19.0, 81.30001, 18.900002, 81.500015, 18.900002, 81.80001);
((GeneralPath)shape).curveTo(18.900002, 82.10001, 19.000002, 82.30001, 19.2, 82.50001);
((GeneralPath)shape).curveTo(19.5, 82.700005, 20.1, 83.00001, 21.2, 83.200005);
((GeneralPath)shape).curveTo(22.300001, 83.4, 23.1, 83.700005, 23.6, 84.00001);
((GeneralPath)shape).curveTo(24.1, 84.30001, 24.5, 84.600006, 24.800001, 85.100006);
((GeneralPath)shape).curveTo(25.1, 85.600006, 25.2, 86.100006, 25.2, 86.8);
((GeneralPath)shape).curveTo(25.2, 87.4, 25.0, 88.0, 24.7, 88.5);
((GeneralPath)shape).curveTo(24.400002, 89.0, 23.900002, 89.4, 23.2, 89.7);
((GeneralPath)shape).curveTo(22.6, 90.0, 21.800001, 90.1, 20.800001, 90.1);
((GeneralPath)shape).curveTo(19.400002, 90.1, 18.400002, 89.799995, 17.6, 89.2);
((GeneralPath)shape).curveTo(17.0, 88.4, 16.6, 87.5, 16.4, 86.3);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_1_1);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1_2 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1_2
paint = new Color(76, 108, 123, 255);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(27.1, 89.8);
((GeneralPath)shape).lineTo(27.1, 79.1);
((GeneralPath)shape).lineTo(30.6, 79.1);
((GeneralPath)shape).curveTo(31.9, 79.1, 32.8, 79.2, 33.2, 79.299995);
((GeneralPath)shape).curveTo(33.8, 79.49999, 34.3, 79.799995, 34.8, 80.399994);
((GeneralPath)shape).curveTo(35.2, 80.899994, 35.399998, 81.59999, 35.399998, 82.49999);
((GeneralPath)shape).curveTo(35.399998, 83.19999, 35.3, 83.69999, 34.999996, 84.19999);
((GeneralPath)shape).curveTo(34.799995, 84.59999, 34.499996, 84.99999, 34.099995, 85.29999);
((GeneralPath)shape).curveTo(33.699993, 85.59999, 33.299995, 85.69999, 32.999996, 85.79999);
((GeneralPath)shape).curveTo(32.499996, 85.89999, 31.699997, 85.999985, 30.699997, 85.999985);
((GeneralPath)shape).lineTo(29.299997, 85.999985);
((GeneralPath)shape).lineTo(29.299997, 90.09998);
((GeneralPath)shape).lineTo(27.1, 90.09998);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(29.3, 80.9);
((GeneralPath)shape).lineTo(29.3, 83.9);
((GeneralPath)shape).lineTo(30.5, 83.9);
((GeneralPath)shape).curveTo(31.4, 83.9, 31.9, 83.8, 32.2, 83.700005);
((GeneralPath)shape).curveTo(32.5, 83.600006, 32.7, 83.4, 32.9, 83.200005);
((GeneralPath)shape).curveTo(33.100002, 83.00001, 33.100002, 82.700005, 33.100002, 82.4);
((GeneralPath)shape).curveTo(33.100002, 82.0, 33.000004, 81.700005, 32.800003, 81.4);
((GeneralPath)shape).curveTo(32.600002, 81.1, 32.3, 81.0, 31.9, 81.0);
((GeneralPath)shape).curveTo(31.6, 81.0, 31.1, 80.9, 30.3, 80.9);
((GeneralPath)shape).lineTo(29.3, 80.9);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_1_2);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1_3 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1_3
paint = new Color(76, 108, 123, 255);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(37.2, 89.8);
((GeneralPath)shape).lineTo(37.2, 79.1);
((GeneralPath)shape).lineTo(41.8, 79.1);
((GeneralPath)shape).curveTo(43.0, 79.1, 43.8, 79.2, 44.3, 79.4);
((GeneralPath)shape).curveTo(44.8, 79.6, 45.2, 79.9, 45.6, 80.4);
((GeneralPath)shape).curveTo(45.899998, 80.9, 46.1, 81.5, 46.1, 82.1);
((GeneralPath)shape).curveTo(46.1, 82.9, 45.899998, 83.6, 45.399998, 84.1);
((GeneralPath)shape).curveTo(44.899998, 84.6, 44.199997, 85.0, 43.3, 85.1);
((GeneralPath)shape).curveTo(43.8, 85.4, 44.2, 85.7, 44.5, 86.0);
((GeneralPath)shape).curveTo(44.8, 86.3, 45.2, 86.9, 45.7, 87.7);
((GeneralPath)shape).lineTo(47.0, 89.799995);
((GeneralPath)shape).lineTo(44.4, 89.799995);
((GeneralPath)shape).lineTo(42.800003, 87.49999);
((GeneralPath)shape).curveTo(42.200005, 86.69999, 41.9, 86.09999, 41.600002, 85.899994);
((GeneralPath)shape).curveTo(41.4, 85.7, 41.2, 85.49999, 40.9, 85.49999);
((GeneralPath)shape).curveTo(40.7, 85.399994, 40.300003, 85.399994, 39.800003, 85.399994);
((GeneralPath)shape).lineTo(39.4, 85.399994);
((GeneralPath)shape).lineTo(39.4, 89.899994);
((GeneralPath)shape).lineTo(37.2, 89.899994);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(39.4, 83.6);
((GeneralPath)shape).lineTo(41.0, 83.6);
((GeneralPath)shape).curveTo(42.1, 83.6, 42.7, 83.6, 43.0, 83.5);
((GeneralPath)shape).curveTo(43.3, 83.4, 43.5, 83.3, 43.6, 83.0);
((GeneralPath)shape).curveTo(43.699997, 82.8, 43.8, 82.5, 43.8, 82.2);
((GeneralPath)shape).curveTo(43.8, 81.799995, 43.7, 81.5, 43.5, 81.299995);
((GeneralPath)shape).curveTo(43.3, 81.1, 43.0, 80.899994, 42.7, 80.899994);
((GeneralPath)shape).curveTo(42.5, 80.899994, 42.0, 80.899994, 41.100002, 80.899994);
((GeneralPath)shape).lineTo(39.4, 80.899994);
((GeneralPath)shape).lineTo(39.4, 83.6);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_1_3);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1_4 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1_4
paint = new Color(76, 108, 123, 255);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(47.7, 84.5);
((GeneralPath)shape).curveTo(47.7, 83.4, 47.9, 82.5, 48.2, 81.7);
((GeneralPath)shape).curveTo(48.4, 81.2, 48.8, 80.7, 49.2, 80.2);
((GeneralPath)shape).curveTo(49.600002, 79.799995, 50.100002, 79.399994, 50.600002, 79.2);
((GeneralPath)shape).curveTo(51.300003, 78.899994, 52.100002, 78.799995, 52.9, 78.799995);
((GeneralPath)shape).curveTo(54.5, 78.799995, 55.800003, 79.299995, 56.7, 80.299995);
((GeneralPath)shape).curveTo(57.7, 81.299995, 58.100002, 82.6, 58.100002, 84.399994);
((GeneralPath)shape).curveTo(58.100002, 86.09999, 57.600002, 87.49999, 56.7, 88.49999);
((GeneralPath)shape).curveTo(55.7, 89.49999, 54.5, 89.99999, 52.9, 89.99999);
((GeneralPath)shape).curveTo(51.300003, 89.99999, 50.0, 89.49999, 49.100002, 88.49999);
((GeneralPath)shape).curveTo(48.2, 87.6, 47.7, 86.2, 47.7, 84.5);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(49.9, 84.4);
((GeneralPath)shape).curveTo(49.9, 85.6, 50.2, 86.5, 50.800003, 87.200005);
((GeneralPath)shape).curveTo(51.4, 87.8, 52.100002, 88.100006, 53.000004, 88.100006);
((GeneralPath)shape).curveTo(53.900005, 88.100006, 54.600002, 87.8, 55.100002, 87.200005);
((GeneralPath)shape).curveTo(55.7, 86.600006, 55.9, 85.600006, 55.9, 84.4);
((GeneralPath)shape).curveTo(55.9, 83.200005, 55.600002, 82.3, 55.100002, 81.6);
((GeneralPath)shape).curveTo(54.600002, 81.0, 53.800003, 80.7, 52.9, 80.7);
((GeneralPath)shape).curveTo(52.0, 80.7, 51.300003, 81.0, 50.7, 81.6);
((GeneralPath)shape).curveTo(50.2, 82.3, 49.9, 83.2, 49.9, 84.4);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_1_4);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1_5 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1_5
paint = new Color(76, 108, 123, 255);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(63.8, 79.1);
((GeneralPath)shape).lineTo(66.0, 79.1);
((GeneralPath)shape).lineTo(66.0, 85.9);
((GeneralPath)shape).curveTo(66.0, 86.8, 65.9, 87.5, 65.8, 88.0);
((GeneralPath)shape).curveTo(65.600006, 88.6, 65.200005, 89.1, 64.600006, 89.5);
((GeneralPath)shape).curveTo(64.00001, 89.9, 63.300007, 90.1, 62.400005, 90.1);
((GeneralPath)shape).curveTo(61.300007, 90.1, 60.500004, 89.799995, 59.900005, 89.2);
((GeneralPath)shape).curveTo(59.300007, 88.6, 59.000004, 87.7, 59.000004, 86.6);
((GeneralPath)shape).lineTo(61.100002, 86.4);
((GeneralPath)shape).curveTo(61.100002, 87.0, 61.2, 87.5, 61.4, 87.700005);
((GeneralPath)shape).curveTo(61.600002, 88.100006, 62.0, 88.3, 62.5, 88.3);
((GeneralPath)shape).curveTo(63.0, 88.3, 63.3, 88.200005, 63.5, 87.9);
((GeneralPath)shape).curveTo(63.7, 87.6, 63.8, 87.1, 63.8, 86.200005);
((GeneralPath)shape).lineTo(63.8, 79.1);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_1_5);
g.setTransform(defaultTransform__0_1);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_2 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_2
paint = new LinearGradientPaint(new Point2D.Double(35.61909866333008, 64.5), new Point2D.Double(35.61909866333008, 18.90559959411621), new float[] {0.0f,1.0f}, new Color[] {new Color(173, 204, 220, 255),new Color(76, 108, 123, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
shape = new GeneralPath();
((GeneralPath)shape).moveTo(28.2, 44.6);
((GeneralPath)shape).curveTo(26.800001, 45.6, 25.5, 46.699997, 24.2, 47.699997);
((GeneralPath)shape).curveTo(21.5, 49.699997, 18.900002, 51.799995, 16.2, 53.799995);
((GeneralPath)shape).curveTo(15.800001, 54.099995, 15.6, 54.099995, 15.200001, 53.899994);
((GeneralPath)shape).curveTo(14.700001, 53.599995, 14.1, 53.299995, 13.500001, 52.999992);
((GeneralPath)shape).curveTo(13.200001, 52.79999, 13.100001, 52.59999, 13.100001, 52.29999);
((GeneralPath)shape).curveTo(13.100001, 45.199993, 13.100001, 38.19999, 13.100001, 31.09999);
((GeneralPath)shape).curveTo(13.100001, 30.89999, 13.300001, 30.49999, 13.500001, 30.39999);
((GeneralPath)shape).curveTo(14.100001, 29.99999, 14.800001, 29.69999, 15.400001, 29.39999);
((GeneralPath)shape).curveTo(15.700001, 29.19999, 16.0, 29.39999, 16.300001, 29.59999);
((GeneralPath)shape).curveTo(18.500002, 31.299992, 20.7, 32.999992, 22.900002, 34.59999);
((GeneralPath)shape).curveTo(24.7, 35.999992, 26.500002, 37.39999, 28.300001, 38.69999);
((GeneralPath)shape).curveTo(28.400002, 38.59999, 28.6, 38.49999, 28.7, 38.39999);
((GeneralPath)shape).curveTo(35.3, 31.99999, 41.9, 25.59999, 48.4, 19.19999);
((GeneralPath)shape).curveTo(48.7, 18.89999, 49.0, 18.79999, 49.4, 18.999989);
((GeneralPath)shape).curveTo(52.2, 20.099989, 55.0, 21.19999, 57.800003, 22.399988);
((GeneralPath)shape).curveTo(58.000004, 22.499989, 58.200005, 22.799988, 58.300003, 22.999989);
((GeneralPath)shape).curveTo(58.4, 23.099989, 58.300003, 23.299988, 58.300003, 23.499989);
((GeneralPath)shape).curveTo(58.300003, 35.69999, 58.300003, 47.799988, 58.300003, 59.99999);
((GeneralPath)shape).curveTo(58.300003, 60.89999, 58.300003, 60.89999, 57.4, 61.19999);
((GeneralPath)shape).curveTo(54.7, 62.299988, 52.100002, 63.299988, 49.5, 64.39999);
((GeneralPath)shape).curveTo(49.0, 64.59998, 48.7, 64.499985, 48.4, 64.19999);
((GeneralPath)shape).curveTo(41.9, 57.799988, 35.4, 51.49999, 28.800001, 45.19999);
((GeneralPath)shape).curveTo(28.6, 45.0, 28.4, 44.8, 28.2, 44.6);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(47.2, 50.4);
((GeneralPath)shape).curveTo(47.2, 44.600002, 47.2, 38.800003, 47.2, 33.0);
((GeneralPath)shape).curveTo(43.3, 35.9, 39.5, 38.8, 35.6, 41.7);
((GeneralPath)shape).curveTo(39.5, 44.6, 43.3, 47.5, 47.2, 50.4);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(22.9, 41.7);
((GeneralPath)shape).curveTo(21.0, 40.0, 19.1, 38.3, 17.099998, 36.5);
((GeneralPath)shape).curveTo(17.099998, 40.0, 17.099998, 43.4, 17.099998, 46.9);
((GeneralPath)shape).curveTo(19.0, 45.2, 20.9, 43.4, 22.9, 41.7);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_2);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_3 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_3
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_3_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_3_0
paint = new LinearGradientPaint(new Point2D.Double(45.06919860839844, 73.4574966430664), new Point2D.Double(58.56919860839844, 86.9574966430664), new float[] {0.0f,0.35f,0.532f,0.675f,0.799f,0.908f,1.0f}, new Color[] {new Color(255, 255, 255, 255),new Color(250, 251, 251, 255),new Color(237, 241, 244, 255),new Color(221, 229, 233, 255),new Color(199, 211, 218, 255),new Color(173, 189, 199, 255),new Color(146, 165, 176, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 101.0f));
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.0, 0.8);
((GeneralPath)shape).lineTo(72.0, 27.5);
((GeneralPath)shape).lineTo(45.0, 27.5);
((GeneralPath)shape).lineTo(45.0, 0.8);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_3_0);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_3_1 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_3_1
paint = new Color(0, 0, 0, 0);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.0, 0.8);
((GeneralPath)shape).lineTo(72.0, 27.5);
((GeneralPath)shape).lineTo(45.0, 27.5);
((GeneralPath)shape).lineTo(45.0, 0.8);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.fill(shape);
paint = new Color(113, 145, 161, 255);
stroke = new BasicStroke(2.0f,0,2,4.0f,null,0.0f);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.0, 0.8);
((GeneralPath)shape).lineTo(72.0, 27.5);
((GeneralPath)shape).lineTo(45.0, 27.5);
((GeneralPath)shape).lineTo(45.0, 0.8);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(defaultTransform__0_3_1);
g.setTransform(defaultTransform__0_3);
g.setTransform(defaultTransform__0);
g.setTransform(defaultTransform_);
}
/**
* Returns the X of the bounding box of the original SVG image.
*
* @return The X of the bounding box of the original SVG image.
*/
public static double getOrigX() {
return 0.12999999523162842;
}
/**
* Returns the Y of the bounding box of the original SVG image.
*
* @return The Y of the bounding box of the original SVG image.
*/
public static double getOrigY() {
return 0.0;
}
/**
* Returns the width of the bounding box of the original SVG image.
*
* @return The width of the bounding box of the original SVG image.
*/
public static double getOrigWidth() {
return 0.7400000095367432;
}
/**
* Returns the height of the bounding box of the original SVG image.
*
* @return The height of the bounding box of the original SVG image.
*/
public static double getOrigHeight() {
return 0.9979999661445618;
}
/** The current width of this resizable icon. */
private int width;
/** The current height of this resizable icon. */
private int height;
/**
* Creates a new transcoded SVG image. It is recommended to use the
* {@link #of(int, int)} method to obtain a pre-configured instance.
*/
public ext_csproj() {
this.width = (int) getOrigWidth();
this.height = (int) getOrigHeight();
}
@Override
public int getIconHeight() {
return height;
}
@Override
public int getIconWidth() {
return width;
}
@Override
public void setDimension(Dimension newDimension) {
this.width = newDimension.width;
this.height = newDimension.height;
}
@Override
public boolean isHiDpiAware() {
return true;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(x, y);
double coef1 = (double) this.width / getOrigWidth();
double coef2 = (double) this.height / getOrigHeight();
double coef = Math.min(coef1, coef2);
g2d.clipRect(0, 0, this.width, this.height);
g2d.scale(coef, coef);
g2d.translate(-getOrigX(), -getOrigY());
if (coef1 != coef2) {
if (coef1 < coef2) {
int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0);
g2d.translate(0, extraDy);
} else {
int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0);
g2d.translate(extraDx, 0);
}
}
Graphics2D g2ForInner = (Graphics2D) g2d.create();
innerPaint(g2ForInner);
g2ForInner.dispose();
g2d.dispose();
}
/**
* Returns an instance of this icon with specified dimensions.
*/
public static NeonIcon of(int width, int height) {
ext_csproj base = new ext_csproj();
base.width = width;
base.height = height;
return new NeonIcon(base);
}
/**
* Returns a {@link UIResource} instance of this icon with specified dimensions.
*/
public static NeonIconUIResource uiResourceOf(int width, int height) {
ext_csproj base = new ext_csproj();
base.width = width;
base.height = height;
return new NeonIconUIResource(base);
}
}
| 48.639053 | 577 | 0.693147 |
e15347997380ad29f751815e5a398f5905b4e44b | 491 | package com.madx.mybatis.endpoints.implementations;
import javax.ejb.EJB;
import javax.ws.rs.Path;
import com.madx.mybatis.TimeBean;
import com.madx.mybatis.endpoints.interfaces.ITime;
@Path("/time")
public class Times implements ITime{
@EJB
private TimeBean timeService;
@Override
public String now() {
return timeService.now();
}
@Override
public String ok() {
return timeService.normalRun();
}
@Override
public String ko() {
return timeService.exceptionRun();
}
} | 16.931034 | 51 | 0.739308 |
a23f050c76aa6d76f2f721b62b019ee1422f9607 | 6,608 | package org.culpan.j6502;
import javax.swing.*;
import java.lang.reflect.Member;
/**
* Created by harryculpan on 4/18/15.
*/
public class J6502Cpu extends J6502Instructions {
protected CpuListener cpuListener;
public J6502Cpu(CpuListener cpuListener) {
this.cpuListener = cpuListener;
}
int programCounter;
int stackPointer = 0x01FF;
int a_reg = 0;
int x_reg = 0;
int y_reg = 0;
boolean singleStep = true;
boolean doNextStep = false;
FlagStatus flags[] = new FlagStatus[8];
final static int NEGATIVE_FLAG = 7;
final static int OVERFLOW_FLAG = 6;
final static int UNUSED_FLAG = 5;
final static int BREAK_FLAG = 4;
final static int DECIMAL_FLAG = 3;
final static int INTERRUPT_FLAG = 2;
final static int ZERO_FLAG = 1;
final static int CARRY_FLAG = 0;
public void reset() {
stackPointer = 0x01FF;
setA_reg(0);
setX_reg(0);
setY_reg(0);
singleStep = true;
setProgramCounter((J6502Memory.get(0xFFFD) << 8) + J6502Memory.get(0xFFFC));
for (int i = 0; i < flags.length; i++) {
flags[i] = FlagStatus.Off;
}
flags[5] = FlagStatus.On; // Always on
updatedFlags();
}
public synchronized void run() {
while (true) {
while (isSingleStep() && !doNextStep) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
doNextStep = false;
executeNextStep();
}
}
public void executeNextStep() {
int instr = J6502Memory.get(programCounter);
int instrSize = instructionSizes[instr];
int arg = 0;
if (instrSize == 2) {
arg = J6502Memory.get(programCounter + 1);
} else if (instrSize == 3) {
arg = (J6502Memory.get(programCounter + 2) << 8) + J6502Memory.get(programCounter + 1);
}
int effective_addr = arg;
int value = arg;
switch (instructionModes[instr]) {
case ACC:
value = getA_reg();
break;
case ABX:
effective_addr = arg + getX_reg();
break;
case ABY:
effective_addr = arg + getY_reg();
break;
case ABS:
value = J6502Memory.get(arg);
break;
case IND:
effective_addr = (J6502Memory.get(effective_addr + 1) << 8) + J6502Memory.get(effective_addr);
break;
case REL:
value += programCounter + (byte)arg;
break;
}
setProgramCounter(programCounter + instrSize);
switch (instr) {
case 0x4C:
setProgramCounter(effective_addr);
break;
case 0x8D:
J6502Memory.set(effective_addr, a_reg);
break;
case 0xA0:
setY_reg(value);
break;
case 0xA9:
setA_reg(value);
break;
}
if (cpuListener != null) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
cpuListener.updateVideo();
}
});
}
}
public int getProgramCounter() {
return programCounter;
}
public void setProgramCounter(int programCounter) {
if (cpuListener != null) {
cpuListener.programCounterChanged(this, this.programCounter, programCounter);
}
this.programCounter = programCounter;
}
public int getStackPointer() {
return stackPointer;
}
public void setStackPointer(int stackPointer) {
this.stackPointer = stackPointer;
}
public void push(int value) {
int oldStackPointer = stackPointer;
J6502Memory.set(stackPointer--, value);
if (stackPointer < 0x0100) {
stackPointer = 0x01FF;
}
if (cpuListener != null) {
cpuListener.stackPointerChanged(this, oldStackPointer, stackPointer);
}
}
public int pop() {
int oldStackPointer = stackPointer;
int result = J6502Memory.get(stackPointer++);
if (stackPointer > 0x01FF) {
stackPointer = 0x0100;
}
if (cpuListener != null) {
cpuListener.stackPointerChanged(this, oldStackPointer, stackPointer);
}
return result;
}
public boolean isSingleStep() {
return singleStep;
}
public void setSingleStep(boolean singleStep) {
this.singleStep = singleStep;
}
public int getY_reg() {
return y_reg;
}
public void setY_reg(int y_reg) {
flags[ZERO_FLAG] = (y_reg == 0 ? FlagStatus.On : FlagStatus.Off);
flags[NEGATIVE_FLAG] = ((y_reg & 128) != 0 ? FlagStatus.On : FlagStatus.Off);
if (cpuListener != null) {
cpuListener.yRegisterChanged(this, this.y_reg, y_reg);
cpuListener.flagStatusChanged(this, flags);
}
this.y_reg = y_reg;
}
public int getX_reg() {
return x_reg;
}
public void setX_reg(int x_reg) {
flags[ZERO_FLAG] = (x_reg == 0 ? FlagStatus.On : FlagStatus.Off);
flags[NEGATIVE_FLAG] = ((x_reg & 128) != 0 ? FlagStatus.On : FlagStatus.Off);
if (cpuListener != null) {
cpuListener.xRegisterChanged(this, this.x_reg, x_reg);
cpuListener.flagStatusChanged(this, flags);
}
this.x_reg = x_reg;
}
public int getA_reg() {
return a_reg;
}
public void setA_reg(int a_reg) {
flags[ZERO_FLAG] = (a_reg == 0 ? FlagStatus.On : FlagStatus.Off);
flags[NEGATIVE_FLAG] = ((a_reg & 128) != 0 ? FlagStatus.On : FlagStatus.Off);
if (cpuListener != null) {
cpuListener.accumulatorChanged(this, this.a_reg, a_reg);
cpuListener.flagStatusChanged(this, flags);
}
this.a_reg = a_reg;
}
public CpuListener getCpuListener() {
return cpuListener;
}
public void setCpuListener(CpuListener cpuListener) {
this.cpuListener = cpuListener;
}
public void updatedFlags() {
if (cpuListener != null) {
cpuListener.flagStatusChanged(this, flags);
}
}
public void nextStep() {
doNextStep = true;
}
}
| 26.861789 | 110 | 0.546156 |
d453ca87f5d70b96face2a071d16d721febafda3 | 3,691 | package com.luojilab.component.componentlib.router.ui;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* <p><b>Package:</b> com.luojilab.component.componentlib.router.ui </p>
* <p><b>Project:</b> DDComponentForAndroid </p>
* <p><b>Classname:</b> AbsDispatcherActivity </p>
* <p><b>Description:</b> It is the basic activity to handle intent call from web.
* <p>
* Register your own impl each component as follow in manifest:
* <p>
* <p>
* <pre class="prettyprint">
* <activity android:name=".XXXXXXX">
* <intent-filter>
* <data
* android:host="AAA.BBB.CCC"
* android:scheme="http"/>
* <action android:name="android.intent.action.VIEW"/>
* <category android:name="android.intent.category.DEFAULT"/>
* <category android:name="android.intent.category.BROWSABLE"/>
* </intent-filter>
* </activity>
* </pre>
* <p>
* <p>
* Created by leobert on 14/01/2018.
*/
public abstract class AbsDispatcherActivity extends AppCompatActivity {
@Override
protected final void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleUriRequestFromOuter(getIntent().getData());
}
@Override
public final void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
handleUriRequestFromOuter(getIntent().getData());
}
@Override
protected final void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleUriRequestFromOuter(intent.getData());
}
private void handleUriRequestFromOuter(Uri uri) {
onBeforeHandle();
if (uri == null) {
onNullUri();
return;
}
if (needTransferUri(uri))
uri = transferUri(uri);
VerifyResult verifyResult = UIRouter.getInstance().verifyUri(uri, null, true);
if (verifyResult.isSuccess()) {
try {
UIRouter.getInstance().openUri(this, uri, generateBasicBundle());
} catch (Exception e) {
e.printStackTrace();
onExceptionWhenOpenUri(uri, e);
}
} else {
onVerifyFailed(verifyResult.getThrowable());
}
onHandled();
}
protected abstract boolean needTransferUri(Uri uri);
protected abstract Uri transferUri(Uri uri);
/**
*
*/
protected abstract void onBeforeHandle();
/**
* if got an null uri, this will be called
*/
protected abstract void onNullUri();
// /**
// * missing required param on preCondition period;
// */
// @Deprecated
// protected abstract void onParamException(ParamException e);
//
// /**
// * no one matched for the uri,may uri error or component is not mounted
// */
// @Deprecated
// protected abstract void onNonMatchedException(UiRouterException.NonMatchedException e);
protected abstract void onVerifyFailed(@Nullable Throwable throwable);
/**
* get exception when handle openUri
*/
protected abstract void onExceptionWhenOpenUri(Uri uri, Exception e);
/**
* maybe finish this activity is better
*/
protected abstract void onHandled();
/**
* override this if you have some basic params need to deliver.
*
* @return an Empty Bundle
*/
protected Bundle generateBasicBundle() {
return new Bundle();
}
}
| 28.175573 | 114 | 0.651043 |
8f21c27f47f58b6336590efc015f48f261eff8eb | 2,257 | package com.base.engine.core;
import com.base.engine.audio.AudioEngine;
import com.base.engine.rendering.RenderingEngine;
import com.base.engine.rendering.Window;
public class CoreEngine {
private boolean isRunning;
private Game game;
private double frameTime;
private RenderingEngine renderingEngine;
private AudioEngine audioEngine;
public CoreEngine(double framerate, Game game) {
this.isRunning = false;
this.game = game;
this.frameTime = 1.0 / framerate;
}
public void createWindow(int width, int height, String title) {
Window.createWindow(width, height, title);
this.renderingEngine = new RenderingEngine();
this.audioEngine = new AudioEngine();
}
public void start() {
if (!isRunning) {
run();
}
}
public void stop() {
if (isRunning) {
isRunning = false;
}
return;
}
private void run() {
isRunning = true;
int frames = 0;
long frameConter = 0;
game.init();
double lastTime = Time.getTime();
double unprocessedTime = 0;
while (isRunning) {
boolean render = false;
double startTime = Time.getTime();
double passedTime = startTime - lastTime;
lastTime = startTime;
unprocessedTime += passedTime;
frameConter += passedTime;
while (unprocessedTime > frameTime) {
render = true;
unprocessedTime -= frameTime;
if (Window.isCloseRequested()) {
stop();
}
game.input((float) frameTime);
audioEngine.input((float) frameTime);
Input.update();
game.update((float) frameTime);
if (frameConter >= 1.0) {
System.out.println(frames);
frames = 0;
frameConter = 0;
}
}
if (render) {
game.render(renderingEngine);
Window.render();
audioEngine.update(renderingEngine.getMainCamera().getTransform().getPos(),
renderingEngine.getMainCamera().getTransform().getRot().getForward(),
renderingEngine.getMainCamera().getTransform().getRot().getUp());
frames++;
} else {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
cleanUp();
}
private void cleanUp() {
Window.dispose();
AudioEngine.cleanUp();
}
}
| 21.093458 | 80 | 0.6358 |
d2357fa22678f80654446962f52dbf1ebd2e6744 | 197 | package mf.dao;
import mf.entity.MfAdEntity;
/**
*
*
* @author dengfan
* @email [email protected]
* @date 2017-03-06 22:25:21
*/
public interface MfAdDao extends BaseDao<MfAdEntity> {
}
| 13.133333 | 54 | 0.670051 |
46933547788c02a71fe5c4c3077adacba220d6a8 | 3,669 | package net.glasslauncher.guis.chat;
import com.google.common.collect.ImmutableList;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.glasslauncher.guis.util.Unit;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
public interface FormattedText {
Optional<Unit> STOP_ITERATION = Optional.of(Unit.INSTANCE);
FormattedText EMPTY = new FormattedText() {
public <T> Optional<T> visit(ContentConsumer<T> contentConsumer) {
return Optional.empty();
}
@Environment(EnvType.CLIENT)
public <T> Optional<T> visit(StyledContentConsumer<T> styledContentConsumer, Style style) {
return Optional.empty();
}
};
<T> Optional<T> visit(ContentConsumer<T> contentConsumer);
@Environment(EnvType.CLIENT)
<T> Optional<T> visit(StyledContentConsumer<T> styledContentConsumer, Style style);
static FormattedText of(final String string) {
return new FormattedText() {
public <T> Optional<T> visit(ContentConsumer<T> contentConsumer) {
return contentConsumer.accept(string);
}
@Environment(EnvType.CLIENT)
public <T> Optional<T> visit(StyledContentConsumer<T> styledContentConsumer, Style style) {
return styledContentConsumer.accept(style, string);
}
};
}
@Environment(EnvType.CLIENT)
static FormattedText of(final String string, final Style style) {
return new FormattedText() {
public <T> Optional<T> visit(ContentConsumer<T> contentConsumer) {
return contentConsumer.accept(string);
}
public <T> Optional<T> visit(StyledContentConsumer<T> styledContentConsumer, Style stylex) {
return styledContentConsumer.accept(style.applyTo(stylex), string);
}
};
}
@Environment(EnvType.CLIENT)
static FormattedText composite(FormattedText... formattedTexts) {
return composite((List) ImmutableList.copyOf((Object[])formattedTexts));
}
@Environment(EnvType.CLIENT)
static FormattedText composite(final List<FormattedText> list) {
return new FormattedText() {
public <T> Optional<T> visit(ContentConsumer<T> contentConsumer) {
Iterator var2 = list.iterator();
Optional optional;
do {
if (!var2.hasNext()) {
return Optional.empty();
}
FormattedText formattedText = (FormattedText)var2.next();
optional = formattedText.visit(contentConsumer);
} while(!optional.isPresent());
return optional;
}
public <T> Optional<T> visit(StyledContentConsumer<T> styledContentConsumer, Style style) {
Iterator var3 = list.iterator();
Optional optional;
do {
if (!var3.hasNext()) {
return Optional.empty();
}
FormattedText formattedText = (FormattedText)var3.next();
optional = formattedText.visit(styledContentConsumer, style);
} while(!optional.isPresent());
return optional;
}
};
}
default String getString() {
StringBuilder stringBuilder = new StringBuilder();
this.visit((string) -> {
stringBuilder.append(string);
return Optional.empty();
});
return stringBuilder.toString();
}
public interface ContentConsumer<T> {
Optional<T> accept(String string);
}
@Environment(EnvType.CLIENT)
public interface StyledContentConsumer<T> {
Optional<T> accept(Style style, String string);
}
}
| 31.62931 | 101 | 0.638049 |
4d36af83b4b512fe27401849147d6ad3c94f187a | 658 | package org.jboss.eap.qe.microprofile.jwt.testapp.jaxrs;
import org.eclipse.microprofile.jwt.JsonWebToken;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/secured-endpoint")
@ApplicationScoped
public class SecuredJaxRsEndpoint {
@Inject
private JsonWebToken callerPrincipal;
@GET
public Response echoRawTokenValue() {
return Response.ok()
.entity(callerPrincipal.getRawToken())
.type(MediaType.TEXT_PLAIN)
.build();
}
}
| 24.37037 | 56 | 0.709726 |
d1b8f760db28f232900889598f7bfa5ca0614147 | 3,712 | package com.cactusteam.money.data.dao;
// THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS
// KEEP INCLUDES - put your custom includes here
import android.os.Parcel;
// KEEP INCLUDES END
/**
* Entity mapped to table "CURRENCY_RATE".
*/
public class CurrencyRate implements android.os.Parcelable {
private Long id;
/** Not-null value. */
private java.util.Date date;
/** Not-null value. */
private String sourceCurrencyCode;
/** Not-null value. */
private String destCurrencyCode;
private double rate;
// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END
public CurrencyRate() {
}
public CurrencyRate(Long id) {
this.id = id;
}
public CurrencyRate(Long id, java.util.Date date, String sourceCurrencyCode, String destCurrencyCode, double rate) {
this.id = id;
this.date = date;
this.sourceCurrencyCode = sourceCurrencyCode;
this.destCurrencyCode = destCurrencyCode;
this.rate = rate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/** Not-null value. */
public java.util.Date getDate() {
return date;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setDate(java.util.Date date) {
this.date = date;
}
/** Not-null value. */
public String getSourceCurrencyCode() {
return sourceCurrencyCode;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setSourceCurrencyCode(String sourceCurrencyCode) {
this.sourceCurrencyCode = sourceCurrencyCode;
}
/** Not-null value. */
public String getDestCurrencyCode() {
return destCurrencyCode;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setDestCurrencyCode(String destCurrencyCode) {
this.destCurrencyCode = destCurrencyCode;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
// KEEP METHODS - put your custom methods here
public double convertTo(double amount, String toCurrencyCode) {
if (toCurrencyCode.equals(sourceCurrencyCode)) {
// from dest to source
return com.cactusteam.money.data.DataUtils.INSTANCE.round(amount / rate, 2);
} else {
// from source to dest
return amount * rate;
}
}
public boolean same(String currencyCode1, String currencyCode2) {
return (currencyCode1.equals(sourceCurrencyCode) && currencyCode2.equals(destCurrencyCode))
|| (currencyCode2.equals(sourceCurrencyCode) && currencyCode1.equals(destCurrencyCode));
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(sourceCurrencyCode);
parcel.writeString(destCurrencyCode);
parcel.writeDouble(rate);
}
protected CurrencyRate(Parcel in) {
sourceCurrencyCode = in.readString();
destCurrencyCode = in.readString();
rate = in.readDouble();
}
public static final Creator<CurrencyRate> CREATOR = new Creator<CurrencyRate>() {
@Override
public CurrencyRate createFromParcel(Parcel in) {
return new CurrencyRate(in);
}
@Override
public CurrencyRate[] newArray(int size) {
return new CurrencyRate[size];
}
};
// KEEP METHODS END
}
| 27.701493 | 120 | 0.637123 |
00028b5b6d5a5f1e221e1142674f8b1101b37191 | 13,219 | package prover;
import java.util.LinkedList;
import java.util.Stack;
public abstract class Prover
{
public static void prove(Logic input)
{
// Feedback
System.out.println("Attempting to prove: |- "+input.toString());
// Initialise lists
LinkedList<Logic> lhs = new LinkedList<Logic>();
LinkedList<Logic> rhs = new LinkedList<Logic>();
LinkedList<String> log = new LinkedList<String>();
LinkedList<String> dcTabu = new LinkedList<String>();
Stack<LinkedList<Logic>> lhsDC = new Stack<LinkedList<Logic>>();
Stack<LinkedList<Logic>> rhsDC = new Stack<LinkedList<Logic>>();
// Add the input to the RHS (expected to conclude $F for theorems)
rhs.add(input);
log.add("[o] "+input.toString()+" [Input]");
boolean mod = true;
int i;
while(mod)
{
boolean abort = false;
mod = false;
// Check consistency
for(Logic elem : lhs)
if(elem.isLiteral)
for(Logic compare : rhs)
if(compare.isLiteral)
if(((Literal)compare).toString().equals(((Literal)elem).toString()))
{
// Found complimentary pair; conclude $F
log.add(((Literal)elem).toString()+" [o] "+(((Literal)compare).toString())+" [$F]");
abort = true;
}
// When finding $F, backtrack if possible, terminate otherwise
if(abort && lhsDC.size() == 0 && rhsDC.size() == 0)
break;
else if(abort && lhsDC.size() > 0 && rhsDC.size() > 0)
{
abort = false;
// Retrieve LHS and RHS
lhs = lhsDC.pop();
rhs = rhsDC.pop();
// Convert to proper string format and log
String s = "";
int j;
for(j = 0 ; j < lhs.size(); j++)
{
if(j == 0)
s+=lhs.get(j).toString();
else
s+=(", "+lhs.get(j).toString());
}
s+=" [o] ";
for(j = 0 ; j < rhs.size(); j++)
{
if(j == 0)
s+=rhs.get(j).toString();
else
s+=(", "+rhs.get(j).toString());
}
s+=" [Backtrack DC #"+(lhsDC.size()+1)+"]";
log.add(s);
mod = true;
}
// Apply alpha and beta rules
if(!mod)
for(i = 0 ; i < lhs.size() ; i++)
{
// Starting at the LHS
Logic elem = lhs.get(i);
// Check for L-NEG on both literals and formulas
if(elem.negation)
{
lhs.remove(elem);
elem.negation = false;
rhs.add(elem);
log.add("[o] "+elem.toString()+" [L-NEG]");
mod = true;
break;
}
if(!elem.isLiteral)
{
if(((Formula)elem).conn == Formula.Connective.AND)
{
// Check for L-AND
lhs.remove(elem);
lhs.add(((Formula)elem).fst);
lhs.add(((Formula)elem).snd);
log.add(((Formula)elem).fst.toString()+", "+((Formula)elem).snd.toString()+" [o] [L-AND]");
mod = true;
break;
}
else if(((Formula)elem).conn == Formula.Connective.OR)
{
// Check for L-OR (2 variants)
Logic lhsAdd1 = null;
Logic lhsAdd2 = null;
for(Logic form : rhs)
{
if(((Formula)elem).fst.toString().equals(form.toString()))
{
// Variant 1
lhsAdd1 = ((Formula)elem).snd;
log.add(((Formula)elem).snd.toString()+" [o] [L-OR1]");
}
}
for(Logic form : rhs)
{
if(((Formula)elem).snd.toString().equals(form.toString()))
{
// Variant 2
lhsAdd2 = ((Formula)elem).fst;
log.add(((Formula)elem).fst.toString()+" [o] [L-OR2]");
}
}
// Delay changes for concurrency
if(lhsAdd1 != null || lhsAdd2 != null)
{
lhs.remove(elem);
if(lhsAdd1 != null)
lhs.add(lhsAdd1);
if(lhsAdd2 != null)
lhs.add(lhsAdd2);
mod = true;
break;
}
}
else if(((Formula)elem).conn == Formula.Connective.IMP)
{
// Check for L-IMP (2 variants)
Logic lhsAdd = null;
Logic rhsAdd = null;
for(Logic form : lhs)
{
if(((Formula)elem).fst.toString().equals(form.toString()))
{
// Variant 1
lhsAdd = ((Formula)elem).snd;
log.add(((Formula)elem).snd.toString()+" [o] [L-IMP1]");
}
}
for(Logic form : rhs)
{
if(((Formula)elem).snd.toString().equals(form.toString()))
{
// Variant 2
rhsAdd = ((Formula)elem).fst;
log.add("[o] "+((Formula)elem).fst.toString()+" [L-IMP2]");
}
}
// Delay changes for concurrency
if(lhsAdd != null || rhsAdd != null)
{
lhs.remove(elem);
if(lhsAdd != null)
lhs.add(lhsAdd);
if(rhsAdd != null)
rhs.add(rhsAdd);
mod = true;
break;
}
}
else if(((Formula)elem).conn == Formula.Connective.LEQ)
{
// Check for L-LEQ (4 variants)
Logic lhsAdd1 = null;
Logic lhsAdd2 = null;
Logic rhsAdd1 = null;
Logic rhsAdd2 = null;
for(Logic form : lhs)
{
if(((Formula)elem).fst.toString().equals(form.toString()))
{
// Variant 1
lhsAdd1 = ((Formula)elem).snd;
log.add(((Formula)elem).snd.toString()+" [o] [L-LEQ1]");
}
else if(((Formula)elem).snd.toString().equals(form.toString()))
{
// Variant 2
lhsAdd2 = ((Formula)elem).fst;
log.add(((Formula)elem).fst.toString()+" [o] [L-LEQ2]");
}
}
for(Logic form : rhs)
{
if(((Formula)elem).fst.toString().equals(form.toString()))
{
// Variant 3
rhsAdd1 = ((Formula)elem).snd;
log.add("[o] "+((Formula)elem).snd.toString()+" [L-LEQ3]");
}
else if(((Formula)elem).snd.toString().equals(form.toString()))
{
// Variant 4
rhsAdd2 = ((Formula)elem).fst;
log.add("[o] "+((Formula)elem).fst.toString()+" [L-LEQ4]");
}
}
// Delay changes for concurrency
if(lhsAdd1 != null || lhsAdd2 != null || rhsAdd1 != null || rhsAdd2 != null)
{
lhs.remove(elem);
if(lhsAdd1 != null)
lhs.add(lhsAdd1);
if(lhsAdd2 != null)
lhs.add(lhsAdd2);
if(rhsAdd1 != null)
rhs.add(rhsAdd1);
if(rhsAdd2 != null)
rhs.add(rhsAdd2);
mod = true;
break;
}
}
}
}
if(!mod)
for(i = 0 ; i < rhs.size(); i++)
{
// Continuing on the RHS
Logic elem = rhs.get(i);
// Check for R-NEG on both literals and formulas
if(elem.negation)
{
rhs.remove(elem);
elem.negation = false;
lhs.add(elem);
log.add(elem.toString()+" [o] [R-NEG]");
mod = true;
break;
}
if(!elem.isLiteral)
{
if(((Formula)elem).conn == Formula.Connective.OR)
{
// Check for R-OR
rhs.remove(elem);
rhs.add(((Formula)elem).fst);
rhs.add(((Formula)elem).snd);
log.add("[o] "+((Formula)elem).fst.toString()+", "+((Formula)elem).snd.toString()+" [R-OR]");
mod = true;
break;
}
else if(((Formula)elem).conn == Formula.Connective.IMP)
{
// Check for R-IMP
rhs.remove(elem);
rhs.add(((Formula)elem).snd);
lhs.add(((Formula)elem).fst);
log.add(((Formula)elem).fst.toString()+" [o] "+((Formula)elem).snd.toString()+" [R-IMP]");
mod = true;
break;
}
else if(((Formula)elem).conn == Formula.Connective.AND)
{
// Check for R-AND (2 variants)
Logic rhsAdd1 = null;
Logic rhsAdd2 = null;
for(Logic form : lhs)
{
if(((Formula)elem).fst.toString().equals(form.toString()))
{
// Variant 1
rhsAdd1 = ((Formula)elem).snd;
log.add("[o] "+((Formula)elem).snd.toString()+" [R-AND1]");
}
}
for(Logic form : lhs)
{
if(((Formula)elem).snd.toString().equals(form.toString()))
{
// Variant 2
rhsAdd2 = ((Formula)elem).fst;
log.add("[o] "+((Formula)elem).fst.toString()+" [R-AND2]");
}
}
// Delay changes for concurrency
if(rhsAdd1 != null || rhsAdd2 != null)
{
rhs.remove(elem);
if(rhsAdd1 != null)
rhs.add(rhsAdd1);
if(rhsAdd2 != null)
rhs.add(rhsAdd2);
mod = true;
break;
}
}
else if(((Formula)elem).conn == Formula.Connective.LEQ)
{
// Check for R-LEQ (4 variants)
Logic lhsAdd1 = null;
Logic lhsAdd2 = null;
Logic rhsAdd1 = null;
Logic rhsAdd2 = null;
for(Logic form : lhs)
{
if(((Formula)elem).fst.toString().equals(form.toString()))
{
// Variant 1
rhsAdd1 = ((Formula)elem).snd;
log.add("[o] "+((Formula)elem).snd.toString()+" [R-LEQ1]");
}
else if(((Formula)elem).snd.toString().equals(form.toString()))
{
// Variant 2
rhsAdd2 = ((Formula)elem).fst;
log.add("[o] "+((Formula)elem).fst.toString()+" [R-LEQ2]");
}
}
for(Logic form : rhs)
{
if(((Formula)elem).fst.toString().equals(form.toString()))
{
// Variant 3
lhsAdd1 = ((Formula)elem).snd;
log.add(((Formula)elem).snd.toString()+" [o] [R-LEQ3]");
}
else if(((Formula)elem).snd.toString().equals(form.toString()))
{
// Variant 4
lhsAdd2 = ((Formula)elem).fst;
log.add(((Formula)elem).fst.toString()+" [o] [R-LEQ4]");
}
}
// Delay changes for concurrency
if(lhsAdd1 != null || lhsAdd2 != null || rhsAdd1 != null || rhsAdd2 != null)
{
rhs.remove(elem);
if(lhsAdd1 != null)
lhs.add(lhsAdd1);
if(lhsAdd2 != null)
lhs.add(lhsAdd2);
if(rhsAdd1 != null)
rhs.add(rhsAdd1);
if(rhsAdd2 != null)
rhs.add(rhsAdd2);
mod = true;
break;
}
}
}
}
// Apply DC if necessary
if(!mod)
{
for(Logic elem : lhs)
{
boolean skip = false;;
if(!elem.isLiteral)
{
// Apply DC on left side Beta rule from LHS
Logic dcElem = null;
if(!dcTabu.contains((((Formula)elem).fst).toString()))
dcElem = ((Formula)elem).fst;
else if(!dcTabu.contains((((Formula)elem).snd).toString()))
dcElem = ((Formula)elem).snd;
else
skip = true;
if(!skip)
{
// Make copies of LHS and RHS for backtracking
dcTabu.add(dcElem.toString());
LinkedList<Logic> lhsBackTrack = new LinkedList<Logic>();
LinkedList<Logic> rhsBackTrack = new LinkedList<Logic>();
for(Logic lhsElem : lhs)
{
if(lhsElem.isLiteral)
lhsBackTrack.add(new Literal((Literal)lhsElem));
else
lhsBackTrack.add(new Formula((Formula)lhsElem));
}
for(Logic rhsElem : rhs)
{
if(rhsElem.isLiteral)
rhsBackTrack.add(new Literal((Literal)rhsElem));
else
rhsBackTrack.add(new Formula((Formula)rhsElem));
}
if(dcElem.isLiteral)
rhsBackTrack.add(new Literal((Literal)dcElem));
else
rhsBackTrack.add(new Formula((Formula)dcElem));
// Push the copies on a stack with added DC element
lhsDC.push(lhsBackTrack);
rhsDC.push(rhsBackTrack);
lhs.add(dcElem);
// Log DC
log.add(dcElem.toString()+" [o] [DC #"+lhsDC.size()+"]");
mod = true;
break;
}
}
}
}
if(!mod)
{
for(Logic elem : rhs)
{
boolean skip = false;
if(!elem.isLiteral)
{
// Apply DC on right side Beta rule
Logic dcElem = null;
if(!dcTabu.contains((((Formula)elem).fst).toString()))
dcElem = ((Formula)elem).fst;
else if(!dcTabu.contains((((Formula)elem).snd).toString()))
dcElem = ((Formula)elem).snd;
else
skip = true;
if(!skip)
{
// Make copies of LHS and RHS for backtracking
dcTabu.add(dcElem.toString());
LinkedList<Logic> lhsBackTrack = new LinkedList<Logic>();
LinkedList<Logic> rhsBackTrack = new LinkedList<Logic>();
for(Logic lhsElem : lhs)
{
if(lhsElem.isLiteral)
lhsBackTrack.add(new Literal((Literal)lhsElem));
else
lhsBackTrack.add(new Formula((Formula)lhsElem));
}
for(Logic rhsElem : rhs)
{
if(rhsElem.isLiteral)
rhsBackTrack.add(new Literal((Literal)rhsElem));
else
rhsBackTrack.add(new Formula((Formula)rhsElem));
}
if(dcElem.isLiteral)
lhsBackTrack.add(new Literal((Literal)dcElem));
else
lhsBackTrack.add(new Formula((Formula)dcElem));
// Push the copies on a stack with added DC element
lhsDC.push(lhsBackTrack);
rhsDC.push(rhsBackTrack);
rhs.add(dcElem);
// Log DC
log.add("[o] "+dcElem.toString()+" [DC #"+rhsDC.size()+"]");
mod = true;
break;
}
}
}
}
}
// Print results
for(String s : log)
System.out.println(s);
}
}
| 25.421154 | 99 | 0.511688 |
ad63fcdc6443f0694a7dd1a2d078601852c6c523 | 1,487 | package my.jedis;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.params.SetParams;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class AccessRedisCluster {
public static void main(String[] args) {
Set<HostAndPort> hps = new HashSet<>();
for (int port = 7001; port <= 7006; port++) {
hps.add(new HostAndPort("39.100.242.198", port));
// hps.add(new HostAndPort("192.168.0.97", port));
}
access(hps, "f75B1X609aJ1");
}
private static void access(Set<HostAndPort> hps, String password) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(100);
config.setMaxIdle(20);
config.setMinIdle(2);
config.setMaxWaitMillis(3000);
config.setTestOnBorrow(true);
config.setTestWhileIdle(true);
config.setBlockWhenExhausted(false);
JedisCluster jc = new JedisCluster(hps, 5000, 5000, 5,
password, config);
for (int i = 0; i < 100; i++) {
String key = UUID.randomUUID().toString();
String value = UUID.randomUUID().toString();
jc.set(key, value, SetParams.setParams().ex(60));
System.out.println(jc.get(key));
}
System.out.println("Access succeed, " + Arrays.toString(hps.toArray()));
}
}
| 33.044444 | 80 | 0.630128 |
ed18440096c963b816a11ad70494efd9bf62d041 | 5,415 | package com.rwxlicai.base;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import com.activeandroid.ActiveAndroid;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.rwxlicai.R;
import com.umeng.socialize.PlatformConfig;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
/**
* Created by xuebing on 15/12/28.
*/
public class BaseApplication extends Application {
protected ImageLoader imageLoader;
public static Context applicationContext;
public SharedPreferences sharedPreferences;
public static final String APP_ID = "com.xem.mzbphoneapp";
@Override
public void onCreate() {
super.onCreate();
applicationContext = getApplicationContext();
// activeAndroid初始化
ActiveAndroid.initialize(this);
//初始化键值对存储
sharedPreferences = getSharedPreferences(APP_ID, MODE_PRIVATE);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this)
.memoryCacheExtraOptions(480, 800)
// max width, max height,即保存的每个缓存文件的最大长宽
.discCacheExtraOptions(480, 800, null)
// Can slow ImageLoader, use it carefully (Better don't use
// it)/设置缓存的详细信息,最好不要设置这个
.threadPoolSize(3)
// 线程池内加载的数量
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
// You can pass your own memory cache
// implementation/你可以通过自己的内存缓存实现
.memoryCacheSize(2 * 1024 * 1024)
.discCacheSize(50 * 1024 * 1024)
.discCacheFileNameGenerator(new Md5FileNameGenerator())
// 将保存的时候的URI名称用MD5 加密
.tasksProcessingOrder(QueueProcessingType.LIFO)
.discCacheFileCount(100)
// 缓存的文件数量
.discCache(
new UnlimitedDiscCache(new File(Environment
.getExternalStorageDirectory()
+ "/avater")))
// 自定义缓存路径
.defaultDisplayImageOptions(getDisplayOptions())
.imageDownloader(
new BaseImageDownloader(this, 5 * 1000, 30 * 1000))
.writeDebugLogs() // Remove for release app
.build();// 开始构建
ImageLoader.getInstance().init(config);
}
private DisplayImageOptions getDisplayOptions() {
DisplayImageOptions options;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.launcher) // 设置图片在下载期间显示的图片
.showImageForEmptyUri(R.mipmap.launcher)// 设置图片Uri为空或是错误的时候显示的图片
.showImageOnFail(R.mipmap.launcher) // 设置图片加载/解码过程中错误时候显示的图片
.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
.cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
.considerExifParams(true) // 是否考虑JPEG图像EXIF参数(旋转,翻转)
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
.bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
.resetViewBeforeLoading(true)// 设置图片在下载前是否重置,复位
.displayer(new RoundedBitmapDisplayer(20))// 是否设置为圆角,弧度为多少
.displayer(new FadeInBitmapDisplayer(100))// 是否图片加载好后渐入的动画时间
.build();// 构建完成
return options;
}
private List<Activity> mList = new LinkedList<Activity>();
private static BaseApplication instance;
public synchronized static BaseApplication getInstance() {
if (null == instance) {
instance = new BaseApplication();
}
return instance;
}
// add Activity
public void addActivity(Activity activity) {
mList.add(activity);
}
public void exit() {
try {
for (Activity activity : mList) {
if (activity != null)
activity.finish();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
//各个平台的配置,建议放在全局Application或者程序入口
{
PlatformConfig.setWeixin("wxe4cbfd958d053f38", "9493b056c24b61db05141ec0ce55e425");
PlatformConfig.setQQZone("1105149864", "KEYukI6WLtnZf9DWWq4");
}
}
| 39.525547 | 91 | 0.643398 |
6d2ba1ddff7ab60337c860439c520693ec4e7d08 | 5,569 | /**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.keyvalue.dbkvs.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.Closeable;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import com.google.common.collect.Sets;
import com.palantir.common.base.ClosableIterator;
import com.palantir.common.base.ClosableIterators;
import com.palantir.exception.PalantirInterruptedException;
public class LazyClosableIteratorTest {
@Test
public void testInterruptsDontCauseLeaksMultiple() throws Exception {
for (int i = 1; i <= 100; i++) {
try {
// Because race conditions are hard...
testInterruptsDontCauseLeaks();
} catch (Throwable e) {
throw new RuntimeException("Failure during run " + i, e);
}
}
}
@Test // QA-89231
public void testInterruptsDontCauseLeaks() throws Exception {
Set<Integer> opened = Sets.newConcurrentHashSet();
Set<Integer> closed = Sets.newConcurrentHashSet();
List<FutureTask<ClosableIterator<String>>> tasks = Lists.newArrayList();
for (int i = 0; i < 2; i++) {
tasks.add(createNewFutureTask(i, opened, closed));
}
tasks.add(createInterruptTask(Thread.currentThread(), opened, closed));
for (int i = 2; i < 4; i++) {
tasks.add(createNewFutureTask(i, opened, closed));
}
ExecutorService exec = Executors.newFixedThreadPool(2);
Queue<Future<ClosableIterator<String>>> futures = Queues.newArrayDeque();
futures.addAll(tasks);
for (FutureTask<?> task : tasks) {
exec.submit(task);
}
LazyClosableIterator<String> iter = new LazyClosableIterator<String>(futures);
List<String> output = Lists.newArrayList();
try {
while(iter.hasNext()) {
output.add(iter.next());
}
assertTrue(Thread.interrupted()); // race didn't do the thing this time.
} catch (PalantirInterruptedException e) {
assertTrue(Thread.interrupted()); // clear interrupted exception
}
iter.close();
exec.shutdownNow();
exec.awaitTermination(1, TimeUnit.SECONDS);
assertEquals(opened, closed);
assertTrue("output not in allowable state: " + output,
output.equals(Lists.newArrayList("0-1", "0-2", "1-1", "1-2")) ||
output.equals(Lists.newArrayList("0-1", "0-2")) ||
output.isEmpty());
}
private FutureClosableIteratorTask<String> createInterruptTask(final Thread curThread,
final Set<Integer> opened, final Set<Integer> closed) {
return new FutureClosableIteratorTask<String>(new Callable<ClosableIterator<String>>() {
@Override
public ClosableIterator<String> call() {
opened.add(-1);
curThread.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
closed.add(-1);
}
throw new RuntimeException();
}
});
}
private FutureClosableIteratorTask<String> createNewFutureTask(final int num,
final Set<Integer> opened, final Set<Integer> closed) {
return new FutureClosableIteratorTask<String>(new Callable<ClosableIterator<String>>() {
@Override
public ClosableIterator<String> call() throws Exception {
final Iterator<String> iter = Iterators.forArray(num + "-1", num + "-2");
opened.add(num);
ClosableIterator<String> result = ClosableIterators.wrap(
new AbstractIterator<String>() {
@Override
protected String computeNext() {
if (iter.hasNext()) {
return iter.next();
} else {
return endOfData();
}
}
},
new Closeable() {
@Override
public void close() {
closed.add(num);
}
});
return result;
}
});
}
}
| 38.406897 | 96 | 0.588795 |
c8b7f516f3dce4477f551b3cd2953f81bd40bda5 | 4,633 | package com.michael.demo.jdk.io.aio;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
/**
* 负责对每一个socketChannel的数据获取事件进行监听。<p>
* <p>
* 重要的说明:一个socketchannel都会有一个独立工作的SocketChannelReadHandle对象(CompletionHandler接口的实现),
* 其中又都将独享一个“文件状态标示”对象FileDescriptor、
* 一个独立的由程序员定义的Buffer缓存(这里我们使用的是ByteBuffer)、
* 所以不用担心在服务器端会出现“窜对象”这种情况,因为JAVA AIO框架已经帮您组织好了。<p>
* <p>
* 但是最重要的,用于生成channel的对象:AsynchronousChannelProvider是单例模式,无论在哪组socketchannel,
* 对是一个对象引用(但这没关系,因为您不会直接操作这个AsynchronousChannelProvider对象)。
*
* @author keep_trying
*/
public class SocketChannelReadHandle implements CompletionHandler<Integer, StringBuffer> {
/**
* 日志
*/
private static final Log LOGGER = LogFactory.getLog(SocketChannelReadHandle.class);
private AsynchronousSocketChannel socketChannel;
/**
* 专门用于进行这个通道数据缓存操作的ByteBuffer<br>
* 当然,您也可以作为CompletionHandler的attachment形式传入。<br>
* 这是,在这段示例代码中,attachment被我们用来记录所有传送过来的Stringbuffer了。
*/
private ByteBuffer byteBuffer;
public SocketChannelReadHandle(AsynchronousSocketChannel socketChannel, ByteBuffer byteBuffer) {
this.socketChannel = socketChannel;
this.byteBuffer = byteBuffer;
}
/* (non-Javadoc)
* @see java.nio.channels.CompletionHandler#completed(java.lang.Object, java.lang.Object)
*/
@Override
public void completed(Integer result, StringBuffer historyContext) {
//如果条件成立,说明客户端主动终止了TCP套接字,这时服务端终止就可以了
if (result == -1) {
try {
this.socketChannel.close();
} catch (IOException e) {
SocketChannelReadHandle.LOGGER.error(e);
}
return;
}
SocketChannelReadHandle.LOGGER.info("completed(Integer result, Void attachment) : 然后我们来取出通道中准备好的值");
/*
* 实际上,由于我们从Integer result知道了本次channel从操作系统获取数据总长度
* 所以实际上,我们不需要切换成“读模式”的,但是为了保证编码的规范性,还是建议进行切换。
*
* 另外,无论是JAVA AIO框架还是JAVA NIO框架,都会出现“buffer的总容量”小于“当前从操作系统获取到的总数据量”,
* 但区别是,JAVA AIO框架中,我们不需要专门考虑处理这样的情况,因为JAVA AIO框架已经帮我们做了处理(做成了多次通知)
* */
this.byteBuffer.flip();
byte[] contexts = new byte[1024];
this.byteBuffer.get(contexts, 0, result);
this.byteBuffer.clear();
try {
String nowContent = new String(contexts, 0, result, "UTF-8");
historyContext.append(nowContent);
SocketChannelReadHandle.LOGGER.info("================目前的传输结果:" + historyContext);
} catch (UnsupportedEncodingException e) {
SocketChannelReadHandle.LOGGER.error(e);
}
//如果条件成立,说明还没有接收到“结束标记”
if (historyContext.indexOf("over") == -1) {
return;
} else {
//清空已经读取的缓存,并从新切换为写状态(这里要注意clear()和capacity()两个方法的区别)
this.byteBuffer.clear();
SocketChannelReadHandle.LOGGER.info("客户端发来的信息======message : " + historyContext);
//======================================================
// 当然接受完成后,可以在这里正式处理业务了
//======================================================
//回发数据,并关闭channel
ByteBuffer sendBuffer = null;
try {
sendBuffer = ByteBuffer.wrap(URLEncoder.encode("你好客户端,这是服务器的返回数据", "UTF-8").getBytes());
this.socketChannel.write(sendBuffer);
this.socketChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//=========================================================================
// 和上篇文章的代码相同,我们以“over”符号作为客户端完整信息的标记
//=========================================================================
SocketChannelReadHandle.LOGGER.info("=======收到完整信息,开始处理业务=========");
historyContext = new StringBuffer();
//还要继续监听(一次监听一次通知)
this.socketChannel.read(this.byteBuffer, historyContext, this);
}
/* (non-Javadoc)
* @see java.nio.channels.CompletionHandler#failed(java.lang.Throwable, java.lang.Object)
*/
@Override
public void failed(Throwable exc, StringBuffer historyContext) {
SocketChannelReadHandle.LOGGER.info("=====发现客户端异常关闭,服务器将关闭TCP通道");
try {
this.socketChannel.close();
} catch (IOException e) {
SocketChannelReadHandle.LOGGER.error(e);
}
}
} | 36.769841 | 108 | 0.608677 |
6e5407284fb0a933d204f8f2f1aee9a0d68d1712 | 161 | package com.journaldev.abstractfactory;
import com.journaldev.beans.Computer;
public interface ComputerAbstractFactory {
public Computer createComputer();
}
| 17.888889 | 42 | 0.826087 |
59ca550aa396a8b29b839ed80de872e86659c771 | 556 | package steelkiwi.com.library.interpolator;
import android.view.animation.Interpolator;
/**
* Created by yaroslav on 5/3/17.
*/
public class BounceInterpolator implements Interpolator {
private double amplitude;
private double frequency;
public BounceInterpolator(double amplitude, double frequency) {
this.amplitude = amplitude;
this.frequency = frequency;
}
public float getInterpolation(float time) {
return (float) (-1 * Math.pow(Math.E, -time / amplitude) * Math.cos(frequency * time) + 1);
}
}
| 24.173913 | 99 | 0.694245 |
0d93a295c0cd8d2039136da77a3ba879a31d3006 | 1,787 | package com.yuzhyn.azylee.core.datas.datetimes;
import java.util.Date;
public class DatePassTool {
/**
* 计算距离现在多久,非精确
* @param date 参数
* @return 返回
*/
public static String before(Date date) {
Date now = new Date();
long l = now.getTime() - date.getTime();
long day = l / (24 * 60 * 60 * 1000);
long hour = (l / (60 * 60 * 1000) - day * 24);
long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
String r = "";
if (day > 0) {
r += day + "天";
} else if (hour > 0) {
r += hour + "小时";
} else if (min > 0) {
r += min + "分";
} else if (s > 0) {
r += s + "秒";
}
r += "前";
return r;
}
/**
* 计算距离现在多久,精确
* @param date 参数
* @return 返回
*/
public static String beforeAccurate(Date date) {
Date now = new Date();
long l = now.getTime() - date.getTime();
long day = l / (24 * 60 * 60 * 1000);
long hour = (l / (60 * 60 * 1000) - day * 24);
long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
String r = "";
if (day > 0) {
r += day + "天";
}
if (hour > 0) {
r += hour + "小时";
}
if (min > 0) {
r += min + "分";
}
if (s > 0) {
r += s + "秒";
}
r += "前";
return r;
}
// public static void main(String[] args) {
// Date a = DateTool.toDate(2012,12,5,5,6,6);
// Log.e(before(a));
// Log.e(beforeAccurate(a));
// }
}
| 26.671642 | 77 | 0.396754 |
701c89d20dca14085570ce77f335c65ccb1a7668 | 1,002 | package com.wy.jvm;
/**
* 类加载器(ClassLoader):顶层为BootStrap,该加载器并不属于Java类,而是为了加载Java类存在的原生(native)组件
* BootStrap主要加载jre/lib/rt.jar,所有追溯到最顶层的ClassLoader都是null,即BootStrap
* ExtClassLoader:BootStrap的下一层,主要加载jre/lib/ext/*.jar,如果将其他jar包放在该目录下,则其加载类则为ExtClassLoader
* AppClassLoader:ExtClassLoader的子加载类,默认的系统加载类,主要加载classpath下的jar包
*
* ClassLoader的加载顺序:当前线程的类加载器加载第一个类->如果类加载器中引入了其他类,则其他类也由当前ClassLoader加载
* ->每个ClassLoader加载类时,又先委托给其上级ClassLoader,这样是为了保证字节码文件的唯一性
* ->所有上级ClassLoader没有加载到类时则会回到发起者ClassLoader,还加载不了则抛异常,不会再去找发起者的子ClassLoader
*
* 自定义的ClassLoader必须继承{@link ClassLoader},重写loadClass,findClass,defineClass方法
*
* @auther 飞花梦影
* @date 2021-05-10 23:28:02
* @git {@link https://github.com/dreamFlyingFlower}
*/
public class S_ClassLoader {
public static void main(String[] args) {
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
try {
systemClassLoader.loadClass("使用指定的类加载器加载某个类");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} | 34.551724 | 91 | 0.796407 |
d85209b8615e3bfe97837c9e9a0348f8b49850ca | 3,898 | package de.appsist.am.actions;
import de.appsist.am.ActionFailedException;
import de.appsist.am.PersistenceHandler;
import de.appsist.ape.Guide;
import de.appsist.ape.Node;
import de.appsist.ape.annotations.ContentAnnotation;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author simon.schwantzer(at)im-c.de
*/
public class DeleteNodeAction extends BaseAction {
private final static Logger LOGGER = Logger.getLogger(DeleteNodeAction.class.getName());
private final Node node;
private final Guide guide;
private final PersistenceHandler persistenceHandler;
private Set<Node> previousNodes, nextNodes;
private final Map<String, File> backupPackages;
public DeleteNodeAction(Node nodeToDelete, Guide guide, PersistenceHandler persistenceHandler) {
this.guide = guide;
this.persistenceHandler = persistenceHandler;
this.node = nodeToDelete;
this.backupPackages = new HashMap<>();
}
@Override
public void perform() {
previousNodes = new HashSet<>(node.getPreviousNodes());
nextNodes = new HashSet<>(node.getNextNodes());
try {
// Remove step from guide.
guide.removeNode(node);
// Delete related content packages.
ContentAnnotation content = node.getContent();
if (content != null) {
for (String contentId : content.getContentPackages().values()) {
File backup = persistenceHandler.backupContentPackage(guide.getId(), contentId);
backupPackages.put(contentId, backup);
persistenceHandler.deleteContentPackage(guide.getId(), contentId);
}
}
// Persist changes.
persistenceHandler.writeGuide(guide);
notifyActionPerformed();
} catch (IllegalArgumentException | IllegalStateException e) {
LOGGER.log(Level.WARNING, "Failed to remove node: {0}", e.getMessage());
notifyActionFailed(new ActionFailedException("Failed to remove node.", e));
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to write guide.", e);
notifyActionFailed(new ActionFailedException("Failed to write guide.", e));
}
}
@Override
public void undo() {
try {
// Add step to guide.
Optional<Node> anyPredecessor = previousNodes.stream().findAny();
if (anyPredecessor.isPresent()) {
guide.addNode(node, anyPredecessor.get());
} else {
guide.addNode(node);
}
previousNodes.forEach(predecessor -> node.addPrevious(predecessor));
nextNodes.forEach(successor -> node.addNext(successor));
// Restore related content packages.
backupPackages.forEach((contentId, backupDir) -> persistenceHandler.restoreContentPackage(guide.getId(), contentId, backupDir));
// Persist changes.
persistenceHandler.writeGuide(guide);
notifyActionUndone();
} catch (IllegalArgumentException | IllegalStateException e) {
LOGGER.log(Level.WARNING, "Failed to restore node: {0}", e.getMessage());
notifyUndoFailed(new ActionFailedException("Failed to restore node.", e));
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to write guide.", e);
notifyUndoFailed(new ActionFailedException("Failed to write guide.", e));
}
}
@Override
public String getDescription() {
return "Schritt/Kapitel löschen";
}
}
| 37.84466 | 140 | 0.631862 |
58ee9e1e8c5d79b898440c882bf900e1cfda162f | 655 | package com.capgemini.mrchecker.webapi.mts.pages;
import com.capgemini.mrchecker.common.mts.data.User;
import io.qameta.allure.Step;
import io.restassured.response.Response;
public class LoginPage extends MTSWebApiBasePage {
@Step("Log-in")
public Response login(User user) {
Response response = getLoginRequestBuilder().body(user)
.post(getEndpoint());
accessToken = response.header("Authorization");
return response;
}
@Step("Log-out a user")
public void logout() {
accessToken = "";
}
public boolean isUserLogged() {
return !accessToken.isEmpty();
}
@Override
public String getEndpoint() {
return "/login";
}
}
| 19.848485 | 57 | 0.719084 |
a53411b02e85271088874b841d0413c99f88bd4c | 2,572 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.services.task.audit.impl.model;
import java.util.ArrayList;
import java.util.List;
public class AuditTaskData {
private AuditTaskImpl auditTask;
private List<TaskEventImpl> taskEvents = new ArrayList<>();
private List<TaskVariableImpl> taskInputs;
private List<TaskVariableImpl> taskOutputs;
public AuditTaskData(AuditTaskImpl auditTask) {
this.auditTask = auditTask;
}
public AuditTaskData(AuditTaskImpl auditTask, TaskEventImpl taskEvent) {
this.auditTask = auditTask;
this.taskEvents.add(taskEvent);
}
public AuditTaskData(AuditTaskImpl auditTask, List<TaskEventImpl> taskEvents) {
this.auditTask = auditTask;
this.taskEvents = taskEvents;
}
public AuditTaskData(AuditTaskImpl auditTask, List<TaskEventImpl> taskEvents, List<TaskVariableImpl> taskInputs, List<TaskVariableImpl> taskOutputs) {
this.auditTask = auditTask;
this.taskEvents = taskEvents;
this.taskInputs = taskInputs;
this.taskOutputs = taskOutputs;
}
public AuditTaskImpl getAuditTask() {
return auditTask;
}
public void setAuditTask(AuditTaskImpl auditTask) {
this.auditTask = auditTask;
}
public List<TaskEventImpl> getTaskEvents() {
return taskEvents;
}
public void setTaskEvents(List<TaskEventImpl> taskEvents) {
this.taskEvents = taskEvents;
}
public List<TaskVariableImpl> getTaskInputs() {
return taskInputs;
}
public void setTaskInputs(List<TaskVariableImpl> taskInputs) {
this.taskInputs = taskInputs;
}
public List<TaskVariableImpl> getTaskOutputs() {
return taskOutputs;
}
public void setTaskOutputs(List<TaskVariableImpl> taskOutputs) {
this.taskOutputs = taskOutputs;
}
public void addTaskEvent(TaskEventImpl taskEvent) {
this.taskEvents.add(taskEvent);
}
}
| 28.577778 | 154 | 0.700622 |
bd396e5fd2b9b3e2797477fc99bead12f4691a34 | 28,244 | /*
* $Header: /home/cvspublic/jakarta-tomcat-4.0/jasper/src/share/org/apache/jasper/JspC.java,v 1.12 2001/09/18 00:16:34 craigmcc Exp $
* $Revision: 1.12 $
* $Date: 2001/09/18 00:16:34 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.jasper;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.jasper.compiler.JspReader;
import org.apache.jasper.compiler.ServletWriter;
import org.apache.jasper.compiler.TagLibraries;
import org.apache.jasper.compiler.Compiler;
import org.apache.jasper.compiler.CommandLineCompiler;
import org.apache.jasper.compiler.TldLocationsCache;
import org.apache.jasper.servlet.JasperLoader;
import org.apache.jasper.servlet.JspCServletContext;
import org.apache.jasper.logging.Logger;
import org.apache.jasper.logging.JasperLogger;
/**
* Shell for the jspc compiler. Handles all options associated with the
* command line and creates compilation contexts which it then compiles
* according to the specified options.
*
* @author Danno Ferrin
* @author Pierre Delisle
*/
public class JspC implements Options { //, JspCompilationContext {
public static final String DEFAULT_IE_CLASS_ID =
"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
public static final String SWITCH_VERBOSE = "-v";
public static final String SWITCH_QUIET = "-q";
public static final String SWITCH_OUTPUT_DIR = "-d";
public static final String SWITCH_OUTPUT_SIMPLE_DIR = "-dd";
public static final String SWITCH_IE_CLASS_ID = "-ieplugin";
public static final String SWITCH_PACKAGE_NAME = "-p";
public static final String SWITCH_CLASS_NAME = "-c";
public static final String SWITCH_FULL_STOP = "--";
public static final String SWITCH_URI_BASE = "-uribase";
public static final String SWITCH_URI_ROOT = "-uriroot";
public static final String SWITCH_FILE_WEBAPP = "-webapp";
public static final String SWITCH_WEBAPP_INC = "-webinc";
public static final String SWITCH_WEBAPP_XML = "-webxml";
public static final String SWITCH_MAPPED = "-mapped";
public static final String SWITCH_DIE = "-die";
public static final int NO_WEBXML = 0;
public static final int INC_WEBXML = 10;
public static final int ALL_WEBXML = 20;
public static final int DEFAULT_DIE_LEVEL = 1;
public static final int NO_DIE_LEVEL = 0;
// future direction
//public static final String SWITCH_XML_OUTPUT = "-xml";
boolean largeFile = false;
boolean mappedFile = false;
int jspVerbosityLevel = Logger.INFORMATION;
File scratchDir;
String ieClassId = DEFAULT_IE_CLASS_ID;
//String classPath;
String targetPackage;
String targetClassName;
String uriBase;
String uriRoot;
String webxmlFile;
int webxmlLevel;
int dieLevel;
boolean dieOnExit = false;
static int die; // I realize it is duplication, but this is for
// the static main catch
boolean dirset;
Vector extensions;
/**
* Cache for the TLD locations
*/
private TldLocationsCache tldLocationsCache = null;
public boolean getKeepGenerated() {
// isn't this why we are running jspc?
return true;
}
public boolean getLargeFile() {
return largeFile;
}
/**
* Are we supporting HTML mapped servlets?
*/
public boolean getMappedFile() {
return mappedFile;
}
// Off-line compiler, no need for security manager
public Object getProtectionDomain() {
return null;
}
public boolean getSendErrorToClient() {
// implied send to System.err
return true;
}
public String getIeClassId() {
return ieClassId;
}
public int getJspVerbosityLevel() {
return jspVerbosityLevel;
}
public File getScratchDir() {
return scratchDir;
}
public Class getJspCompilerPlugin() {
// we don't compile, so this is meanlingless
return null;
}
public String getJspCompilerPath() {
// we don't compile, so this is meanlingless
return null;
}
public TldLocationsCache getTldLocationsCache() {
return tldLocationsCache;
}
public String getJavaEncoding() {
return "UTF-8";
}
public String getClassPath() {
return System.getProperty("java.class.path");
}
int argPos;
// value set by beutifully obsfucscated java
boolean fullstop = false;
String args[];
private void pushBackArg() {
if (!fullstop) {
argPos--;
}
}
private String nextArg() {
if ((argPos >= args.length)
|| (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) {
return null;
} else {
return args[argPos++];
}
}
private String nextFile() {
if (fullstop) argPos++;
if (argPos >= args.length) {
return null;
} else {
return args[argPos++];
}
}
public JspC(String[] arg, PrintStream log) {
args = arg;
String tok;
int verbosityLevel = Logger.WARNING;
dieLevel = NO_DIE_LEVEL;
die = dieLevel;
while ((tok = nextArg()) != null) {
if (tok.equals(SWITCH_QUIET)) {
verbosityLevel = Logger.WARNING;
} else if (tok.equals(SWITCH_VERBOSE)) {
verbosityLevel = Logger.INFORMATION;
} else if (tok.startsWith(SWITCH_VERBOSE)) {
try {
verbosityLevel
= Integer.parseInt(tok.substring(SWITCH_VERBOSE.length()));
} catch (NumberFormatException nfe) {
log.println(
"Verbosity level "
+ tok.substring(SWITCH_VERBOSE.length())
+ " is not valid. Option ignored.");
}
} else if (tok.equals(SWITCH_OUTPUT_DIR)) {
tok = nextArg();
if (tok != null) {
scratchDir = new File(new File(tok).getAbsolutePath());
dirset = true;
} else {
// either an in-java call with an explicit null
// or a "-d --" sequence should cause this,
// which would mean default handling
/* no-op */
scratchDir = null;
}
} else if (tok.equals(SWITCH_OUTPUT_SIMPLE_DIR)) {
tok = nextArg();
if (tok != null) {
scratchDir = new File(new File(tok).getAbsolutePath());
dirset = false;
} else {
// either an in-java call with an explicit null
// or a "-d --" sequence should cause this,
// which would mean default handling
/* no-op */
scratchDir = null;
}
} else if (tok.equals(SWITCH_PACKAGE_NAME)) {
targetPackage = nextArg();
} else if (tok.equals(SWITCH_CLASS_NAME)) {
targetClassName = nextArg();
} else if (tok.equals(SWITCH_URI_BASE)) {
uriBase = nextArg();
} else if (tok.equals(SWITCH_URI_ROOT)) {
uriRoot = nextArg();
} else if (tok.equals(SWITCH_WEBAPP_INC)) {
webxmlFile = nextArg();
if (webxmlFile != null) {
webxmlLevel = INC_WEBXML;
}
} else if (tok.equals(SWITCH_WEBAPP_XML)) {
webxmlFile = nextArg();
if (webxmlFile != null) {
webxmlLevel = ALL_WEBXML;
}
} else if (tok.equals(SWITCH_MAPPED)) {
mappedFile = true;
} else if (tok.startsWith(SWITCH_DIE)) {
try {
dieLevel = Integer.parseInt(
tok.substring(SWITCH_DIE.length()));
} catch (NumberFormatException nfe) {
dieLevel = DEFAULT_DIE_LEVEL;
}
die = dieLevel;
} else {
pushBackArg();
// Not a recognized Option? Start treting them as JSP Pages
break;
}
}
Constants.jasperLog = new JasperLogger();
Constants.jasperLog.setVerbosityLevel(verbosityLevel);
}
public boolean parseFile(PrintStream log, String file, Writer servletout, Writer mappingout)
{
try {
CommandLineContext clctxt = new CommandLineContext(
getClassPath(), file, uriBase, uriRoot, false,
this);
if ((targetClassName != null) && (targetClassName.length() > 0)) {
clctxt.setServletClassName(targetClassName);
}
if (targetPackage != null) {
clctxt.setServletPackageName(targetPackage);
}
if (dirset) {
clctxt.setOutputInDirs(true);
}
ArrayList urls = new ArrayList();
if (new File(clctxt.getRealPath("/")).exists()) {
File classes = new File(clctxt.getRealPath("/WEB-INF/classes"));
try {
if (classes.exists()) {
urls.add(classes.getCanonicalFile().toURL());
}
} catch (IOException ioe) {
// failing a toCanonicalPath on a file that
// exists() should be a JVM regression test,
// therefore we have permission to freak out
throw new RuntimeException(ioe.toString());
}
File lib = new File(clctxt.getRealPath("/WEB-INF/lib"));
if (lib.exists() && lib.isDirectory()) {
String[] libs = lib.list();
for (int i = 0; i < libs.length; i++) {
try {
File libFile = new File(lib.toString()
+ File.separator
+ libs[i]);
urls.add(libFile.getCanonicalFile().toURL());
} catch (IOException ioe) {
// failing a toCanonicalPath on a file that
// exists() should be a JVM regression test,
// therefore we have permission to freak out
throw new RuntimeException(ioe.toString());
}
}
}
}
StringTokenizer tokenizer = new StringTokenizer
(clctxt.getClassPath(), File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
String path = tokenizer.nextToken();
try {
File libFile = new File(path);
urls.add(libFile.toURL());
} catch (IOException ioe) {
// Failing a toCanonicalPath on a file that
// exists() should be a JVM regression test,
// therefore we have permission to freak uot
throw new RuntimeException(ioe.toString());
}
}
urls.add(new File
(clctxt.getRealPath("/")).getCanonicalFile().toURL());
URLClassLoader loader = new URLClassLoader
((URL[])(urls.toArray(new URL[urls.size()])));
clctxt.setClassLoader(loader);
CommandLineCompiler clc = new CommandLineCompiler(clctxt);
clc.compile();
targetClassName = null;
String thisServletName;
if (clc.getPackageName() == null) {
thisServletName = clc.getClassName();
} else {
thisServletName = clc.getPackageName()
+ '.' + clc.getClassName();
}
if (servletout != null) {
servletout.write("\n\t<servlet>\n\t\t<servlet-name>");
servletout.write(thisServletName);
servletout.write("</servlet-name>\n\t\t<servlet-class>");
servletout.write(thisServletName);
servletout.write("</servlet-class>\n\t</servlet>\n");
}
if (mappingout != null) {
mappingout.write("\n\t<servlet-mapping>\n\t\t<servlet-name>");
mappingout.write(thisServletName);
mappingout.write("</servlet-name>\n\t\t<url-pattern>");
mappingout.write(file.replace('\\', '/'));
mappingout.write("</url-pattern>\n\t</servlet-mapping>\n");
}
return true;
} catch (JasperException je) {
//je.printStackTrace(log);
Constants.message("jspc.error.jasperException",
new Object[] {file, je}, Logger.ERROR);
if (dieLevel != NO_DIE_LEVEL) {
dieOnExit = true;
}
} catch (FileNotFoundException fne) {
Constants.message("jspc.error.fileDoesNotExist",
new Object[] {fne.getMessage()}, Logger.WARNING);
} catch (Exception e) {
Constants.message("jspc.error.generalException",
new Object[] {file, e}, Logger.ERROR);
e.printStackTrace();
if (dieLevel != NO_DIE_LEVEL) {
dieOnExit = true;
}
}
return false;
}
public void parseFiles(PrintStream log) throws JasperException {
boolean scratchDirSet = (scratchDir != null);
boolean urirootSet = (uriRoot != null);
// set up a scratch/output dir if none is provided
if (scratchDir == null) {
String temp = System.getProperty("java.io.tempdir");
if (temp == null) {
temp = "";
}
scratchDir = new File(new File(temp).getAbsolutePath());
}
File f = new File(args[argPos]);
while (!f.exists()) {
boolean webApp = false;
if (SWITCH_FILE_WEBAPP.equals(args[argPos])) {
webApp = true;
if (args.length > argPos + 1) {
f = new File(args[argPos + 1]);
} else {
// end of arguments, nothing left to parse
Constants.message("jspc.error.emptyWebApp",
Logger.ERROR);
return;
}
}
if (!f.exists()) {
Constants.message("jspc.error.fileDoesNotExist",
new Object[] {f}, Logger.WARNING);
argPos++;
if (webApp) {
argPos++;
}
if (argPos >= args.length) {
// end of arguments, nothing left to parse
return;
} else {
f = new File(args[argPos]);
}
}
}
if (uriRoot == null) {
if (SWITCH_FILE_WEBAPP.equals(args[argPos])) {
if (args.length > argPos + 1) {
f = new File(args[argPos + 1]);
} else {
// end of arguments, nothing left to parse
return;
}
}
// set up the uri root if none is explicitly set
String tUriBase = uriBase;
if (tUriBase == null) {
tUriBase = "/";
}
try {
if (f.exists()) {
f = new File(f.getCanonicalPath());
while (f != null) {
File g = new File(f, "WEB-INF");
if (g.exists() && g.isDirectory()) {
uriRoot = f.getCanonicalPath();
uriBase = tUriBase;
Constants.message("jspc.implicit.uriRoot",
new Object[] { uriRoot },
Logger.INFORMATION);
break;
}
if (f.exists() && f.isDirectory()) {
tUriBase = "/" + f.getName() + "/" + tUriBase;
}
String fParent = f.getParent();
if (fParent == null) {
f = new File(args[argPos]);
fParent = f.getParent();
if (fParent == null) {
fParent = File.separator;
}
uriRoot = new File(fParent).getCanonicalPath();
uriBase = "/";
break;
} else {
f = new File(fParent);
}
// If there is no acceptible candidate, uriRoot will
// remain null to indicate to the CompilerContext to
// use the current working/user dir.
}
}
} catch (IOException ioe) {
// since this is an optional default and a null value
// for uriRoot has a non-error meaning, we can just
// pass straight through
}
}
String file = nextFile();
File froot = new File(uriRoot);
String ubase = null;
try {
ubase = froot.getCanonicalPath();
} catch (IOException ioe) {
// if we cannot get the base, leave it null
}
while (file != null) {
if (SWITCH_FILE_WEBAPP.equals(file)) {
String base = nextFile();
if (base == null) {
Constants.message("jspc.error.emptyWebApp",
Logger.ERROR);
return;
}// else if (".".equals(base)) {
// base = "";
//}
String oldRoot = uriRoot;
if (!urirootSet) {
uriRoot = base;
}
Vector pages = new Vector();
Stack dirs = new Stack();
dirs.push(base);
if (extensions == null) {
extensions = new Vector();
extensions.addElement("jsp");
}
while (!dirs.isEmpty()) {
String s = dirs.pop().toString();
//System.out.println("--" + s);
f = new File(s);
if (f.exists() && f.isDirectory()) {
String[] files = f.list();
String ext;
for (int i = 0; i < files.length; i++) {
File f2 = new File(s, files[i]);
//System.out.println(":" + f2.getPath());
if (f2.isDirectory()) {
dirs.push(f2.getPath());
//System.out.println("++" + f2.getPath());
} else {
ext = files[i].substring(
files[i].lastIndexOf('.') + 1);
if (extensions.contains(ext)) {
//System.out.println(s + "?" + files[i]);
pages.addElement(
s + File.separatorChar + files[i]);
} else {
//System.out.println("not done:" + ext);
}
}
}
}
}
String ubaseOld = ubase;
File frootOld = froot;
froot = new File(uriRoot);
try {
ubase = froot.getCanonicalPath();
} catch (IOException ioe) {
// if we cannot get the base, leave it null
}
//System.out.println("==" + ubase);
Writer mapout;
CharArrayWriter servletout, mappingout;
try {
if (webxmlLevel >= INC_WEBXML) {
File fmapings = new File(webxmlFile);
mapout = new FileWriter(fmapings);
servletout = new CharArrayWriter();
mappingout = new CharArrayWriter();
} else {
mapout = null;
servletout = null;
mappingout = null;
}
if (webxmlLevel >= ALL_WEBXML) {
mapout.write(Constants.getString("jspc.webxml.header"));
} else if (webxmlLevel>= INC_WEBXML) {
mapout.write(Constants.getString("jspc.webinc.header"));
}
} catch (IOException ioe) {
mapout = null;
servletout = null;
mappingout = null;
}
try {
JspCServletContext context =
new JspCServletContext
(new PrintWriter(System.out),
new URL("file:" + ubase.replace('\\','/') + "/"));
tldLocationsCache = new TldLocationsCache(context);
} catch (MalformedURLException me) {
System.out.println("**" + me);
}
Enumeration e = pages.elements();
while (e.hasMoreElements())
{
String nextjsp = e.nextElement().toString();
try {
if (ubase != null) {
File fjsp = new File(nextjsp);
String s = fjsp.getCanonicalPath();
//System.out.println("**" + s);
if (s.startsWith(ubase)) {
nextjsp = s.substring(ubase.length());
}
}
} catch (IOException ioe) {
// if we got problems dont change the file name
}
if (nextjsp.startsWith("." + File.separatorChar)) {
nextjsp = nextjsp.substring(2);
}
parseFile(log, nextjsp, servletout, mappingout);
}
uriRoot = oldRoot;
ubase = ubaseOld;
froot = frootOld;
if (mapout != null) {
try {
servletout.writeTo(mapout);
mappingout.writeTo(mapout);
if (webxmlLevel >= ALL_WEBXML) {
mapout.write(Constants.getString("jspc.webxml.footer"));
} else if (webxmlLevel >= INC_WEBXML) {
mapout.write(Constants.getString("jspc.webinc.footer"));
}
mapout.close();
} catch (IOException ioe) {
// noting to do if it fails since we are done with it
}
}
} else {
try {
if (ubase != null) {
try {
JspCServletContext context =
new JspCServletContext
(new PrintWriter(System.out),
new URL("file:" + ubase.replace('\\','/') + '/'));
tldLocationsCache = new
TldLocationsCache(context);
} catch (MalformedURLException me) {
System.out.println("**" + me);
}
File fjsp = new File(file);
String s = fjsp.getCanonicalPath();
if (s.startsWith(ubase)) {
file = s.substring(ubase.length());
}
}
} catch (IOException ioe) {
// if we got problems dont change the file name
}
parseFile(log, file, null, null);
}
file = nextFile();
}
if (dieOnExit) {
System.exit(die);
}
}
public static void main(String arg[]) {
if (arg.length == 0) {
System.out.println(Constants.getString("jspc.usage"));
} else {
try {
JspC jspc = new JspC(arg, System.out);
jspc.parseFiles(System.out);
} catch (JasperException je) {
System.err.print("error:");
System.err.println(je.getMessage());
if (die != NO_DIE_LEVEL) {
System.exit(die);
}
}
}
}
}
| 37.658667 | 133 | 0.482297 |
117d97b24d5bb018b971da3c021e77b94d7d66cd | 3,787 | package com.gempukku.swccgo.cards.set2.light;
import com.gempukku.swccgo.cards.AbstractNormalEffect;
import com.gempukku.swccgo.common.*;
import com.gempukku.swccgo.filters.Filter;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.GameUtils;
import com.gempukku.swccgo.logic.TriggerConditions;
import com.gempukku.swccgo.logic.actions.RequiredGameTextTriggerAction;
import com.gempukku.swccgo.logic.effects.LoseCardFromTableEffect;
import com.gempukku.swccgo.logic.effects.PutUndercoverEffect;
import com.gempukku.swccgo.logic.timing.EffectResult;
import java.util.Collections;
import java.util.List;
/**
* Set: A New Hope
* Type: Effect
* Title: Undercover
*/
public class Card2_040 extends AbstractNormalEffect {
public Card2_040() {
super(Side.LIGHT, 5, PlayCardZoneOption.ATTACHED, Title.Undercover);
setLore("Alliance Intelligence expends considerable resources to infiltrate the Imperial military bureaucracy, but the ISB's security sweeps make these shadowy operations dangerous.");
setGameText("Deploy on your spy at a site and cross spy to opponent's side. Spy is now Undercover. During your deploy phase, may voluntarily 'break cover' (lose Effect) if at a site. (Immune to Alter.)");
addIcons(Icon.A_NEW_HOPE);
addImmuneToCardTitle(Title.Alter);
}
@Override
protected Filter getGameTextValidDeployTargetFilter(SwccgGame game, PhysicalCard self, PlayCardOptionId playCardOptionId, boolean asReact) {
return Filters.and(Filters.your(self), Filters.spy, Filters.at(Filters.site), Filters.not(Filters.undercover_spy));
}
@Override
protected List<RequiredGameTextTriggerAction> getGameTextRequiredAfterTriggers(final SwccgGame game, EffectResult effectResult, final PhysicalCard self, int gameTextSourceCardId) {
return getRequiredAfterTriggers(game, effectResult, self, gameTextSourceCardId);
}
@Override
protected List<RequiredGameTextTriggerAction> getGameTextRequiredAfterTriggersWhenInactiveInPlay(SwccgGame game, EffectResult effectResult, PhysicalCard self, int gameTextSourceCardId) {
return getRequiredAfterTriggers(game, effectResult, self, gameTextSourceCardId);
}
private List<RequiredGameTextTriggerAction> getRequiredAfterTriggers(final SwccgGame game, EffectResult effectResult, final PhysicalCard self, int gameTextSourceCardId) {
// Check condition(s)
if (TriggerConditions.justDeployed(game, effectResult, self)) {
PhysicalCard attachedTo = self.getAttachedTo();
RequiredGameTextTriggerAction action = new RequiredGameTextTriggerAction(self, gameTextSourceCardId);
action.setPerformingPlayer(self.getOwner());
action.setText("Put " + GameUtils.getFullName(attachedTo) + " Undercover");
action.setActionMsg("Put " + GameUtils.getCardLink(attachedTo) + " Undercover");
// Perform result(s)
action.appendEffect(
new PutUndercoverEffect(action, attachedTo));
return Collections.singletonList(action);
}
// Check condition(s)
if (TriggerConditions.coverBroken(game, effectResult, Filters.hasAttached(self))) {
RequiredGameTextTriggerAction action = new RequiredGameTextTriggerAction(self, gameTextSourceCardId);
action.setText("Make lost");
action.setActionMsg("Make " + GameUtils.getCardLink(self) + " lost");
// Perform result(s)
action.appendEffect(
new LoseCardFromTableEffect(action, self));
return Collections.singletonList(action);
}
return null;
}
} | 50.493333 | 214 | 0.739107 |
06d3064a9f5d7531a4827d30e7066560037fa450 | 1,486 | /*
* $Id: PlanCMTemplate5ContactsActionBean.java,v 1.1 2009/09/24 16:48:07 pjfsilva Exp $
*
* Copyright (c) Critical Software S.A., All Rights Reserved.
* (www.criticalsoftware.com)
*
* This software is the proprietary information of Critical Software S.A.
* Use is subject to license terms.
*
* Last changed on $Date: 2009/09/24 16:48:07 $
* Last changed by $Author: pjfsilva $
*/
package com.criticalsoftware.certitools.presentation.action.plan;
import com.criticalsoftware.certitools.entities.jcr.Template5Contacts;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
/**
* Template 5 - Contacts list / search
*
* @author pjfsilva
*/
public class PlanCMTemplate5ContactsActionBean extends PlanCMTemplateActionBean {
private Template5Contacts template;
@DefaultHandler
public Resolution insertTemplate() {
setTemplateToFolder(new Template5Contacts());
return new ForwardResolution(PlanCMOperationsActionBean.class, "insertFolderPrepareTree");
}
public Resolution updateTemplate() {
setTemplateToFolder(new Template5Contacts());
return new ForwardResolution(PlanCMOperationsActionBean.class, "updateFolderPrepareTree");
}
public Template5Contacts getTemplate() {
return template;
}
public void setTemplate(Template5Contacts template) {
this.template = template;
}
} | 31.617021 | 98 | 0.748318 |
5c0f698bb82bcf3d08d81b13fe926a427679cbaf | 1,854 | /*
* 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.
*/
/**
* Project : MapleFetion
* Package : net.solosky.maplefetion.protocol.notify
* File : DefaultNotifyHandler.java
* Author : solosky < [email protected] >
* Created : 2009-11-26
* License : Apache License 2.0
*/
package net.solosky.maplefetion.client.notify;
import net.solosky.maplefetion.FetionException;
import net.solosky.maplefetion.sipc.SipcNotify;
import net.solosky.maplefetion.sipc.SipcReceipt;
/**
* 飞信秀的通知处理
*
* @author solosky <[email protected]>
*/
public class FetionShowNotifyHandler extends AbstractNotifyHandler
{
/* (non-Javadoc)
* @see net.solosky.maplefetion.protocol.ISIPNotifyHandler#handle(net.solosky.maplefetion.sip.SIPNotify)
*/
@Override
public void handle(SipcNotify notify) throws FetionException
{
SipcReceipt receipt = this.dialog.getMessageFactory()
.createDefaultReceipt(notify.getFrom(),
Integer.toString(notify.getCallID()), notify.getSequence());
this.dialog.process(receipt);
}
}
| 34.981132 | 109 | 0.717907 |
492521523ba61195d8315a9a8eb3f32c52088d0a | 923 | package uk.gov.hmcts.reform.iahomeofficeintegrationapi.infrastructure.client;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import uk.gov.hmcts.reform.iahomeofficeintegrationapi.domain.entities.HomeOfficeInstruct;
import uk.gov.hmcts.reform.iahomeofficeintegrationapi.domain.entities.HomeOfficeInstructResponse;
@FeignClient(name = "home-office-instruct-api", url = "${home-office.api.url}")
public interface HomeOfficeInstructApi {
@PostMapping("/ichallenge/applicationInstruct/setInstruct")
HomeOfficeInstructResponse sendNotification(
@RequestHeader(AUTHORIZATION) String bearerToken,
@RequestBody HomeOfficeInstruct request
);
}
| 43.952381 | 97 | 0.828819 |
b3cc462e28e3b8c68b43b1ecf3c4e592d4f44518 | 6,092 | package strategy.api.pay.alipay;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;
import strategy.MchLevelEnum;
import strategy.PayResponseBOEnum;
import strategy.api.pay.alipay.sdk.AlipayClient;
import strategy.api.pay.alipay.sdk.AlipayTradeCreateRequest;
import strategy.api.pay.alipay.sdk.AlipayTradeCreateResponse;
import strategy.dto.PayOrderInfoDTO;
import strategy.dto.PayProfitSharingDTO;
import strategy.exception.PayServiceException;
import java.math.BigDecimal;
/**
* Created with IntelliJ IDEA.
*
* @Author: GuoFei
* @Date: 2022/02/24/15:04
* @Description:
*/
public class AliPayUtil {
/**
* 支付宝小程序支付
* 二级商户就是服务商支付 一级是普通支付
* @param payOrderInfoDTO
* @return
* @throws PayServiceException
*/
public static AliPayMiniResultDTO aliMiniPay(PayOrderInfoDTO payOrderInfoDTO) throws PayServiceException {
boolean isSp = false;
if (payOrderInfoDTO.getMchLevelEnum() == MchLevelEnum.SECOND_MCH) {
isSp = true;
}
if (isSp) {
AliPayMchConfigDTO mchConfig = null;
if (payOrderInfoDTO.getProfitSharingStatus()) {
if (CollectionUtils.isEmpty(payOrderInfoDTO.getPayProfitSharingDTOList())) {
throw new PayServiceException(PayResponseBOEnum.ERROR_04119);
}
PayProfitSharingDTO payProfitSharingDTO = payOrderInfoDTO.getPayProfitSharingDTOList().get(0);
mchConfig = (AliPayMchConfigDTO) payProfitSharingDTO.getMchConfig();
} else {
throw new PayServiceException(PayResponseBOEnum.ERROR_04119);
}
mchConfig.setAppId(mchConfig.getMiniAppId());
mchConfig.setAlipayPublicKey(mchConfig.getMiniAlipayPublicKey());
mchConfig.setPrivateKey(mchConfig.getMiniPrivateKey());
// 实例化客户端
AlipayClient alipayClient = getAlipayClient(mchConfig);
AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no", payOrderInfoDTO.getTradeNo());
jsonObject.put("total_amount", payOrderInfoDTO.getTotalOrderAmount().multiply(new BigDecimal(100)).intValue());
jsonObject.put("subject", payOrderInfoDTO.getDescription());
jsonObject.put("buyer_id", payOrderInfoDTO.getUserId());
request.setBizContent(jsonObject.toJSONString());
AlipayTradeCreateResponse response = null;
try {
response = alipayClient.execute(request);
if (response.isSuccess()) {
AliPayMiniResultDTO aliPayMiniResultDTO = new AliPayMiniResultDTO();
aliPayMiniResultDTO.setInfo(response.getBody());
aliPayMiniResultDTO.setTradeNo(response.getTradeNo());
aliPayMiniResultDTO.setOutTradeNo(response.getOutTradeNo());
return aliPayMiniResultDTO;
} else {
throw new PayServiceException(PayResponseBOEnum.ERROR_05000);
}
} catch (Exception e) {
//logger.error("[alipay] 统一下单失败 ,error->{}", e);
throw new PayServiceException(PayResponseBOEnum.ERROR_04020);
}
} else {
AliPayMchConfigDTO aliPayMchConfigDTO = (AliPayMchConfigDTO) payOrderInfoDTO.getMchConfig();
aliPayMchConfigDTO.setAppId(aliPayMchConfigDTO.getMiniAppId());
aliPayMchConfigDTO.setAlipayPublicKey(aliPayMchConfigDTO.getMiniAlipayPublicKey());
aliPayMchConfigDTO.setPrivateKey(aliPayMchConfigDTO.getMiniPrivateKey());
AlipayClient alipayClient = getAlipayClient(aliPayMchConfigDTO);
AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
JSONObject jsonObject = new JSONObject();
jsonObject.put("out_trade_no", payOrderInfoDTO.getTradeNo());
jsonObject.put("total_amount", payOrderInfoDTO.getTotalOrderAmount().multiply(new BigDecimal(100)).intValue());
jsonObject.put("subject", payOrderInfoDTO.getDescription());
jsonObject.put("buyer_id", payOrderInfoDTO.getUserId());
request.setBizContent(jsonObject.toJSONString());
AlipayTradeCreateResponse response = null;
try {
response = alipayClient.execute(request);
if (response.isSuccess()) {
AliPayMiniResultDTO aliPayMiniResultDTO = new AliPayMiniResultDTO();
aliPayMiniResultDTO.setInfo(response.getBody());
aliPayMiniResultDTO.setTradeNo(response.getTradeNo());
aliPayMiniResultDTO.setOutTradeNo(response.getOutTradeNo());
return aliPayMiniResultDTO;
} else {
//logger.error("[alipay] 统一下单失败 ,SubMsg->{},", response.getSubMsg());
throw new PayServiceException(PayResponseBOEnum.ERROR_05000);
}
} catch (Exception e) {
//logger.error("[alipay] 统一下单失败 ,error->{}", e);
throw new PayServiceException(PayResponseBOEnum.ERROR_04020);
}
}
}
private static AlipayClient getAlipayClient(AliPayMchConfigDTO aliPayMchConfigDTO){
AlipayClient alipayClient = AliMchConfigCache.get(aliPayMchConfigDTO.getAppId());
if (alipayClient == null){
/*alipayClient = new DefaultAlipayClient(
aliPayMchConfigDTO.getServerUrl(),
aliPayMchConfigDTO.getAppId(),
aliPayMchConfigDTO.getPrivateKey(),
aliPayMchConfigDTO.getFormat(),
aliPayMchConfigDTO.getCharset(),
aliPayMchConfigDTO.getAlipayPublicKey(),
aliPayMchConfigDTO.getSignType());*/
AliMchConfigCache.put(aliPayMchConfigDTO.getAppId(), alipayClient);
}
return alipayClient;
}
}
| 47.224806 | 123 | 0.64478 |
c93430f68add4197cc8f8c2eaaf2ce26b3d06de7 | 21,160 | /**
* WRML - Web Resource Modeling Language
* __ __ ______ __ __ __
* /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
* \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
* \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
* \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
*
* http://www.wrml.org
*
* Copyright (C) 2011 - 2013 Mark Masse <[email protected]> (OSS project WRML.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wrml.werminal.dialog;
import com.googlecode.lanterna.gui.Border;
import com.googlecode.lanterna.gui.Component;
import com.googlecode.lanterna.gui.Component.Alignment;
import com.googlecode.lanterna.gui.component.Label;
import com.googlecode.lanterna.gui.component.Panel.Orientation;
import com.googlecode.lanterna.gui.layout.LinearLayout;
import com.googlecode.lanterna.gui.listener.ComponentAdapter;
import com.googlecode.lanterna.terminal.TerminalSize;
import org.wrml.model.rest.Document;
import org.wrml.runtime.CompositeKey;
import org.wrml.runtime.Context;
import org.wrml.runtime.Keys;
import org.wrml.runtime.KeysBuilder;
import org.wrml.runtime.rest.ApiLoader;
import org.wrml.runtime.schema.ProtoSlot;
import org.wrml.runtime.schema.Prototype;
import org.wrml.runtime.schema.SchemaLoader;
import org.wrml.werminal.Werminal;
import org.wrml.werminal.action.WerminalAction;
import org.wrml.werminal.component.HistoryCheckListBox;
import org.wrml.werminal.component.WerminalTextBox;
import org.wrml.werminal.terminal.*;
import org.wrml.werminal.window.WerminalWindow;
import java.net.URI;
import java.util.*;
public class OpenModelDialog extends WerminalWindow {
private static final String DEFAULT_KEYS_PANEL_LABEL = " Keys: ";
private static final String ENTER_KEYS_BUTTON_LABEL = "Enter Keys...";
private static final String SHOW_HISTORY_BUTTON_LABEL = "History...";
WerminalTextBox _HeapIdTextBox;
WerminalTextBox _SchemaUriTextBox;
TerminalAppPanel _KeysPanel;
WerminalAction _ConfirmAction;
Set<String> _KeySlotNames;
Map<URI, WerminalTextBox> _KeyInputs;
HistoryCheckListBox _SchemaUriHistoryCheckBoxList;
Map<URI, Map<String, WerminalTextBox>> _CompositeKeyInputs;
URI _SchemaUri;
/**
* for testing -- no need to mock {@code werminal.context}
*/
OpenModelDialog() {
super(null, null);
}
public OpenModelDialog(final Werminal werminal, final String title, final WerminalAction confirmAction,
final WerminalAction dismissAction) {
super(werminal, title);
final URI schemaUri = werminal.getContext().getSchemaLoader().getApiSchemaUri();
init(werminal, confirmAction, dismissAction, schemaUri);
}
/**
* @param werminal
* @param confirmAction
* @param dismissAction
*/
private void init(final Werminal werminal, final WerminalAction confirmAction, final WerminalAction dismissAction,
final URI schemaUri) {
_ConfirmAction = confirmAction;
_KeyInputs = new LinkedHashMap<>();
_CompositeKeyInputs = new LinkedHashMap<>();
_KeySlotNames = new LinkedHashSet<>();
setBorder(new Border.Standard());
// setBetweenComponentsPadding(0);
addEmptySpace();
//
// Schema ID
//
final WerminalAction enterKeysAction = new WerminalAction(getWerminal(), ENTER_KEYS_BUTTON_LABEL) {
@Override
public void doAction() {
_SchemaUri = getSchemaUri();
updateKeysPanel(_SchemaUri, null);
}
};
final TerminalAppButton enterKeysButton = new TerminalAppButton(enterKeysAction);
_SchemaUriTextBox = new WerminalTextBox(werminal, 60, URI.class, enterKeysAction) {
@Override
protected void setText(final String stringValue, final boolean clearValue) {
super.setText(stringValue, clearValue);
enterKeysAction.doAction();
}
};
final TerminalAppTextBoxPanel schemaUriTextBoxPanel = new TerminalAppTextBoxPanel(werminal, " Schema (URI): ",
_SchemaUriTextBox);
schemaUriTextBoxPanel.addComponent(enterKeysButton);
_SchemaUriTextBox.addComponentListener(new ComponentAdapter() {
@Override
public void onComponentInvalidated(final Component component) {
final boolean canEnterKeys;
final String schemaUriText = _SchemaUriTextBox.getText();
if (schemaUriText == null || schemaUriText.trim().isEmpty()) {
canEnterKeys = false;
}
else {
final URI schemaUri = getSchemaUri();
canEnterKeys = schemaUri != null && schemaUri.equals(_SchemaUri);
}
// enterKeysButton.setVisible(canEnterKeys);
if (!canEnterKeys) {
updateKeysPanel(null, null);
}
}
});
addComponent(schemaUriTextBoxPanel);
addEmptySpace();
final TerminalAppPanel historyPanel = new TerminalAppPanel(werminal, " History: ", new Border.Standard(),
Orientation.VERTICAL);
_SchemaUriHistoryCheckBoxList = new HistoryCheckListBox(_SchemaUriTextBox, null, confirmAction);
_SchemaUriHistoryCheckBoxList.setPreferredSize(new TerminalSize(70, 10));
historyPanel.addComponent(_SchemaUriHistoryCheckBoxList);
addComponent(historyPanel);
addEmptySpace();
//
// Keys
//
// addComponent(new Label("Keys: ", 70, Alignment.START), SizePolicy.CONSTANT);
_KeysPanel = new TerminalAppPanel(werminal, DEFAULT_KEYS_PANEL_LABEL, new Border.Bevel(true),
Orientation.VERTICAL);
addComponent(_KeysPanel, LinearLayout.GROWS_VERTICALLY);
// Heap ID
_HeapIdTextBox = new WerminalTextBox(werminal, 60, UUID.class, confirmAction);
addEmptySpace();
//
// Dialog buttons
//
final TerminalAppToolBar footerToolBar = new TerminalAppToolBar(werminal, new Component[]{
new TerminalAppButtonPanel(confirmAction), new TerminalAppButtonPanel(dismissAction)});
addComponent(footerToolBar);
setSchemaUri(schemaUri);
final Context context = werminal.getContext();
}
public UUID getHeapId() {
return (UUID) _HeapIdTextBox.getValue();
}
public Keys getKeys() {
final URI schemaUri = getSchemaUri();
if (schemaUri == null) {
return null;
}
final Context context = getApp().getContext();
final ApiLoader apiLoader = context.getApiLoader();
final SchemaLoader schemaLoader = context.getSchemaLoader();
final URI documentSchemaUri = schemaLoader.getDocumentSchemaUri();
final KeysBuilder keysBuilder = new KeysBuilder();
final Set<URI> keySchemaUris = _KeyInputs.keySet();
for (final URI keySchemaUri : keySchemaUris) {
final WerminalTextBox keyTextBox = _KeyInputs.get(keySchemaUri);
final Object keyValue;
try {
keyValue = keyTextBox.getValue();
}
catch (final Exception e) {
continue;
}
if (keyValue != null) {
keysBuilder.addKey(keySchemaUri, keyValue);
}
}
if (_KeyInputs.containsKey(documentSchemaUri)) {
// Build and add the document keys (if uri value != null)
final WerminalTextBox uriTextBox = _KeyInputs.get(documentSchemaUri);
if (uriTextBox != null) {
final URI uri = uriTextBox.getValue();
if (uri != null) {
Keys surrogateKeys = apiLoader.buildDocumentKeys(uri, schemaUri);
keysBuilder.addAll(surrogateKeys);
}
}
}
if (!_CompositeKeyInputs.isEmpty()) {
final Set<URI> compositeKeySchemaUris = _CompositeKeyInputs.keySet();
outer:
for (final URI compositeKeySchemaUri : compositeKeySchemaUris) {
final SortedMap<String, Object> compositeKeySlots = new TreeMap<String, Object>();
final Map<String, WerminalTextBox> compositeKeyTextBoxes = _CompositeKeyInputs
.get(compositeKeySchemaUri);
for (final String compositeKeySlotName : compositeKeyTextBoxes.keySet()) {
final WerminalTextBox compositeKeyTextBox = compositeKeyTextBoxes.get(compositeKeySlotName);
final Object keyComponentValue;
try {
keyComponentValue = compositeKeyTextBox.getValue();
}
catch (final Exception e) {
continue outer;
}
if (keyComponentValue == null) {
continue outer;
}
compositeKeySlots.put(compositeKeySlotName, keyComponentValue);
}
if (!compositeKeySlots.isEmpty()) {
keysBuilder.addKey(compositeKeySchemaUri, new CompositeKey(compositeKeySlots));
}
}
}
return keysBuilder.toKeys();
}
public void setKeys(final Keys keys) {
updateKeysPanel(getSchemaUri(), keys);
}
public URI getSchemaUri() {
try {
return (URI) _SchemaUriTextBox.getValue();
}
catch (final Exception e) {
return null;
}
}
public HistoryCheckListBox getSchemaUriHistoryCheckBoxList() {
return _SchemaUriHistoryCheckBoxList;
}
public URI setSchemaUri(final URI schemaUri) {
_SchemaUri = schemaUri;
final URI oldSchemaUri = (URI) _SchemaUriTextBox.setValue(schemaUri, false);
updateKeysPanel(schemaUri, null);
return oldSchemaUri;
}
private boolean addKeyInput(final URI schemaUri, final Prototype keyDeclaredPrototype, final Keys keys) {
final Werminal werminal = getWerminal();
final Context context = werminal.getContext();
final SchemaLoader schemaLoader = context.getSchemaLoader();
final URI keyDeclaredSchemaUri = keyDeclaredPrototype.getSchemaUri();
if (_KeyInputs.containsKey(keyDeclaredSchemaUri)) {
return false;
}
final SortedSet<String> keySlotNames = keyDeclaredPrototype.getDeclaredKeySlotNames();
if (keySlotNames == null || keySlotNames.isEmpty()) {
// The schema declare's *zero* key slots
return false;
}
if (keySlotNames.size() == 1) {
// The schema declare's *only one* key slot
final String keySlotName = keySlotNames.first();
if (_KeySlotNames.contains(keySlotName)) {
return false;
}
final Class<?> keySlotType = (Class<?>) keyDeclaredPrototype.getKeyType();
final TerminalAppTextBoxPanel keyTextBoxPanel = createKeyInput(schemaUri, keyDeclaredPrototype,
keySlotName, keySlotType, 60);
final WerminalTextBox keyTextBox = (WerminalTextBox) keyTextBoxPanel.getTextBox();
_KeysPanel.addComponent(keyTextBoxPanel);
_KeysPanel.addEmptySpace();
_KeyInputs.put(keyDeclaredSchemaUri, keyTextBox);
_KeySlotNames.add(keySlotName);
final URI documentSchemaUri = schemaLoader.getDocumentSchemaUri();
final boolean isDocumentPrototype = keyDeclaredSchemaUri.equals(documentSchemaUri);
if (isDocumentPrototype) {
keyTextBox.addComponentListener(new ComponentAdapter() {
@Override
public void onComponentInvalidated(final Component component) {
final URI uri;
try {
uri = (URI) keyTextBox.getValue();
updateKeysPanelDocumentSurrogateKeyInputs(uri);
}
catch (final Exception ex) {
return;
}
}
});
}
return true;
}
else {
// The schema declare's *more than one* key slot
final SortedMap<String, WerminalTextBox> compositeKeyTextBoxes = new TreeMap<>();
for (final String keySlotName : keySlotNames) {
if (_KeySlotNames.contains(keySlotName)) {
continue;
}
final ProtoSlot protoSlot = keyDeclaredPrototype.getProtoSlot(keySlotName);
if (protoSlot == null) {
continue;
}
final Class<?> keyComponentType = (Class<?>) protoSlot.getHeapValueType();
final TerminalAppTextBoxPanel keyTextBoxPanel = createKeyInput(schemaUri, keyDeclaredPrototype,
keySlotName, keyComponentType, 60);
final WerminalTextBox keyTextBox = (WerminalTextBox) keyTextBoxPanel.getTextBox();
compositeKeyTextBoxes.put(keySlotName, keyTextBox);
_KeysPanel.addComponent(keyTextBoxPanel);
_KeysPanel.addEmptySpace();
_KeySlotNames.add(keySlotName);
}
if (compositeKeyTextBoxes.isEmpty()) {
return false;
}
_CompositeKeyInputs.put(keyDeclaredSchemaUri, compositeKeyTextBoxes);
return true;
}
}
private void addKeyMessageLabel() {
addMessageLabel("Enter a Schema URI and *click* the \"" + ENTER_KEYS_BUTTON_LABEL + "\" button.",
Alignment.LEFT_CENTER);
}
private void addMessageLabel(final String message, final Alignment alignment) {
final Label label = new Label(message);
label.setAlignment(alignment);
_KeysPanel.addEmptySpace();
_KeysPanel.addComponent(label, LinearLayout.MAXIMIZES_HORIZONTALLY);
_KeysPanel.addEmptySpace();
}
private TerminalAppTextBoxPanel createKeyInput(final URI schemaUri, final Prototype keyDeclaredPrototype,
final String keyInputName, final Class<?> keyInputType, final int keyInputWidth) {
final Werminal werminal = getWerminal();
final WerminalTextBox keyTextBox = new WerminalTextBox(getWerminal(), keyInputWidth, keyInputType,
_ConfirmAction);
final Class<?> schemaInterface = keyDeclaredPrototype.getSchemaBean().getIntrospectedClass();
final String schemaTitle = schemaInterface.getSimpleName();
final String keyInputTypeTitle = keyInputType.getSimpleName();
final String panelTitle = " " + schemaTitle + "." + keyInputName + " (" + keyInputTypeTitle + "): ";
final TerminalAppTextBoxPanel keyTextBoxPanel = new TerminalAppTextBoxPanel(werminal, panelTitle, keyTextBox);
final WerminalAction showHistoryAction = new WerminalAction(getWerminal(), SHOW_HISTORY_BUTTON_LABEL) {
@Override
public void doAction() {
final Prototype prototype = werminal.getContext().getSchemaLoader().getPrototype(schemaUri);
final SortedSet<Object> keyHistory = werminal.getSlotValueHistory(schemaUri, keyInputName);
if (keyHistory != null && !keyHistory.isEmpty()) {
final String popupTitle = "Key History - " + prototype.getTitle() + " - " + panelTitle;
final HistoryPopup historyPopup = new HistoryPopup(werminal, popupTitle, keyTextBox);
final HistoryCheckListBox keyHistoryCheckListBox = historyPopup.getHistoryCheckListBox();
keyHistoryCheckListBox.addItems(keyHistory);
werminal.showWindow(historyPopup);
}
else {
werminal.showMessageBox("Empty Key History",
"\nUnfortunately, there are no saved history values associated with the \"" + schemaTitle
+ "." + keyInputName + "\" key slot.");
}
setFocus(keyTextBox);
}
};
final TerminalAppButton showHistoryButton = new TerminalAppButton(showHistoryAction);
keyTextBoxPanel.addComponent(showHistoryButton);
return keyTextBoxPanel;
}
private void updateKeysPanel(final URI schemaUri, final Keys keys) {
_KeysPanel.removeAllComponents();
_KeyInputs.clear();
_KeySlotNames.clear();
if (schemaUri == null) {
_KeysPanel.setTitle(DEFAULT_KEYS_PANEL_LABEL);
addKeyMessageLabel();
return;
}
final Context context = getWerminal().getContext();
final SchemaLoader schemaLoader = context.getSchemaLoader();
final Prototype prototype;
final Class<?> schemaInterface;
try {
prototype = schemaLoader.getPrototype(schemaUri);
schemaInterface = schemaLoader.getSchemaInterface(schemaUri);
}
catch (final Exception e) {
addKeyMessageLabel();
return;
}
final String title = String.format(" %1s%2s", prototype.getSchemaBean().getIntrospectedClass().getSimpleName(),
DEFAULT_KEYS_PANEL_LABEL);
_KeysPanel.setTitle(title);
_KeysPanel.addEmptySpace();
URI uri = null;
// Put Document's key first
if (Document.class.isAssignableFrom(schemaInterface)) {
final URI documentSchemaUri = schemaLoader.getDocumentSchemaUri();
final Prototype documentPrototype = schemaLoader.getPrototype(documentSchemaUri);
addKeyInput(schemaUri, documentPrototype, keys);
final WerminalTextBox textBox = _KeyInputs.get(documentSchemaUri);
uri = getWerminal().getDefaultDocumentUri(schemaUri);
if (uri != null) {
textBox.setText(uri.toString());
uri = (URI) textBox.getValue();
}
}
// Add all of the other key inputs; skipping Document's since we already made it first.
if (!Document.class.equals(schemaInterface)) {
addKeyInput(schemaUri, prototype, keys);
final Set<Prototype> basePrototypes = prototype.getDeclaredBasePrototypes();
for (final Prototype basePrototype : basePrototypes) {
addKeyInput(schemaUri, basePrototype, keys);
}
}
/*
* TODO: Need to support opening by heap id?
*
* if (!_KeyInputs.isEmpty()) { // Added some keys.
*
* // or... heap id addMessageLabel("or", Alignment.CENTER); }
*
* // Add the heap id for UUID-based look-ups (for...debugging?) final TerminalAppTextBoxPanel
* heapIdTextBoxPanel = new TerminalAppTextBoxPanel(werminal, " Model.heapId [UUID]: ", _HeapIdTextBox);
* _KeysPanel.addComponent(heapIdTextBoxPanel);
*/
if (uri != null) {
updateKeysPanelDocumentSurrogateKeyInputs(uri);
}
}
private void updateKeysPanelDocumentSurrogateKeyInputs(final URI uri) {
if (uri == null) {
return;
}
final Context context = getWerminal().getContext();
final SchemaLoader schemaLoader = context.getSchemaLoader();
final ApiLoader apiLoader = context.getApiLoader();
final URI documentSchemaUri = schemaLoader.getDocumentSchemaUri();
final Keys allDocumentKeys = apiLoader.buildDocumentKeys(uri, getSchemaUri());
if (allDocumentKeys != null && allDocumentKeys.getCount() > 1) {
final Set<URI> keyedSchemaUris = allDocumentKeys.getKeyedSchemaUris();
for (final URI keyedSchemaUri : keyedSchemaUris) {
if (!keyedSchemaUri.equals(documentSchemaUri)) {
if (_KeyInputs.containsKey(keyedSchemaUri)) {
final WerminalTextBox surrogateKeyTextBox = _KeyInputs.get(keyedSchemaUri);
final Object surrogateKeyValue = allDocumentKeys.getValue(keyedSchemaUri);
surrogateKeyTextBox.setValue(surrogateKeyValue);
}
}
}
}
}
}
| 35.503356 | 133 | 0.61569 |
bcd99365714ca92ed6073c7ef1aee04c55d31291 | 2,342 | import java.util.List;
import java.util.stream.IntStream;
public class FirstOperationCharacter {
public static void main(String[] args) {
String[] input0 = new String[] {"(2 + 2) * 2", "2 + 2 * 2", "((2 + 2) * 2) * 3 + (2 + (2 * 2))", "2+((22+2222)+(2222+222))", "2 + 3 * 45 * 56 + 198 + 10938 * 102938 + 5", "1022224552222222 * 3", "4 * 3 + 2"};
int[] expectedOutput = new int[] {3, 6, 28, 6, 6, 17, 2};
assert input0.length == expectedOutput.length : String.format("# input0 = %d, # expectedOutput = %d", input0.length, expectedOutput.length);
IntStream.range(0, expectedOutput.length).forEach(i -> {
int actualOutput = firstOperationCharacter(input0[i]);
assert actualOutput == expectedOutput[i] : String.format("firstOperationCharacter(\"%s\") returned %d, but expected %d", input0[i], actualOutput, expectedOutput[i]);
});
System.out.println(String.format("PASSES %d out of %d tests", expectedOutput.length, expectedOutput.length));
}
static int firstOperationCharacter(String expr) {
List<Character> ADD_SUB_OPS = List.of('+', '-');
List<Character> MUL_DIV_OPS = List.of('*', '/');
int ADD_SUB_PRIORITY = 1;
int MUL_DIV_PRIORITY = 2;
int parenthesisPriority = 0;
int maxParenthesisPriority = -1;
int maxOperationPriority = -1;
int firstOperationIndex = 0;
for (int i = 0; i < expr.length(); i++) {
char c = expr.charAt(i);
if (c == '(') {
parenthesisPriority++;
} else if (c == ')') {
parenthesisPriority--;
} else if (ADD_SUB_OPS.contains(c)) {
if (maxParenthesisPriority < parenthesisPriority) {
maxParenthesisPriority = parenthesisPriority;
maxOperationPriority = ADD_SUB_PRIORITY;
firstOperationIndex = i;
} else if (maxParenthesisPriority == parenthesisPriority && maxOperationPriority < ADD_SUB_PRIORITY) {
maxOperationPriority = ADD_SUB_PRIORITY;
firstOperationIndex = i;
}
} else if (MUL_DIV_OPS.contains(c)) {
if (maxParenthesisPriority < parenthesisPriority) {
maxParenthesisPriority = parenthesisPriority;
maxOperationPriority = MUL_DIV_PRIORITY;
firstOperationIndex = i;
} else if (maxParenthesisPriority == parenthesisPriority && maxOperationPriority < MUL_DIV_PRIORITY) {
maxOperationPriority = MUL_DIV_PRIORITY;
firstOperationIndex = i;
}
}
}
return firstOperationIndex;
}
}
| 43.37037 | 210 | 0.679334 |
893e567c2851e2a4b023f6193745e837e2e3b525 | 518 | package nl.tudelft.gogreen.shared.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.jfoenix.controls.JFXSlider;
import javafx.scene.control.Control;
public enum InputType {
@JsonProperty("FLOAT")
FLOAT(0);
private Integer controlId;
InputType(Integer controlId) {
this.controlId = controlId;
}
/**
* get Options based on Activity.
*
* @return Control
*/
public Control getControl() {
return new JFXSlider(0, 100, 50);
}
}
| 19.923077 | 53 | 0.662162 |
3cf723c0645a23da198c31ad6fc8fcaed2556003 | 1,214 | package io.github.yzernik.squeakand;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import java.io.Serializable;
import io.github.yzernik.squeakand.server.SqueakServerAddress;
import io.github.yzernik.squeaklib.core.Signing;
@Entity(
tableName = SqueakRoomDatabase.TABLE_NAME_SERVER,
indices = {@Index(value = {"serverAddress"}, unique = true)})
@TypeConverters({Converters.class})
public class SqueakServer implements Serializable {
@PrimaryKey(autoGenerate = true)
public int server_id;
public String serverName;
@NonNull
public SqueakServerAddress serverAddress;
public SqueakServer() {
}
@Ignore
public SqueakServer(String serverName, SqueakServerAddress serverAddress) {
this.serverName = serverName;
this.serverAddress = serverAddress;
}
@Ignore
public int getId() {
return server_id;
}
@Ignore
public String getName() {
return serverName;
}
@Ignore
public SqueakServerAddress getAddress() {
return serverAddress;
}
}
| 22.481481 | 79 | 0.714992 |
09ec7da1aecab9be553021bc4da7fcdcc15ae5ee | 4,060 | package com.sargis_ohanyan.sargapps.entidades;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import java.util.Random;
public class Catapulta extends Actor {
private float angulo;
private Body bodySierra;
private boolean direccion = true;
private Fixture fixture;
private Vector2 posicion;
private Random random;
private TextureRegion region;
private Sprite sprite;
private Texture textura;
private int tipIA;
private int valorXaleatorio;
private int valorYaleatorio;
private float variableVelocidad;
private World world;
/* renamed from: x1 */
private float f315x1;
/* renamed from: x2 */
private float f316x2;
public Catapulta(World world2, Texture textura2, Vector2 posicion2) {
this.world = world2;
this.textura = textura2;
this.posicion = posicion2;
this.region = new TextureRegion(textura2);
this.sprite = new Sprite(this.region, (int) getX(), (int) getY(), 180, 180);
this.sprite.setRegion(0, 0, 357, 361);
BodyDef bd = new BodyDef();
bd.position.set(posicion2);
bd.type = BodyType.KinematicBody;
this.bodySierra = world2.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(3.0f, 0.25f);
FixtureDef fixDef = new FixtureDef();
fixDef.shape = shape;
fixDef.density = 0.0f;
this.fixture = this.bodySierra.createFixture(fixDef);
shape.dispose();
this.sprite.setSize(540.0f, 45.0f);
this.random = new Random();
this.tipIA = 1;
}
public Catapulta(World world2, Texture textura2, Vector2 posicion2, float x1, float x2, int tipo) {
this.world = world2;
this.textura = textura2;
this.posicion = posicion2;
this.f315x1 = x1;
this.f316x2 = x2;
this.region = new TextureRegion(textura2);
this.sprite = new Sprite(this.region, (int) getX(), (int) getY(), 180, 180);
this.sprite.setRegion(0, 0, 357, 361);
BodyDef bd = new BodyDef();
bd.position.set(posicion2);
bd.type = BodyType.KinematicBody;
this.bodySierra = world2.createBody(bd);
PolygonShape shape = new PolygonShape();
shape.setAsBox(5.0f, 0.05f);
FixtureDef fixDef = new FixtureDef();
fixDef.shape = shape;
fixDef.density = 0.0f;
this.fixture = this.bodySierra.createFixture(fixDef);
this.fixture.setUserData("sierra");
shape.dispose();
this.sprite.setSize(180.0f, 180.0f);
this.tipIA = tipo;
this.variableVelocidad = 11.0f;
}
public void draw(Batch batch, float parentAlpha) {
setPosition((this.bodySierra.getPosition().f232x - 1.0f) * 90.0f, (this.bodySierra.getPosition().f233y - 1.0f) * 90.0f);
this.sprite.draw(batch);
}
public void act(float deltaTime) {
rotate();
setPosition((this.bodySierra.getPosition().f232x - 3.0f) * 90.0f, (this.bodySierra.getPosition().f233y - 0.25f) * 90.0f);
this.sprite.setOriginCenter();
this.sprite.setPosition(getX(), getY());
}
public void rotate() {
this.bodySierra.setAngularVelocity(4.0f);
this.angulo = (float) Math.toDegrees((double) this.bodySierra.getAngle());
this.sprite.setRotation(this.angulo);
}
public void dispensar() {
this.bodySierra.destroyFixture(this.fixture);
this.world.destroyBody(this.bodySierra);
}
}
| 36.25 | 129 | 0.661823 |
3375ed2dc098532e596bb94a6697f080a472b722 | 951 | package com.example.stockmarket.service;
import java.util.List;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import com.example.stockmarket.dto.Stock;
@Stateless
public class StockmarketServiceClient {
@Schedule(second = "*/5", hour = "*", minute = "*")
public void callRestApi() {
var stock = ClientBuilder.newClient()
.target("http://localhost:8080/stockmarket/api/v1/stocks")
.path("orcl")
.request(MediaType.APPLICATION_JSON)
.get(Stock.class);
System.err.println(stock);
var stocks = ClientBuilder.newClient()
.target("http://localhost:8080/stockmarket/api/v1/stocks")
.queryParam("page", 0)
.queryParam("size", 25)
.request(MediaType.APPLICATION_JSON)
.get(new GenericType<List<Stock>>() { });
System.err.println(stocks);
}
}
| 28.818182 | 73 | 0.684543 |
67f1ce5acc20e59689550414dfe587afe7b87cc5 | 957 | package com.github.dumpram.mceval.rtimes;
import java.util.HashMap;
import java.util.List;
import com.github.dumpram.mceval.interfaces.IResponseTime;
import com.github.dumpram.mceval.models.MCTask;
import com.github.dumpram.mceval.models.MCTaskSet;
public class ResponseTimeHI implements IResponseTime {
@Override
public int responseTime(int i, MCTaskSet set) {
List<MCTask> tasks = set.getTasks();
MCTask task = tasks.get(i);
int R = 0;
int C = task.getWCET(1);
int D = task.getD();
int t = C;
while (R != t && R <= D) {
R = t;
t = C;
for (int j = 0; j < i; j++) {
MCTask taskJ = tasks.get(j);
if (taskJ.getL() > 0) {
t = (int) (t + (int)Math.ceil((double)R / taskJ.getT()) *
taskJ.getWCET(1));
}
}
}
return R;
}
@Override
public String printResponseTime(int i, HashMap<Integer, Integer> priorityOrder, MCTaskSet orderedSet) {
// TODO Auto-generated method stub
return null;
}
}
| 22.785714 | 104 | 0.650993 |
eb92277519241ec0406b9a44a67487fcf407b7ea | 2,914 | package io.codekvast.javaagent.appversion;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.Test;
public class PropertiesAppVersionStrategyTest {
private final Collection<File> VALID_URIS =
Arrays.asList(
new File(System.getProperty("user.dir") + File.separator + "src/test/resources"));
private final String VALID_ABSOLUTE_PATH =
getClass().getResource("/PropertiesAppVersionStrategyTest.conf").getPath();
private final String VALID_RELATIVE_PATH = "PropertiesAppVersionStrategyTest.conf";
private final String INVALID_FILE = "NON-EXISTING-FILE";
private final AppVersionStrategy strategy = new PropertiesAppVersionStrategy();
@Test
public void should_resolve_when_valid_absolute_path_and_valid_single_property() {
String args[] = {"property", VALID_ABSOLUTE_PATH, "version"};
assertThat(strategy.canHandle(args), is(true));
assertThat(strategy.resolveAppVersion(VALID_URIS, args), is("1.2.3"));
}
@Test
public void should_resolve_when_valid_relative_path_and_valid_single_property() {
String args[] = {"properties", VALID_RELATIVE_PATH, "version"};
assertThat(strategy.canHandle(args), is(true));
assertThat(strategy.resolveAppVersion(VALID_URIS, args), is("1.2.3"));
}
@Test
public void should_resolve_when_valid_absolute_path_and_valid_dual_properties() {
String args[] = {"properties", VALID_ABSOLUTE_PATH, "version", "build"};
assertThat(strategy.canHandle(args), is(true));
assertThat(strategy.resolveAppVersion(VALID_URIS, args), is("1.2.3-4711"));
}
@Test
public void should_resolve_when_valid_absolute_path_and_valid_triple_properties() {
String args[] = {"properties", VALID_ABSOLUTE_PATH, "version", "build", "qualifier"};
assertThat(strategy.canHandle(args), is(true));
assertThat(strategy.resolveAppVersion(VALID_URIS, args), is("1.2.3-4711-all"));
}
@Test
public void should_not_resolve_when_invalidBaseName() {
String args[] = {"properties", INVALID_FILE, "version", "build"};
assertThat(strategy.canHandle(args), is(true));
assertThat(strategy.resolveAppVersion(VALID_URIS, args), is("<unknown>"));
}
@Test
public void should_resolve_when_validFirstProperty_and_invalidSecondProperty() {
String args[] = {"properties", VALID_ABSOLUTE_PATH, "version", "foobar"};
assertThat(strategy.canHandle(args), is(true));
assertThat(strategy.resolveAppVersion(VALID_URIS, args), is("1.2.3"));
}
@Test
public void should_resolve_when_invalidFirstProperty_and_validSecondProperty() {
String args[] = {"properties", VALID_ABSOLUTE_PATH, "foobar", "version"};
assertThat(strategy.canHandle(args), is(true));
assertThat(strategy.resolveAppVersion(VALID_URIS, args), is("1.2.3"));
}
}
| 36.425 | 92 | 0.74571 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.