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 |
|---|---|---|---|---|---|
4d6cfb5fd23302392ce3c3806a9d7ef6f38a29c4 | 2,389 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.db.impl.core.jdbc;
import java.sql.SQLException;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class DataAccessException extends RuntimeException {
/**
* Constructor for DataAccessException.
*
* @param msg the detail message
*/
public DataAccessException(String msg) {
super(msg);
}
public DataAccessException(Throwable cause) {
super(cause);
}
/**
* Constructor for DataAccessException.
*
* @param msg the detail message
* @param cause the root cause (usually from using a underlying data access API such as JDBC)
*/
public DataAccessException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Retrieve the innermost cause of this exception, if any.
*
* @return the innermost exception, or {@code null} if none
* @since 2.0
*/
public Throwable getRootCause() {
Throwable rootCause = null;
Throwable cause = this.getCause();
while (cause != null && cause != rootCause) {
rootCause = cause;
cause = cause.getCause();
}
return rootCause;
}
@Override
public String toString() {
Throwable rootException = this.getCause() instanceof SQLException
? ((SQLException) this.getCause()).getNextException()
: this.getRootCause();
if (rootException == null) {
return ExceptionUtils.getStackTrace(this.getCause());
} else {
return ExceptionUtils.getStackTrace(this.getCause())
+ "\nWith Root Cause: " + ExceptionUtils.getStackTrace(rootException);
}
}
}
| 31.434211 | 98 | 0.623692 |
09b5cf91b7d69d70140a6e7e8b81a271f8b1cee9 | 147 | package de.jaggl.sqlbuilder.core.domain;
/**
* @author Martin Schumacher
*
* @since 2.0.0
*/
public interface Size
{
String getValue();
}
| 12.25 | 40 | 0.659864 |
973b4513b4b3f23ebf51380cc4131528cf6778c2 | 2,737 | /*
* Copyright 2017 Organizations participating in ISAAC, ISAAC's KOMET, and SOLOR development include the
US Veterans Health Administration, OSHERA, and the Health Services Platform Consortium..
*
* 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 sh.komet.gui.control;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import sh.isaac.api.observable.ObservableCategorizedVersion;
import sh.komet.gui.manifold.Manifold;
import sh.komet.gui.style.StyleClasses;
/**
*
* @author kec
*/
public final class VersionPanel extends BadgedVersionPanel {
public VersionPanel(Manifold manifold, ObservableCategorizedVersion categorizedVersion,
OpenIntIntHashMap stampOrderHashMap) {
super(manifold, categorizedVersion, stampOrderHashMap);
if (categorizedVersion.getStampSequence() == -1) {
throw new IllegalStateException("StampSequence = -1: \n" + categorizedVersion);
}
revertCheckBox.setSelected(false);
this.getStyleClass()
.add(StyleClasses.VERSION_PANEL.toString());
this.expandControl.setVisible(false);
this.addAttachmentControl.setVisible(false);
//this.setBackground(new Background(new BackgroundFill(Color.IVORY, CornerRadii.EMPTY, Insets.EMPTY)));
}
@Override
public void addExtras() {
// move the badge, replace edit control with revert checkbox.
gridpane.getChildren()
.remove(editControl);
gridpane.getChildren()
.remove(stampControl);
gridpane.getChildren()
.remove(revertCheckBox);
GridPane.setConstraints(stampControl, 0, 0, 1, 1, HPos.LEFT, VPos.BASELINE, Priority.NEVER, Priority.NEVER);
gridpane.getChildren()
.add(stampControl);
GridPane.setConstraints(revertCheckBox, columns, 0, 1, 1, HPos.RIGHT, VPos.BASELINE, Priority.NEVER, Priority.NEVER, new Insets(0,4,1,0));
gridpane.getChildren()
.add(revertCheckBox);
}
@Override
protected boolean isLatestPanel() {
return false;
}
}
| 38.013889 | 144 | 0.714651 |
8f750f41be50169144b679d133d500251733b68b | 8,759 | package com.studiomediatech;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.studiomediatech.events.QueryRecordedEvent;
import com.studiomediatech.queryresponse.QueryBuilder;
import com.studiomediatech.queryresponse.util.Logging;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.function.ToLongFunction;
import java.util.stream.Collectors;
public class QueryPublisher implements Logging {
// This is a Fib!
private static final int MAX_SIZE = 2584;
private static final int SLIDING_WINDOW = 40;
static ToLongFunction<QueryPublisher.Stat> statToLong = s -> ((Number) s.value).longValue();
private List<QueryPublisher.Stat> queries = new LinkedList<>();
private List<QueryPublisher.Stat> responses = new LinkedList<>();
private List<Double> successRates = new LinkedList<>();
private List<Double> latencies = new LinkedList<>();
private List<Double> throughputs = new LinkedList<>();
private List<Double> tps = new LinkedList<>();
private final QueryBuilder queryBuilder;
private final SimpleWebSocketHandler handler;
public QueryPublisher(SimpleWebSocketHandler handler, QueryBuilder queryBuilder) {
this.handler = handler;
this.queryBuilder = queryBuilder;
}
@EventListener
void on(QueryRecordedEvent event) {
log().info("HANDLING {}", event);
String query = event.getQuery();
long timeout = event.getTimeout();
Optional<Integer> maybe = event.getLimit();
List<Object> orEmptyResponse = Arrays.asList("No responses");
if (maybe.isPresent()) {
int limit = maybe.get();
handler.handleResponse(queryBuilder.queryFor(query, Object.class)
.waitingFor(timeout)
.takingAtMost(limit)
.orDefaults(orEmptyResponse), event.getPublisherId());
} else {
handler.handleResponse(queryBuilder.queryFor(query, Object.class)
.waitingFor(timeout)
.orDefaults(orEmptyResponse), event.getPublisherId());
}
}
@Scheduled(fixedDelay = 1000 * 7)
void query() {
Collection<QueryPublisher.Stat> stats = queryBuilder.queryFor("query-response/stats",
QueryPublisher.Stat.class)
.waitingFor(2L, ChronoUnit.SECONDS).orEmpty();
stats.forEach(stat -> System.out.println("GOT STAT: " + stat));
long countQueriesSum = stats.stream()
.filter(stat -> "count_queries".equals(stat.key))
.mapToLong(statToLong)
.sum();
long countResponsesSum = stats.stream()
.filter(stat -> "count_consumed_responses".equals(stat.key))
.mapToLong(statToLong).sum();
long countFallbacksSum = stats.stream()
.filter(stat -> "count_fallbacks".equals(stat.key))
.mapToLong(statToLong).sum();
double successRate = calculateAndAggregateSuccessRate(countQueriesSum, countResponsesSum);
handler.handleCountQueriesAndResponses(countQueriesSum, countResponsesSum, countFallbacksSum, successRate,
successRates);
Long minLatency = stats.stream()
.filter(stat -> "min_latency".equals(stat.key))
.mapToLong(statToLong).min()
.orElse(-1);
long maxLatency = stats.stream()
.filter(stat -> "max_latency".equals(stat.key))
.mapToLong(statToLong).max()
.orElse(-1);
double avgLatency = stats.stream()
.filter(stat -> "avg_latency".equals(stat.key))
.mapToDouble(stat -> (double) stat.value)
.average()
.orElse(0.0d);
aggregateLatencies(avgLatency);
handler.handleLatency(minLatency, maxLatency, avgLatency, latencies);
// Order is important!!
double throughputQueries = calculateThroughput("throughput_queries", stats, queries);
double throughputResponses = calculateThroughput("throughput_responses", stats, responses);
double throughputAvg = calculateAndAggregateThroughputAvg(queries, responses, null);
handler.handleThroughput(throughputQueries, throughputResponses, throughputAvg, throughputs);
Map<String, List<QueryPublisher.Stat>> nodes = stats.stream()
.filter(s -> StringUtils.hasText(s.uuid))
.collect(Collectors.groupingBy(s -> s.uuid));
for (Entry<String, List<QueryPublisher.Stat>> node : nodes.entrySet()) {
Stat stat = new Stat();
stat.uuid = node.getKey();
stat.key = "avg_throughput";
stat.value = calculateAndAggregateThroughputAvg(queries, responses, node.getKey());
node.getValue().add(stat);
}
handler.handleNodes(nodes);
}
private void aggregateLatencies(double avgLatency) {
if (latencies.size() > MAX_SIZE) {
latencies.remove(0);
}
latencies.add(avgLatency);
}
private double calculateAndAggregateSuccessRate(long countQueriesSum, long countResponsesSum) {
double n = 1.0 * countResponsesSum;
double d = 1.0 * Math.max(1.0, countQueriesSum);
double rate = Math.round((n / d) * 100.0 * 10.0) / 10.0;
if (successRates.size() > MAX_SIZE) {
successRates.remove(0);
}
successRates.add(rate);
return rate;
}
private double calculateAndAggregateThroughputAvg(List<QueryPublisher.Stat> queries,
List<QueryPublisher.Stat> responses, String node) {
List<QueryPublisher.Stat> all = new ArrayList<>();
if (node != null) {
all.addAll(queries.stream().filter(s -> node.equals(s.uuid)).collect(Collectors.toList()));
all.addAll(responses.stream().filter(s -> node.equals(s.uuid)).collect(Collectors.toList()));
} else {
all.addAll(queries);
all.addAll(responses);
}
all.sort(Comparator.comparing(s -> s.timestamp));
if (all.size() < 2) {
return 0.0;
}
long newest = all.get(all.size() - 1).timestamp;
long oldest = all.get(0).timestamp;
long duration = (newest - oldest) / 1000;
if (duration < 1) {
return 0.0;
}
double sum = 1.0 * all.stream().mapToLong(statToLong).sum();
double tp = Math.round((sum / duration) * 1000000.0) / 1000000.0;
if (tps.size() > SLIDING_WINDOW) {
tps.remove(0);
}
tps.add(tp);
if (throughputs.size() > MAX_SIZE) {
throughputs.remove(0);
}
double avg = tps.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
throughputs.add(avg);
return avg;
}
private double calculateThroughput(String key, Collection<QueryPublisher.Stat> source,
List<QueryPublisher.Stat> dest) {
List<QueryPublisher.Stat> ts = source.stream().filter(stat -> key.equals(stat.key))
.sorted(Comparator.comparing(s -> s.timestamp)).collect(Collectors.toList());
for (QueryPublisher.Stat stat : ts) {
if (dest.size() > MAX_SIZE) {
dest.remove(0);
}
dest.add(stat);
}
if (dest.size() < 2) {
return 0.0;
}
long newest = dest.get(dest.size() - 1).timestamp;
long oldest = dest.get(0).timestamp;
long duration = (newest - oldest) / 1000;
if (duration < 1) {
return 0.0;
}
double sum = 1.0 * dest.stream().mapToLong(statToLong).sum();
return Math.round((sum / duration) * 1000000.0) / 1000000.0;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Stat {
@JsonProperty
public String key;
@JsonProperty
public Object value;
@JsonProperty
public Long timestamp;
@JsonProperty
public String uuid;
@Override
public String toString() {
return key + "=" + value + (timestamp != null ? " " + timestamp : "")
+ (uuid != null ? " uuid=" + uuid : "");
}
}
}
| 31.507194 | 114 | 0.61571 |
5eb73178904c732be40ee036aefe2a9431ff83d2 | 174 | package com.akkademy.kvstore;
public class AckSet {
private static final AckSet ACK_SET = new AckSet();
public static AckSet get(){
return ACK_SET;
}
}
| 17.4 | 55 | 0.666667 |
4030ec581f693b393a33a181ce68ac382ee20adf | 441 | package quick.pager.shop.param;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* banner 请求参数
*
* @author siguiyang
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class BannerParam extends Param {
private static final long serialVersionUID = 2378276818835084161L;
/**
* 活动标题
*/
private String title;
private String bannerType;
/**
* 分享渠道
*/
private String shareChannel;
}
| 15.206897 | 70 | 0.671202 |
ea6c4ed68990f5e8d5544e9413aa6c3c634765b9 | 1,050 | package io.spring.enrollmentsystem.feature.enrollment;
import io.spring.enrollmentsystem.common.mapper.ReferenceMapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;
/**
* (Enrollment) mapper
*
* @author Khoale
* @since 2021-09-02 (00:39:59)
*/
@Mapper(uses = {ReferenceMapper.class})
public interface EnrollmentMapper {
EnrollmentMapper INSTANCE = Mappers.getMapper(EnrollmentMapper.class);
@Mapping(target = "studentId", source = "student.id")
@Mapping(target = "sectionId", source = "section.id")
EnrollmentDto toEnrollmentDto(Enrollment enrollment);
@Mapping(target = "student", source = "studentId")
@Mapping(target = "section", source = "sectionId")
@Mapping(target = "enrollmentStatus", ignore = true)
@Mapping(target = "accessCode", ignore = true)
Enrollment toEnrollment(EnrollmentDto enrollmentDto);
Enrollment toExistingEnrollment(EnrollmentDto enrollmentDto, @MappingTarget Enrollment enrollment);
} | 32.8125 | 103 | 0.749524 |
01bd390a7dbbd817a52c91b263bbd09f04c3dd4a | 4,269 | package tsocket.zby.com.tsocket.activity;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.StringRes;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.hwangjr.rxbus.RxBus;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import tsocket.zby.com.tsocket.AppApplication;
import tsocket.zby.com.tsocket.AppConstants;
import tsocket.zby.com.tsocket.AppString;
import tsocket.zby.com.tsocket.R;
import tsocket.zby.com.tsocket.utils.SharedPerfenceUtils;
public class BaseActivity extends Activity {
protected float phone_density;//屏幕密度
protected AppApplication mApp;
/**
* Rx广播替代
*/
//Subscription mRxSubscription;
private Toast mToast;
private int lastLanguageItem = -1;
private boolean isRxRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applyKitKatTranslucency(R.color.layout_header);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
phone_density = getResources().getDisplayMetrics().density; //屏幕密度
mApp = (AppApplication) getApplication();
}
/**
* 显示toast消息, 避免多个重复的toast队列显示
*/
public void showToast(String str) {
if (mToast == null) {//沉浸式菜单,会导致toast文字偏移,必须使用ApplicationContext
mToast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG);
}
mToast.setDuration(Toast.LENGTH_LONG);
mToast.setText(str);
mToast.show();
}
/**
* 显示toast
*/
public void showToast(@StringRes int resId) {
showToast(getString(resId));
}
/**
* 订阅事件,接收推送消息
*/
protected void subscribePushMessage() {
if (!isRxRegister) {
synchronized (this) {
if (!isRxRegister) {
RxBus.get().register(this);
isRxRegister = true;
}
}
}
}
@Override
protected void onResume() {
if (lastLanguageItem == -1) {
lastLanguageItem = SharedPerfenceUtils.getSetupData(this)
.readInt(AppString.language, AppConstants.language_default);
} else {
//跟之前的语言发生了变化
if (lastLanguageItem != SharedPerfenceUtils.getSetupData(this)
.readInt(AppString.language, AppConstants.language_default)) {
onLanguageChange();
}
}
super.onResume();
}
/**
* 取消订阅
*/
protected void unSubscribePushMessage() {
if (isRxRegister) {
synchronized (this) {
if (isRxRegister) {
RxBus.get().unregister(this);
isRxRegister = false;
}
}
}
}
//@Subscribe(thread = EventThread.MAIN_THREAD)
//public void onReceive(String cmdResult) {
//
//}
/**
* 接收到推送消息
*/
//protected void onReceiverCmd(Object message) {
// if(message==null) return;
//}
/**
* 应用内修改语言,对于已打开的页面,就无法重新修改,所以手动在赋值一次
*/
protected void onLanguageChange() {
}
/**
* Apply KitKat specific translucency.
*/
protected void applyKitKatTranslucency(@ColorRes int statusBarTintResource) {
// KitKat translucent navigation/status bar.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
SystemBarTintManager mTintManager = new SystemBarTintManager(this);
mTintManager.setStatusBarTintEnabled(true);
mTintManager.setStatusBarTintResource(statusBarTintResource);//通知栏所需颜色
}
}
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}
| 28.085526 | 85 | 0.622628 |
40c9f5dc9827624900966a3c836f3790cdf89239 | 814 | package cellclasses;
import javafx.scene.paint.Color;
public class SegregationCell extends Cell {
private boolean isEmpty;
private boolean isRed;
private boolean isBlue;
public SegregationCell(int x, int y){
super(x,y);
setUp();
}
private void setUp(){
isEmpty = true;
isRed = false;
isBlue = false;
}
public boolean isEmpty(){
return isEmpty;
}
public boolean isRed(){
return isRed;
}
public boolean isBlue(){
return isBlue;
}
public void makeRed(){
setColor(Color.RED);
setFalse();
isRed = true;
}
public void makeBlue(){
setColor(Color.BLUE);
setFalse();
isBlue = true;
}
public void makeEmpty(){
setColor(getDefault());
setFalse();
isEmpty = true;
}
private void setFalse(){
isEmpty = false;
isRed = false;
isBlue = false;
}
}
| 14.034483 | 43 | 0.657248 |
756007e9fb8e63b8dead96beaa56878ba8c08d7e | 3,411 | package mage.sets;
import mage.cards.ExpansionSet;
import mage.constants.Rarity;
import mage.constants.SetType;
/**
* @author TheElk801
*/
public final class HistoricAnthology5 extends ExpansionSet {
private static final HistoricAnthology5 instance = new HistoricAnthology5();
public static HistoricAnthology5 getInstance() {
return instance;
}
private HistoricAnthology5() {
super("Historic Anthology 5", "HA5", ExpansionSet.buildDate(2021, 5, 27), SetType.MAGIC_ARENA);
this.blockName = "Reprint";
this.hasBoosters = false;
this.hasBasicLands = false;
cards.add(new SetCardInfo("Ancient Grudge", 12, Rarity.COMMON, mage.cards.a.AncientGrudge.class));
cards.add(new SetCardInfo("Atarka's Command", 21, Rarity.RARE, mage.cards.a.AtarkasCommand.class));
cards.add(new SetCardInfo("Court Homunculus", 1, Rarity.COMMON, mage.cards.c.CourtHomunculus.class));
cards.add(new SetCardInfo("Dragonstorm", 13, Rarity.RARE, mage.cards.d.Dragonstorm.class));
cards.add(new SetCardInfo("Dromoka's Command", 22, Rarity.RARE, mage.cards.d.DromokasCommand.class));
cards.add(new SetCardInfo("Elesh Norn, Grand Cenobite", 2, Rarity.MYTHIC, mage.cards.e.EleshNornGrandCenobite.class));
cards.add(new SetCardInfo("Grisly Salvage", 23, Rarity.COMMON, mage.cards.g.GrislySalvage.class));
cards.add(new SetCardInfo("Ichor Wellspring", 24, Rarity.COMMON, mage.cards.i.IchorWellspring.class));
cards.add(new SetCardInfo("Intangible Virtue", 3, Rarity.UNCOMMON, mage.cards.i.IntangibleVirtue.class));
cards.add(new SetCardInfo("Into the North", 16, Rarity.COMMON, mage.cards.i.IntoTheNorth.class));
cards.add(new SetCardInfo("Jin-Gitaxias, Core Augur", 5, Rarity.MYTHIC, mage.cards.j.JinGitaxiasCoreAugur.class));
cards.add(new SetCardInfo("Kolaghan's Command", 20, Rarity.RARE, mage.cards.k.KolaghansCommand.class));
cards.add(new SetCardInfo("Merfolk Looter", 6, Rarity.COMMON, mage.cards.m.MerfolkLooter.class));
cards.add(new SetCardInfo("Ojutai's Command", 18, Rarity.RARE, mage.cards.o.OjutaisCommand.class));
cards.add(new SetCardInfo("Ray of Revelation", 4, Rarity.COMMON, mage.cards.r.RayOfRevelation.class));
cards.add(new SetCardInfo("Relic of Progenitus", 25, Rarity.COMMON, mage.cards.r.RelicOfProgenitus.class));
cards.add(new SetCardInfo("Reverse Engineer", 7, Rarity.UNCOMMON, mage.cards.r.ReverseEngineer.class));
cards.add(new SetCardInfo("Sheoldred, Whispering One", 10, Rarity.MYTHIC, mage.cards.s.SheoldredWhisperingOne.class));
cards.add(new SetCardInfo("Silumgar's Command", 19, Rarity.RARE, mage.cards.s.SilumgarsCommand.class));
cards.add(new SetCardInfo("Stifle", 8, Rarity.RARE, mage.cards.s.Stifle.class));
cards.add(new SetCardInfo("Trash for Treasure", 14, Rarity.UNCOMMON, mage.cards.t.TrashForTreasure.class));
cards.add(new SetCardInfo("Urabrask the Hidden", 15, Rarity.MYTHIC, mage.cards.u.UrabraskTheHidden.class));
cards.add(new SetCardInfo("Vault Skirge", 11, Rarity.COMMON, mage.cards.v.VaultSkirge.class));
cards.add(new SetCardInfo("Vorinclex, Voice of Hunger", 17, Rarity.MYTHIC, mage.cards.v.VorinclexVoiceOfHunger.class));
cards.add(new SetCardInfo("Whirler Rogue", 9, Rarity.UNCOMMON, mage.cards.w.WhirlerRogue.class));
}
}
| 66.882353 | 127 | 0.720023 |
bc4cce8f2095964da0c9578632dcfa56e41f4653 | 357 | package com.yong.resource.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
/**
* @author LiangYong
* @createdDate 2017/11/11
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ResourceServerConfiguration.class})
public @interface EnableYongResourceServer {
}
| 19.833333 | 53 | 0.787115 |
d3276cd467c1e86718904bd68720d528894bd691 | 765 | package org.bulldog.beagleboneblack.io;
import org.bulldog.core.gpio.Pin;
import org.bulldog.core.io.bus.i2c.I2cSignalType;
import org.bulldog.linux.io.LinuxI2cBus;
public class BBBI2cBus extends LinuxI2cBus {
private Pin sdaPin;
private Pin sclPin;
private int frequency;
public BBBI2cBus(String name, String deviceFilePath, Pin sdaPin, Pin sclPin, int frequency) {
super(name, deviceFilePath);
this.sdaPin = sdaPin;
this.sclPin = sclPin;
sdaPin.addFeature(new BBBI2cPinFeature(this, sdaPin, I2cSignalType.SDA));
sclPin.addFeature(new BBBI2cPinFeature(this, sclPin, I2cSignalType.SCL));
}
public Pin getSCL() {
return sclPin;
}
public Pin getSDA() {
return sdaPin;
}
@Override
public int getFrequency() {
return frequency;
}
}
| 22.5 | 94 | 0.751634 |
cb602aa792f9a68b771a6f317caf44d9f968d65b | 460 | /*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package de.hybris.platform.outboundsync.job;
import de.hybris.platform.outboundsync.dto.OutboundItemDTO;
import javax.validation.constraints.NotNull;
public interface RootItemChangeSender
{
/**
* Consume the {@link OutboundItemDTO}
*
* @param change A change that is not eligible for sending to the
*/
void sendPopulatedItem(@NotNull OutboundItemDTO change);
}
| 24.210526 | 78 | 0.763043 |
92f0f91f53921ff85b4efff7bbd6ff243998996d | 2,379 | /*
* Copyright (C) 2019-2021 ConnectorIO sp. z o.o.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* https://www.gnu.org/licenses/gpl-3.0.txt
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package org.connectorio.addons.binding.bacnet.internal.profile;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import org.openhab.core.thing.profiles.Profile;
import org.openhab.core.thing.profiles.ProfileCallback;
import org.openhab.core.thing.profiles.ProfileContext;
import org.openhab.core.thing.profiles.ProfileFactory;
import org.openhab.core.thing.profiles.ProfileType;
import org.openhab.core.thing.profiles.ProfileTypeProvider;
import org.openhab.core.thing.profiles.ProfileTypeUID;
import org.osgi.service.component.annotations.Component;
@Component(service = {ProfileFactory.class, ProfileTypeProvider.class})
public class BACnetProfileFactory implements ProfileFactory, ProfileTypeProvider {
@Override
public Profile createProfile(ProfileTypeUID profileTypeUID, ProfileCallback callback, ProfileContext profileContext) {
if (BACnetProfiles.RESET_PROFILE_TYPE.equals(profileTypeUID)) {
return new ResetProfile(callback, profileContext);
}
if (BACnetProfiles.PRIORITY_PROFILE_TYPE.equals(profileTypeUID)) {
return new PriorityProfile(callback, profileContext);
}
return null;
}
@Override
public Collection<ProfileTypeUID> getSupportedProfileTypeUIDs() {
return Arrays.asList(BACnetProfiles.PRIORITY_PROFILE_TYPE, BACnetProfiles.RESET_PROFILE_TYPE);
}
@Override
public Collection<ProfileType> getProfileTypes(Locale locale) {
return Arrays.asList(BACnetProfiles.PRIORITY_PROFILE, BACnetProfiles.RESET_PROFILE);
}
}
| 39 | 120 | 0.781841 |
95f09e444e13881813e5255642dcb0b660fd3fe0 | 280 | package internal;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
@ApplicationPath("webapi")
public class WebapiConfig extends ResourceConfig {
public WebapiConfig() {
packages(this.getClass().getPackage().getName());
}
}
| 21.538462 | 57 | 0.746429 |
34a892ddd2a4621918c7314760f77e08cb3156b4 | 9,512 | package com.nutiteq.fragmentmap;
import java.util.ArrayList;
import java.util.List;
import com.nutiteq.MapView;
import com.nutiteq.advancedmap.R;
import com.nutiteq.components.Color;
import com.nutiteq.components.Components;
import com.nutiteq.components.MapPos;
import com.nutiteq.components.Options;
import com.nutiteq.geometry.Marker;
import com.nutiteq.geometry.VectorElement;
import com.nutiteq.layers.Layer;
import com.nutiteq.projections.EPSG3857;
import com.nutiteq.rasterdatasources.HTTPRasterDataSource;
import com.nutiteq.rasterdatasources.RasterDataSource;
import com.nutiteq.rasterlayers.RasterLayer;
import com.nutiteq.style.MarkerStyle;
import com.nutiteq.ui.MapListener;
import com.nutiteq.utils.UnscaledBitmapLoader;
import com.nutiteq.vectorlayers.MarkerLayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
/**
*
* This fragment is a demonstration how to embed MapView in a Fragment class and how to serialize the state.
* The state serialization needs to be customized for each use case separately. Note: serialization of layer elements is not needed when
* the elements are loaded from external data source, in that case the list of layers has to be simply rebuild in OnCreateView.
* When elements are added dynamically, then custom serialization is needed. In this example we have a custom marker layer
* and to serialize/restore each marker, we keep its state in MarkerState class. Actual markers are created in onActivityCreated method.
*
* @author mtehver
*
*/
public class MapFragment extends Fragment {
/**
* Interface for marker selection listener
*/
public interface OnMarkerSelectedListener {
void onMarkerSelected(Marker marker, String info);
}
/**
* Custom map event listener
*/
private class MapEventListener extends MapListener {
@Override
public void onVectorElementClicked(VectorElement vectorElement, double x, double y, boolean longClick) {
if (vectorElement instanceof Marker) {
selectMarker((Marker) vectorElement, true);
}
}
@Override
public void onLabelClicked(VectorElement vectorElement, boolean longClick) {
}
@Override
public void onMapClicked(final double x, final double y, final boolean longClick) {
}
@Override
public void onMapMoved() {
}
}
/**
* State class for each marker, supports serialization to Bundle class
*/
private class MarkerState {
MapPos mapPos;
String info;
boolean selected;
MarkerState(MapPos mapPos, String info) {
this.mapPos = mapPos;
this.info = info;
this.selected = false;
}
MarkerState(Bundle bundle) {
mapPos = new MapPos(bundle.getDoubleArray("mapPos"));
info = bundle.getString("info");
selected = bundle.getBoolean("selected");
}
Bundle saveState() {
Bundle bundle = new Bundle();
bundle.putDoubleArray("mapPos", mapPos.toArray());
bundle.putString("info", info);
bundle.putBoolean("selected", selected);
return bundle;
}
}
private MapView mapView;
private Layer baseLayer;
private MarkerLayer markerLayer;
private Marker selectedMarker;
private MarkerStyle normalMarkerStyle;
private MarkerStyle selectedMarkerStyle;
private List<MarkerState> markerStates = new ArrayList<MarkerState>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// MapView initialization
mapView = new MapView(getActivity());
mapView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mapView.setComponents(new Components());
// Create base layer
RasterDataSource dataSource = new HTTPRasterDataSource(new EPSG3857(), 0, 18, "http://otile1.mqcdn.com/tiles/1.0.0/osm/{zoom}/{x}/{y}.png");
baseLayer = new RasterLayer(dataSource, 0);
mapView.getLayers().setBaseLayer(baseLayer);
// Create marker layer
markerLayer = new MarkerLayer(baseLayer.getProjection());
mapView.getLayers().addLayer(markerLayer);
// Styles for markers
normalMarkerStyle = MarkerStyle.builder().setSize(0.5f).setBitmap(
UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.olmarker)
).build();
selectedMarkerStyle = MarkerStyle.builder().setSize(0.65f).setColor(Color.RED).setBitmap(
UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.olmarker)
).build();
// Add event listener
MapEventListener mapListener = new MapEventListener();
mapView.getOptions().setMapListener(mapListener);
// Activate some mapview options to make it smoother - optional
mapView.getOptions().setPreloading(true);
mapView.getOptions().setSeamlessHorizontalPan(true);
mapView.getOptions().setTileFading(true);
mapView.getOptions().setKineticPanning(true);
mapView.getOptions().setDoubleClickZoomIn(true);
mapView.getOptions().setDualClickZoomOut(true);
// set sky bitmap - optional, default - white
mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setSkyOffset(4.86f);
mapView.getOptions().setSkyBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.sky_small));
// Map background, visible if no map tiles loaded - optional, default - white
mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setBackgroundPlaneBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.background_plane));
mapView.getOptions().setClearColor(Color.WHITE);
return mapView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mapView.setComponents(null);
selectedMarker = null;
normalMarkerStyle = null;
selectedMarkerStyle = null;
baseLayer = null;
markerLayer = null;
mapView = null;
}
@Override
public void onStart() {
super.onStart();
mapView.startMapping();
}
@Override
public void onStop() {
mapView.stopMapping();
super.onStop();
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save camera/viewpoint state
state.putDoubleArray("focusPoint", mapView.getFocusPoint().toArray());
state.putFloat("zoom", mapView.getZoom());
state.putFloat("rotation", mapView.getMapRotation());
state.putFloat("tilt", mapView.getTilt());
// Save markers
Bundle markersBundle = new Bundle();
for (int i = 0; i < markerStates.size(); i++) {
MarkerState markerState = markerStates.get(i);
markersBundle.putBundle("" + i, markerState.saveState());
}
state.putBundle("markers", markersBundle);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore camera state
mapView.setFocusPoint(new MapPos(savedInstanceState.getDoubleArray("focusPoint")));
mapView.setZoom(savedInstanceState.getFloat("zoom"));
mapView.setMapRotation(savedInstanceState.getFloat("rotation"));
mapView.setTilt(savedInstanceState.getFloat("tilt"));
// Restore markers
Bundle markersBundle = savedInstanceState.getBundle("markers");
for (int i = 0; i < markersBundle.size(); i++) {
MarkerState markerState = new MarkerState(markersBundle.getBundle("" + i));
markerStates.add(markerState);
}
} else {
// Initialize camera state
mapView.setFocusPoint(baseLayer.getProjection().fromWgs84(25.4426f, 42.7026f));
mapView.setZoom(8.0f);
mapView.setMapRotation(0f);
mapView.setTilt(90.0f);
// Create random markers, centered around focus point
MapPos focusPoint = mapView.getFocusPoint();
for (int i = 0; i < 20; i++) {
MapPos mapPos = new MapPos(focusPoint.x + (Math.random() - 0.5f) * 100000, focusPoint.y + (Math.random() - 0.5f) * 100000);
MapPos wgs84 = mapView.getLayers().getBaseProjection().toWgs84(mapPos.x, mapPos.y);
String info = "Marker " + i + "\nWGS84 " + String.format("%.4f, %.4f", wgs84.x, wgs84.y);
markerStates.add(new MarkerState(mapPos, info));
}
}
// Initialize marker layer based on markerStates list
for (MarkerState markerState : markerStates) {
Marker marker = new Marker(markerState.mapPos, null, normalMarkerStyle, markerState);
markerLayer.add(marker);
if (markerState.selected) {
selectMarker(marker, false);
}
}
}
protected void selectMarker(Marker marker, boolean updateListener) {
if (selectedMarker == marker) {
return;
}
if (selectedMarker != null) {
MarkerState selectedMarkerState = (MarkerState) selectedMarker.userData;
selectedMarkerState.selected = false;
selectedMarker.setStyle(normalMarkerStyle);
}
MarkerState markerState = (MarkerState) marker.userData;
markerState.selected = true;
marker.setStyle(selectedMarkerStyle);
selectedMarker = marker;
mapView.selectVectorElement(marker);
OnMarkerSelectedListener listener = (OnMarkerSelectedListener) getActivity();
if (updateListener && listener != null) {
listener.onMarkerSelected(marker, markerState.info);
}
}
}
| 34.842491 | 144 | 0.713099 |
4aac316b8d31389d4f16da5df899bc0ddd822620 | 3,255 | package com.oq_io.cs_challenge;
import java.io.File;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.apache.logging.log4j.LogManager;
import com.oq_io.cs_challenge.dao.Event;
import com.oq_io.cs_challenge.utils.DbConnect;
import com.oq_io.cs_challenge.utils.EventProcessor;
import com.oq_io.cs_challenge.utils.LogParser;
/**
* Simple event log parse logic focusing on limited memory usage and transactional database calls
* Uses Hibernate entity creation currently configured for jdbc:hsqldb:mem
* Log file streaming and Database batch transactions for resource comptability
* @author oq_io
* @version 0.1
* @since 2022-03-13
*/
public class App {
private static Logger logger = LogManager.getLogger(App.class);
/**
* This is the main method calling App.class
* @param args [0] file input json file of events.
* @return Nothing.
* @exception catch if args file does not exist
*/
public static void main(String[] args) {
if (args == null || args.length != 1) {
logger.error("Arguments should be a FilePath.");
throw new IllegalArgumentException("Please check the arguments and run again.");
}
File temp = new File(args[0]);
if(temp.exists()) {
logger.info("Working on: "+temp.getAbsolutePath());
new App(temp);
}else {
logger.error(args[0]+" is not a file");
}
}
/**
* Class take File input calls LogParser to read json and insert to db configured
* Then runs EventProcessor to execute db level business rules to calculate duration and alert of paired evetns
* @param file input json file of events
*/
public App(File file) {
DbConnect dbConnect = new DbConnect();
LogParser parser = new LogParser(file,dbConnect);
logger.info(parser.getStatsProcRows()+" rows, processed in "+parser.getStatsProcTime()+"ms");
EventProcessor eventProcess = new EventProcessor(dbConnect);
logger.info(eventProcess.getStatsProcRows()+" events' duration calculated, processed in "+eventProcess.getStatsProcTime()+"ms");
Session session = dbConnect.getSession();
Long totalEvents = (Long) session.createQuery("SELECT count(*) from Event").getSingleResult();
logger.info("Totals events: "+totalEvents);
String completeEventsQuery = "select count(*) "
+ " from Event eS "
+ " join Event eF ON eF.id = eS.id AND eF.state = 'FINISHED' AND eS.state = 'STARTED'";
Long completeEvents = (Long) session.createQuery(completeEventsQuery).getSingleResult();
logger.info("Totals complete events: "+completeEvents);
String orphanEventsQuery = "select count(*) from Event where id not in ("
+ " select eS.id from Event eS join Event eF ON eF.id = eS.id AND eF.state = 'FINISHED' AND eS.state = 'STARTED')";
Long orphanEvents = (Long) session.createQuery(orphanEventsQuery).getSingleResult();
logger.info("Totals orphan events: "+orphanEvents);
Double avgDuration = (Double) session.createQuery("SELECT avg(duration) from Event where state = :state")
.setParameter("state", Event.State.FINISHED)
.getSingleResult();
logger.info("Average durarion of events: "+String.format("%.2f",avgDuration)+"ms");
session.close();
}
}
| 33.90625 | 130 | 0.704455 |
6c86ef71ef6dda2e420622dd90ef4324e14f77db | 1,315 | package com.example.lunchtray.data;
import java.lang.System;
/**
* Map of available menu items to be displayed in the menu fragments.
*/
@kotlin.Metadata(mv = {1, 5, 1}, k = 1, d1 = {"\u0000\u001c\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010$\n\u0002\u0010\u000e\n\u0002\u0018\u0002\n\u0002\b\u0003\b\u00c6\u0002\u0018\u00002\u00020\u0001B\u0007\b\u0002\u00a2\u0006\u0002\u0010\u0002R\u001d\u0010\u0003\u001a\u000e\u0012\u0004\u0012\u00020\u0005\u0012\u0004\u0012\u00020\u00060\u0004\u00a2\u0006\b\n\u0000\u001a\u0004\b\u0007\u0010\b\u00a8\u0006\t"}, d2 = {"Lcom/example/lunchtray/data/DataSource;", "", "()V", "menuItems", "", "", "Lcom/example/lunchtray/model/MenuItem;", "getMenuItems", "()Ljava/util/Map;", "app_debug"})
public final class DataSource {
@org.jetbrains.annotations.NotNull()
public static final com.example.lunchtray.data.DataSource INSTANCE = null;
@org.jetbrains.annotations.NotNull()
private static final java.util.Map<java.lang.String, com.example.lunchtray.model.MenuItem> menuItems = null;
private DataSource() {
super();
}
@org.jetbrains.annotations.NotNull()
public final java.util.Map<java.lang.String, com.example.lunchtray.model.MenuItem> getMenuItems() {
return null;
}
} | 57.173913 | 613 | 0.707224 |
e135de94afbd934b930b66451514c94a3722612c | 2,127 | package dev.utils.common.encrypt;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import dev.utils.JCLogUtils;
/**
* detail: DES对称加密(Data Encryption Standard,数据加密标准,对称加密算法)
* Created by Ttt
*/
public final class DESUtils {
private DESUtils() {
}
// 日志TAG
private static final String TAG = CRCUtils.class.getSimpleName();
/**
* 返回可逆算法DES的密钥
* @param key 前8字节将被用来生成密钥。
* @return 生成的密钥
* @throws Exception
*/
public static Key getDESKey(byte[] key){
try {
DESKeySpec des = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(des);
} catch (Exception e){
JCLogUtils.eTag(TAG, e, "getDESKey");
}
return null;
}
/**
* DES 加密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key){
try {
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherBytes = cipher.doFinal(data);
return cipherBytes;
} catch (Exception e){
JCLogUtils.eTag(TAG, e, "encrypt");
}
return null;
}
/**
* DES 解密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key){
try {
SecretKey secretKey = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainBytes = cipher.doFinal(data);
return plainBytes;
} catch (Exception e){
JCLogUtils.eTag(TAG, e, "decrypt");
}
return null;
}
}
| 25.626506 | 78 | 0.587682 |
bd200973906a3548002232c7af4436825045cbf5 | 14,811 | /*
* Copyright (C) 2008 The Guava 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.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
import static com.google.common.collect.ImmutableMapEntry.createEntryArray;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMapEntry.NonTerminalImmutableMapEntry;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.Serializable;
import java.util.IdentityHashMap;
import java.util.function.BiConsumer;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Implementation of {@link ImmutableMap} with two or more entries.
*
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Gregory Kick
*/
@GwtCompatible(serializable = true, emulated = true)
@ElementTypesAreNonnullByDefault
final class RegularImmutableMap<K, V> extends ImmutableMap<K, V> {
@SuppressWarnings("unchecked")
static final ImmutableMap<Object, Object> EMPTY =
new RegularImmutableMap<>((Entry<Object, Object>[]) ImmutableMap.EMPTY_ENTRY_ARRAY, null, 0);
/**
* Closed addressing tends to perform well even with high load factors. Being conservative here
* ensures that the table is still likely to be relatively sparse (hence it misses fast) while
* saving space.
*/
@VisibleForTesting static final double MAX_LOAD_FACTOR = 1.2;
/**
* Maximum allowed false positive probability of detecting a hash flooding attack given random
* input.
*/
@VisibleForTesting static final double HASH_FLOODING_FPP = 0.001;
/**
* Maximum allowed length of a hash table bucket before falling back to a j.u.HashMap based
* implementation. Experimentally determined.
*/
@VisibleForTesting static final int MAX_HASH_BUCKET_LENGTH = 8;
// entries in insertion order
@VisibleForTesting final transient Entry<K, V>[] entries;
// array of linked lists of entries
@CheckForNull private final transient @Nullable ImmutableMapEntry<K, V>[] table;
// 'and' with an int to get a table index
private final transient int mask;
static <K, V> ImmutableMap<K, V> fromEntries(Entry<K, V>... entries) {
return fromEntryArray(entries.length, entries, /* throwIfDuplicateKeys= */ true);
}
/**
* Creates an ImmutableMap from the first n entries in entryArray. This implementation may replace
* the entries in entryArray with its own entry objects (though they will have the same key/value
* contents), and may take ownership of entryArray.
*/
static <K, V> ImmutableMap<K, V> fromEntryArray(
int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys) {
checkPositionIndex(n, entryArray.length);
if (n == 0) {
@SuppressWarnings("unchecked") // it has no entries so the type variables don't matter
ImmutableMap<K, V> empty = (ImmutableMap<K, V>) EMPTY;
return empty;
}
try {
return fromEntryArrayCheckingBucketOverflow(n, entryArray, throwIfDuplicateKeys);
} catch (BucketOverflowException e) {
// probable hash flooding attack, fall back to j.u.HM based implementation and use its
// implementation of hash flooding protection
return JdkBackedImmutableMap.create(n, entryArray, throwIfDuplicateKeys);
}
}
private static <K, V> ImmutableMap<K, V> fromEntryArrayCheckingBucketOverflow(
int n, @Nullable Entry<K, V>[] entryArray, boolean throwIfDuplicateKeys)
throws BucketOverflowException {
/*
* The cast is safe: n==entryArray.length means that we have filled the whole array with Entry
* instances, in which case it is safe to cast it from an array of nullable entries to an array
* of non-null entries.
*/
@SuppressWarnings("nullness")
Entry<K, V>[] entries =
(n == entryArray.length) ? (Entry<K, V>[]) entryArray : createEntryArray(n);
int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR);
@Nullable ImmutableMapEntry<K, V>[] table = createEntryArray(tableSize);
int mask = tableSize - 1;
// If duplicates are allowed, this IdentityHashMap will record the final Entry for each
// duplicated key. We will use this final Entry to overwrite earlier slots in the entries array
// that have the same key. Then a second pass will remove all but the first of the slots that
// have this Entry. The value in the map becomes false when this first entry has been copied, so
// we know not to copy the remaining ones.
IdentityHashMap<Entry<K, V>, Boolean> duplicates = null;
int dupCount = 0;
for (int entryIndex = n - 1; entryIndex >= 0; entryIndex--) {
// requireNonNull is safe because the first `n` elements have been filled in.
Entry<K, V> entry = requireNonNull(entryArray[entryIndex]);
K key = entry.getKey();
V value = entry.getValue();
checkEntryNotNull(key, value);
int tableIndex = Hashing.smear(key.hashCode()) & mask;
ImmutableMapEntry<K, V> keyBucketHead = table[tableIndex];
ImmutableMapEntry<K, V> newEntry =
checkNoConflictInKeyBucket(key, value, keyBucketHead, throwIfDuplicateKeys);
if (newEntry == null) {
// prepend, not append, so the entries can be immutable
newEntry =
(keyBucketHead == null)
? makeImmutable(entry, key, value)
: new NonTerminalImmutableMapEntry<K, V>(key, value, keyBucketHead);
} else {
if (duplicates == null) {
duplicates = new IdentityHashMap<>();
}
duplicates.put(newEntry, true);
dupCount++;
// Make sure we are not overwriting the original entries array, in case we later do
// buildOrThrow(). We would want an exception to include two values for the duplicate key.
if (entries == entryArray) {
entries = entries.clone();
}
}
table[tableIndex] = newEntry;
entries[entryIndex] = newEntry;
}
if (duplicates != null) {
// Explicit type parameters needed here to avoid a problem with nullness inference.
entries = RegularImmutableMap.<K, V>removeDuplicates(entries, n, n - dupCount, duplicates);
int newTableSize = Hashing.closedTableSize(entries.length, MAX_LOAD_FACTOR);
if (newTableSize != tableSize) {
return fromEntryArrayCheckingBucketOverflow(
entries.length, entries, /* throwIfDuplicateKeys= */ true);
}
}
return new RegularImmutableMap<>(entries, table, mask);
}
/**
* Constructs a new entry array where each duplicated key from the original appears only once, at
* its first position but with its final value. The {@code duplicates} map is modified.
*
* @param entries the original array of entries including duplicates
* @param n the number of valid entries in {@code entries}
* @param newN the expected number of entries once duplicates are removed
* @param duplicates a map of canonical {@link Entry} objects for each duplicate key. This map
* will be updated by the method, setting each value to false as soon as the {@link Entry} has
* been included in the new entry array.
* @return an array of {@code newN} entries where no key appears more than once.
*/
static <K, V> Entry<K, V>[] removeDuplicates(
Entry<K, V>[] entries, int n, int newN, IdentityHashMap<Entry<K, V>, Boolean> duplicates) {
Entry<K, V>[] newEntries = createEntryArray(newN);
for (int in = 0, out = 0; in < n; in++) {
Entry<K, V> entry = entries[in];
Boolean status = duplicates.get(entry);
// null=>not dup'd; true=>dup'd, first; false=>dup'd, not first
if (status != null) {
if (status) {
duplicates.put(entry, false);
} else {
continue; // delete this entry; we already copied an earlier one for the same key
}
}
newEntries[out++] = entry;
}
return newEntries;
}
/** Makes an entry usable internally by a new ImmutableMap without rereading its contents. */
static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry, K key, V value) {
boolean reusable =
entry instanceof ImmutableMapEntry && ((ImmutableMapEntry<K, V>) entry).isReusable();
return reusable ? (ImmutableMapEntry<K, V>) entry : new ImmutableMapEntry<K, V>(key, value);
}
/** Makes an entry usable internally by a new ImmutableMap. */
static <K, V> ImmutableMapEntry<K, V> makeImmutable(Entry<K, V> entry) {
return makeImmutable(entry, entry.getKey(), entry.getValue());
}
private RegularImmutableMap(
Entry<K, V>[] entries, @CheckForNull @Nullable ImmutableMapEntry<K, V>[] table, int mask) {
this.entries = entries;
this.table = table;
this.mask = mask;
}
/**
* Checks if the given key already appears in the hash chain starting at {@code keyBucketHead}. If
* it does not, then null is returned. If it does, then if {@code throwIfDuplicateKeys} is true an
* {@code IllegalArgumentException} is thrown, and otherwise the existing {@link Entry} is
* returned.
*
* @throws IllegalArgumentException if another entry in the bucket has the same key and {@code
* throwIfDuplicateKeys} is true
* @throws BucketOverflowException if this bucket has too many entries, which may indicate a hash
* flooding attack
*/
@CanIgnoreReturnValue
static <K, V> @Nullable ImmutableMapEntry<K, V> checkNoConflictInKeyBucket(
Object key,
Object newValue,
@CheckForNull ImmutableMapEntry<K, V> keyBucketHead,
boolean throwIfDuplicateKeys)
throws BucketOverflowException {
int bucketSize = 0;
for (; keyBucketHead != null; keyBucketHead = keyBucketHead.getNextInKeyBucket()) {
if (keyBucketHead.getKey().equals(key)) {
if (throwIfDuplicateKeys) {
checkNoConflict(/* safe= */ false, "key", keyBucketHead, key + "=" + newValue);
} else {
return keyBucketHead;
}
}
if (++bucketSize > MAX_HASH_BUCKET_LENGTH) {
throw new BucketOverflowException();
}
}
return null;
}
static class BucketOverflowException extends Exception {}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
return get(key, table, mask);
}
@CheckForNull
static <V> V get(
@CheckForNull Object key,
@CheckForNull @Nullable ImmutableMapEntry<?, V>[] keyTable,
int mask) {
if (key == null || keyTable == null) {
return null;
}
int index = Hashing.smear(key.hashCode()) & mask;
for (ImmutableMapEntry<?, V> entry = keyTable[index];
entry != null;
entry = entry.getNextInKeyBucket()) {
Object candidateKey = entry.getKey();
/*
* Assume that equals uses the == optimization when appropriate, and that
* it would check hash codes as an optimization when appropriate. If we
* did these things, it would just make things worse for the most
* performance-conscious users.
*/
if (key.equals(candidateKey)) {
return entry.getValue();
}
}
return null;
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
checkNotNull(action);
for (Entry<K, V> entry : entries) {
action.accept(entry.getKey(), entry.getValue());
}
}
@Override
public int size() {
return entries.length;
}
@Override
boolean isPartialView() {
return false;
}
@Override
ImmutableSet<Entry<K, V>> createEntrySet() {
return new ImmutableMapEntrySet.RegularEntrySet<>(this, entries);
}
@Override
ImmutableSet<K> createKeySet() {
return new KeySet<>(this);
}
@GwtCompatible(emulated = true)
private static final class KeySet<K> extends IndexedImmutableSet<K> {
private final RegularImmutableMap<K, ?> map;
KeySet(RegularImmutableMap<K, ?> map) {
this.map = map;
}
@Override
K get(int index) {
return map.entries[index].getKey();
}
@Override
public boolean contains(@CheckForNull Object object) {
return map.containsKey(object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
public int size() {
return map.size();
}
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
@SuppressWarnings("unused")
private static class SerializedForm<K> implements Serializable {
final ImmutableMap<K, ?> map;
SerializedForm(ImmutableMap<K, ?> map) {
this.map = map;
}
Object readResolve() {
return map.keySet();
}
private static final long serialVersionUID = 0;
}
}
@Override
ImmutableCollection<V> createValues() {
return new Values<>(this);
}
@GwtCompatible(emulated = true)
private static final class Values<K, V> extends ImmutableList<V> {
final RegularImmutableMap<K, V> map;
Values(RegularImmutableMap<K, V> map) {
this.map = map;
}
@Override
public V get(int index) {
return map.entries[index].getValue();
}
@Override
public int size() {
return map.size();
}
@Override
boolean isPartialView() {
return true;
}
// No longer used for new writes, but kept so that old data can still be read.
@GwtIncompatible // serialization
@SuppressWarnings("unused")
private static class SerializedForm<V> implements Serializable {
final ImmutableMap<?, V> map;
SerializedForm(ImmutableMap<?, V> map) {
this.map = map;
}
Object readResolve() {
return map.values();
}
private static final long serialVersionUID = 0;
}
}
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
private static final long serialVersionUID = 0;
}
| 36.212714 | 100 | 0.680508 |
0d5811b629a887b6b8b1b497a708a8f53cba40c0 | 1,696 | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.levien.synthesizer.core.soundfont;
import java.io.IOException;
import com.levien.synthesizer.core.wave.RiffInputStream;
/**
* A Modulator is a SoundFont data structure. They are read in by this library, but then ignored.
*/
public class Modulator {
public Modulator(RiffInputStream input) throws IOException {
sourceOperator = new ModulatorSource(input.readWord());
destinationOperator = input.readWord();
amount = input.readShort();
amountOperator = new ModulatorSource(input.readWord());
transform = input.readWord();
}
public String toString() {
return
"Modulator {\n" +
" source operator: \n" +
sourceOperator + "\n" +
" destination operator: " + destinationOperator + "\n" +
" amount: " + amount + "\n" +
" amount operator: \n" +
amountOperator + "\n" +
" transform: " + transform + "\n" +
"}";
}
public ModulatorSource sourceOperator;
public int destinationOperator;
public short amount;
public ModulatorSource amountOperator;
public int transform;
}
| 31.407407 | 98 | 0.684552 |
60ea1abb872a980997b77adb55d538529c7860c0 | 24,370 |
package org.drip.sample.multicurve;
import java.util.*;
import org.drip.analytics.date.*;
import org.drip.analytics.support.*;
import org.drip.market.otc.*;
import org.drip.param.creator.*;
import org.drip.param.market.CurveSurfaceQuoteContainer;
import org.drip.param.valuation.*;
import org.drip.product.creator.*;
import org.drip.product.definition.*;
import org.drip.product.rates.*;
import org.drip.quant.common.FormatUtil;
import org.drip.service.env.EnvManager;
import org.drip.spline.basis.*;
import org.drip.spline.stretch.MultiSegmentSequenceBuilder;
import org.drip.state.creator.*;
import org.drip.state.discount.*;
import org.drip.state.forward.ForwardCurve;
import org.drip.state.identifier.ForwardLabel;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2017 Lakshmi Krishnamurthy
* Copyright (C) 2016 Lakshmi Krishnamurthy
* Copyright (C) 2015 Lakshmi Krishnamurthy
* Copyright (C) 2014 Lakshmi Krishnamurthy
* Copyright (C) 2013 Lakshmi Krishnamurthy
*
* This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
* libraries targeting analysts and developers
* https://lakshmidrip.github.io/DRIP/
*
* DRIP is composed of four main libraries:
*
* - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
* - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
* - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
* - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
*
* - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
* Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
* Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
* Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
* Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
*
* - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
* Incorporator, Holdings Constraint, and Transaction Costs.
*
* - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
*
* - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
*
* 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.
*/
/**
* FloatFloatForwardCurve contains the sample demonstrating the full functionality behind creating highly
* customized spline based forward curves.
*
* The first sample illustrates the creation and usage of the xM-6M Tenor Basis Swap:
* - Construct the 6M-xM float-float basis swap.
* - Calculate the corresponding starting forward rate off of the discount curve.
* - Construct the shape preserving forward curve off of Cubic Polynomial Basis Spline.
* - Construct the shape preserving forward curve off of Quartic Polynomial Basis Spline.
* - Construct the shape preserving forward curve off of Hyperbolic Tension Based Basis Spline.
* - Set the discount curve based component market parameters.
* - Set the discount curve + cubic polynomial forward curve based component market parameters.
* - Set the discount curve + quartic polynomial forward curve based component market parameters.
* - Set the discount curve + hyperbolic tension forward curve based component market parameters.
* - Compute the following forward curve metrics for each of cubic polynomial forward, quartic
* polynomial forward, and KLK Hyperbolic tension forward curves:
* - Reference Basis Par Spread
* - Derived Basis Par Spread
* - Compare these with a) the forward rate off of the discount curve, b) The LIBOR rate, and c) The
* Input Basis Swap Quote.
*
* The second sample illustrates how to build and test the forward curves across various tenor basis. It
* shows the following steps:
* - Construct the Discount Curve using its instruments and quotes.
* - Build and run the sampling for the 1M-6M Tenor Basis Swap from its instruments and quotes.
* - Build and run the sampling for the 3M-6M Tenor Basis Swap from its instruments and quotes.
* - Build and run the sampling for the 6M-6M Tenor Basis Swap from its instruments and quotes.
* - Build and run the sampling for the 12M-6M Tenor Basis Swap from its instruments and quotes.
*
* @author Lakshmi Krishnamurthy
*/
public class FloatFloatForwardCurve {
private static final FixFloatComponent OTCFixFloat (
final JulianDate dtSpot,
final String strCurrency,
final String strMaturityTenor,
final double dblCoupon)
{
FixedFloatSwapConvention ffConv = IBORFixedFloatContainer.ConventionFromJurisdiction (
strCurrency,
"ALL",
strMaturityTenor,
"MAIN"
);
return ffConv.createFixFloatComponent (
dtSpot,
strMaturityTenor,
dblCoupon,
0.,
1.
);
}
private static final FloatFloatComponent OTCFloatFloat (
final JulianDate dtSpot,
final String strCurrency,
final String strDerivedTenor,
final String strMaturityTenor,
final double dblBasis)
{
FloatFloatSwapConvention ffConv = IBORFloatFloatContainer.ConventionFromJurisdiction (strCurrency);
return ffConv.createFloatFloatComponent (
dtSpot,
strDerivedTenor,
strMaturityTenor,
dblBasis,
1.
);
}
/*
* Construct the Array of Deposit Instruments from the given set of parameters
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final CalibratableComponent[] DepositInstrumentsFromMaturityDays (
final JulianDate dtEffective,
final int[] aiDay,
final int iNumFutures,
final String strCurrency)
throws Exception
{
CalibratableComponent[] aCalibComp = new CalibratableComponent[aiDay.length + iNumFutures];
for (int i = 0; i < aiDay.length; ++i)
aCalibComp[i] = SingleStreamComponentBuilder.Deposit (
dtEffective,
dtEffective.addBusDays (
aiDay[i],
strCurrency
),
ForwardLabel.Create (
strCurrency,
"3M"
)
);
CalibratableComponent[] aEDF = SingleStreamComponentBuilder.ForwardRateFuturesPack (
dtEffective,
iNumFutures,
strCurrency
);
for (int i = aiDay.length; i < aiDay.length + iNumFutures; ++i)
aCalibComp[i] = aEDF[i - aiDay.length];
return aCalibComp;
}
/*
* Construct the Array of Swap Instruments from the given set of parameters
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final CalibratableComponent[] SwapInstrumentsFromMaturityTenor (
final JulianDate dtSpot,
final String strCurrency,
final String[] astrMaturityTenor,
final double[] adblCoupon)
throws Exception
{
FixFloatComponent[] aIRS = new FixFloatComponent[astrMaturityTenor.length];
for (int i = 0; i < astrMaturityTenor.length; ++i)
aIRS[i] = OTCFixFloat (
dtSpot,
strCurrency,
astrMaturityTenor[i],
adblCoupon[i]
);
return aIRS;
}
/*
* Construct the discount curve using the following steps:
* - Construct the array of cash instruments and their quotes.
* - Construct the array of swap instruments and their quotes.
* - Construct a shape preserving and smoothing KLK Hyperbolic Spline from the cash/swap instruments.
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final MergedDiscountForwardCurve MakeDC (
final JulianDate dtSpot,
final String strCurrency,
final double dblBump)
throws Exception
{
/*
* Construct the array of Deposit instruments and their quotes.
*/
CalibratableComponent[] aDepositComp = DepositInstrumentsFromMaturityDays (
dtSpot,
new int[] {},
0,
strCurrency
);
double[] adblDepositQuote = new double[] {}; // Futures
/*
* Construct the array of Swap instruments and their quotes.
*/
double[] adblSwapQuote = new double[] {
// 0.00092 + dblBump, // 6M
0.0009875 + dblBump, // 9M
0.00122 + dblBump, // 1Y
0.00223 + dblBump, // 18M
0.00383 + dblBump, // 2Y
0.00827 + dblBump, // 3Y
0.01245 + dblBump, // 4Y
0.01605 + dblBump, // 5Y
0.02597 + dblBump // 10Y
};
String[] astrSwapManifestMeasure = new String[] {
// "SwapRate", // 6M
"SwapRate", // 9M
"SwapRate", // 1Y
"SwapRate", // 18M
"SwapRate", // 2Y
"SwapRate", // 3Y
"SwapRate", // 4Y
"SwapRate", // 5Y
"SwapRate" // 10Y
};
CalibratableComponent[] aSwapComp = SwapInstrumentsFromMaturityTenor (
dtSpot,
strCurrency,
// new java.lang.String[] {"6M", "9M", "1Y", "18M", "2Y", "3Y", "4Y", "5Y", "10Y"},
new java.lang.String[] {
"9M", "1Y", "18M", "2Y", "3Y", "4Y", "5Y", "10Y"
},
adblSwapQuote
);
/*
* Construct a shape preserving and smoothing KLK Hyperbolic Spline from the cash/swap instruments.
*/
return ScenarioDiscountCurveBuilder.CubicKLKHyperbolicDFRateShapePreserver (
"KLK_HYPERBOLIC_SHAPE_TEMPLATE",
new ValuationParams (
dtSpot,
dtSpot,
"USD"
),
aDepositComp,
adblDepositQuote,
null,
aSwapComp,
adblSwapQuote,
astrSwapManifestMeasure,
false
);
}
/*
* Construct an array of float-float swaps from the corresponding reference (6M) and the derived legs.
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final FloatFloatComponent[] MakexM6MBasisSwap (
final JulianDate dtSpot,
final String strCurrency,
final String[] astrMaturityTenor,
final int iTenorInMonths)
throws Exception
{
FloatFloatComponent[] aFFC = new FloatFloatComponent[astrMaturityTenor.length];
for (int i = 0; i < astrMaturityTenor.length; ++i)
aFFC[i] = OTCFloatFloat (
dtSpot,
strCurrency,
iTenorInMonths + "M",
astrMaturityTenor[i],
0.
);
return aFFC;
}
/*
* This sample illustrates the creation and usage of the xM-6M Tenor Basis Swap. It shows the following:
* - Construct the 6M-xM float-float basis swap.
* - Calculate the corresponding starting forward rate off of the discount curve.
* - Construct the shape preserving forward curve off of Cubic Polynomial Basis Spline.
* - Construct the shape preserving forward curve off of Quartic Polynomial Basis Spline.
* - Construct the shape preserving forward curve off of Hyperbolic Tension Based Basis Spline.
* - Set the discount curve based component market parameters.
* - Set the discount curve + cubic polynomial forward curve based component market parameters.
* - Set the discount curve + quartic polynomial forward curve based component market parameters.
* - Set the discount curve + hyperbolic tension forward curve based component market parameters.
* - Compute the following forward curve metrics for each of cubic polynomial forward, quartic
* polynomial forward, and KLK Hyperbolic tension forward curves:
* - Reference Basis Par Spread
* - Derived Basis Par Spread
* - Compare these with a) the forward rate off of the discount curve, b) The LIBOR rate, and c) The
* Input Basis Swap Quote.
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final Map<String, ForwardCurve> xM6MBasisSample (
final JulianDate dtSpot,
final String strCurrency,
final MergedDiscountForwardCurve dc,
final int iTenorInMonths,
final String[] astrxM6MFwdTenor,
final String strManifestMeasure,
final double[] adblxM6MBasisSwapQuote)
throws Exception
{
System.out.println ("-----------------------------------------------------------------------------------------------------------------------------");
System.out.println (" SPL => n=3 | n=4 | KLK | | |");
System.out.println ("--------------------------------------------------------------------------------------------------------| LOG DF | LIBOR |");
System.out.println (" MSR => RECALC | REFEREN | DERIVED | RECALC | REFEREN | DERIVED | RECALC | REFEREN | DERIVED | | |");
System.out.println ("-----------------------------------------------------------------------------------------------------------------------------");
/*
* Construct the 6M-xM float-float basis swap.
*/
FloatFloatComponent[] aFFC = MakexM6MBasisSwap (
dtSpot,
strCurrency,
astrxM6MFwdTenor,
iTenorInMonths
);
String strBasisTenor = iTenorInMonths + "M";
ValuationParams valParams = new ValuationParams (
dtSpot,
dtSpot,
strCurrency
);
/*
* Calculate the starting forward rate off of the discount curve.
*/
double dblStartingFwd = dc.forward (
dtSpot.julian(),
dtSpot.addTenor (strBasisTenor).julian()
);
/*
* Set the discount curve based component market parameters.
*/
CurveSurfaceQuoteContainer mktParams = MarketParamsBuilder.Create (
dc,
null,
null,
null,
null,
null,
null
);
Map<String, ForwardCurve> mapForward = new HashMap<String, ForwardCurve>();
/*
* Construct the shape preserving forward curve off of Cubic Polynomial Basis Spline.
*/
ForwardCurve fcxMCubic = ScenarioForwardCurveBuilder.ShapePreservingForwardCurve (
"CUBIC_FWD" + strBasisTenor,
ForwardLabel.Create (
strCurrency,
strBasisTenor
),
valParams,
null,
mktParams,
null,
MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
new PolynomialFunctionSetParams (4),
aFFC,
strManifestMeasure,
adblxM6MBasisSwapQuote,
dblStartingFwd
);
mapForward.put (
" CUBIC_FWD" + strBasisTenor,
fcxMCubic
);
/*
* Set the discount curve + cubic polynomial forward curve based component market parameters.
*/
CurveSurfaceQuoteContainer mktParamsCubicFwd = MarketParamsBuilder.Create (
dc,
fcxMCubic,
null,
null,
null,
null,
null,
null
);
/*
* Construct the shape preserving forward curve off of Quartic Polynomial Basis Spline.
*/
ForwardCurve fcxMQuartic = ScenarioForwardCurveBuilder.ShapePreservingForwardCurve (
"QUARTIC_FWD" + strBasisTenor,
ForwardLabel.Create (
strCurrency,
strBasisTenor
),
valParams,
null,
mktParams,
null,
MultiSegmentSequenceBuilder.BASIS_SPLINE_POLYNOMIAL,
new PolynomialFunctionSetParams (5),
aFFC,
strManifestMeasure,
adblxM6MBasisSwapQuote,
dblStartingFwd
);
mapForward.put (
" QUARTIC_FWD" + strBasisTenor,
fcxMQuartic
);
/*
* Set the discount curve + quartic polynomial forward curve based component market parameters.
*/
CurveSurfaceQuoteContainer mktParamsQuarticFwd = MarketParamsBuilder.Create (
dc,
fcxMQuartic,
null,
null,
null,
null,
null,
null
);
/*
* Construct the shape preserving forward curve off of Hyperbolic Tension Based Basis Spline.
*/
ForwardCurve fcxMKLKHyper = ScenarioForwardCurveBuilder.ShapePreservingForwardCurve (
"KLKHYPER_FWD" + strBasisTenor,
ForwardLabel.Create (
strCurrency,
strBasisTenor
),
valParams,
null,
mktParams,
null,
MultiSegmentSequenceBuilder.BASIS_SPLINE_KLK_HYPERBOLIC_TENSION,
new ExponentialTensionSetParams (1.),
aFFC,
strManifestMeasure,
adblxM6MBasisSwapQuote,
dblStartingFwd
);
mapForward.put (
"KLKHYPER_FWD" + strBasisTenor,
fcxMKLKHyper
);
/*
* Set the discount curve + hyperbolic tension forward curve based component market parameters.
*/
CurveSurfaceQuoteContainer mktParamsKLKHyperFwd = MarketParamsBuilder.Create (
dc,
fcxMKLKHyper,
null,
null,
null,
null,
null,
null
);
int i = 0;
int iFreq = 12 / iTenorInMonths;
/*
* Compute the following forward curve metrics for each of cubic polynomial forward, quartic
* polynomial forward, and KLK Hyperbolic tension forward curves:
* - Reference Basis Par Spread
* - Derived Basis Par Spread
*
* Further compare these with a) the forward rate off of the discount curve, b) the LIBOR rate, and
* c) Input Basis Swap Quote.
*/
for (String strMaturityTenor : astrxM6MFwdTenor) {
int iFwdEndDate = dtSpot.addTenor (strMaturityTenor).julian();
int iFwdStartDate = dtSpot.addTenor (strMaturityTenor).subtractTenor (strBasisTenor).julian();
FloatFloatComponent ffc = aFFC[i++];
CaseInsensitiveTreeMap<Double> mapCubicValue = ffc.value (
valParams,
null,
mktParamsCubicFwd,
null
);
CaseInsensitiveTreeMap<Double> mapQuarticValue = ffc.value (
valParams,
null,
mktParamsQuarticFwd,
null
);
CaseInsensitiveTreeMap<Double> mapKLKHyperValue = ffc.value (
valParams,
null,
mktParamsKLKHyperFwd,
null
);
System.out.println (" " + strMaturityTenor + " => " +
FormatUtil.FormatDouble (fcxMCubic.forward (iFwdEndDate), 2, 2, 100.) + " | " +
FormatUtil.FormatDouble (mapCubicValue.get ("ReferenceParBasisSpread"), 2, 2, 1.) + " | " +
FormatUtil.FormatDouble (mapCubicValue.get ("DerivedParBasisSpread"), 2, 2, 1.) + " | " +
FormatUtil.FormatDouble (fcxMQuartic.forward (iFwdEndDate), 2, 2, 100.) + " | " +
FormatUtil.FormatDouble (mapQuarticValue.get ("ReferenceParBasisSpread"), 2, 2, 1.) + " | " +
FormatUtil.FormatDouble (mapQuarticValue.get ("DerivedParBasisSpread"), 2, 2, 1.) + " | " +
FormatUtil.FormatDouble (fcxMKLKHyper.forward (iFwdEndDate), 2, 2, 100.) + " | " +
FormatUtil.FormatDouble (mapKLKHyperValue.get ("ReferenceParBasisSpread"), 2, 2, 1.) + " | " +
FormatUtil.FormatDouble (mapKLKHyperValue.get ("DerivedParBasisSpread"), 2, 2, 1.) + " | " +
FormatUtil.FormatDouble (iFreq * java.lang.Math.log (dc.df (iFwdStartDate) / dc.df (iFwdEndDate)), 1, 2, 100.) + " | " +
FormatUtil.FormatDouble (dc.libor (iFwdStartDate, iFwdEndDate), 1, 2, 100.) + " | "
);
}
return mapForward;
}
/*
* This sample illustrates how to build and test the forward curves across various tenor basis. It shows
* the following steps:
* - Construct the Discount Curve using its instruments and quotes.
* - Build and run the sampling for the 1M-6M Tenor Basis Swap from its instruments and quotes.
* - Build and run the sampling for the 3M-6M Tenor Basis Swap from its instruments and quotes.
* - Build and run the sampling for the 12M-6M Tenor Basis Swap from its instruments and quotes.
*
* USE WITH CARE: This sample ignores errors and does not handle exceptions.
*/
private static final void CustomForwardCurveBuilderSample (
final String strManifestMeasure)
throws Exception
{
String strCurrency = "USD";
JulianDate dtToday = DateUtil.Today().addTenor ("0D");
/*
* Construct the Discount Curve using its instruments and quotes
*/
MergedDiscountForwardCurve dc = MakeDC (
dtToday,
strCurrency,
0.
);
System.out.println ("\n-----------------------------------------------------------------------------------------------------------------------------");
System.out.println ("--------------------------------------------------- 1M-6M Basis Swap --------------------------------------------------");
/*
* Build and run the sampling for the 1M-6M Tenor Basis Swap from its instruments and quotes.
*/
xM6MBasisSample (
dtToday,
strCurrency,
dc,
1,
new String[] {
"1Y", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y"
},
strManifestMeasure,
new double[] {
0.00551, // 1Y
0.00387, // 2Y
0.00298, // 3Y
0.00247, // 4Y
0.00211, // 5Y
0.00185, // 6Y
0.00165, // 7Y
0.00150, // 8Y
0.00137, // 9Y
0.00127, // 10Y
0.00119, // 11Y
0.00112, // 12Y
0.00096, // 15Y
0.00079, // 20Y
0.00069, // 25Y
0.00062 // 30Y
}
);
/*
* Build and run the sampling for the 3M-6M Tenor Basis Swap from its instruments and quotes.
*/
System.out.println ("\n-----------------------------------------------------------------------------------------------------------------------------");
System.out.println ("--------------------------------------------------- 3M-6M Basis Swap --------------------------------------------------");
xM6MBasisSample (
dtToday,
strCurrency,
dc,
3,
new String[] {
"1Y", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y"
},
strManifestMeasure,
new double[] {
0.00186, // 1Y
0.00127, // 2Y
0.00097, // 3Y
0.00080, // 4Y
0.00067, // 5Y
0.00058, // 6Y
0.00051, // 7Y
0.00046, // 8Y
0.00042, // 9Y
0.00038, // 10Y
0.00035, // 11Y
0.00033, // 12Y
0.00028, // 15Y
0.00022, // 20Y
0.00020, // 25Y
0.00018 // 30Y
}
);
/*
* Build and run the sampling for the 12M-6M Tenor Basis Swap from its instruments and quotes.
*/
System.out.println ("\n-----------------------------------------------------------------------------------------------------------------------------");
System.out.println ("--------------------------------------------------- 12M-6M Basis Swap --------------------------------------------------");
xM6MBasisSample (
dtToday,
strCurrency,
dc,
12,
new String[] {
"1Y", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y",
"35Y", "40Y" // Extrapolated
},
strManifestMeasure,
new double[] {
-0.00212, // 1Y
-0.00152, // 2Y
-0.00117, // 3Y
-0.00097, // 4Y
-0.00082, // 5Y
-0.00072, // 6Y
-0.00063, // 7Y
-0.00057, // 8Y
-0.00051, // 9Y
-0.00047, // 10Y
-0.00044, // 11Y
-0.00041, // 12Y
-0.00035, // 15Y
-0.00028, // 20Y
-0.00025, // 25Y
-0.00022, // 30Y
-0.00022, // 35Y Extrapolated
-0.00022, // 40Y Extrapolated
}
);
}
public static final void main (
final String[] astrArgs)
throws Exception
{
/*
* Initialize the Credit Analytics Library
*/
EnvManager.InitEnv ("");
System.out.println ("\n-----------------------------------------------------------------------------------------------------------------------------");
System.out.println ("-----------------------------------------------------------------------------------------------------------------------------");
System.out.println ("----------------------------------------------- BASIS ON THE DERIVED LEG -----------------------------------------------");
System.out.println ("-----------------------------------------------------------------------------------------------------------------------------");
CustomForwardCurveBuilderSample ("DerivedParBasisSpread");
System.out.println ("\n-----------------------------------------------------------------------------------------------------------------------------");
System.out.println ("-----------------------------------------------------------------------------------------------------------------------------");
System.out.println ("---------------------------------------------- BASIS ON THE REFERENCE LEG ----------------------------------------------");
System.out.println ("-----------------------------------------------------------------------------------------------------------------------------");
CustomForwardCurveBuilderSample ("ReferenceParBasisSpread");
}
}
| 31.567358 | 153 | 0.621994 |
cadf401857f720be9e13172f549be55d1d38a771 | 395 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.viejar.viejamedi.security.service;
import javax.enterprise.context.ApplicationScoped;
/**
*
* @author Administrador
*/
@ApplicationScoped
public class PasswordEncrypt {
}
| 21.944444 | 80 | 0.718987 |
c98a620409d6feff0b46171f87901f12d0b2f8d5 | 6,164 | /**
*
* Licensed Property to China UnionPay Co., Ltd.
*
* (C) Copyright of China UnionPay Co., Ltd. 2010
* All Rights Reserved.
*
*
* Modification History:
* =============================================================================
* Author Date Description
* ------------ ---------- ---------------------------------------------------
* xshu 2014-05-28 证书工具类.
* =============================================================================
*/
package com.egzosn.pay.common.util.sign;
import com.egzosn.pay.common.util.str.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.util.*;
/**
* acpsdk证书工具类,主要用于对证书的加载和使用
* date 2016-7-22 下午2:46:20
* 声明:以下代码只是为了方便接入方测试而提供的样例代码,商户可以根据自己需要,按照技术文档编写。该代码仅供参考,不提供编码,性能,规范性等方面的保障
*/
public class CertDescriptor {
protected static final Log LOG = LogFactory.getLog(CertDescriptor.class);
/** 证书容器,存储对商户请求报文签名私钥证书. */
private KeyStore keyStore = null;
/** 验签公钥/中级证书 */
private X509Certificate publicKeyCert = null;
/** 验签根证书 */
private X509Certificate rootKeyCert = null;
/**
* 通过证书路径初始化为公钥证书
* @param path 证书地址
* @return X509 证书
*/
private static X509Certificate initCert(String path) {
X509Certificate encryptCertTemp = null;
CertificateFactory cf = null;
FileInputStream in = null;
try {
cf = CertificateFactory.getInstance("X.509");
in = new FileInputStream(path);
encryptCertTemp = (X509Certificate) cf.generateCertificate(in);
// 打印证书加载信息,供测试阶段调试
if (LOG.isWarnEnabled()) {
LOG.warn("[" + path + "][CertId=" + encryptCertTemp.getSerialNumber().toString() + "]");
}
} catch (CertificateException e) {
LOG.error("InitCert Error", e);
} catch (FileNotFoundException e) {
LOG.error("InitCert Error File Not Found", e);
}finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
LOG.error(e.toString());
}
}
}
return encryptCertTemp;
}
/**
* 通过keyStore 获取私钥签名证书PrivateKey对象
*
* @param pwd 证书对应密码
* @return PrivateKey 私钥
*/
public PrivateKey getSignCertPrivateKey(String pwd) {
try {
Enumeration<String> aliasenum = keyStore.aliases();
String keyAlias = null;
if (aliasenum.hasMoreElements()) {
keyAlias = aliasenum.nextElement();
}
PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias,
pwd.toCharArray());
return privateKey;
} catch (KeyStoreException e) {
LOG.error("getSignCertPrivateKey Error", e);
return null;
} catch (UnrecoverableKeyException e) {
LOG.error("getSignCertPrivateKey Error", e);
return null;
} catch (NoSuchAlgorithmException e) {
LOG.error("getSignCertPrivateKey Error", e);
return null;
}
}
/**
* 配置的签名私钥证书certId
*
* @return 证书的物理编号
*/
public String getSignCertId() {
try {
Enumeration<String> aliasenum = keyStore.aliases();
String keyAlias = null;
if (aliasenum.hasMoreElements()) {
keyAlias = aliasenum.nextElement();
}
X509Certificate cert = (X509Certificate) keyStore
.getCertificate(keyAlias);
return cert.getSerialNumber().toString();
} catch (Exception e) {
LOG.error("getSignCertId Error", e);
return null;
}
}
/**
* 将签名私钥证书文件读取为证书存储对象
*
* @param signCertPath 证书文件名
* @param signCertPwd 证书密码
* @param signCertType 证书类型
*/
public void initPrivateSignCert(String signCertPath, String signCertPwd, String signCertType) {
if (null != keyStore) {
keyStore = null;
}
try {
keyStore = getKeyInfo(signCertPath, signCertPwd,signCertType);
if (LOG.isInfoEnabled()) {
LOG.info("InitSignCert Successful. CertId=[" + getSignCertId() + "]");
}
} catch (IOException e) {
LOG.error("InitSignCert Error", e);
}
}
/**
* 将签名私钥证书文件读取为证书存储对象
*
* @param pfxkeyfile 证书文件名
* @param keypwd 证书密码
* @param type 证书类型
* @return 证书对象
* @throws IOException
*/
private KeyStore getKeyInfo(String pfxkeyfile, String keypwd, String type) throws IOException {
if (LOG.isWarnEnabled()) {
LOG.warn("加载签名证书==>" + pfxkeyfile);
}
try(FileInputStream fis = new FileInputStream(pfxkeyfile);) {
KeyStore ks = KeyStore.getInstance(type);
if (LOG.isWarnEnabled()) {
LOG.warn("Load RSA CertPath=[" + pfxkeyfile + "],Pwd=["+ keypwd + "],type=["+type+"]");
}
char[] nPassword = null;
nPassword = null == keypwd || "".equals(keypwd.trim()) ? null: keypwd.toCharArray();
if (null != ks) {
ks.load(fis, nPassword);
}
return ks;
} catch (Exception e) {
LOG.error("getKeyInfo Error", e);
return null;
}
}
/**
* 通过keystore获取私钥证书的certId值
* @param keyStore
* @return
*/
private String getCertIdIdByStore(KeyStore keyStore) {
Enumeration<String> aliasenum = null;
try {
aliasenum = keyStore.aliases();
String keyAlias = null;
if (aliasenum.hasMoreElements()) {
keyAlias = aliasenum.nextElement();
}
X509Certificate cert = (X509Certificate) keyStore
.getCertificate(keyAlias);
return cert.getSerialNumber().toString();
} catch (KeyStoreException e) {
LOG.error("getCertIdIdByStore Error", e);
return null;
}
}
/**
* 加载中级证书
* @param certPath 证书地址
*/
public void initPublicCert(String certPath) {
if (!StringUtils.isEmpty(certPath)) {
publicKeyCert = initCert(certPath);
if (LOG.isInfoEnabled()) {
LOG.info("Load PublicKeyCert Successful");
}
} else if (LOG.isInfoEnabled()) {
LOG.info("PublicKeyCert is empty");
}
}
/**
* 加载根证书
* @param certPath 证书地址
*/
public void initRootCert(String certPath) {
if (!StringUtils.isEmpty(certPath)) {
rootKeyCert = initCert(certPath);
if (LOG.isInfoEnabled()) {
LOG.info("Load RootCert Successful");
}
} else if (LOG.isInfoEnabled()) {
LOG.info("RootCert is empty");
}
}
/**
* 获取公钥/中级证书
* @return X509Certificate
*/
public X509Certificate getPublicCert() {
return publicKeyCert;
}
/**
* 获取中级证书
* @return X509Certificate
*/
public X509Certificate getRootCert() {
return rootKeyCert;
}
}
| 23.891473 | 97 | 0.635788 |
af6d553e5abedd0cc8a100f9d3cb776b73fab31c | 464 | package mb.nabl2.scopegraph;
import mb.nabl2.regexp.IAlphabet;
import mb.nabl2.regexp.IRegExp;
import mb.nabl2.relations.IRelation;
public interface IResolutionParameters<L extends ILabel> {
enum Strategy {
SEARCH, ENVIRONMENTS
}
L getLabelD();
L getLabelR();
IAlphabet<L> getLabels();
IRegExp<L> getPathWf();
IRelation.Immutable<L> getSpecificityOrder();
Strategy getStrategy();
boolean getPathRelevance();
} | 17.185185 | 58 | 0.700431 |
a2afd56366c178a9cb8f7180d7b9260d276ccef6 | 4,187 | package org.diverproject.scarlet.util;
import static org.diverproject.scarlet.util.language.NumberUtilsLanguage.HAS_INTEGER_LENGTH_MINMAX;
import static org.diverproject.scarlet.util.language.StringUtilsLanguage.IS_FLOAT_NULL;
import java.util.regex.Pattern;
import org.diverproject.scarlet.Scarlet;
import org.diverproject.scarlet.util.exceptions.NumberUtilsRuntimeException;
import org.diverproject.scarlet.util.exceptions.StringUtilsRuntimeException;
public class NumberUtils
{
public static final int DECIMAL_DOT_TYPE = 1;
public static final int DECIMAL_COMMA_TYPE = 2;
public static final int DECIMAL_ANY_TYPE = DECIMAL_DOT_TYPE | DECIMAL_COMMA_TYPE;
public static final String INTEGER_REGEX = "^[-+]?(0|[1-9][0-9]*)$";
public static final String COMMA_OR_DOT_REGEX = "[,.]";
public static final String FLOAT_REGEX = "^(?<signal>[+-]?)(?<value>\\d+[{DecimalType}]{1}\\d*|\\d*[{DecimalType}]\\d+|\\d+)(?<expoent>$|[eE](?<expoentSignal>[+-]?)(?<expoentValue>[\\d]+)$)";
public static final String FLOAT_ANY_REGEX = FLOAT_REGEX.replace("{DecimalType}", ".,");
public static final String FLOAT_DOT_REGEX = FLOAT_REGEX.replace("{DecimalType}", ".");
public static final String FLOAT_COMMA_REGEX = FLOAT_REGEX.replace("{DecimalType}", ",");
public static final Pattern PATTERN_ANY = Pattern.compile(FLOAT_ANY_REGEX);
public static final Pattern PATTERN_DOT = Pattern.compile(FLOAT_DOT_REGEX);
public static final Pattern PATTERN_COMMA = Pattern.compile(FLOAT_COMMA_REGEX);
public static final int COMPARE_FAILURE = 0;
public static final int COMPARE_EQUALS = 1;
public static final int COMPARE_MAJOR = 2;
public static final int COMPARE_MINOR = 3;
public static final int BITS_ON_BYTE = 8;
NumberUtils()
{
}
public static boolean hasIntegerFormat(String str)
{
return str.matches(NumberUtils.INTEGER_REGEX);
}
static Pattern getPattern()
{
return getPattern(Scarlet.getInstance().getFloatType());
}
static Pattern getPattern(int value)
{
if (BitwiseUtils.has(value, DECIMAL_DOT_TYPE) && !BitwiseUtils.has(value, DECIMAL_COMMA_TYPE))
return PATTERN_DOT;
if (BitwiseUtils.has(value, DECIMAL_COMMA_TYPE) && !BitwiseUtils.has(value, DECIMAL_DOT_TYPE))
return PATTERN_COMMA;
return PATTERN_ANY;
}
public static boolean isFloatFormat(String str)
{
return hasFloatFormat(str, Scarlet.getInstance().getFloatType());
}
public static boolean hasFloatFormat(String str, int floatType)
{
if (str == null)
throw new StringUtilsRuntimeException(IS_FLOAT_NULL);
return getPattern(floatType).matcher(str).find();
}
public static boolean hasFloatPrecision(String str, int precision)
{
if (!isFloatFormat(str))
return false;
if (str.charAt(0) == '+' || str.charAt(0) == '-')
str = str.substring(1);
str = str.replaceFirst(COMMA_OR_DOT_REGEX, "");
return str.length() <= precision;
}
public static boolean isNumeric(char c)
{
return c >= '0' && c <= '9';
}
public static int compareStringNumber(String str, String str2)
{
if (!hasIntegerFormat(str) || !hasIntegerFormat(str2))
return COMPARE_FAILURE;
if (str.charAt(0) == '-' && str2.charAt(0) != '-')
return COMPARE_MINOR;
if (str2.charAt(0) == '-' && str.charAt(0) != '-')
return COMPARE_MAJOR;
if (str.charAt(0) == '-' && str2.charAt(0) == '-')
{
str = str.substring(1);
str2 = str2.substring(1);
String aux = str;
str = str2;
str2 = aux;
}
else
{
if (str.charAt(0) == '+')
str = str.substring(1);
if (str2.charAt(0) == '+')
str2 = str2.substring(1);
}
int compare = str.length() > str2.length() ? 1 : (str.length() < str2.length() ? -1 : str.compareTo(str2));
return compare < 0 ? COMPARE_MINOR : (compare > 0 ? COMPARE_MAJOR : COMPARE_EQUALS);
}
public static boolean hasNumberRange(String str, long minValue, long maxValue)
{
if (minValue > maxValue)
throw new NumberUtilsRuntimeException(HAS_INTEGER_LENGTH_MINMAX, minValue, maxValue);
return ArrayUtils.in(compareStringNumber(str, Long.toString(minValue)),
COMPARE_EQUALS, COMPARE_MAJOR
) && ArrayUtils.in(compareStringNumber(str, Long.toString(maxValue)),
COMPARE_EQUALS, COMPARE_MINOR
);
}
}
| 30.562044 | 192 | 0.716742 |
ba741d9fb06567b48555d71dbd18301b16529cff | 3,814 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual 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 org.hibernate.validator.internal.cfg.context;
import java.util.Set;
import javax.validation.ParameterNameProvider;
import org.hibernate.validator.cfg.ConstraintMapping;
import org.hibernate.validator.cfg.context.TypeConstraintMappingContext;
import org.hibernate.validator.internal.metadata.core.AnnotationProcessingOptionsImpl;
import org.hibernate.validator.internal.metadata.core.ConstraintHelper;
import org.hibernate.validator.internal.metadata.raw.BeanConfiguration;
import org.hibernate.validator.internal.util.Contracts;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import static org.hibernate.validator.internal.util.CollectionHelper.newHashSet;
import static org.hibernate.validator.internal.util.logging.Messages.MESSAGES;
/**
* Default implementation of {@link ConstraintMapping}.
*
* @author Hardy Ferentschik
* @author Gunnar Morling
* @author Kevin Pollet <kevin.pollet@serli.com> (C) 2011 SERLI
*/
public class DefaultConstraintMapping implements ConstraintMapping {
private static final Log log = LoggerFactory.make();
private final AnnotationProcessingOptionsImpl annotationProcessingOptions;
private final Set<Class<?>> configuredTypes;
private final Set<TypeConstraintMappingContextImpl<?>> typeContexts;
public DefaultConstraintMapping() {
this.annotationProcessingOptions = new AnnotationProcessingOptionsImpl();
this.configuredTypes = newHashSet();
this.typeContexts = newHashSet();
}
@Override
public final <C> TypeConstraintMappingContext<C> type(Class<C> type) {
Contracts.assertNotNull( type, MESSAGES.beanTypeMustNotBeNull() );
if ( configuredTypes.contains( type ) ) {
throw log.getBeanClassHasAlreadyBeConfiguredViaProgrammaticApiException( type.getName() );
}
TypeConstraintMappingContextImpl<C> typeContext = new TypeConstraintMappingContextImpl<C>( this, type );
typeContexts.add( typeContext );
configuredTypes.add( type );
return typeContext;
}
public final AnnotationProcessingOptionsImpl getAnnotationProcessingOptions() {
return annotationProcessingOptions;
}
public Set<Class<?>> getConfiguredTypes() {
return configuredTypes;
}
/**
* Returns all bean configurations configured through this constraint mapping.
*
* @param constraintHelper constraint helper required for building constraint descriptors
* @param parameterNameProvider parameter name provider required for building parameter elements
*
* @return a set of {@link BeanConfiguration}s with an element for each type configured through this mapping
*/
public Set<BeanConfiguration<?>> getBeanConfigurations(ConstraintHelper constraintHelper, ParameterNameProvider parameterNameProvider) {
Set<BeanConfiguration<?>> configurations = newHashSet();
for ( TypeConstraintMappingContextImpl<?> typeContext : typeContexts ) {
configurations.add( typeContext.build( constraintHelper, parameterNameProvider ) );
}
return configurations;
}
}
| 39.319588 | 137 | 0.79549 |
b5ac657f9f61386f6f533783933105b747771e6b | 671 | package com.elseytd.theaurorian.Blocks;
import com.elseytd.theaurorian.TAMod;
import net.minecraft.block.BlockPane;
import net.minecraft.block.material.Material;
public class TABlock_DungeonStoneBars extends BlockPane {
public static final String BLOCKNAME_RUNESTONE = "runestonebars";
public static final String BLOCKNAME_MOONTEMPLE = "moontemplebars";
public TABlock_DungeonStoneBars(String blockname) {
super(Material.IRON, false);
this.setBlockUnbreakable();
this.setResistance(6000000.0F);
this.setCreativeTab(TAMod.CREATIVE_TAB);
this.setRegistryName(blockname);
this.setUnlocalizedName(TAMod.MODID + "." + blockname);
}
}
| 30.5 | 69 | 0.774963 |
fb3c6297764bc0c22eaf913d36b7d43f0326bae0 | 931 | /**
* 2017-10-09
*/
package test.math;
import cn.ancono.math.equation.EquationSup;
import cn.ancono.math.equation.Type;
import cn.ancono.math.numberModels.Calculators;
import cn.ancono.math.numberModels.api.RealCalculator;
import org.junit.Test;
import static cn.ancono.utilities.Printer.print;
/**
* @author liyicheng
* 2017-10-09 19:26
*
*/
public class TestEquation {
/**
*
*/
public TestEquation() {
}
RealCalculator<Double> mc = Calculators.doubleCal();
@Test
public void testSolve() {
print(EquationSup.INSTANCE.solveQuadraticInequality(1d, 2d, 1d, Type.LESS_OR_EQUAL, mc));
print(EquationSup.INSTANCE.solveQuadraticInequality(1d, -2d, -3d, Type.LESS_OR_EQUAL, mc));
print(EquationSup.INSTANCE.solveQuadraticInequality(0d, 2d, -3d, Type.GREATER, mc));
print(EquationSup.INSTANCE.solveQuadraticInequality(1d, -2d, -3d, Type.NOT_EQUAL, mc));
}
}
| 25.861111 | 99 | 0.700322 |
7de6f579a211ff0894979aad4f51703e778f6a15 | 23,645 | /*
* (C) Copyright IBM Corp. 1998-2004. All Rights Reserved.
*
* The program is provided "as is" without any warranty express or
* implied, including the warranty of non-infringement and the implied
* warranties of merchantibility and fitness for a particular purpose.
* IBM will not be liable for any damages suffered by you as a result
* of using the Program. In no event will IBM be liable for any
* special, indirect or consequential damages or lost profits even if
* IBM has been advised of the possibility of their occurrence. IBM
* will not be liable for any third party claims against you.
*/
package com.ibm.richtext.styledtext;
import com.ibm.richtext.textlayout.attributes.AttributeMap;
import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.IOException;
import java.text.CharacterIterator;
/**
* This class is an implementation of MText, a modifyable, styled text
* storage model. Additionally, it supports persistance through the
* Externalizable interface.
* @see MText
*/
/*
10/28/96 {jf} - split the character and paragraph style access and setter function around...
just to keep things interesting.
8/7/96 {jf} - moved paragraph break implementation from AbstractText into Style text.
- added countStyles, getStyles, and ReplaceStyles implementation.
8/14/96 sfb eliminated StyleSheetIterator
8/29/96 {jbr} changed iter-based replace method - doesn't call at() unless it is safe to do so
Also, added checkStartAndLimit for debugging
7/31/98 Switched from Style to AttributeMap
*/
public final class StyledText extends MText implements Externalizable
{
static final String COPYRIGHT =
"(C) Copyright IBM Corp. 1998-1999 - All Rights Reserved";
private static final int CURRENT_VERSION = 1;
private static final long serialVersionUID = 22356934;
/* unicode storage */
private MCharBuffer fCharBuffer;
/* character style storage */
private MStyleBuffer fStyleBuffer;
/* paragraph style storage */
private MParagraphBuffer fParagraphBuffer;
private transient int fTimeStamp = 0;
private transient int[] fDamagedRange = { Integer.MAX_VALUE,
Integer.MIN_VALUE };
private static class ForceModifier extends StyleModifier {
private AttributeMap fStyle = AttributeMap.EMPTY_ATTRIBUTE_MAP;
void setStyle(AttributeMap style) {
fStyle = style;
}
public AttributeMap modifyStyle(AttributeMap style) {
return fStyle;
}
}
// Keep this around foruse in replaceCharStylesWith. OK since
// this class isn't threadsafe anyway.
private transient ForceModifier forceModifier = null;
//======================================================
// CONSTRUCTORS
//======================================================
/**
* Create an empty text object.
*/
public StyledText()
{
this(0);
}
/**
* Create an empty text object ready to hold at least capacity chars.
* @param capacity the minimum capacity of the internal text buffer
*/
public StyledText(int capacity)
{
fCharBuffer = capacity>0? new CharBuffer(capacity) : new CharBuffer();
fStyleBuffer = new StyleBuffer(this, AttributeMap.EMPTY_ATTRIBUTE_MAP);
fParagraphBuffer = new ParagraphBuffer(fCharBuffer);
}
/**
* Create a text object with the characters in the string,
* in the given style.
* @param string the initial contents
* @param initialStyle the style of the initial text
*/
public StyledText(String string, AttributeMap initialStyle)
{
fCharBuffer = new CharBuffer(string.length());
fCharBuffer.replace(0, 0, string, 0, string.length());
fStyleBuffer = new StyleBuffer(this, initialStyle);
fParagraphBuffer = new ParagraphBuffer(fCharBuffer);
}
/**
* Create a text object from the given source.
* @param source the text to copy
*/
public StyledText(MConstText source) {
this();
append(source);
}
/**
* Create a text object from a subrange of the given source.
* @param source the text to copy from
* @param srcStart the index of the first character to copy
* @param srcLimit the index after the last character to copy
*/
public StyledText(MConstText source, int srcStart, int srcLimit) {
this();
replace(0, 0, source, srcStart, srcLimit);
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(CURRENT_VERSION);
out.writeObject(fCharBuffer);
out.writeObject(fStyleBuffer);
out.writeObject(fParagraphBuffer);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
int version = in.readInt();
if (version != CURRENT_VERSION) {
throw new IOException("Invalid version of StyledText: " + version);
}
fCharBuffer = (MCharBuffer) in.readObject();
fStyleBuffer = (MStyleBuffer) in.readObject();
fParagraphBuffer = (MParagraphBuffer) in.readObject();
resetDamagedRange();
}
//======================================================
// MConstText INTERFACES
//======================================================
//--------------------------------------------------------
// character access
//--------------------------------------------------------
/**
* Return the character at offset <code>pos</code>.
* @param pos a valid offset into the text
* @return the character at offset <code>pos</code>
*/
public char at(int pos)
{
return fCharBuffer.at(pos);
}
/**
* Copy the characters in the range [<code>start</code>, <code>limit</code>)
* into the array <code>dst</code>, beginning at <code>dstStart</code>.
* @param start offset of first character which will be copied into the array
* @param limit offset immediately after the last character which will be copied into the array
* @param dst array in which to copy characters. The length of <code>dst</code> must be at least
* (<code>dstStart + limit - start</code>).
*/
public void extractChars(int start, int limit, char[] dst, int dstStart)
{
fCharBuffer.at(start, limit, dst, dstStart);
}
//-------------------------------------------------------
// text model creation
//-------------------------------------------------------
/**
* Create an MConstText containing the characters and styles in the range
* [<code>start</code>, <code>limit</code>).
* @param start offset of first character in the new text
* @param limit offset immediately after the last character in the new text
* @return an MConstText object containing the characters and styles in the given range
*/
public MConstText extract(int start, int limit)
{
return extractWritable(start, limit);
}
/**
* Create an MText containing the characters and styles in the range
* [<code>start</code>, <code>limit</code>).
* @param start offset of first character in the new text
* @param limit offset immediately after the last character in the new text
* @return an MConstText object containing the characters and styles in the given range
*/
public MText extractWritable(int start, int limit)
{
MText text = new StyledText();
text.replace(0, 0, this, start, limit);
text.resetDamagedRange();
return text;
}
//--------------------------------------------------------
// size/capacity
//--------------------------------------------------------
/**
* Return the length of the MConstText object. The length is the number of characters in the text.
* @return the length of the MConstText object
*/
public int length()
{
return fCharBuffer.length();
}
/**
* Create a <code>CharacterIterator</code> over the range [<code>start</code>, <code>limit</code>).
* @param start the beginning of the iterator's range
* @param limit the limit of the iterator's range
* @return a valid <code>CharacterIterator</code> over the specified range
* @see java.text.CharacterIterator
*/
public CharacterIterator createCharacterIterator(int start, int limit)
{
return fCharBuffer.createCharacterIterator(start, limit);
}
//--------------------------------------------------------
// character styles
//--------------------------------------------------------
/**
* Return the index of the first character in the character style run
* containing pos. All characters in a style run have the same character
* style.
* @return the style at offset <code>pos</code>
*/
public int characterStyleStart(int pos) {
checkPos(pos, LESS_THAN_LENGTH);
return fStyleBuffer.styleStart(pos);
}
/**
* Return the index after the last character in the character style run
* containing pos. All characters in a style run have the same character
* style.
* @return the style at offset <code>pos</code>
*/
public int characterStyleLimit(int pos) {
checkPos(pos, NOT_GREATER_THAN_LENGTH);
return fStyleBuffer.styleLimit(pos);
}
/**
* Return the style applied to the character at offset <code>pos</code>.
* @param pos a valid offset into the text
* @return the style at offset <code>pos</code>
*/
public AttributeMap characterStyleAt(int pos)
{
checkPos(pos, NOT_GREATER_THAN_LENGTH);
return fStyleBuffer.styleAt(pos);
}
//--------------------------------------------------------
// paragraph boundaries and styles
//--------------------------------------------------------
/**
* Return the start of the paragraph containing the character at offset <code>pos</code>.
* @param pos a valid offset into the text
* @return the start of the paragraph containing the character at offset <code>pos</code>
*/
public int paragraphStart(int pos)
{
checkPos(pos, NOT_GREATER_THAN_LENGTH);
return fParagraphBuffer.paragraphStart(pos);
}
/**
* Return the limit of the paragraph containing the character at offset <code>pos</code>.
* @param pos a valid offset into the text
* @return the limit of the paragraph containing the character at offset <code>pos</code>
*/
public int paragraphLimit(int pos)
{
checkPos(pos, NOT_GREATER_THAN_LENGTH);
return fParagraphBuffer.paragraphLimit(pos);
}
/**
* Return the paragraph style applied to the paragraph containing offset <code>pos</code>.
* @param pos a valid offset into the text
* @return the paragraph style in effect at <code>pos</code>
*/
public AttributeMap paragraphStyleAt(int pos)
{
checkPos(pos, NOT_GREATER_THAN_LENGTH);
return fParagraphBuffer.paragraphStyleAt(pos);
}
/**
* Return the current time stamp. The time stamp is
* incremented whenever the contents of the MConstText changes.
* @return the current paragraph style time stamp
*/
public int getTimeStamp() {
return fTimeStamp;
}
//======================================================
// MText INTERFACES
//======================================================
//--------------------------------------------------------
// character modfication functions
//--------------------------------------------------------
private void updateDamagedRange(int deleteStart,
int deleteLimit,
int insertLength) {
fDamagedRange[0] = Math.min(fDamagedRange[0], deleteStart);
if (fDamagedRange[1] >= deleteLimit) {
int lengthChange = insertLength - (deleteLimit-deleteStart);
fDamagedRange[1] += lengthChange;
}
else {
fDamagedRange[1] = deleteStart + insertLength;
}
}
/**
* Replace the characters and styles in the range [<code>start</code>, <code>limit</code>) with the characters
* and styles in <code>srcText</code> in the range [<code>srcStart</code>, <code>srcLimit</code>). <code>srcText</code> is not
* modified.
* @param start the offset at which the replace operation begins
* @param limit the offset at which the replace operation ends. The character and style at
* <code>limit</code> is not modified.
* @param text the source for the new characters and styles
* @param srcStart the offset into <code>srcText</code> where new characters and styles will be obtained
* @param srcLimit the offset into <code>srcText</code> where the new characters and styles end
*/
public void replace(int start, int limit, MConstText text, int srcStart, int srcLimit)
{
if (text == this) {
text = new StyledText(text);
}
if (start == limit && srcStart == srcLimit) {
return;
}
checkStartLimit(start, limit);
updateDamagedRange(start, limit, srcLimit-srcStart);
fCharBuffer.replace(start, limit, text, srcStart, srcLimit);
fStyleBuffer.replace(start, limit, text, srcStart, srcLimit);
fParagraphBuffer.replace(start, limit, text, srcStart, srcLimit, fDamagedRange);
fTimeStamp += 1;
}
/**
* Replace the characters and styles in the range [<code>start</code>, <code>limit</code>) with the characters
* and styles in <code>srcText</code>. <code>srcText</code> is not
* modified.
* @param start the offset at which the replace operation begins
* @param limit the offset at which the replace operation ends. The character and style at
* <code>limit</code> is not modified.
* @param text the source for the new characters and styles
*/
public void replace(int start, int limit, MConstText text) {
replace(start, limit, text, 0, text.length());
}
/**
* Replace the characters in the range [<code>start</code>, <code>limit</code>) with the characters
* in <code>srcChars</code> in the range [<code>srcStart</code>, <code>srcLimit</code>). New characters take on the style
* <code>charsStyle</code>.
* <code>srcChars</code> is not modified.
* @param start the offset at which the replace operation begins
* @param limit the offset at which the replace operation ends. The character at
* <code>limit</code> is not modified.
* @param srcChars the source for the new characters
* @param srcStart the offset into <code>srcChars</code> where new characters will be obtained
* @param srcLimit the offset into <code>srcChars</code> where the new characters end
* @param charsStyle the style of the new characters
*/
public void replace(int start, int limit, char[] srcChars, int srcStart, int srcLimit, AttributeMap charsStyle)
{
checkStartLimit(start, limit);
if (start == limit && srcStart == srcLimit) {
return;
}
updateDamagedRange(start, limit, srcLimit-srcStart);
fCharBuffer.replace(start, limit, srcChars, srcStart, srcLimit);
replaceCharStylesWith(start, limit, start + (srcLimit-srcStart), charsStyle);
fParagraphBuffer.deleteText(start, limit, fDamagedRange);
fParagraphBuffer.insertText(start, srcChars, srcStart, srcLimit);
fTimeStamp += 1;
}
private void replaceCharStylesWith(int start, int oldLimit, int newLimit, AttributeMap style) {
if (start < oldLimit) {
fStyleBuffer.deleteText(start, oldLimit);
}
if (start < newLimit) {
if (forceModifier == null) {
forceModifier = new ForceModifier();
}
forceModifier.setStyle(style);
fStyleBuffer.insertText(start, newLimit);
fStyleBuffer.modifyStyles(start, newLimit, forceModifier, null);
}
}
/**
* Replace the characters in the range [<code>start</code>, <code>limit</code>) with the character <code>srcChar</code>.
* The new character takes on the style <code>charStyle</code>
* @param start the offset at which the replace operation begins
* @param limit the offset at which the replace operation ends. The character at
* <code>limit</code> is not modified.
* @param srcChar the new character
* @param charStyle the style of the new character
*/
public void replace(int start, int limit, char srcChar, AttributeMap charStyle)
{
checkStartLimit(start, limit);
updateDamagedRange(start, limit, 1);
fCharBuffer.replace(start, limit, srcChar);
replaceCharStylesWith(start, limit, start + 1, charStyle);
if (start < limit) {
fParagraphBuffer.deleteText(start, limit, fDamagedRange);
}
fParagraphBuffer.insertText(start, srcChar);
fTimeStamp += 1;
}
/**
* Replace the entire contents of this MText (both characters and styles) with
* the contents of <code>srcText</code>.
* @param srcText the source for the new characters and styles
*/
public void replaceAll(MConstText srcText)
{
replace(0, length(), srcText, 0, srcText.length());
}
/**
* Insert the contents of <code>srcText</code> (both characters and styles) into this
* MText at the position specified by <code>pos</code>.
* @param pos The character offset where the new text is to be inserted.
* @param srcText The text to insert.
*/
public void insert(int pos, MConstText srcText)
{
replace(pos, pos, srcText, 0, srcText.length());
}
/**
* Append the contents of <code>srcText</code> (both characters and styles) to the
* end of this MText.
* @param srcText The text to append.
*/
public void append(MConstText srcText)
{
replace(length(), length(), srcText, 0, srcText.length());
}
/**
* Delete the specified range of characters (and styles).
* @param start Offset of the first character to delete.
* @param limit Offset of the first character after the range to delete.
*/
public void remove(int start, int limit)
{
replace(start, limit, (char[])null, 0, 0, AttributeMap.EMPTY_ATTRIBUTE_MAP);
}
/**
* Delete all characters and styles. Always increments time stamp.
*/
public void remove()
{
// rather than going through replace(), just reinitialize the StyledText,
// letting the old data structures fall on the floor
fCharBuffer = new CharBuffer();
fStyleBuffer = new StyleBuffer(this, AttributeMap.EMPTY_ATTRIBUTE_MAP);
fParagraphBuffer = new ParagraphBuffer(fCharBuffer);
fTimeStamp += 1;
fDamagedRange[0] = fDamagedRange[1] = 0;
}
//--------------------------------------------------------
// storage management
//--------------------------------------------------------
/**
* Minimize the amount of memory used by the MText object.
*/
public void compress() {
fCharBuffer.compress();
fStyleBuffer.compress();
fParagraphBuffer.compress();
}
//--------------------------------------------------------
// style modification
//--------------------------------------------------------
/**
* Set the style of all characters in the MText object to
* <code>AttributeMap.EMPTY_ATTRIBUTE_MAP</code>.
*/
public void removeCharacterStyles() {
fStyleBuffer = new StyleBuffer(this, AttributeMap.EMPTY_ATTRIBUTE_MAP);
fTimeStamp += 1;
fDamagedRange[0] = 0;
fDamagedRange[1] = length();
}
/**
* Invoke the given modifier on all character styles from start to limit.
* @param modifier the modifier to apply to the range.
* @param start the start of the range of text to modify.
* @param limit the limit of the range of text to modify.
*/
public void modifyCharacterStyles(int start, int limit, StyleModifier modifier) {
checkStartLimit(start, limit);
boolean modified = fStyleBuffer.modifyStyles(start,
limit,
modifier,
fDamagedRange);
if (modified) {
fTimeStamp += 1;
}
}
/**
* Invoke the given modifier on all paragraph styles in paragraphs
* containing characters in the range [start, limit).
* @param modifier the modifier to apply to the range.
* @param start the start of the range of text to modify.
* @param limit the limit of the range of text to modify.
*/
public void modifyParagraphStyles(int start, int limit, StyleModifier modifier) {
checkStartLimit(start, limit);
boolean modified = fParagraphBuffer.modifyParagraphStyles(start,
limit,
modifier,
fDamagedRange);
if (modified) {
fTimeStamp += 1;
}
}
/**
* Reset the damaged range to an empty interval, and begin accumulating the damaged
* range. The damaged range includes every index where a character, character style,
* or paragraph style has changed.
* @see #damagedRangeStart
* @see #damagedRangeLimit
*/
public void resetDamagedRange() {
fDamagedRange[0] = Integer.MAX_VALUE;
fDamagedRange[1] = Integer.MIN_VALUE;
}
/**
* Return the start of the damaged range.
* If the start is
* <code>Integer.MAX_VALUE</code> and the limit is
* <code>Integer.MIN_VALUE</code>, then the damaged range
* is empty.
* @return the start of the damaged range
* @see #damagedRangeLimit
* @see #resetDamagedRange
*/
public int damagedRangeStart() {
return fDamagedRange[0];
}
/**
* Return the limit of the damaged range.
* If the start is
* <code>Integer.MAX_VALUE</code> and the limit is
* <code>Integer.MIN_VALUE</code>, then the damaged range
* is empty.
* @return the limit of the damaged range
* @see #damagedRangeStart
* @see #resetDamagedRange
*/
public int damagedRangeLimit() {
return fDamagedRange[1];
}
public String toString()
{
String result ="";
for (int i = 0; i < length(); i++) {
result += at(i);
}
return result;
}
//======================================================
// IMPLEMENTATION
//======================================================
/* check a range to see if it is well formed and within the bounds of the text */
private void checkStartLimit(int start, int limit)
{
if (start > limit) {
//System.out.println("Start is less than limit. start:"+start+"; limit:"+limit);
throw new IllegalArgumentException("Start is greater than limit. start:"+start+"; limit:"+limit);
}
if (start < 0) {
//System.out.println("Start is negative. start:"+start);
throw new IllegalArgumentException("Start is negative. start:"+start);
}
if (limit > length()) {
//System.out.println("Limit is greater than length. limit:"+limit);
throw new IllegalArgumentException("Limit is greater than length. limit:"+limit);
}
}
private static final boolean LESS_THAN_LENGTH = false;
private static final boolean NOT_GREATER_THAN_LENGTH = true;
private void checkPos(int pos, boolean endAllowed) {
int lastValidPos = length();
if (endAllowed == LESS_THAN_LENGTH) {
--lastValidPos;
}
if (pos < 0 || pos > lastValidPos) {
throw new IllegalArgumentException("Position is out of range.");
}
}
}
| 34.518248 | 126 | 0.620131 |
8ca53b966bce7905433ab3414917f180a8be5e5a | 5,993 | /*
* Copyright 2019 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.couchbase.client.java.manager.bucket;
import com.couchbase.client.core.Core;
import com.couchbase.client.core.annotation.Stability;
import com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode;
import com.couchbase.client.core.deps.com.fasterxml.jackson.databind.node.ObjectNode;
import com.couchbase.client.core.json.Mapper;
import com.couchbase.client.core.manager.CoreBucketManager;
import com.couchbase.client.core.msg.kv.DurabilityLevel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import static com.couchbase.client.core.util.CbCollections.transformValues;
import static com.couchbase.client.java.manager.bucket.BucketType.MEMCACHED;
import static com.couchbase.client.java.manager.bucket.CreateBucketOptions.createBucketOptions;
import static com.couchbase.client.java.manager.bucket.DropBucketOptions.dropBucketOptions;
import static com.couchbase.client.java.manager.bucket.FlushBucketOptions.flushBucketOptions;
import static com.couchbase.client.java.manager.bucket.GetAllBucketOptions.getAllBucketOptions;
import static com.couchbase.client.java.manager.bucket.GetBucketOptions.getBucketOptions;
import static com.couchbase.client.java.manager.bucket.UpdateBucketOptions.updateBucketOptions;
@Stability.Volatile
public class AsyncBucketManager {
private final CoreBucketManager coreBucketManager;
public AsyncBucketManager(Core core) {
this.coreBucketManager = new CoreBucketManager(core);
}
public CompletableFuture<Void> createBucket(BucketSettings settings) {
return createBucket(settings, createBucketOptions());
}
public CompletableFuture<Void> createBucket(BucketSettings settings, CreateBucketOptions options) {
return coreBucketManager.createBucket(toMap(settings), options.build());
}
public CompletableFuture<Void> updateBucket(BucketSettings settings) {
return updateBucket(settings, updateBucketOptions());
}
public CompletableFuture<Void> updateBucket(BucketSettings settings, UpdateBucketOptions options) {
return coreBucketManager.updateBucket(toMap(settings), options.build());
}
public CompletableFuture<Void> dropBucket(String bucketName) {
return dropBucket(bucketName, dropBucketOptions());
}
public CompletableFuture<Void> dropBucket(String bucketName, DropBucketOptions options) {
return coreBucketManager.dropBucket(bucketName, options.build());
}
public CompletableFuture<BucketSettings> getBucket(String bucketName) {
return getBucket(bucketName, getBucketOptions());
}
public CompletableFuture<BucketSettings> getBucket(String bucketName, GetBucketOptions options) {
return coreBucketManager.getBucket(bucketName, options.build())
.thenApply(parseBucketSettings());
}
private static Function<byte[], BucketSettings> parseBucketSettings() {
return bucketBytes -> {
JsonNode tree = Mapper.decodeIntoTree(bucketBytes);
return BucketSettings.create(tree);
};
}
public CompletableFuture<Map<String, BucketSettings>> getAllBuckets() {
return getAllBuckets(getAllBucketOptions());
}
public CompletableFuture<Map<String, BucketSettings>> getAllBuckets(GetAllBucketOptions options) {
return coreBucketManager.getAllBuckets(options.build())
.thenApply(bucketNameToBytes -> transformValues(bucketNameToBytes, parseBucketSettings()));
}
public CompletableFuture<Void> flushBucket(String bucketName) {
return flushBucket(bucketName, flushBucketOptions());
}
public CompletableFuture<Void> flushBucket(String bucketName, FlushBucketOptions options) {
return coreBucketManager.flushBucket(bucketName, options.build());
}
private Map<String, String> toMap(BucketSettings settings) {
Map<String, String> params = new HashMap<>();
params.put("ramQuotaMB", String.valueOf(settings.ramQuotaMB()));
if (settings.bucketType() != MEMCACHED) {
params.put("replicaNumber", String.valueOf(settings.numReplicas()));
}
params.put("flushEnabled", String.valueOf(settings.flushEnabled() ? 1 : 0));
long maxTTL = settings.maxExpiry().getSeconds();
// Do not send if it's been left at default, else will get an error on CE
if (maxTTL != 0) {
params.put("maxTTL", String.valueOf(maxTTL));
}
if (settings.evictionPolicy() != null) {
// let server assign the default policy for this bucket type
params.put("evictionPolicy", settings.evictionPolicy().alias());
}
// Do not send if it's been left at default, else will get an error on CE
if (settings.compressionMode() != CompressionMode.PASSIVE) {
params.put("compressionMode", settings.compressionMode().alias());
}
if (settings.minimumDurabilityLevel() != DurabilityLevel.NONE) {
params.put("durabilityMinLevel", settings.minimumDurabilityLevel().encodeForManagementApi());
}
if(settings.storageBackend() != null) {
params.put("storageBackend",settings.storageBackend().alias());
}
params.put("name", settings.name());
params.put("bucketType", settings.bucketType().alias());
params.put("conflictResolutionType", settings.conflictResolutionType().alias());
if (settings.bucketType() != BucketType.EPHEMERAL) {
params.put("replicaIndex", String.valueOf(settings.replicaIndexes() ? 1 : 0));
}
return params;
}
}
| 41.331034 | 101 | 0.762723 |
8d93de0b3219c38984dbe0257ca9bfc0a67f65d0 | 1,040 | package seedu.ibook.model.util;
import seedu.ibook.model.IBook;
import seedu.ibook.model.ReadOnlyIBook;
import seedu.ibook.model.product.Category;
import seedu.ibook.model.product.Description;
import seedu.ibook.model.product.DiscountRate;
import seedu.ibook.model.product.DiscountStart;
import seedu.ibook.model.product.Name;
import seedu.ibook.model.product.Price;
import seedu.ibook.model.product.Product;
/**
* Contains utility methods for populating {@code IBook} with sample data.
*/
public class SampleDataUtil {
public static Product[] getSampleProducts() {
return new Product[] {
new Product(new Name("Maggie Mee"), new Category("Noodles"),
new Description(""), new Price("1.99"), new DiscountRate("25"), new DiscountStart("2"))
};
}
public static ReadOnlyIBook getSampleIBook() {
IBook sampleIb = new IBook();
for (Product sampleProduct : getSampleProducts()) {
sampleIb.addProduct(sampleProduct);
}
return sampleIb;
}
}
| 32.5 | 103 | 0.697115 |
94f1eaac04f6b8d0e544c83e995eddd4b0f2d5a3 | 2,058 | /*
* Copyright 2020 SvenAugustus
*
* 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 xyz.flysium.rs.client;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.client.spring.EnableJaxRsProxyClient;
import org.apache.cxf.jaxrs.client.spring.EnableJaxRsWebClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import xyz.flysium.api.HelloService;
/**
* Client.
*
* @author Sven Augustus
*/
@SpringBootApplication
@EnableJaxRsWebClient
@EnableJaxRsProxyClient
public class SampleRestClientApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(SampleRestClientApplication.class)
.web(WebApplicationType.NONE)
.run(args);
}
@Bean
CommandLineRunner initWebClientRunner(final WebClient webClient) {
return new CommandLineRunner() {
@Override
public void run(String... runArgs) throws Exception {
System.out.println(webClient.path("sayHello/ApacheCxfWebClientUser").get(String.class));
}
};
}
@Bean
CommandLineRunner initProxyClientRunner(final HelloService client) {
return new CommandLineRunner() {
@Override
public void run(String... runArgs) throws Exception {
System.out.println(client.sayHello("ApacheCxfProxyUser"));
}
};
}
}
| 29.826087 | 96 | 0.752672 |
e24979c34e8ed9ef0f28b0296b6375295464eff4 | 5,465 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.client.gateway.utils;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.Types;
import org.apache.flink.table.catalog.Catalog;
import org.apache.flink.table.catalog.CommonCatalogOptions;
import org.apache.flink.table.catalog.ConnectorCatalogTable;
import org.apache.flink.table.catalog.GenericInMemoryCatalog;
import org.apache.flink.table.catalog.ObjectPath;
import org.apache.flink.table.factories.CatalogFactory;
import org.apache.flink.table.sources.StreamTableSource;
import org.apache.flink.table.types.DataType;
import org.apache.flink.types.Row;
import org.apache.flink.util.WrappingRuntimeException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Catalog factory for an in-memory catalog that contains a single non-empty table. The contents of
* the table are equal to {@link SimpleCatalogFactory#TABLE_CONTENTS}.
*/
public class SimpleCatalogFactory implements CatalogFactory {
public static final String IDENTIFIER = "simple-catalog";
public static final List<Row> TABLE_CONTENTS =
Arrays.asList(
Row.of(1, "Hello"), Row.of(2, "Hello world"), Row.of(3, "Hello world! Hello!"));
private static final ConfigOption<String> DEFAULT_DATABASE =
ConfigOptions.key(CommonCatalogOptions.DEFAULT_DATABASE_KEY)
.stringType()
.defaultValue("default_database");
private static final ConfigOption<String> TABLE_NAME =
ConfigOptions.key("test-table").stringType().defaultValue("test-table");
@Override
public String factoryIdentifier() {
return IDENTIFIER;
}
@Override
public Set<ConfigOption<?>> requiredOptions() {
return Collections.emptySet();
}
@Override
public Set<ConfigOption<?>> optionalOptions() {
final Set<ConfigOption<?>> options = new HashSet<>();
options.add(DEFAULT_DATABASE);
options.add(TABLE_NAME);
return options;
}
@Override
public Catalog createCatalog(Context context) {
final Configuration configuration = Configuration.fromMap(context.getOptions());
final String database = configuration.getString(DEFAULT_DATABASE);
final String tableName = configuration.getString(TABLE_NAME);
final GenericInMemoryCatalog genericInMemoryCatalog =
new GenericInMemoryCatalog(context.getName(), database);
StreamTableSource<Row> tableSource =
new StreamTableSource<Row>() {
@Override
public DataStream<Row> getDataStream(StreamExecutionEnvironment execEnv) {
return execEnv.fromCollection(TABLE_CONTENTS)
.returns(
new RowTypeInfo(
new TypeInformation[] {Types.INT(), Types.STRING()},
new String[] {"id", "string"}));
}
@Override
public TableSchema getTableSchema() {
return TableSchema.builder()
.field("id", DataTypes.INT())
.field("string", DataTypes.STRING())
.build();
}
@Override
public DataType getProducedDataType() {
return DataTypes.ROW(
DataTypes.FIELD("id", DataTypes.INT()),
DataTypes.FIELD("string", DataTypes.STRING()))
.notNull();
}
};
try {
genericInMemoryCatalog.createTable(
new ObjectPath(database, tableName),
ConnectorCatalogTable.source(tableSource, false),
false);
} catch (Exception e) {
throw new WrappingRuntimeException(e);
}
return genericInMemoryCatalog;
}
}
| 40.783582 | 100 | 0.642086 |
b7c1444b29c612f3a851260e6f5b065e9f927a27 | 7,814 | /**
* blackduck-alert
*
* Copyright (c) 2020 Synopsys, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.synopsys.integration.alert.channel.jira.cloud.web;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import com.synopsys.integration.alert.channel.jira.cloud.JiraChannelKey;
import com.synopsys.integration.alert.channel.jira.cloud.descriptor.JiraDescriptor;
import com.synopsys.integration.alert.common.action.CustomEndpointManager;
import com.synopsys.integration.alert.common.descriptor.config.field.endpoint.ButtonCustomEndpoint;
import com.synopsys.integration.alert.common.enumeration.ConfigContextEnum;
import com.synopsys.integration.alert.common.exception.AlertDatabaseConstraintException;
import com.synopsys.integration.alert.common.exception.AlertException;
import com.synopsys.integration.alert.common.persistence.accessor.ConfigurationAccessor;
import com.synopsys.integration.alert.common.persistence.model.ConfigurationFieldModel;
import com.synopsys.integration.alert.common.rest.ResponseFactory;
import com.synopsys.integration.alert.common.rest.model.FieldModel;
import com.synopsys.integration.alert.common.rest.model.FieldValueModel;
import com.synopsys.integration.exception.IntegrationException;
import com.synopsys.integration.issuetracker.jira.cloud.JiraCloudProperties;
import com.synopsys.integration.issuetracker.jira.common.JiraConstants;
import com.synopsys.integration.jira.common.cloud.service.JiraCloudServiceFactory;
import com.synopsys.integration.jira.common.rest.service.PluginManagerService;
import com.synopsys.integration.rest.request.Response;
@Component
public class JiraCustomEndpoint extends ButtonCustomEndpoint {
private static final Logger logger = LoggerFactory.getLogger(JiraCustomEndpoint.class);
private final JiraChannelKey jiraChannelKey;
private final ResponseFactory responseFactory;
private final ConfigurationAccessor configurationAccessor;
private final Gson gson;
@Autowired
public JiraCustomEndpoint(JiraChannelKey jiraChannelKey, CustomEndpointManager customEndpointManager, ResponseFactory responseFactory, ConfigurationAccessor configurationAccessor, Gson gson) throws AlertException {
super(JiraDescriptor.KEY_JIRA_CONFIGURE_PLUGIN, customEndpointManager, responseFactory);
this.jiraChannelKey = jiraChannelKey;
this.responseFactory = responseFactory;
this.configurationAccessor = configurationAccessor;
this.gson = gson;
}
@Override
public Optional<ResponseEntity<String>> preprocessRequest(FieldModel fieldModel) {
JiraCloudProperties jiraProperties = createJiraProperties(fieldModel);
try {
JiraCloudServiceFactory jiraServicesCloudFactory = jiraProperties.createJiraServicesCloudFactory(logger, gson);
PluginManagerService jiraAppService = jiraServicesCloudFactory.createPluginManagerService();
String username = jiraProperties.getUsername();
String accessToken = jiraProperties.getAccessToken();
Response response = jiraAppService.installMarketplaceCloudApp(JiraConstants.JIRA_APP_KEY, username, accessToken);
if (response.isStatusCodeError()) {
return Optional.of(responseFactory.createBadRequestResponse("", "The Jira Cloud server responded with error code: " + response.getStatusCode()));
}
boolean jiraPluginInstalled = isJiraPluginInstalled(jiraAppService, accessToken, username, JiraConstants.JIRA_APP_KEY);
if (!jiraPluginInstalled) {
return Optional.of(responseFactory.createNotFoundResponse("Was not able to confirm Jira Cloud successfully installed the Jira Cloud plugin. Please verify the installation on you Jira Cloud server."));
}
} catch (IntegrationException e) {
logger.error("There was an issue connecting to Jira Cloud", e);
return Optional.of(responseFactory.createBadRequestResponse("", "The following error occurred when connecting to Jira Cloud: " + e.getMessage()));
} catch (InterruptedException e) {
logger.error("Thread was interrupted while validating jira install.", e);
Thread.currentThread().interrupt();
return Optional.of(responseFactory.createInternalServerErrorResponse("", "Thread was interrupted while validating Jira plugin installation: " + e.getMessage()));
}
return Optional.empty();
}
@Override
protected String createData(FieldModel fieldModel) throws AlertException {
return "Successfully created Alert plugin on Jira Cloud server.";
}
private JiraCloudProperties createJiraProperties(FieldModel fieldModel) {
String url = fieldModel.getFieldValue(JiraDescriptor.KEY_JIRA_URL).orElse("");
String username = fieldModel.getFieldValue(JiraDescriptor.KEY_JIRA_ADMIN_EMAIL_ADDRESS).orElse("");
String accessToken = fieldModel.getFieldValueModel(JiraDescriptor.KEY_JIRA_ADMIN_API_TOKEN)
.map(this::getAppropriateAccessToken)
.orElse("");
return new JiraCloudProperties(url, accessToken, username);
}
private String getAppropriateAccessToken(FieldValueModel fieldAccessToken) {
String accessToken = fieldAccessToken.getValue().orElse("");
boolean accessTokenSet = fieldAccessToken.isSet();
if (StringUtils.isBlank(accessToken) && accessTokenSet) {
try {
return configurationAccessor.getConfigurationsByDescriptorKeyAndContext(jiraChannelKey, ConfigContextEnum.GLOBAL)
.stream()
.findFirst()
.flatMap(configurationModel -> configurationModel.getField(JiraDescriptor.KEY_JIRA_ADMIN_API_TOKEN))
.flatMap(ConfigurationFieldModel::getFieldValue)
.orElse("");
} catch (AlertDatabaseConstraintException e) {
logger.error("Unable to retrieve existing Jira configuration.");
}
}
return accessToken;
}
private boolean isJiraPluginInstalled(PluginManagerService jiraAppService, String accessToken, String username, String appKey) throws IntegrationException, InterruptedException {
long maxTimeForChecks = 5L;
long checkAgain = 1L;
while (checkAgain <= maxTimeForChecks) {
boolean foundPlugin = jiraAppService.getInstalledApp(username, accessToken, appKey).isPresent();
if (foundPlugin) {
return true;
}
TimeUnit.SECONDS.sleep(checkAgain);
checkAgain++;
}
return false;
}
}
| 51.071895 | 218 | 0.740338 |
cbb155b4410d7cf66e98c9eee2117a5377e2b9c7 | 424 | package leetcode.lc344_reverse_string;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public final class LC344ReverseStringTests {
@Test
public void testExample() throws Exception {
char[] s = { 'h', 'e', 'l', 'l', 'o' };
new LC344ReverseString().reverseString(s);
assertArrayEquals(new char[] { 'o', 'l', 'l', 'e', 'h' }, s);
}
}
| 28.266667 | 69 | 0.646226 |
986fde746e67c829e7c25fb562f1ca28d7a87c2c | 8,392 |
public class Util {
public static void main(String[] args) {
System.out.println(Util.averageOfDistribution(new double[] {125.0, 83.0}, new double[] {1.0, 0.0}));
Util.printArray(Util.thresholds(new double[] {0.0, 1.0, 4.0}, 0.6));
}
public static void printWithExtraSpaces(String toPrint, int totalLength)
{
System.out.print(toPrint);
for(int i = toPrint.length(); i < totalLength; i++)
System.out.print(" ");
}
public static void printArray(double[][] values)
{
for(int i = 0; i < values.length; i++)
{
for(int j = 0; j < values[i].length; j++)
{
System.out.print(values[i][j] + " ");
}
System.out.println();
}
}
public static void printArray(int[] values)
{
if(values == null)
{
System.out.println("null array");
return;
}
for(int i = 0; i < values.length; i++)
{
System.out.print(values[i] + " ");
}
System.out.println();
}
public static void printArray(double[] values)
{
if(values == null)
{
System.out.println("null array");
return;
}
for(int i = 0; i < values.length; i++)
{
System.out.print(values[i] + " ");
}
System.out.println();
}
public static void printArray(boolean[] values)
{
if(values == null)
{
System.out.println("null array");
return;
}
for(int i = 0; i < values.length; i++)
{
System.out.print(values[i] + " ");
}
System.out.println();
}
public static void printArray(String[] values)
{
if(values == null)
{
System.out.println("null array");
return;
}
for(int i = 0; i < values.length; i++)
{
System.out.print(values[i] + " ");
}
System.out.println();
}
public static double[] unique(double[] values)
{
if(values.length == 0)
return new double[0];
double[] sorted = Quicksort.sort(Util.copy(values));
int countUnique = 1;
double current = sorted[0];
for(int i = 0; i < sorted.length; i++)
if(current != sorted[i])
{
current = sorted[i];
countUnique++;
}
double[] unique = new double[countUnique];
unique[0] = sorted[0];
current = sorted[0];
int index = 1;
for(int i = 0; i < sorted.length; i++)
if(current != sorted[i])
{
current = sorted[i];
unique[index] = sorted[i];
index++;
}
return unique;
}
public static int maxIndex(double[] values)
{
int index = 0;
double max = values[0];
for(int i = 0; i < values.length; i++)
if(values[i] > max)
{
max = values[i];
index = i;
}
return index;
}
public static double[] fill(double value, int length)
{
double[] out = new double[length];
for(int i = 0; i < length; i++)
out[i] = value;
return out;
}
public static int[] fill(int value, int length)
{
int[] out = new int[length];
for(int i = 0; i < length; i++)
out[i] = value;
return out;
}
public static int indexOf(double value, double[] values)
{
for(int i = 0; i < values.length; i++)
if(values[i] == value)
return i;
return -1;
}
public static double sum(double[] values)
{
double sum = 0.0;
for(double value : values)
sum += value;
return sum;
}
public static double sum(double[][] values)
{
double sum = 0.0;
for(double[] row : values)
sum += sum(row);
return sum;
}
public static boolean[] invert(boolean[] bs)
{
boolean[] bsi = new boolean[bs.length];
for(int i = 0; i < bs.length; i++)
bsi[i] = !bs[i];
return bsi;
}
public static double[] invert(double[] bs)
{
double[] bsi = new double[bs.length];
for(int i = 0; i < bs.length; i++)
bsi[i] = 1.0 - bs[i];
return bsi;
}
public static double[][] sum(double[][] a, double[][] b)
{
if(a == null) return b;
if(b == null) return a;
double[][] c = new double[a.length][];
for(int i = 0; i < a.length; i++)
{
c[i] = new double[a[i].length];
for(int j = 0; j < a[i].length; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
public static double[][] divide(double[][] a, double b)
{
double[][] c = new double[a.length][];
for(int i = 0; i < a.length; i++)
{
c[i] = new double[a[i].length];
for(int j = 0; j < a[i].length; j++)
{
c[i][j] = a[i][j] / b;
}
}
return c;
}
public static void sleep(long millis)
{
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static double[] subtract(double[] a, double[] b)
{
double[] c = new double[a.length];
for(int i = 0; i < a.length; i++)
c[i] = a[i] - b[i];
return c;
}
public static String[] getElsaAttributes()
{
return new String[] {"sex", "indager_w8", "apoe", "bmiobe", "cfib", "chestin", "chol", "clotb", "dheas", "diaval", "eyesurg", "fglu", "hastro", "hasurg", "hdl", "hgb", "hipval", "hscrp", "htfev", "htfvc", "htpf", "htval", "ldl", "mapval", "mch", "mmcrre", "mmgsdavg", "mmgsnavg", "mmlore", "mmlsre", "mmrroc", "mmssre", "mmstre", "pulval", "rtin", "sysval", "trig", "vitd", "wbc", "whval", "wstval", "wtval"};
}
public static double[] count(double[] values, double[] valuesToCount, double[] weights)
{
double[] counts = new double[valuesToCount.length];
for(int valueIndex = 0; valueIndex < valuesToCount.length; valueIndex++)
for(int i = 0; i < values.length; i++)
if(values[i] == valuesToCount[valueIndex])
{
if(weights == null)
counts[valueIndex] += 1.0;
else
counts[valueIndex] += weights[i];
}
return counts;
}
public static double[][] transpose(double[][] values)
{
double[][] transposed = new double[values[0].length][];
for(int i = 0; i < values[0].length; i++)
{
transposed[i] = new double[values.length];
for(int j = 0; j < values.length; j++)
transposed[i][j] = values[j][i];
}
return transposed;
}
public static double averageOfDistribution(double[] count, double[] values)
{
double out = 0.0;
double total = 0.0;
for(int i = 0; i < count.length; i++)
{
out += count[i] * values[i];
total += count[i];
}
if(total == 0.0)
return 0.0;
return out/total;
}
/*
* If values are [0, 1, 4] and threshold is 0.6, it turns them into [0, 0.6, 2.8]
* This method assumes values are sorted in ascending order and the first value is 0.0
*/
public static double[] thresholds(double[] values, double threshold)
{
if(values[0] != 0.0)
return null;
double[] thresholds = new double[values.length];
for(int i = 0; i < values.length; i++)
{
if(i == 0)
thresholds[i] = 0.0;
else
thresholds[i] = values[i-1] + threshold * (values[i] - values[i-1]);
}
return thresholds;
}
/*
* If values are [0, 0.6, 2.8] and value is 0.5, it returns 0
* If values are [0, 0.6, 2.8] and value is 0.7, it returns 1
* If values are [0, 0.6, 2.8] and value is 2.7, it returns 1
* If values are [0, 0.6, 2.8] and value is 2.9, it returns 2
* This method assumes values are sorted in ascending order and the first value is 0.0, and the value is >= 0.0
*/
public static int indexOfTheHighestBelowOrEqual(double[] values, double value)
{
for(int i = values.length - 1; i >= 0; i--)
{
if(values[i] <= value)
return i;
}
return 0;
}
public static int countMatches(double[] a, double[] b)
{
int matches = 0;
for(int i = 0; i < a.length; i++)
if(a[i] == b[i])
matches++;
return matches;
}
public static double countMatchesWeighted(double[] a, double[] b, double[] weights)
{
if(weights == null)
return 0.0 + countMatches(a,b);
double matches = 0;
for(int i = 0; i < a.length; i++)
if(a[i] == b[i])
matches += weights[i];
return matches;
}
public static double[] copy(double[] original)
{
double[] copy = new double[original.length];
for(int i = 0; i < original.length; i++)
copy[i] = original[i];
return copy;
}
public static double[][] copy(double[][] original)
{
double[][] copy = new double[original.length][];
for(int i = 0; i < original.length; i++)
{
copy[i] = new double[original[i].length];
for(int j = 0; j < original[i].length; j++)
copy[i][j] = original[i][j];
}
return copy;
}
}
| 23.908832 | 412 | 0.560653 |
b82637bba818d77bec97aca5fd6f24bfcfaae705 | 1,338 | package in.noobgames.sqliteapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
ProductListFragment mProductListFragment;
InputFragment mInputFragment;
private DBHelper mDBHelper = new DBHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProductListFragment = new ProductListFragment();
mInputFragment = new InputFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frag_container, mProductListFragment)
.commit();
}
public void onAddProductClick(View view) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frag_container, mInputFragment)
.addToBackStack(null)
.commit();
}
public void onInputCancelClick(View view) {
//mInputFragment.onInputCancelClick();
onBackPressed();
}
public void onInputSubmitClick(View view) {
mInputFragment.onInputSubmitClick();
onBackPressed();
}
public DBHelper getDBHelper() {
return mDBHelper;
}
}
| 27.306122 | 63 | 0.657698 |
8736fe12230342baea86fa44b284746665b9eda9 | 933 | package com.ming.core.orm;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.NoRepositoryBean;
import javax.transaction.Transactional;
import java.io.Serializable;
/**
* 自定义 基础 repository
*
* @author ming
* @date 2019-09-23 15:46:43
*/
@NoRepositoryBean
public interface BaseRepository<T extends OrmSuperClass, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T> {
/**
* 逻辑删除
*
* @param id 数据id
* @author ming
* @date 2020-04-13 17:48:23
*/
@Query(value = "update #{#entityName} set deleted = true where id = ?1 ")
@Transactional(rollbackOn = Exception.class)
@Modifying
void logicDeleteById(ID id);
}
| 27.441176 | 141 | 0.736334 |
5664bd536bc89fd619e026c9670d59e6113ef7d9 | 2,221 | package mage.cards.g;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.ActivateAsSorceryActivatedAbility;
import mage.abilities.common.EntersBattlefieldTappedAbility;
import mage.abilities.costs.Cost;
import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.mana.BlackManaAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Zone;
import mage.game.permanent.token.AngelWarriorVigilanceToken;
import mage.target.common.TargetControlledCreaturePermanent;
/**
*
* @author weirddan455
*/
public final class GreatHallOfStarnheim extends CardImpl {
public GreatHallOfStarnheim(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.LAND}, "");
// Great Hall of Starnheim enters the battlefield tapped.
this.addAbility(new EntersBattlefieldTappedAbility());
// {T}: Add {B}.
this.addAbility(new BlackManaAbility());
// {W}{W}{B}, {T}, Sacrifice Great Hall of Starnheim and a creature you control:
// Create a 4/4 white Angel Warrior creature token with flying and vigilance.
// Activate this ability only any time you could cast a sorcery.
Ability ability = new ActivateAsSorceryActivatedAbility(
Zone.BATTLEFIELD,
new CreateTokenEffect(new AngelWarriorVigilanceToken()),
new ManaCostsImpl<>("{W}{W}{B}")
);
ability.addCost(new TapSourceCost());
ability.addCost(new SacrificeSourceCost());
Cost cost = new SacrificeTargetCost(new TargetControlledCreaturePermanent());
cost.setText("and a creature you control");
ability.addCost(cost);
this.addAbility(ability);
}
private GreatHallOfStarnheim(final GreatHallOfStarnheim card) {
super(card);
}
@Override
public GreatHallOfStarnheim copy() {
return new GreatHallOfStarnheim(this);
}
}
| 35.822581 | 88 | 0.72715 |
986b4dd8fb82af00516b0884b9d5d4b5b9a57588 | 38,292 | package com.cy.mobileInterface.authenticated.service;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import com.cy.common.utils.TimeZoneUtils;
import com.cy.core.alumni.dao.AlumniWaitRegistersMapper;
import com.cy.core.alumni.entity.AlumniWaitRegisters;
import com.cy.core.chatDeptGroup.dao.ChatDeptGroupMapper;
import com.cy.core.chatDeptGroup.entity.ChatDeptGroup;
import com.cy.core.chatGroup.entity.ChatGroup;
import com.cy.core.chatGroup.service.ChatGroupService;
import com.cy.core.deptInfo.dao.DeptInfoMapper;
import com.cy.core.deptInfo.entity.DeptInfo;
import com.cy.core.notify.utils.PushUtils;
import com.cy.mobileInterface.alumni.entity.JoinAlumni;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.cy.base.entity.Message;
import com.cy.core.alumni.dao.AlumniMapper;
import com.cy.core.alumni.entity.Alumni;
import com.cy.core.mobileLocal.dao.MobileLocalMapper;
import com.cy.core.mobileLocal.entity.MobileLocal;
import com.cy.core.userProfile.dao.GroupInfoMapper;
import com.cy.core.userProfile.dao.UserProfileMapper;
import com.cy.core.userProfile.entity.GroupInfoEntity;
import com.cy.core.userProfile.entity.UserProfile;
import com.cy.core.userinfo.dao.UserInfoMapper;
import com.cy.core.userinfo.entity.UserInfo;
import com.cy.mobileInterface.authenticated.entity.Authenticated;
import com.cy.system.TigaseUtils;
import static sun.misc.MessageUtils.where;
@Service("authenticatedService")
public class AuthenticatedServiceImpl implements AuthenticatedService {
@Autowired
private UserProfileMapper userProfileMapper;
@Autowired
private UserInfoMapper userInfoMapper;
@Autowired
private GroupInfoMapper groupInfoMapper;
@Autowired
private MobileLocalMapper mobileLocalMapper;
@Autowired
private AlumniMapper alumniMapper;
@Autowired
private ChatDeptGroupMapper chatDeptGroupMapper ;
@Autowired
private ChatGroupService chatGroupService ;
@Autowired
private AlumniWaitRegistersMapper alumniWaitRegistersMapper;
@Autowired
private DeptInfoMapper deptInfoMapper;
@Override
public void updateAuthenticated(Message message, String content) {
try {
Authenticated authenticated = JSON.parseObject(content, Authenticated.class);
if (authenticated.getBaseInfoId() == null || authenticated.getBaseInfoId().size() == 0) {
message.setMsg("baseInfoId为空!");
message.setSuccess(false);
return;
}
if(StringUtils.isNotBlank(authenticated.getAccountNum())){
if(authenticated.getClassmates() == null || authenticated.getClassmates().size() < 1){
message.setMsg("请提供本班同学的姓名!!");
message.setSuccess(false);
return;
}
}else{
if (authenticated.getClassmates() == null || authenticated.getClassmates().size() != 3) {
message.setMsg("请提供3个本班同学的姓名!!");
message.setSuccess(false);
return;
}
}
UserProfile userProfile;
if(StringUtils.isNotBlank(authenticated.getAccountNum())){
userProfile = userProfileMapper.selectByAccountNum(authenticated.getAccountNum());
if(userProfile == null){
message.init(false, "用户ID不存在", null);
return;
}
}else if(StringUtils.isNotBlank(authenticated.getPhoneNum()) && StringUtils.isNotBlank(authenticated.getPassword())){
userProfile = userProfileMapper.selectByPhoneNum(authenticated.getPhoneNum());
if (userProfile == null) {
message.setMsg("账号/密码错误!");
message.setSuccess(false);
return;
}
// 核对密码
if (!authenticated.getPassword().equals(userProfile.getPassword())) {
message.setMsg("账号/密码错误!");
message.setSuccess(false);
return;
}
}else{
message.init(false, "请提供账号/手机号密码", null);
return;
}
int isLock = isLocked(userProfile);
if(isLock == 2){
message.setMsg("您的认证通道已被锁定,请"+(24-(new Date().getTime() - userProfile.getAuthErrTime().getTime())/(60*60*1000))+"小时后再试!");
message.setSuccess(false);
return;
}
//超过24小时或距离上次认证超过10分钟归零
if(isLock == 3 || isLock == 4) {
userProfile.setAuthErrNum(0);
}
// 身份甄别
String classId = authenticated.getBaseInfoId().get(0).substring(0, 16);// 截取班级编号
List<UserInfo> userInfoList = userInfoMapper.selectUserByClassIdLess(classId);
long count = 0;
UserInfo userInfo = null;
for (UserInfo user : userInfoList) {
for (String name : authenticated.getClassmates()) {
if (name.equals(user.getUserName())) {
count++;
break;
}
}
if (user.getUserId().equals(authenticated.getBaseInfoId().get(0))) {
userInfo = user;
}
}
if(StringUtils.isNotBlank(authenticated.getAccountNum())){
if (count < 1 || userInfo == null){
message.setMsg("认证失败!请确保输入了正确的同学姓名");
message.setSuccess(false);
return;
}
}else{
if (count < 3 || userInfo == null) {
if(isLock != 2){
updateAuthErr(userProfile);
}
if(userProfile.getAuthErrNum() >= 3){
message.setMsg("您在10分钟内连续认证错误3次,该功能将锁定24小时!");
message.setSuccess(false);
return;
}
message.setMsg("认证失败!请确保选择的同班同学无误!(还剩"+(3-userProfile.getAuthErrNum())+"次机会)");
message.setSuccess(false);
return;
}
}
if (userInfo.getAccountNum() != null && userInfo.getAccountNum().length() != 0) {
message.setMsg("该用户已经认证过!");
message.setSuccess(false);
return;
}
Map<String,Object> returnMap = authSuccess(userProfile, userInfo);
//更新用户信息
if((int)returnMap.get("code") == 0){
message.setObj(returnMap);
message.setMsg("恭喜你,认证成功!");
message.setSuccess(true);
}else{
message.setMsg("信息保存失败");
message.setSuccess(false);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 通过学号进行认证
* @param message
* @param content
*/
@Override
public void updateAuthenticatedByStuNum(Message message, String content){
try {
Authenticated authenticated = JSON.parseObject(content, Authenticated.class);
if (authenticated.getBaseInfoIdx() == null || authenticated.getBaseInfoIdx().length() == 0) {
message.setMsg("baseInfoId为空!");
message.setSuccess(false);
return;
}
if (authenticated.getStudentnumber() == null) {
message.setMsg("请填写学号!!");
message.setSuccess(false);
return;
}
UserProfile userProfile = userProfileMapper.selectByPhoneNum(authenticated.getPhoneNum());
if (userProfile == null) {
message.setMsg("账号错误!");
message.setSuccess(false);
return;
}
// 核对密码
if (!authenticated.getPassword().equals(userProfile.getPassword())) {
message.setMsg("密码错误!");
message.setSuccess(false);
return;
}
/*int isLock = isLocked(userProfile);
if(isLock == 2){
message.setMsg("您的认证通道已被锁定,请"+(24-(new Date().getTime() - userProfile.getAuthErrTime().getTime())/(60*60*1000))+"小时后再试!");
message.setSuccess(false);
return;
}
//超过24小时或距离上次认证超过10分钟归零
if(isLock == 3 || isLock == 4) {
userProfile.setAuthErrNum(0);
}*/
// 身份甄别
List<UserInfo> userInfoList = userInfoMapper.selectUserByStudentNum(authenticated.getStudentnumber());
UserInfo userInfo = null;
for (UserInfo user : userInfoList) {
if (user.getUserId().equals(authenticated.getBaseInfoIdx())) {
userInfo = user;
}
}
if (userInfo == null) {
/*updateAuthErr(userProfile);
if(userProfile.getAuthErrNum() >= 3){
message.setMsg("您在10分钟内连续认证错误3次,该功能将锁定24小时!");
message.setSuccess(false);
return;
}
message.setMsg("认证失败!请确保填写的学号无误!(还剩"+(3-userProfile.getAuthErrNum())+"次机会)");*/
message.setMsg("认证失败!请确保填写的学号无误!");
message.setSuccess(false);
return;
}
if (userInfo.getAccountNum() != null && userInfo.getAccountNum().length() != 0) {
message.setMsg("该用户已经认证过!");
message.setSuccess(false);
return;
}
Map<String,Object> returnMap = authSuccess(userProfile, userInfo);
//更新用户信息
if((int)returnMap.get("code") == 0){
message.setObj(returnMap);
message.setMsg("恭喜你,认证成功!");
message.setSuccess(true);
}else{
message.setMsg("信息保存失败");
message.setSuccess(false);
}
return;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 通过身份证进行认证
* @param message
* @param content
*/
public void updateAuthenticatedByCard(Message message, String content){
try {
Authenticated authenticated = JSON.parseObject(content, Authenticated.class);
if (authenticated.getBaseInfoIdx() == null || authenticated.getBaseInfoIdx().length() == 0) {
message.setMsg("baseInfoId为空!");
message.setSuccess(false);
return;
}
if (authenticated.getCard() == null) {
message.setMsg("请填写身份证号!!");
message.setSuccess(false);
return;
}
UserProfile userProfile = userProfileMapper.selectByPhoneNum(authenticated.getPhoneNum());
if (userProfile == null) {
message.setMsg("账号错误!");
message.setSuccess(false);
return;
}
// 核对密码
if (!authenticated.getPassword().equals(userProfile.getPassword())) {
message.setMsg("密码错误!");
message.setSuccess(false);
return;
}
/*int isLock = isLocked(userProfile);
if(isLock == 2){
message.setMsg("您的认证通道已被锁定,请"+(24-(new Date().getTime() - userProfile.getAuthErrTime().getTime())/(60*60*1000))+"小时后再试!");
message.setSuccess(false);
return;
}
//超过24小时或距离上次认证超过10分钟归零
if(isLock == 3 || isLock == 4) {
userProfile.setAuthErrNum(0);
}*/
// 身份甄别
List<UserInfo> userInfoList = userInfoMapper.selectUserByCard(authenticated.getCard());
UserInfo userInfo = null;
for (UserInfo user : userInfoList) {
if (user.getUserId().equals(authenticated.getBaseInfoIdx())) {
userInfo = user;
}
}
if (userInfo == null) {
/*updateAuthErr(userProfile);
if(userProfile.getAuthErrNum() >= 3){
message.setMsg("您在10分钟内连续认证错误3次,该功能将锁定24小时!");
message.setSuccess(false);
return;
}
message.setMsg("认证失败!请确认您的身份证号无误!(还剩"+(3-userProfile.getAuthErrNum())+"次机会)");*/
message.setMsg("认证失败!请确认您的身份证号无误!");
message.setSuccess(false);
return;
}
if (userInfo.getAccountNum() != null && userInfo.getAccountNum().length() != 0) {
message.setMsg("该用户已经认证过!");
message.setSuccess(false);
return;
}
Map<String,Object> returnMap = authSuccess(userProfile, userInfo);
//更新用户信息
if((int)returnMap.get("code") == 0){
message.setObj(returnMap);
message.setMsg("恭喜你,认证成功!");
message.setSuccess(true);
}else{
message.setMsg("信息保存失败");
message.setSuccess(false);
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 通过邀请码进行认证
* @param message
* @param content
*/
public void updateAuthenticatedByInviteCode(Message message, String content){
try {
Authenticated authenticated = JSON.parseObject(content, Authenticated.class);
if (authenticated.getBaseInfoIdx() == null || authenticated.getBaseInfoIdx().length() == 0) {
message.setMsg("baseInfoId为空!");
message.setSuccess(false);
return;
}
if (authenticated.getInvitecode() == null) {
message.setMsg("请填写邀请码!!");
message.setSuccess(false);
return;
}
UserProfile userProfile = userProfileMapper.selectByPhoneNum(authenticated.getPhoneNum());
if (userProfile == null) {
message.setMsg("账号错误!");
message.setSuccess(false);
return;
}
// 核对密码
if (!authenticated.getPassword().equals(userProfile.getPassword())) {
message.setMsg("密码错误!");
message.setSuccess(false);
return;
}
/*int isLock = isLocked(userProfile);
if(isLock == 2){
message.setMsg("您的认证通道已被锁定,请"+(24-(new Date().getTime() - userProfile.getAuthErrTime().getTime())/(60*60*1000))+"小时后再试!");
message.setSuccess(false);
return;
}
//超过24小时或距离上次认证超过10分钟归零
if(isLock == 3 || isLock == 4) {
userProfile.setAuthErrNum(0);
}*/
// 身份甄别
List<UserInfo> userInfoList = userInfoMapper.selectUserByInviteCode(authenticated.getInvitecode().toUpperCase());
UserInfo userInfo = null;
if(userInfoList == null || userInfoList.isEmpty()) {
/*updateAuthErr(userProfile);
if(userProfile.getAuthErrNum() >= 3){
message.setMsg("您在10分钟内连续认证错误3次,该功能将锁定24小时!");
message.setSuccess(false);
return;
}
message.setMsg("认证失败!请确认您的邀请码无误!(还剩"+(3-userProfile.getAuthErrNum())+"次机会)");*/
message.setMsg("认证失败!请确认您的邀请码无误!");
message.setSuccess(false);
return;
}
if (userInfoList.get(0).getUserId().equals(authenticated.getBaseInfoIdx())) {
userInfo = userInfoList.get(0);
}
if (userInfo == null) {
updateAuthErr(userProfile);
message.setMsg("找不到认证用户信息!");
message.setSuccess(false);
return;
}
if (userInfo.getAccountNum() != null && userInfo.getAccountNum().length() != 0) {
message.setMsg("该用户已经认证过!");
message.setSuccess(false);
return;
}
Map<String,Object> returnMap = authSuccess(userProfile, userInfo);
//更新用户信息
if((int)returnMap.get("code") == 0){
message.setObj(returnMap);
message.setMsg("恭喜你,认证成功!");
message.setSuccess(true);
}else{
message.setMsg("信息保存失败");
message.setSuccess(false);
}
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 手机端取消认证接口
* @param message
* @param content
*/
@Override
public void cancleUserAuthentication(Message message, String content){
try {
Authenticated authenticated = JSON.parseObject(content, Authenticated.class);
if (authenticated.getBaseInfoIdx() == null || authenticated.getBaseInfoIdx().length() == 0) {
message.setMsg("baseInfoId为空!");
message.setSuccess(false);
return;
}
UserProfile userProfile;
if(StringUtils.isNotBlank(authenticated.getAccountNum())){
userProfile = userProfileMapper.selectByAccountNum(authenticated.getAccountNum());
if (userProfile == null) {
message.setMsg("账号不存在!");
message.setSuccess(false);
return;
}
}else if(StringUtils.isNotBlank(authenticated.getPhoneNum()) && StringUtils.isNotBlank(authenticated.getPassword())){
userProfile = userProfileMapper.selectByPhoneNum(authenticated.getPhoneNum());
if (userProfile == null) {
message.setMsg("账号不存在!");
message.setSuccess(false);
return;
}
// 核对密码
if (!authenticated.getPassword().equals(userProfile.getPassword())) {
message.setMsg("密码错误!");
message.setSuccess(false);
return;
}
}else{
message.setMsg("请提供账号或手机号!");
message.setSuccess(false);
return;
}
String userId = authenticated.getBaseInfoIdx();
//通过userId找到accountNum
String accountNum = userInfoMapper.selectAccountNumByUserId(userId);
if(StringUtils.isBlank(accountNum)) {
message.setMsg("用户对应校友不正确!");
message.setSuccess(false);
return;
}
//删除user_info与userbase_info下的accountNum
userInfoMapper.deleteAccountNumByUserId(userId);
userInfoMapper.deleteAccountNumByUserIdBase(userId);
String baseInfoIds = userProfile.getBaseInfoId();
if(StringUtils.isNotBlank(baseInfoIds)) {
String[] baseInfoId = baseInfoIds.split(",");
if (baseInfoId.length == 1) {
//如果baseInfoId唯一值,authenticated字段置为0,并且清理baseInfoId、groupName与classes
userProfile.setAuthenticated("0");
userProfile.setBaseInfoId("");
userProfile.setGroupName("");
userProfile.setClasses("");
Map<String, Object> map = new HashMap<String, Object>();
map.put("accountNum", accountNum);
map.put("class", baseInfoIds.substring(0, 16));
userInfoMapper.deleteGroupUser(map);
} else if (baseInfoId.length > 1) {
//如果baseInfoId不唯一,截取baseInfoId,利用剩余的baseInfoId更新groupName与classes
baseInfoIds = "";
String groupNames = "";
String classes = "";
int count = 0;
for (String baseId : baseInfoId) {
if (!baseId.equals(userId)) {
if (count == 0) {
baseInfoIds = baseId;
groupNames = baseId.substring(0, 16);
classes = userInfoMapper.selectClassNameByUserId(baseId);
} else {
baseInfoIds += StringUtils.isNotBlank(baseInfoIds)?("," + baseId): baseId;
groupNames += StringUtils.isNotBlank(groupNames)?("," + baseId.substring(0, 16)): groupNames;
classes += StringUtils.isNotBlank(classes)? ("_" + userInfoMapper.selectClassNameByUserId(baseId)):classes;
}
count++;
} else {
Map<String, Object> map = new HashMap<String, Object>();
map.put("accountNum", accountNum);
map.put("class", baseId.substring(0, 16));
userInfoMapper.deleteGroupUser(map);
}
}
userProfile.setBaseInfoId(baseInfoIds);
userProfile.setGroupName(groupNames);
userProfile.setClasses(classes);
}
userProfileMapper.update(userProfile);
//从环信删除该用户
ChatDeptGroup deptGroup = new ChatDeptGroup();
deptGroup.setDeptId(authenticated.getBaseInfoIdx().substring(0, 16));
List<ChatDeptGroup> deptGroupList = chatDeptGroupMapper.query(deptGroup);
deptGroup = deptGroupList.get(0);
chatGroupService.removeMemberFromGroup(deptGroup.getGroupId(), userProfile.getAccountNum());
}
try {
PushUtils.pushGroupAll(userId, userId, accountNum, 1);
}catch (Exception e ) {
e.printStackTrace();
}
// // 更新用户认证信息
// Map<String, String> baseMap = userProfileMapper.selectBaseInfo(userProfile.getAccountNum());
// if(baseMap == null) {
// baseMap = Maps.newHashMap() ;
// }
// baseMap.put("accountNum", userProfile.getAccountNum()) ;
// userProfileMapper.clearBaseInfoId(baseMap);
message.setMsg("已取消认证");
message.setSuccess(true);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取认证所需的姓名
* @param message
* @param content
*/
@Override
public void getAuthenticatedName(Message message, String content){
try{
if(StringUtils.isBlank(content) || content == null){
message.setMsg("没有任何请求参数");
message.setSuccess(false);
return;
}
Map<String, Object> map= JSON.parseObject(content, Map.class);
String strStudyPathId = (String) map.get("strStudyPathId");
if(StringUtils.isBlank(strStudyPathId) || strStudyPathId ==null){
message.setMsg("strStudyPathId为空");
message.setSuccess(false);
return;
}
UserInfo userInfo = userInfoMapper.selectUserInfoByUserId(strStudyPathId);
if(userInfo == null){
message.setMsg("无法查询到此校友信息");
message.setSuccess(false);
return;
}
List<String> list = new ArrayList<String>();
//随机获取同班除自己以外的3名同学且跟自己不重名的同学
List<String> classmates = userInfoMapper.getClassMates(strStudyPathId);
if(classmates == null || classmates.size()<3){
message.setMsg("该班级没有足够的同学用于此认证方式");
message.setSuccess(false);
return;
}
StringBuffer dummyNameWhere = new StringBuffer() ;
dummyNameWhere.append("WHERE ") ;
int i = 0 ;
for (String className : classmates) {
if(i != 0 ) {
dummyNameWhere.append(" or ") ;
}
dummyNameWhere.append("name != '").append(className).append("' ") ;
i++ ;
}
//将5名同班同学加入
list.addAll(classmates);
map.put("dummyNameWhere",dummyNameWhere.toString()) ;
map.put("limit", 9-classmates.size());
List<String> dummyList = userInfoMapper.findDummyName6(map) ;
list.addAll(dummyList) ;
// while (true){
// String othersName = getRandomName();
// if(!list.contains(othersName)){
// list.add(othersName);
// }
//
// if(list.size()==9) break;
// }
// //随机获取其他班级的20名同学
// List<String> others = new ArrayList<>();
//
// int count = 0;
// while (true){
// others = userInfoMapper.getOtherClassStudents(strStudyPathId);
// others.removeAll(classmates);
// if(others.size()>=6) break;
// count ++;
//
// if(count >10){
// message.setMsg("总体人数不足以用于验证");
// message.setSuccess(false);
// return;
// }
// }
//
// for(int i = 0; i < 6; i++){
// list.add(others.get(i));
// }
//打乱顺序
Collections.shuffle(list);
message.setMsg("获取成功");
message.setObj(list);
message.setSuccess(true);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 是否锁定
* @param userProfile
* @return
*/
private int isLocked(UserProfile userProfile){
if(userProfile.getAuthErrTime() == null || userProfile.getAuthErrNum() == 0){
return 0;
}
long timeDifference = new Date().getTime()-userProfile.getAuthErrTime().getTime();
//如果错误次数达到3次且离上次错误时间少于24小时
if(userProfile.getAuthErrNum() >=3 && timeDifference <= 24*60*60*1000 ){
return 2;
}else if(userProfile.getAuthErrNum() >=3 && timeDifference >= 24*60*60*1000){
return 3;
}else if(userProfile.getAuthErrNum() > 0 && timeDifference <= 10*60*1000){
return 1;
}else if(userProfile.getAuthErrNum() > 0 && timeDifference >= 10*60*1000){
return 4;
} else{
return 0;
}
}
/**
* 认证成功更新信息
*/
private void updateAuthSuccss(UserProfile userProfile){
userProfile.setAuthErrNum(0);
userProfileMapper.updateAuthErr(userProfile);
}
/**
* 认证错误更新信息
*/
private void updateAuthErr(UserProfile userProfile){
userProfile.setAuthErrNum(userProfile.getAuthErrNum()+1);
userProfileMapper.updateAuthErr(userProfile);
}
/**
* 自动加入分会For一键入会
* @param userId
* @param accountNum
*/
public void autoJoinAlumni(String userId, String accountNum){
AlumniWaitRegisters awr = new AlumniWaitRegisters();
awr.setUserId(userId);
awr.setIsWorked("0");
List<AlumniWaitRegisters> list = alumniWaitRegistersMapper.selectList(awr);
if(list != null && list.size() > 0){
for(AlumniWaitRegisters tmp: list){
Map<String, String> map = new HashMap<>();
map.put("accountNum",accountNum);
map.put("alumniId",tmp.getAlumniId());
map.put("delFlag", "0");
map.put("status","20");
JoinAlumni checkStatus = alumniMapper.selectUserAlumni(map);
if(checkStatus != null){
alumniMapper.updateUserAlumni(map);
}else{
map.put("joinTime", (new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
alumniMapper.saveUserAlumni(map);
}
tmp.setIsWorked("1");
alumniWaitRegistersMapper.update(tmp);
}
}
}
/**
* 认证成功后所执行的操作
* @param userProfile
* @param userInfo
* @return
*/
public Map<String,Object> authSuccess(UserProfile userProfile, UserInfo userInfo){
int code = 1;
Map<String,Object> returnMap = new HashMap<>();
try{
updateAuthSuccss(userProfile);
if(StringUtils.isNotBlank(userProfile.getPhoneNum()) && userProfile.getPhoneNum().length() > 7) {
// 获取电话号码归属地
MobileLocal mobileLocal = mobileLocalMapper.selectByMobileNumber(userProfile.getPhoneNum().substring(0, 7));
if (mobileLocal != null) {
String local = mobileLocal.getMobileArea();
String[] array = local.split(" ");
Map<String, Object> alumniMap = new HashMap<String, Object>();
if (array.length == 2) {
alumniMap.put("region1", array[0]);
alumniMap.put("region2", array[1]);
} else {
alumniMap.put("region1", array[0]);
}
// 获取校友会
List<Alumni> list = alumniMapper.selectByRegion(alumniMap);
// 随机选择一个校友会
if (list != null && list.size() > 0) {
userProfile.setAlumni_id(list.get(0).getAlumniId());
}
}
}
// 更新userprofile表
if (userInfo.getSex() != null && userInfo.getSex().equals("男")) {
userProfile.setSex("0");
} else if(userInfo.getSex() != null && userInfo.getSex().equals("女")) {
userProfile.setSex("1");
}else {
userProfile.setSex("");
}
userProfile.setPicture(StringUtils.isNotBlank(userProfile.getPicture())? userProfile.getPicture() : "");
userProfile.setAuthenticated("1");
String baseInfoId = userProfile.getBaseInfoId() == null ?"": userProfile.getBaseInfoId();
String groupName = userProfile.getGroupName()==null?"": userProfile.getGroupName();
String classes = userProfile.getClasses()==null?"":userProfile.getClasses();
baseInfoId += StringUtils.isNotBlank(baseInfoId)?("," + userInfo.getUserId()): userInfo.getUserId();
classes += StringUtils.isNotBlank(classes)?("," + userInfo.getUserId().substring(0, 16)): userInfo.getUserId().substring(0, 16);
groupName += StringUtils.isNotBlank(groupName)? ("_" + userInfo.getFullName()):userInfo.getFullName();
userProfile.setBaseInfoId(baseInfoId);
userProfile.setGroupName(groupName);
userProfile.setClasses(classes);
userProfileMapper.update(userProfile);
// 同步到userinfo表
userInfo.setTelId(userProfile.getPhoneNum());
userInfo.setUseTime(TimeZoneUtils.getDate());
userInfo.setAccountNum(userProfile.getAccountNum());
userInfo.setAlumniId(userProfile.getAlumni_id());
userInfo.setPicUrl(userProfile.getPictureUrl());
userInfoMapper.updateAuthen2User(userInfo);
// 验证班级环信群组是否存在,如不存在创建
ChatDeptGroup deptGroup = new ChatDeptGroup() ;
deptGroup.setDeptId(userInfo.getUserId().substring(0, 16));
List<ChatDeptGroup> deptGroupList = chatDeptGroupMapper.query(deptGroup) ;
String groupId = null ;
if(deptGroupList == null || deptGroupList.isEmpty()) {
ChatGroup group = new ChatGroup() ;
group.setName(userInfo.getClassName());
group.setIntroduction(userInfo.getSchoolName() + "," + userInfo.getDepartName() + "," + userInfo.getGradeName() + "," + userInfo.getClassName());
group.setType("1");
chatGroupService.insert(group);
groupId = group.getId() ;
deptGroup.preInsert();
deptGroup.setGroupId(groupId);
chatDeptGroupMapper.insert(deptGroup);
} else {
deptGroup = deptGroupList.get(0) ;
}
// 将认证对象添加到群组中
chatGroupService.addMemberToGroup(deptGroup.getGroupId(),userProfile.getAccountNum()) ;
try {
PushUtils.pushGroupAll(userInfo.getUserId(),userInfo.getUserId(),userProfile.getAccountNum(), 2);
}catch (Exception e ) {
e.printStackTrace();
}
// 自动加入一键设置的入会
autoJoinAlumni(userInfo.getUserId(), userProfile.getAccountNum());
// 更新用户认证信息
// Map<String, String> baseMap = userProfileMapper.selectBaseInfo(userProfile.getAccountNum());
// if(baseMap == null) {
// baseMap = Maps.newHashMap() ;
// }
// baseMap.put("accountNum", userProfile.getAccountNum()) ;
// userProfileMapper.clearBaseInfoId(baseMap);
//获取主要是第几位,卡号、班级信息、用户信息
UserProfile userProfileNew =userProfileMapper.selectByAccountNum(userProfile.getAccountNum());
String baseInfoIdSub = userInfo.getUserId().substring(0, 14);
//获取认证的同学校同年级的个数
long count = userProfileMapper.countAuthenticatedUserProfile(baseInfoIdSub);
DeptInfo deptInfo = deptInfoMapper.findById(userInfo.getUserId().substring(0, 16));
String name = userProfileNew.getName();
String sex = userProfileNew.getSex();
String[] message = deptInfo.getFullName().split(",");
String alumni = message[0];
String academy = message[1];
String grade = message[2];
String className = message[3];
returnMap.put("code", 0);
returnMap.put("authNumber", count);
returnMap.put("name", name);
returnMap.put("sex", sex);
returnMap.put("alumni", alumni);
returnMap.put("academy", academy);
returnMap.put("grade", grade);
returnMap.put("className", className);
code = 0;
}catch (Exception e){
code = -1;
returnMap.put("code",-1);
throw new RuntimeException(e);
}
return returnMap;
}
/**
* 獲取隨機姓名
* @return
*/
private String getRandomName(){
return getLastName()+getFirstName();
}
/**
* 獲取隨機名
* @return
*/
private String getFirstName(){
Random random=new Random();
String[] firstName = {"致远","俊驰","雨泽","烨磊","晟睿","文昊","修洁","黎昕","远航","旭尧","鸿涛","伟祺","荣轩","越泽","浩宇","瑾瑜",
"皓轩","擎宇","志泽","子轩","睿渊","弘文","哲瀚","雨泽","楷瑞","建辉","晋鹏","天磊","绍辉","泽洋","鑫磊","鹏煊","昊强","伟宸",
"博超","君浩","子骞","鹏涛","炎彬","鹤轩","越彬","风华","靖琪 ","明辉","伟诚","明轩","健柏","修杰","志泽","弘文",
"懿轩","烨伟","苑博","伟泽","熠彤","鸿煊","博涛","烨霖","烨","正豪","昊然","明杰","立诚","立轩","立辉","峻熙","弘文",
"熠彤","鸿煊","烨霖","哲瀚","鑫鹏","昊天","思聪","展鹏","志强","炫明","雪松","思源","智渊","思淼","晓啸","天宇","浩然","文轩",
"鹭洋","振家","晓博","昊焱","金鑫","锦程","嘉熙","鹏飞","子默","思远","浩轩","语堂","聪健","梦琪","之桃","慕青",
"尔岚","初夏","沛菡","傲珊","曼文","乐菱","惜文","香寒","新柔","语蓉","海安","夜蓉","涵柏","水桃","醉蓝","语琴","从彤","傲晴","语兰",
"又菱","碧彤","元霜","怜梦","紫寒","妙彤","曼易","南莲","紫翠","雨寒","易烟","如萱","若南","寻真","晓亦","向珊","慕灵","以蕊","映易",
"雪柳","海云","凝天","沛珊","寒云","冰旋","宛儿","绿真","晓霜","碧凡","夏菡","曼香","若烟","半梦","雅绿","冰蓝","灵槐","平安","书翠",
"翠风","代云","梦曼","梦柏","醉易","访旋","亦玉","凌萱","怀亦","笑蓝","靖柏","夜蕾","冰夏","梦松","书雪","乐枫",
"念薇","靖雁","从寒","觅波","静曼","凡旋","以亦","念露","芷蕾","千兰","新波","新蕾","雁玉","冷卉","紫山","千琴","傲芙","盼山",
"怀蝶","冰兰","山柏","翠萱","问旋","白易","问筠","如霜","半芹","丹珍","冰彤","亦寒","之瑶","冰露","尔珍","谷雪","乐萱","涵菡","海莲",
"傲蕾","青槐","易梦","惜雪","宛海","之柔","夏青","亦瑶","妙菡","紫蓝","幻柏","元风","冰枫","访蕊","芷蕊","凡蕾","凡柔","安蕾","天荷",
"含玉","书兰","雅琴","书瑶","从安","夏槐","念芹","代曼","秋翠","白晴","海露","代荷","含玉","书蕾","听白","灵雁","雪青",
"乐瑶","含烟","涵双","平蝶","雅蕊","傲之","灵薇","含蕾","从梦","从蓉","初丹","听兰","听蓉","语芙","夏彤","凌瑶","忆翠","幻灵","怜菡",
"紫南","依珊","妙竹","访烟","怜蕾","映寒","友绿","冰萍","惜霜","凌香","芷蕾","雁卉","迎梦","元柏","代萱","紫真","千青","凌寒","紫安",
"寒安","怀蕊","秋荷","涵雁","以山","凡梅","盼曼","翠彤","谷冬","冷安","千萍","冰烟","雅阳","友绿","南松","诗云","飞风","寄灵","书芹",
"幼蓉","以蓝","笑寒","忆寒","秋烟","芷巧","水香","醉波","夜山","芷卉","向彤","小玉","幼南","凡梦","尔曼","念波","迎松",
"青寒","涵蕾","碧菡","映秋","盼烟","忆山","以寒","寒香","小凡","代亦","梦露","映波","友蕊","寄凡","怜蕾","雁枫","水绿","曼荷",
"笑珊","寒珊","谷南","慕儿","夏岚","友儿","小萱","紫青","妙菱","冬寒","曼柔","语蝶","青筠","夜安","觅海","问安","晓槐","雅山","访云",
"翠容","寒凡","以菱","冬云","含玉","访枫","含卉","夜白","冷安","灵竹","醉薇","元珊","幻波","盼夏","元瑶","迎曼","水云","访琴",
"谷波","笑白","妙海","紫霜","凌旋","怜寒","凡松","翠安","凌雪","绮菱","代云","香薇","冬灵","凌珍","沛文","紫槐",
"幻柏","采文","雪旋","盼海","映梦","安雁","映容","凝阳","访风","天亦","小霜","雪萍","半雪","山柳","谷雪","靖易","白薇","梦菡",
"飞绿","如波","又晴","友易","香菱","冬亦","问雁","海冬","秋灵","凝芙","念烟","白山","从灵","尔芙","迎蓉","念寒","翠绿","翠芙","靖儿",
"妙柏","千凝","小珍","妙旋","雪枫","夏菡","绮琴","雨双","听枫","觅荷","凡之","晓凡","雅彤","孤风","从安","绮彤","之玉","雨珍","幻丝",
"代梅","青亦","元菱","海瑶","飞槐","听露","梦岚","幻竹","谷云","忆霜","水瑶","慕晴","秋双","雨真","觅珍","丹雪","元枫","思天","如松",
"妙晴","谷秋","妙松","晓夏","宛筠","碧琴","盼兰","小夏","安容","青曼","千儿","寻双","涵瑶","冷梅","秋柔","思菱","醉波","醉柳","以寒",
"迎夏","向雪","以丹","依凝","如柏","雁菱","凝竹","宛白","初柔","南蕾","书萱","梦槐","南琴","绿海","沛儿","晓瑶","凝蝶","紫雪","念双",
"念真","曼寒","凡霜","飞雪","雪兰","雅霜","从蓉","冷雪","靖巧","觅翠","凡白","乐蓉","迎波","丹烟","梦旋","书双","念桃","夜天",
"安筠","觅柔","初南","秋蝶","千易","安露","诗蕊","山雁","友菱","香露","晓兰","白卉","语山","冷珍","秋翠","夏柳","如之","忆南","书易",
"翠桃","寄瑶","如曼","问柳","幻桃","又菡","醉蝶","亦绿","诗珊","听芹","新之","易巧","念云","晓灵","静枫","夏蓉","如南","幼丝","秋白",
"冰安","秋白","南风","醉山","初彤","凝海","紫文","凌晴","雅琴","傲安","傲之","初蝶","代芹","诗霜","碧灵","诗柳","夏柳","采白","慕梅",
"乐安","冬菱","紫安","宛凝","雨雪","易真","安荷","静竹","代柔","丹秋","绮梅","依白","凝荷","幼珊","忆彤","凌青","之桃","芷荷","听荷",
"代玉","念珍","梦菲","夜春","千秋","白秋","谷菱","飞松","初瑶","惜灵","梦易","新瑶","碧曼","友瑶","雨兰","夜柳","芷珍","含芙",
"夜云","依萱","凝雁","以莲","安南","幼晴","尔琴","飞阳","白凡","沛萍","雪瑶","向卉","采文","乐珍","寒荷","觅双","白桃","安卉","迎曼",
"盼雁","乐松","涵山","问枫","以柳","含海","翠曼","忆梅","涵柳","海蓝","晓曼","代珊","忆丹","静芙","绮兰","梦安","千雁","凝珍",
"梦容","冷雁","飞柏","翠琴","寄真","秋荷","代珊","初雪","雅柏","怜容","如风","南露","紫易","冰凡","海雪","语蓉","碧玉",
"语风","凝梦","从雪","白枫","傲云","白梅","念露","慕凝","雅柔","盼柳","从霜","怀柔","怜晴","夜蓉","若菱","芷文",
"南晴","梦寒","初翠","灵波","问夏","惜海","亦旋","沛芹","幼萱","白凝","初露","迎海","绮玉","凌香","寻芹","映真","含雁",
"寒松","寻雪","青烟","问蕊","灵阳","雪巧","丹萱","凡双","孤萍","紫菱","寻凝","傲柏","傲儿","友容","灵枫","曼凝","若蕊",
"思枫","水卉","问梅","念寒","诗双","翠霜","夜香","寒蕾","凡阳","冷玉","平彤","语薇","幻珊","紫夏","凌波","芷蝶","丹南","之双","凡波",
"思雁","白莲","如容","采柳","沛岚","惜儿","夜玉","水儿","半凡","语海","听莲","幻枫","念柏","冰珍","思山","凝蕊","天玉","思萱",
"向梦","笑南","夏旋","之槐","元灵","以彤","采萱","巧曼","绿兰","平蓝","问萍","绿蓉","靖柏","迎蕾","碧曼","思卉","白柏","妙菡","怜阳",
"雨柏","雁菡","梦之","又莲","乐荷","凝琴","书南","白梦","初瑶","平露","含巧","慕蕊","半莲","醉卉","青雪","雅旋",
"巧荷","飞丹","若灵","诗兰","青梦","海菡","灵槐","忆秋","寒凝","凝芙","绮山","尔蓉","尔冬","映萱","白筠","冰双",
"访彤","绿柏","夏云","笑翠","晓灵","含双","盼波","以云","怜翠","雁风","之卉","平松","问儿","绿柳","如蓉","曼容","天晴","丹琴","惜天",
"寻琴","依瑶","涵易","忆灵","从波","依柔","问兰","山晴","怜珊","之云","飞双","傲白","沛春","雨南","梦之","笑阳","代容","友琴","雁梅",
"友桃","从露","语柔","傲玉","觅夏","晓蓝","新晴","雨莲","凝旋","绿旋","幻香","觅双","冷亦","忆雪","友卉","幻翠","靖柔","寻菱","丹翠",
"安阳","雅寒","惜筠","尔安","雁易","飞瑶","夏兰","沛蓝","静丹","山芙","笑晴","新烟","笑旋","雁兰","凌翠","秋莲","书桃","傲松","语儿",
"映菡","初曼","听云","初夏","雅香","语雪","初珍","白安","冰薇","诗槐","冷玉","冰巧","之槐","夏寒","诗筠","新梅","白曼","安波","从阳",
"含桃","曼卉","笑萍","晓露","寻菡","沛白","平灵","水彤","安彤","涵易","乐巧","依风","紫南","易蓉","紫萍","惜萱","诗蕾","寻绿",
"诗双","寻云","孤丹","谷蓝","山灵","友梅","从云","盼旋","幼旋","尔蓝","沛山","觅松","冰香","依玉","冰之","妙梦",
"以冬","曼青","冷菱","雪曼","安白","千亦","凌蝶","又夏","南烟","靖易","沛凝","翠梅","书文","雪卉","乐儿","安青","初蝶","寄灵",
"惜寒","雨竹","冬莲","绮南","翠柏","平凡","亦玉","孤兰","秋珊","新筠","半芹","夏瑶","念文","涵蕾","雁凡","谷兰","灵凡","凝云",
"曼云","丹彤","南霜","夜梦","从筠","雁芙","语蝶","依波","晓旋","念之","盼芙","曼安","采珊","初柳","曼安","南珍","妙芙","语柳",
"含莲","晓筠","夏山","尔容","念梦","傲南","问薇","雨灵","凝安","冰海","初珍","宛菡","冬卉","盼晴","冷荷","寄翠","幻梅","如凡","语梦",
"易梦","雁荷","代芙","醉易","夏烟","依秋","依波","紫萱","涵易","忆之","幻巧","水风","安寒","白亦","怜雪","听南","念蕾","梦竹","千凡",
"寄琴","采波","元冬","思菱","平卉","笑柳","雪卉","谷梦","绿蝶","飞荷","平安","孤晴","芷荷","曼冬","尔槐","以旋","绿蕊","初夏",
"怜南","千山","雨安","水风","寄柔","幼枫","凡桃","新儿","夏波","雨琴","静槐","元槐","映阳","飞薇","小凝","映寒","傲菡","谷蕊","笑槐",
"飞兰","笑卉","迎荷","元冬","书竹","半烟","绮波","小之","觅露","夜雪","寒梦","尔风","白梅","雨旋","芷珊","山彤","尔柳","沛柔","灵萱",
"沛凝","白容","乐蓉","映安","依云","映冬","凡雁","梦秋","醉柳","梦凡","若云","元容","怀蕾","灵寒","天薇","白风","访波","亦凝","易绿",
"夜南","曼凡","亦巧","青易","冰真","白萱","友安","诗翠","雪珍","海之","小蕊","又琴","香彤","语梦","惜蕊","迎彤","沛白","雁山","易蓉",
"雪晴","诗珊","冰绿","半梅","笑容","沛凝","念瑶","如冬","向真","从蓉","亦云","向雁","尔蝶","冬易","丹亦","夏山","醉香","盼夏","孤菱",
"安莲","问凝","冬萱","晓山","雁蓉","梦蕊","山菡","南莲","飞双","思萱","怀梦","雨梅","冷霜","向松","迎梅","听双","山蝶",
"夜梅","醉冬","雨筠","平文","青文","半蕾","幼菱","寻梅","含之","香之","含蕊","亦玉","靖荷","碧萱","寒云","向南","书雁","怀薇","思菱",
"忆文","若山","向秋","凡白","绮烟","从蕾","天曼","又亦","依琴","曼彤","沛槐","又槐","元绿","安珊","夏之","易槐","宛亦","白翠","丹云",
"问寒","易文","傲易","青旋","思真","妙之","半双","若翠","初兰","怀曼","惜萍","初之","幻儿","千风","天蓉","雅青","寄文","代天",
"惜珊","向薇","冬灵","惜芹","凌青","谷芹","雁桃","映雁","书兰","寄风","访烟","绮晴","傲柔","寄容","以珊","紫雪","芷容","书琴","寻桃",
"涵阳","怀寒","易云","采蓝","代秋","惜梦","尔烟","谷槐","怀莲","涵菱","水蓝","访冬","冬卉","安双","冰岚","香薇","语芹",
"静珊","幻露","静柏","小翠","雁卉","访文","凌文","芷云","思柔","巧凡","慕山","依云","千柳","从凝","安梦","香旋","映天",
"安柏","平萱","以筠","忆曼","新竹","绮露","觅儿","碧蓉","白竹","飞兰","曼雁","雁露","凝冬","含灵","初阳","海秋","冰双","绿兰","盼易",
"思松","梦山","友灵","绿竹","灵安","凌柏","秋柔","又蓝","尔竹","青枫","问芙","语海","灵珊","凝丹","小蕾","迎夏","水之","飞珍",
"冰夏","亦竹","飞莲","海白","元蝶","芷天","怀绿","尔容","元芹","若云","寒烟","听筠","采梦","凝莲","元彤","觅山","代桃","冷之","盼秋",
"秋寒","慕蕊","海亦","初晴","巧蕊","听安","芷雪","以松","梦槐","寒梅","香岚","寄柔","映冬","孤容","晓蕾","安萱","听枫","夜绿","雪莲",
"从丹","碧蓉","绮琴","雨文","幼荷","青柏","初蓝","忆安","盼晴","寻冬","雪珊","梦寒","迎南","如彤","采枫","若雁","翠阳","沛容","幻翠",
"山兰","芷波","雪瑶","寄云","慕卉","冷松","涵梅","书白","雁卉","宛秋","傲旋","新之","凡儿","夏真","静枫","乐双","白玉","问玉",
"寄松","丹蝶","元瑶","冰蝶","访曼","代灵","芷烟","白易","尔阳","怜烟","平卉","丹寒","访梦","绿凝","冰菱","语蕊","思烟","忆枫","映菱",
"凌兰","曼岚","若枫","傲薇","凡灵","乐蕊","秋灵","谷槐","觅云"};
int tmp = (int)(Math.random()*100);
int index;
if(tmp < 50){
index = random.nextInt(107);
}else{
index = random.nextInt(firstName.length-109)+108;
}
String first = firstName[index]; //獲取隨機名
return first;
}
/**
* 獲取隨機姓
* @return
*/
private String getLastName(){
Random random=new Random();
/* 598 百家姓 */
String[] lastName= {"赵","孙","李","周","吴","郑","王","陈","张","卫","蒋","沈","韩","杨","朱","秦","许","何","吕","曹",
"施","孔","曹","严","华","金","魏","陶","冯","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","钱","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","褚","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","尤","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
//設定姓氏出現的概率
int tmp = (int)(Math.random()*100);
int index;
if(tmp < 90){
index = random.nextInt(19);
}else if(tmp < 95){
index = random.nextInt(69)+20;
}else{
index = random.nextInt(lastName.length-91)+90;
}
String last = lastName[index]; //获得一个随机的姓氏
return last;
}
}
| 36.124528 | 151 | 0.592865 |
418ca186ab8472ad0b2c380223bb3db9fe85b84e | 3,713 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.quantum.biblioteca.ejb;
import co.edu.uniandes.quantum.biblioteca.entities.BlogEntity;
import co.edu.uniandes.quantum.biblioteca.exceptions.BusinessLogicException;
import co.edu.uniandes.quantum.biblioteca.persistence.BlogPersistence;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
*
* @author da.leon
*/
@Stateless
public class BlogLogic
{
private static final Logger LOGGER = Logger.getLogger(BlogLogic.class.getName());
@Inject
private BlogPersistence persistence;
/**
* Devuelve los Blog que se encuentran en la base de datos.
* @return los Blogs como una lista de objetos.
* Corresponde a la lógica de GET Blogs
*/
public List<BlogEntity> getBlogs() {
LOGGER.info("Inicia proceso de consultar todos los blogs");
List<BlogEntity> blog = persistence.findAll();
LOGGER.info("Termina proceso de consultar todos los blogs");
return blog;
}
/**
* Devuelve el Blog que se encuentran en la base de datos con el id dado.
* @param id del blog a buscar en la DB.
* @return el blog como un objeto Entity.
* Corresponde a la lógica de GET Blogs/{id}
*/
public BlogEntity getBlog(Long id) {
LOGGER.log(Level.INFO, "Inicia proceso de consultar coomentario con id={0}", id);
BlogEntity blog = persistence.find(id);
if (blog == null)
{
LOGGER.log(Level.SEVERE, "El blog con el id {0} no existe", id);
}
LOGGER.log(Level.INFO, "Termina proceso de consultar blog con id={0}", id);
return blog;
}
/**
* Devuelve el blog que se hizo persistir en la base de datos.
* @param entity blog a persistir
* @return el blog como un objeto Entity.
* Corresponde a la lógica de POST/Blog
*/
public BlogEntity crearBlog(BlogEntity entity) throws BusinessLogicException {
LOGGER.info("Inicia proceso de creación de Blog");
persistence.create(entity);
LOGGER.info("Termina proceso de creación de Blog");
return entity;
}
/**
* Método privado desde el cual se verifica que un id sea valido para un Blog.
* @param id a verificar.
* @return true si es valido, false en caso contrario.
*/
private boolean validateId(Long id)
{
return !(id==null||id ==0);
}
/**
* Devuelve el blog que se actualizo en la base de datos.
* @param id del blog a actualizar.
* @param entity blog a actualizar
* @return el blog como un objeto Entity.
* Corresponde a la lógica de PUT Blog/{id}
*/
public BlogEntity updateBlog(Long id, BlogEntity entity) throws BusinessLogicException {
LOGGER.log(Level.INFO, "Inicia proceso de actualizar Blog con id={0}", id);
if (!validateId(entity.getId())) {
throw new BusinessLogicException("El (id) es inválido");
}
BlogEntity newEntity = persistence.update(entity);
LOGGER.log(Level.INFO, "Termina proceso de actualizar Blog con id={0}", entity.getId());
return newEntity;
}
/**
* Devuelve el Blog que se borrará de la base de datos.
* @param id del Blog a borrar.
* Corresponde a la lógica de DELETE Blog/{id}
*/
public void deleteBlog(Long id) {
LOGGER.log(Level.INFO, "Inicia proceso de borrar blog con id={0}", id);
persistence.delete(id);
LOGGER.log(Level.INFO, "Termina proceso de borrar blog con id={0}", id);
}
} | 33.151786 | 96 | 0.668731 |
10e93a48a9400c429643d555356ba20134e2fe04 | 7,571 | package springbook.learningtest.spring.ioc;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Provider;
import javax.servlet.ServletException;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean;
import org.springframework.beans.factory.config.ServiceLocatorFactoryBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class ScopeTest {
@Test
public void singletonScope() {
ApplicationContext ac = new AnnotationConfigApplicationContext(SingletonBean.class, SingletonClientBean.class);
Set<SingletonBean> bean = new HashSet<SingletonBean>();
bean.add(ac.getBean(SingletonBean.class));
bean.add(ac.getBean(SingletonBean.class));
assertThat(bean.size(), is(1));
bean.add(ac.getBean(SingletonClientBean.class).bean1);
bean.add(ac.getBean(SingletonClientBean.class).bean2);
assertThat(bean.size(), is(1));
}
static class SingletonBean {}
static class SingletonClientBean {
@Autowired SingletonBean bean1;
@Autowired SingletonBean bean2;
}
@Test
public void prototypeScope() {
ApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class, PrototypeClientBean.class);
Set<PrototypeBean> bean = new HashSet<PrototypeBean>();
bean.add(ac.getBean(PrototypeBean.class));
assertThat(bean.size(), is(1));
bean.add(ac.getBean(PrototypeBean.class));
assertThat(bean.size(), is(2));
bean.add(ac.getBean(PrototypeClientBean.class).bean1);
assertThat(bean.size(), is(3));
bean.add(ac.getBean(PrototypeClientBean.class).bean2);
assertThat(bean.size(), is(4));
}
@Component("prototypeBean") @Scope("prototype") static class PrototypeBean {}
static class PrototypeClientBean {
@Autowired PrototypeBean bean1;
@Autowired PrototypeBean bean2;
}
@Test
public void objectFactory() {
ApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class, ObjectFactoryConfig.class);
ObjectFactory<PrototypeBean> factoryBeanFactory = ac.getBean("prototypeBeanFactory", ObjectFactory.class);
Set<PrototypeBean> bean = new HashSet<PrototypeBean>();
for(int i=1; i<=4; i++) {
bean.add(factoryBeanFactory.getObject());
assertThat(bean.size(), is(i));
}
}
@Configuration
static class ObjectFactoryConfig {
@Bean public ObjectFactoryCreatingFactoryBean prototypeBeanFactory() {
ObjectFactoryCreatingFactoryBean factoryBean = new ObjectFactoryCreatingFactoryBean();
factoryBean.setTargetBeanName("prototypeBean");
return factoryBean;
}
}
@Test
public void serviceLocatorFactoryBean() {
ApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class, ServiceLocatorConfig.class);
PrototypeBeanFactory factory = ac.getBean(PrototypeBeanFactory.class);
Set<PrototypeBean> bean = new HashSet<PrototypeBean>();
for(int i=1; i<=4; i++) {
bean.add(factory.getPrototypeBean());
assertThat(bean.size(), is(i));
}
}
interface PrototypeBeanFactory { PrototypeBean getPrototypeBean(); }
@Configuration
static class ServiceLocatorConfig {
@Bean public ServiceLocatorFactoryBean prototypeBeanFactory() {
ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
factoryBean.setServiceLocatorInterface(PrototypeBeanFactory.class);
return factoryBean;
}
}
@Test
public void providerTest() {
ApplicationContext ac = new AnnotationConfigApplicationContext(PrototypeBean.class, ProviderClient.class);
ProviderClient client = ac.getBean(ProviderClient.class);
Set<PrototypeBean> bean = new HashSet<PrototypeBean>();
for(int i=1; i<=4; i++) {
bean.add(client.prototypeBeanProvider.get());
assertThat(bean.size(), is(i));
}
}
static class ProviderClient {
@Resource Provider<PrototypeBean> prototypeBeanProvider;
}
static class AnnotationConfigDispatcherServlet extends DispatcherServlet {
private Class<?>[] classes;
public AnnotationConfigDispatcherServlet(Class<?> ...classes) {
super();
this.classes = classes;
}
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
AbstractRefreshableWebApplicationContext wac = new AbstractRefreshableWebApplicationContext() {
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException {
AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(beanFactory);
reader.register(classes);
}
};
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.refresh();
return wac;
}
}
MockHttpServletResponse response = new MockHttpServletResponse();
@Test
public void requestScope() throws ServletException, IOException {
MockServletConfig ctx = new MockServletConfig(new MockServletContext(), "spring");
DispatcherServlet ds = new AnnotationConfigDispatcherServlet(HelloController.class, HelloService.class, RequestBean.class, BeanCounter.class);
ds.init(new MockServletConfig());
BeanCounter counter = ds.getWebApplicationContext().getBean(BeanCounter.class);
ds.service(new MockHttpServletRequest("GET", "/hello"), this.response);
assertThat(counter.addCounter, is(2));
assertThat(counter.size(), is(1));
ds.service(new MockHttpServletRequest("GET", "/hello"), this.response);
assertThat(counter.addCounter, is(4));
assertThat(counter.size(), is(2));
for(String name : ((AbstractRefreshableWebApplicationContext)ds.getWebApplicationContext()).getBeanFactory().getRegisteredScopeNames()) {
System.out.println(name);
}
}
@RequestMapping("/") static class HelloController {
@Autowired HelloService helloService;
@Autowired Provider<RequestBean> requestBeanProvider;
@Autowired BeanCounter beanCounter;
@RequestMapping("hello") public String hello() {
beanCounter.addCounter++;
beanCounter.add(requestBeanProvider.get());
helloService.hello();
return "";
}
}
static class HelloService {
@Autowired Provider<RequestBean> requestBeanProvider;
@Autowired BeanCounter beanCounter;
public void hello() {
beanCounter.addCounter++;
beanCounter.add(requestBeanProvider.get());
}
}
@Scope(value="request") static class RequestBean {}
static class BeanCounter extends HashSet { int addCounter = 0; };
}
| 37.666667 | 144 | 0.784969 |
31b19f0ae4d836b7cc8bdf62178577b4513ad4a8 | 2,282 | package org.opencloudb.sqlexecute;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class MultiThreadSelectTest {
private static void testSequnce(Connection theCon) throws SQLException {
boolean autCommit = System.currentTimeMillis() % 2 == 1;
theCon.setAutoCommit(autCommit);
String sql = "select * from company ";
Statement stmt = theCon.createStatement();
int charChoise = (int) (System.currentTimeMillis() % 3);
if (charChoise == 0) {
stmt.executeQuery("SET NAMES UTF8;");
} else if (charChoise == 1) {
stmt.executeQuery("SET NAMES latin1;");
}
if (charChoise == 2) {
stmt.executeQuery("SET NAMES gb2312;");
}
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
System.out.println(Thread.currentThread().getName() + " get seq " + rs.getLong(1));
} else {
System.out.println(Thread.currentThread().getName() + " can't get seq ");
}
if (autCommit == false) {
theCon.commit();
}
stmt.close();
}
private static Connection getCon(String url, String user, String passwd) throws SQLException {
Connection theCon = DriverManager.getConnection(url, user, passwd);
return theCon;
}
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
final String url = "jdbc:mysql://localhost:8066/TESTDB";
final String user = "test";
final String password = "test";
List<Thread> threads = new ArrayList<Thread>(100);
for (int i = 0; i < 50; i++) {
threads.add(new Thread() {
public void run() {
Connection con;
try {
con = getCon(url, user, password);
for (int i = 0; i < 10000; i++) {
testSequnce(con);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
for (Thread thred : threads) {
thred.start();
}
boolean hasRunning = true;
while (hasRunning) {
hasRunning = false;
for (Thread thred : threads) {
if (thred.isAlive()) {
try {
Thread.sleep(1000);
hasRunning = true;
} catch (InterruptedException e) {
}
}
}
}
}
}
| 23.525773 | 95 | 0.644172 |
968263af77c14b34f25163d9e03d29dcf75fb9fc | 1,214 | package beans;
//- 컨텐츠 생성에 사진을(3개 Fix) 업로드하기 위한 필드(변수)를 모아 놓은 Dto 입니다
public class Host_Content_Photo_Dto {
private int host_content_photo_no;
private int host_content_no;
private String host_content_original_file;
private String host_content_edit_file;
public Host_Content_Photo_Dto() {
super();
}
public int getHost_content_photo_no() {
return host_content_photo_no;
}
public void setHost_content_photo_no(int host_content_photo_no) {
this.host_content_photo_no = host_content_photo_no;
}
public int getHost_content_no() {
return host_content_no;
}
public void setHost_content_no(int host_content_no) {
this.host_content_no = host_content_no;
}
public String getHost_content_original_file() {
return host_content_original_file;
}
public void setHost_content_original_file(String host_content_original_file) {
this.host_content_original_file = host_content_original_file;
}
public String getHost_content_edit_file() {
return host_content_edit_file;
}
public void setHost_content_edit_file(String host_content_edit_file) {
this.host_content_edit_file = host_content_edit_file;
}
}
| 19.901639 | 80 | 0.751236 |
ba56495cb30f02bd64befdfd08693bbbe5d90aa1 | 289 | package com.github.fluent.hibernate.cfg.scanner.other.persistent;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
*
* @author V.Ladynev
*/
@Entity
@Table
public class OtherRootEntity {
@Entity
@Table
public static class OtherNestedEntity {
}
}
| 13.761905 | 65 | 0.716263 |
bf36efdf20b82d061129d91993c954038b945df0 | 2,257 | package com.atlas.skynet.zuul.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.atlas.model.ErrorCode;
import com.atlas.model.Result;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
/**
* @description 数据拦截示例,一般用于请求头的拦截,为了方便浏览器实验,
* 暂时用普通参数方式,可以用POSTMAN更方便测试各种情况的拦截
* http://127.0.0.1/api/atlas/sayMyName?name=张三&authcode=10001
* http://127.0.0.1/api/atlas/getPort?authcode=10001
* @className AccessUserNameFilter
* @author anytron
* @date 2020年2月6日上午3:26:26
* @version 1.0
*/
public class AccessUserNameFilter extends ZuulFilter {
private static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
logger.info(String.format("%s AccessUserNameFilter request to %s", request.getMethod(), request.getRequestURL().toString()));
String authcode = request.getParameter("authcode");// 获取请求的参数
if (StringUtils.isNotBlank(authcode)) {// 如果请求的参数不为空则通过
ctx.setSendZuulResponse(true);// 对该请求进行路由
ctx.setResponseStatusCode(200);
ctx.set("isSuccess", true);// 设值,让下一个Filter看到上一个Filter的状态
return null;
} else {
ctx.setSendZuulResponse(false);// 过滤该请求,不对其进行路由
ctx.setResponseStatusCode(401);// 返回错误码
Result<String> result = new Result<String>(ErrorCode.AUTH_ERROR);
String resultStr = JSON.toJSONString(result);
ctx.setResponseBody(resultStr);// 返回错误内容
ctx.set("isSuccess", false);
HttpServletResponse response = ctx.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
return null;
}
}
@Override
public boolean shouldFilter() {
return true;// 是否执行该过滤器,此处为true,说明需要过滤
}
@Override
public int filterOrder() {
return 0;// 优先级为0,数字越大,优先级越低
}
@Override
public String filterType() {
return "pre";// 前置过滤器
}
}
| 31.347222 | 128 | 0.722198 |
1520d33406235bd50ff0be0389e4e7d4ab4c0f00 | 514 | package org.gjt.sp.jedit.bsh;
public class LHSVariable extends LHS {
LHSVariable( NameSpace nameSpace, String varName, boolean localVar )
{
type = VARIABLE;
this.localVar = localVar;
this.varName = varName;
this.nameSpace = nameSpace;
}
public Object assign( Object val, boolean strictJava )
throws UtilEvalError{
if ( localVar )
nameSpace.setLocalVariable( varName, val, strictJava );
else
nameSpace.setVariable( varName, val, strictJava );
return val;
}
}
| 22.347826 | 70 | 0.690661 |
a9426b84098a14c765e9638554275bcdad93716a | 387 | package modelo;
/**
*
* @author Müller Gonçalves
* @since 16/04/2018 - 16:41
* @version 1.0
*/
public class Saque {
private double saque;
public Saque() {
}
public Saque(double saque) {
this.saque = saque;
}
public double getSaque() {
return saque;
}
public void setSaque(double saque) {
this.saque = saque;
}
}
| 13.821429 | 40 | 0.555556 |
e6016342c8345ffa933a483e8fa265c63c95cd98 | 6,319 | package cloud.tianai.rpc.springboot;
import cloud.tianai.rpc.core.bootstrap.ServerBootstrap;
import cloud.tianai.rpc.remoting.api.RpcInvocationPostProcessor;
import cloud.tianai.rpc.springboot.exception.RpcProviderRegisterException;
import cloud.tianai.rpc.springboot.properties.RpcProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import static cloud.tianai.rpc.common.constant.CommonConstant.WEIGHT_KEY;
/**
* @Author: 天爱有情
* @Date: 2020/05/01 17:42
* @Description: 默认的RpcProviderHandler执行器
*/
@Slf4j
public class DefaultRpcProviderHandler implements RpcProviderHandler, BeanFactoryAware, ApplicationListener<ApplicationStartedEvent> {
/**
* 存储RpcProviderBean的容器.
*/
private Map<Object, RpcProviderBean> rpcProviderMap = new ConcurrentHashMap<>(16);
private RpcProperties rpcProperties;
private ConfigurableListableBeanFactory beanFactory;
private boolean autoInit;
private AtomicBoolean init = new AtomicBoolean(false);
public DefaultRpcProviderHandler(RpcProperties rpcProperties, boolean autoInit) {
this.rpcProperties = rpcProperties;
this.autoInit = autoInit;
}
@Override
public RpcProperties getRpcProperties() {
return rpcProperties;
}
@Override
public void registerProvider(Object bean, RpcProviderBean providerBean) {
if (isInit()) {
throw new RpcProviderRegisterException("请在 执行 init() 方法前进行注册Provider");
}
rpcProviderMap.remove(bean);
rpcProviderMap.put(bean, providerBean);
}
@Override
public RpcProviderBean getProvider(Object bean) {
return rpcProviderMap.get(bean);
}
@Override
public Collection<RpcProviderBean> listProviderBeans() {
return rpcProviderMap.values();
}
@Override
public Collection<Object> listProviderSources() {
return rpcProviderMap.keySet();
}
@Override
public void init() {
if (!init.compareAndSet(false, true)) {
log.warn("[{}] 已经被初始化,不可重复调用", this.getClass().getName());
return;
}
if (getRpcProviderMap().isEmpty()) {
return;
}
ServerBootstrap serverBootstrap = getServerBootstrap();
final ServerBootstrap finalServerBootstrap = serverBootstrap;
getRpcProviderMap().forEach((bean, providerBean) -> {
Class<?> targetClass;
if (AopUtils.isAopProxy(bean)) {
targetClass = AopUtils.getTargetClass(bean);
} else {
targetClass = bean.getClass();
}
Class<?> interfaceClass = targetClass.getInterfaces()[0];
Map<String, Object> paramMap = new HashMap<>(8);
Map<String, String> parameters = providerBean.getParameters();
if (!CollectionUtils.isEmpty(parameters)) {
parameters.forEach(paramMap::put);
}
// 权重
paramMap.put(WEIGHT_KEY, String.valueOf(providerBean.getWeight()));
// 注册
finalServerBootstrap.register(interfaceClass, bean, paramMap);
log.info("TIANAI-RPC SERVER register[{}]", interfaceClass.getName());
});
// 注册完的话直接清空即可, 优化内存
this.rpcProviderMap.clear();
}
private ServerBootstrap getServerBootstrap() {
ServerBootstrap serverBootstrap;
try {
serverBootstrap = beanFactory.getBean(ServerBootstrap.class);
} catch (NoSuchBeanDefinitionException e) {
synchronized (this) {
try {
serverBootstrap = beanFactory.getBean(ServerBootstrap.class);
} catch (NoSuchBeanDefinitionException ex) {
serverBootstrap = createServerBootstrap();
beanFactory.registerSingleton(serverBootstrap.getClass().getName(), serverBootstrap);
}
}
}
return serverBootstrap;
}
private ServerBootstrap createServerBootstrap() {
// 读取对应的invocationPostProcessor并进行装配
List<RpcInvocationPostProcessor> rpcInvocationPostProcessors = getRpcInvocationPostProcessors();
ServerBootstrap serverBootstrap = new ServerBootstrapBuilder()
.setRpcProperties(rpcProperties)
.setRpcInvocationPostProcessors(rpcInvocationPostProcessors)
.buildAndStart();
return serverBootstrap;
}
private List<RpcInvocationPostProcessor> getRpcInvocationPostProcessors() {
List<RpcInvocationPostProcessor> result = new LinkedList<>();
String[] names = beanFactory.getBeanNamesForType(RpcInvocationPostProcessor.class, true, false);
for (String name : names) {
RpcInvocationPostProcessor bean = beanFactory.getBean(name, RpcInvocationPostProcessor.class);
result.add(bean);
}
// 排序
AnnotationAwareOrderComparator.sort(result);
return result;
}
@Override
public boolean isInit() {
return init.get();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
public void setRpcProviderMap(Map<Object, RpcProviderBean> rpcProviderMap) {
this.rpcProviderMap = rpcProviderMap;
}
public Map<Object, RpcProviderBean> getRpcProviderMap() {
return rpcProviderMap;
}
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
if (autoInit && !isInit()) {
init();
}
}
}
| 36.108571 | 134 | 0.682861 |
89d71567f5d754a6e451468d68e8e8df4682cf11 | 3,786 | package com.example.fitnessapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.jetbrains.annotations.NotNull;
import java.io.Serializable;
import models.User;
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText)findViewById(R.id.loginEmail);
password = (EditText)findViewById(R.id.loginPassword);
Intent logoutIntent = getIntent();
boolean isLogoutWanted = logoutIntent.getBooleanExtra("isLogoutWanted", false);
try {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null && isLogoutWanted != false) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("User", user);
startActivity(intent);
}
}
catch (Exception exception) {
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void redirectToRegister(View view) {
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
}
public void login(View view) {
String email = this.email.getText().toString();
String password = this.password.getText().toString();
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>(){
@Override
public void onComplete(@NonNull @NotNull Task<AuthResult> task) {
try {
if (task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Successfully logged in!",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(LoginActivity.this, "Invalid email or password!",
Toast.LENGTH_LONG).show();
}
}
catch (Exception exception) {
Toast.makeText(LoginActivity.this, "Oops, something went wrong!",
Toast.LENGTH_LONG).show();
}
}
});
}
public void logout() {
try {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Intent logoutFromMain = getIntent();
if (user != null && logoutFromMain != null) {
FirebaseAuth.getInstance().signOut();
Toast.makeText(this, "Successfully logged out!", Toast.LENGTH_LONG).show();
Intent logoutIntent = new Intent(this, LoginActivity.class);
logoutIntent.putExtra("isLogoutWanted", true);
startActivity(logoutIntent);
}
}
catch (Exception exception) {
Toast.makeText(this, "Oops, something went wrong!", Toast.LENGTH_LONG).show();
}
}
} | 39.030928 | 138 | 0.616746 |
7beca1fe73afda97cae560f86c5782e38999fc3c | 4,055 | package mblog.core.persist.service.impl;
import mblog.base.lang.Common;
import mblog.base.lang.EnumProject;
import mblog.base.lang.EnumTaskStatus;
import mblog.core.data.GeneralizeTask;
import mblog.core.data.Resume;
import mblog.core.persist.dao.GeneralizeListDao;
import mblog.core.persist.dao.GeneralizeTaskDao;
import mblog.core.persist.entity.GeneralizeTaskPO;
import mblog.core.persist.service.GeneralizeService;
import mblog.core.persist.utils.BeanMapUtils;
import mblog.core.task.BaoshixingqiuTask;
import mblog.core.task.BitfishTask;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
public class GeneralizeServiceImpl implements GeneralizeService {
@Autowired
private GeneralizeTaskDao generalizeTaskDao;
@Autowired
private GeneralizeListDao generalizeListDao;
@Override
public void addTask(GeneralizeTask task) {
GeneralizeTaskPO po = new GeneralizeTaskPO();
BeanUtils.copyProperties(task, po);
po.setStatus(EnumTaskStatus.STOPED.getName());
generalizeTaskDao.save(po);
}
@Override
public Page<GeneralizeTask> list(Pageable pageable) {
Page<GeneralizeTaskPO> page = generalizeTaskDao.findAll(pageable);
List<GeneralizeTask> rets = new ArrayList<>();
page.getContent().forEach(po -> {
GeneralizeTask ret = BeanMapUtils.copy(po);
ret.setStatus(EnumTaskStatus.valueOf(ret.getStatus()).getValue());
rets.add(ret);
});
return new PageImpl<>(rets, pageable, page.getTotalElements());
}
@Override
@Transactional
@CacheEvict(value = "commentsCaches", allEntries = true)
public void delete(List<Long> ids) {
generalizeTaskDao.deleteAllByIdIn(ids);
}
@Override
public Page<Resume> getResumeList(Pageable pageable) {
return null;
}
@Override
public String startTaskById(Long id) {
GeneralizeTaskPO taskPO = generalizeTaskDao.findById(id);
if(taskPO == null){
return "任务不存在";
}
if(EnumTaskStatus.RUNNING.getName().equals(taskPO.getStatus())){
return "任务已经在运行中";
}
return startTask(taskPO);
}
private String startTask(GeneralizeTaskPO taskPO){
Thread thread = null;
if(taskPO.getProject().equals(EnumProject.BITFISH.getValue())) {
thread = new BitfishTask(taskPO, generalizeTaskDao, generalizeListDao);
}
else if(taskPO.getProject().equals(EnumProject.BAOSHI_XINGQIU.getValue())){
thread = new BaoshixingqiuTask(taskPO, generalizeTaskDao, generalizeListDao);
}
else{
return "项目不存在";
}
Common.threadList.put(Common.GENERALIZE_THREAD+taskPO.getId(), thread);
Common.cachedThreadPool.execute(thread);
taskPO.setStatus(EnumTaskStatus.RUNNING.getName());
taskPO.setSuccessCount(0);
taskPO.setFailedCount(0);
generalizeTaskDao.save(taskPO);
return "操作成功";
}
@Override
public String stopTask(Long id) {
GeneralizeTaskPO taskPO = generalizeTaskDao.findById(id);
if(taskPO == null){
return "任务不存在";
}
if(EnumTaskStatus.STOPED.getName().equals(taskPO.getStatus())){
return "任务已经停止";
}
Thread thread = Common.threadList.get(Common.GENERALIZE_THREAD+id);
if(thread != null){
Common.threadList.remove(Common.GENERALIZE_THREAD+id);
}
taskPO.setStatus(EnumTaskStatus.STOPED.getName());
generalizeTaskDao.save(taskPO);
return "操作成功";
}
@Override
public void initTask() {
}
}
| 32.44 | 89 | 0.6873 |
ba34567619294bb4ac1b22adfa7f4b8cf6e55158 | 1,170 | package com.ugiant.modules.sys.web;
import java.util.List;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.ugiant.common.utils.PageUtils;
import com.ugiant.common.web.BaseController;
import com.ugiant.modules.sys.model.Dict;
import com.ugiant.modules.sys.service.DictService;
/**
* 字典 控制器
* @author lingyuwang
*
*/
public class DictController extends BaseController {
private DictService dictService = DictService.service;
/**
* 字典管理页
* @return
*/
public void index() {
List<Record> typeList = dictService.findTypeList();
this.setAttr("typeList", typeList);
int pageNo = PageUtils.getPageNo(this.getRequest(), this.getResponse(), this.getParaToInt("pageNo"), this.getParaToBoolean("repage"));
int pageSize = PageUtils.getPageSize(this.getParaToInt("pageSize"));
Dict dict = this.getModel(Dict.class); // 字典
Page<Record> page = dictService.findPageByDict(pageNo, pageSize, dict);
this.setAttr("page", page);
this.render("dictList.jsp");
}
/**
* 字典添加页
* @return
*/
public void form() {
this.render("dictForm.jsp");
}
}
| 26 | 137 | 0.695726 |
1ffd593bc1d8cb6c697bd3da212c03dc9f782f40 | 2,037 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.12
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.pjsip.pjsua;
public enum pjsip_transport_type_e {
PJSIP_TRANSPORT_UNSPECIFIED,
PJSIP_TRANSPORT_UDP,
PJSIP_TRANSPORT_TCP,
PJSIP_TRANSPORT_TLS,
PJSIP_TRANSPORT_SCTP,
PJSIP_TRANSPORT_LOOP,
PJSIP_TRANSPORT_LOOP_DGRAM,
PJSIP_TRANSPORT_START_OTHER,
PJSIP_TRANSPORT_IPV6(pjsuaJNI.PJSIP_TRANSPORT_IPV6_get()),
PJSIP_TRANSPORT_UDP6(pjsuaJNI.PJSIP_TRANSPORT_UDP6_get()),
PJSIP_TRANSPORT_TCP6(pjsuaJNI.PJSIP_TRANSPORT_TCP6_get()),
PJSIP_TRANSPORT_TLS6(pjsuaJNI.PJSIP_TRANSPORT_TLS6_get());
public final int swigValue() {
return swigValue;
}
public static pjsip_transport_type_e swigToEnum(int swigValue) {
pjsip_transport_type_e[] swigValues = pjsip_transport_type_e.class.getEnumConstants();
if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
return swigValues[swigValue];
for (pjsip_transport_type_e swigEnum : swigValues)
if (swigEnum.swigValue == swigValue)
return swigEnum;
throw new IllegalArgumentException("No enum " + pjsip_transport_type_e.class + " with value " + swigValue);
}
@SuppressWarnings("unused")
private pjsip_transport_type_e() {
this.swigValue = SwigNext.next++;
}
@SuppressWarnings("unused")
private pjsip_transport_type_e(int swigValue) {
this.swigValue = swigValue;
SwigNext.next = swigValue+1;
}
@SuppressWarnings("unused")
private pjsip_transport_type_e(pjsip_transport_type_e swigEnum) {
this.swigValue = swigEnum.swigValue;
SwigNext.next = this.swigValue+1;
}
private final int swigValue;
private static class SwigNext {
private static int next = 0;
}
}
| 32.333333 | 111 | 0.694649 |
995a648dcd4abf136c60ae58c33eb6bee1cbf5ff | 325 | /**
* Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending
*/
package io.deephaven.web.client.fu;
/**
* A place to put things like isDevMode() property accessors.
*/
public class JsSettings {
public static boolean isDevMode() {
return "true".equals(System.getProperty("dh.dev", "false"));
}
}
| 21.666667 | 68 | 0.673846 |
d2be3896e96fbb54058bc33d365f9a15e92cf789 | 391 | package com.spacetimecat.collection;
final class BasicIterableFromJavaLang<A> implements BasicFiniteIterable<A>
{
private final java.lang.Iterable<A> i;
public BasicIterableFromJavaLang (java.lang.Iterable<A> i)
{
this.i = i;
}
@Override
public BasicFiniteIterator<A> iterator ()
{
return new BasicIteratorFromJavaUtil<>(i.iterator());
}
}
| 21.722222 | 74 | 0.685422 |
a519a7ee41b7952416afb2b11ca49b7b9f5a8d01 | 4,567 | package com.crescentflare.bitletsynchronizerexample.model.shared;
import android.os.Handler;
import android.text.TextUtils;
import com.crescentflare.bitletsynchronizer.bitlet.BitletHandler;
import com.crescentflare.bitletsynchronizer.bitlet.BitletObserver;
import com.crescentflare.bitletsynchronizerexample.HashUtil;
import com.crescentflare.bitletsynchronizerexample.Settings;
import com.crescentflare.bitletsynchronizerexample.network.Api;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import java.io.IOException;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Shared model: simple bitlet implementation
* Provides a base class for a bitlet implementation for a simple model
*/
public class SimpleBitlet<T> implements BitletHandler<T>
{
// ---
// Members
// ---
private String path;
private long expireTime;
private Map<String, Object> mockedJsonMap;
private Class<T> classObject;
// ---
// Initialization
// ---
public SimpleBitlet(String path, long expireTime, Map<String, Object> mockedJsonMap, Class<T> classObject)
{
this.path = path;
this.expireTime = expireTime;
this.mockedJsonMap = mockedJsonMap;
this.classObject = classObject;
}
// ---
// Implementation
// ---
public void load(final BitletObserver<T> observer)
{
String serverAddress = Settings.instance.getServerAddress();
if (!TextUtils.isEmpty(serverAddress))
{
Api.getInstance(serverAddress).model().getModel(serverAddress + path).enqueue(new Callback<ResponseBody>()
{
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
{
String stringBody = null;
try
{
stringBody = response.body().string();
}
catch (IOException ignored)
{
}
observer.setBitletExpireTime(System.currentTimeMillis() + expireTime);
parseAndFinish(stringBody, null, observer);
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable exception)
{
observer.setException(exception);
observer.finish();
}
});
}
else
{
observer.setBitletExpireTime(System.currentTimeMillis() + expireTime);
parseAndFinish(null, mockedJsonMap, observer);
}
}
// ---
// Asynchronous parsing
// ---
private void parseAndFinish(final String stringJson, final Map<String, Object> mapJson, final BitletObserver<T> observer)
{
final Handler handler = new Handler();
new Thread(new Runnable()
{
@Override
public void run()
{
// Parse
Gson gson = new GsonBuilder().create();
T parsedBitlet = null;
String parsedHash = null;
if (stringJson != null)
{
parsedBitlet = gson.fromJson(stringJson, classObject);
parsedHash = HashUtil.generateMD5(stringJson);
}
else if (mapJson != null)
{
JsonElement jsonElement = gson.toJsonTree(mockedJsonMap);
parsedBitlet = gson.fromJson(jsonElement, classObject);
parsedHash = HashUtil.generateMD5(mapJson.toString());
}
// Finalize and inform observer on main thread
final T bitlet = parsedBitlet;
final String bitletHash = parsedHash;
handler.post(new Runnable()
{
@Override
public void run()
{
if (bitlet != null)
{
observer.setBitlet(bitlet);
}
if (bitletHash != null)
{
observer.setBitletHash(bitletHash);
}
observer.finish();
}
});
}
}).start();
}
}
| 31.496552 | 125 | 0.542807 |
2cdd520e19367e4cd3f40277f972dde801854dc8 | 518 | package com.journaldev.easymock;
import static org.easymock.EasyMock.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class EasyMockAgrumentMatcherComparisonExample {
@Test
public void test() {
List<Integer> mock = mock(ArrayList.class);
expect(mock.add(lt(10))).andReturn(true);
expect(mock.add(geq(10))).andReturn(false);
replay(mock);
assertTrue(mock.add(5));
assertFalse(mock.add(100));
}
} | 20.72 | 55 | 0.735521 |
7f7e811cab66fcb920d0137ad31f84c477651340 | 1,283 | package org.bdxjug.api.domain.team;
import lombok.Data;
/**
*
* @author lfo
*/
@Data
public class TeamMate implements Comparable<TeamMate> {
private final TeamMateID Id;
private final String firstName;
private final String lastName;
private final int year;
private String role;
private String urlAvatar;
@Override
public int compareTo(TeamMate other) {
final int compareRole = compareRole(role, other.role);
if (compareRole == 0) {
return lastName.compareTo(other.lastName);
}
return compareRole;
}
// président then non null role first.
private int compareRole(String role, String otherRole) {
if ((role == null || role.isEmpty()) && (otherRole == null || otherRole.isEmpty())) {
return 0;
}
if (role == null || role.isEmpty()) {
return 1;
}
if (otherRole == null || otherRole.isEmpty()) {
return -1;
}
if (PRESIDENT.equalsIgnoreCase(role)) {
return -1;
}
if (PRESIDENT.equalsIgnoreCase(otherRole)) {
return 1;
}
return 0;
}
private static final String PRESIDENT = "Président";
}
| 25.66 | 94 | 0.558846 |
ee4aac0c0d2858bb5491a2a5c6cd6396beed51fd | 1,439 | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.skylarkbuildapi.android.AndroidManifestApi;
import javax.annotation.Nullable;
/**
* A {@link StampedAndroidManifest} with placeholders removed to avoid interfering with the legacy
* manifest merger.
*
* <p>TODO(b/30817309) Just use {@link StampedAndroidManifest} once the legacy merger is removed.
*/
public class ProcessedAndroidManifest extends StampedAndroidManifest implements AndroidManifestApi {
ProcessedAndroidManifest(Artifact manifest, @Nullable String pkg, boolean exported) {
super(manifest, pkg, exported);
}
@Override
public boolean equals(Object object) {
return (object instanceof ProcessedAndroidManifest) && super.equals(object);
}
}
| 38.891892 | 100 | 0.772064 |
08b6b237cccc07052cfa961bd102094d3e16c20d | 4,991 | /*
* 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.kafka.streams.state.internals;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.state.KeyValueIterator;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import static org.apache.kafka.test.StreamsTestUtils.toList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class FilteredCacheIteratorTest {
private static final CacheFunction IDENTITY_FUNCTION = new CacheFunction() {
@Override
public Bytes key(final Bytes cacheKey) {
return cacheKey;
}
@Override
public Bytes cacheKey(final Bytes key) {
return key;
}
};
@SuppressWarnings("unchecked")
private final InMemoryKeyValueStore<Bytes, LRUCacheEntry> store = new InMemoryKeyValueStore("name", null, null);
private final KeyValue<Bytes, LRUCacheEntry> firstEntry = KeyValue.pair(Bytes.wrap("a".getBytes()),
new LRUCacheEntry("1".getBytes()));
private final List<KeyValue<Bytes, LRUCacheEntry>> entries = Utils.mkList(
firstEntry,
KeyValue.pair(Bytes.wrap("b".getBytes()),
new LRUCacheEntry("2".getBytes())),
KeyValue.pair(Bytes.wrap("c".getBytes()),
new LRUCacheEntry("3".getBytes())));
private FilteredCacheIterator allIterator;
private FilteredCacheIterator firstEntryIterator;
@Before
public void before() {
store.putAll(entries);
final HasNextCondition allCondition = new HasNextCondition() {
@Override
public boolean hasNext(final KeyValueIterator<Bytes, ?> iterator) {
return iterator.hasNext();
}
};
allIterator = new FilteredCacheIterator(
new DelegatingPeekingKeyValueIterator<>("",
store.all()), allCondition, IDENTITY_FUNCTION);
final HasNextCondition firstEntryCondition = new HasNextCondition() {
@Override
public boolean hasNext(final KeyValueIterator<Bytes, ?> iterator) {
return iterator.hasNext() && iterator.peekNextKey().equals(firstEntry.key);
}
};
firstEntryIterator = new FilteredCacheIterator(
new DelegatingPeekingKeyValueIterator<>("",
store.all()), firstEntryCondition, IDENTITY_FUNCTION);
}
@Test
public void shouldAllowEntryMatchingHasNextCondition() {
final List<KeyValue<Bytes, LRUCacheEntry>> keyValues = toList(allIterator);
assertThat(keyValues, equalTo(entries));
}
@Test
public void shouldPeekNextKey() {
while (allIterator.hasNext()) {
final Bytes nextKey = allIterator.peekNextKey();
final KeyValue<Bytes, LRUCacheEntry> next = allIterator.next();
assertThat(next.key, equalTo(nextKey));
}
}
@Test
public void shouldPeekNext() {
while (allIterator.hasNext()) {
final KeyValue<Bytes, LRUCacheEntry> peeked = allIterator.peekNext();
final KeyValue<Bytes, LRUCacheEntry> next = allIterator.next();
assertThat(peeked, equalTo(next));
}
}
@Test
public void shouldNotHaveNextIfHasNextConditionNotMet() {
assertTrue(firstEntryIterator.hasNext());
firstEntryIterator.next();
assertFalse(firstEntryIterator.hasNext());
}
@Test
public void shouldFilterEntriesNotMatchingHasNextCondition() {
final List<KeyValue<Bytes, LRUCacheEntry>> keyValues = toList(firstEntryIterator);
assertThat(keyValues, equalTo(Utils.mkList(firstEntry)));
}
@Test(expected = UnsupportedOperationException.class)
public void shouldThrowUnsupportedOperationExeceptionOnRemove() {
allIterator.remove();
}
}
| 38.099237 | 116 | 0.660589 |
659d5b87887f6e9bfe86f8b8ac903fbad9295675 | 7,548 | // --------------------------------------------------------------------------------
// Copyright 2002-2021 Echo Three, LLC
//
// 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.echothree.ui.web.main.action.humanresources.employee;
import com.echothree.control.user.search.common.SearchUtil;
import com.echothree.control.user.search.common.form.GetEmployeeResultsForm;
import com.echothree.control.user.search.common.form.SearchEmployeesForm;
import com.echothree.control.user.search.common.result.GetEmployeeResultsResult;
import com.echothree.control.user.search.common.result.SearchEmployeesResult;
import com.echothree.model.control.employee.common.transfer.EmployeeResultTransfer;
import com.echothree.model.control.search.common.SearchConstants;
import com.echothree.ui.web.main.framework.ForwardConstants;
import com.echothree.ui.web.main.framework.MainBaseAction;
import com.echothree.ui.web.main.framework.ParameterConstants;
import com.echothree.util.common.command.CommandResult;
import com.echothree.util.common.command.ExecutionResult;
import com.echothree.view.client.web.struts.CustomActionForward;
import com.echothree.view.client.web.struts.sprout.annotation.SproutAction;
import com.echothree.view.client.web.struts.sprout.annotation.SproutForward;
import com.echothree.view.client.web.struts.sprout.annotation.SproutProperty;
import com.echothree.view.client.web.struts.sslext.config.SecureActionMapping;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
@SproutAction(
path = "/HumanResources/Employee/Main",
mappingClass = SecureActionMapping.class,
name = "EmployeeMain",
properties = {
@SproutProperty(property = "secure", value = "true")
},
forwards = {
@SproutForward(name = "Display", path = "/action/HumanResources/Employee/Result", redirect = true),
@SproutForward(name = "Review", path = "/action/HumanResources/Employee/Review", redirect = true),
@SproutForward(name = "Form", path = "/humanresources/employee/main.jsp")
}
)
public class MainAction
extends MainBaseAction<MainActionForm> {
private String getPartyName(HttpServletRequest request)
throws NamingException {
GetEmployeeResultsForm commandForm = SearchUtil.getHome().getGetEmployeeResultsForm();
String partyName = null;
commandForm.setSearchTypeName(SearchConstants.SearchType_HUMAN_RESOURCES);
CommandResult commandResult = SearchUtil.getHome().getEmployeeResults(getUserVisitPK(request), commandForm);
ExecutionResult executionResult = commandResult.getExecutionResult();
GetEmployeeResultsResult result = (GetEmployeeResultsResult)executionResult.getResult();
Collection employeeResults = result.getEmployeeResults();
Iterator iter = employeeResults.iterator();
if(iter.hasNext()) {
partyName = ((EmployeeResultTransfer)iter.next()).getPartyName();
}
return partyName;
}
@Override
public ActionForward executeAction(ActionMapping mapping, MainActionForm actionForm, HttpServletRequest request, HttpServletResponse response)
throws Exception {
String forwardKey;
String partyName = null;
String firstName = actionForm.getFirstName();
String middleName = actionForm.getMiddleName();
String lastName = actionForm.getLastName();
if(wasPost(request)) {
SearchEmployeesForm commandForm = SearchUtil.getHome().getSearchEmployeesForm();
commandForm.setSearchTypeName(SearchConstants.SearchType_HUMAN_RESOURCES);
commandForm.setFirstName(firstName);
commandForm.setFirstNameSoundex(actionForm.getFirstNameSoundex().toString());
commandForm.setMiddleName(middleName);
commandForm.setMiddleNameSoundex(actionForm.getMiddleNameSoundex().toString());
commandForm.setLastName(lastName);
commandForm.setLastNameSoundex(actionForm.getLastNameSoundex().toString());
commandForm.setEmployeeName(actionForm.getEmployeeName());
commandForm.setPartyName(actionForm.getPartyName());
commandForm.setEmployeeStatusChoice(actionForm.getEmployeeStatusChoice());
commandForm.setEmployeeAvailabilityChoice(actionForm.getEmployeeAvailabilityChoice());
commandForm.setCreatedSince(actionForm.getCreatedSince());
commandForm.setModifiedSince(actionForm.getModifiedSince());
CommandResult commandResult = SearchUtil.getHome().searchEmployees(getUserVisitPK(request), commandForm);
if(commandResult.hasErrors()) {
setCommandResultAttribute(request, commandResult);
forwardKey = ForwardConstants.FORM;
} else {
ExecutionResult executionResult = commandResult.getExecutionResult();
SearchEmployeesResult result = (SearchEmployeesResult)executionResult.getResult();
int count = result.getCount();
if(count == 0 || count > 1) {
forwardKey = ForwardConstants.DISPLAY;
} else {
partyName = getPartyName(request);
forwardKey = ForwardConstants.REVIEW;
}
}
} else {
actionForm.setFirstName(request.getParameter(ParameterConstants.FIRST_NAME));
actionForm.setMiddleName(request.getParameter(ParameterConstants.MIDDLE_NAME));
actionForm.setLastName(request.getParameter(ParameterConstants.LAST_NAME));
forwardKey = ForwardConstants.FORM;
}
CustomActionForward customActionForward = new CustomActionForward(mapping.findForward(forwardKey));
if(forwardKey.equals(ForwardConstants.REVIEW)) {
Map<String, String> parameters = new HashMap<>(1);
parameters.put(ParameterConstants.PARTY_NAME, partyName);
customActionForward.setParameters(parameters);
} else if(forwardKey.equals(ForwardConstants.DISPLAY)) {
Map<String, String> parameters = new HashMap<>(4);
if(firstName != null) {
parameters.put(ParameterConstants.FIRST_NAME, firstName);
}
if(middleName != null) {
parameters.put(ParameterConstants.MIDDLE_NAME, middleName);
}
if(lastName != null) {
parameters.put(ParameterConstants.LAST_NAME, lastName);
}
customActionForward.setParameters(parameters);
}
return customActionForward;
}
} | 47.772152 | 146 | 0.693429 |
bb4ddca3106928dffaafb01dc8135b75a8af8e04 | 1,442 | package com.ara.approvalshipment.utils;
import com.ara.approvalshipment.models.Grade;
import com.ara.approvalshipment.models.Shipment;
import com.ara.approvalshipment.models.ShipmentDetail;
import com.ara.approvalshipment.models.Stock;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface AppService {
@GET("pt_android_app.php")
Call<ResponseBody> validateUser(@Query("action") String action, @Query("user_id") String loginId,
@Query("password") String password);
@GET("pt_android_app.php")
Call<List<Shipment>> listShipments(@Query("action") String action, @Query("godown_id") int godownId);
@GET("pt_android_app.php")
Call<List<Grade>> listGrades(@Query("action") String action, @Query("godown_id") int godownId);
@GET("pt_android_app.php")
Call<List<Stock>> listStocks(@Query("action") String action, @Query("from_date") String fromDate,
@Query("to_date") String toDate, @Query("godown_id") int godownId);
@GET("pt_android_app.php")
Call<List<Shipment>> listShipments(@Query("action") String action, @Query("godown_id") int godownId
, @Query("search") String search);
@GET("pt_android_app.php")
Call<ShipmentDetail> getShipmentDetail(@Query("action") String action, @Query("godown_id") int godownId);
}
| 36.05 | 109 | 0.701803 |
d46340754617b1e296beed51b1deb7f4d1effd1a | 4,370 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.query.criteria;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
/**
* @author Steve Ebersole
*/
public class BasicCriteriaExecutionTests extends BaseNonConfigCoreFunctionalTestCase {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { BasicEntity.class };
}
@Test
public void testExecutingBasicCriteriaQuery() {
final CriteriaBuilder criteriaBuilder = sessionFactory().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery();
final Root<BasicEntity> root = criteria.from( BasicEntity.class );
criteria.select( root );
inSession(
session -> session.createQuery( criteria ).list()
);
}
@Test
public void testExecutingBasicCriteriaQueryInStatelessSession() {
final CriteriaBuilder criteriaBuilder = sessionFactory().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery();
final Root<BasicEntity> root = criteria.from( BasicEntity.class );
criteria.select( root );
inStatelessSession(
session -> session.createQuery( criteria ).list()
);
}
@Test
public void testExecutingBasicCriteriaQueryLiteralPredicate() {
final CriteriaBuilder criteriaBuilder = sessionFactory().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery();
final Root<BasicEntity> root = criteria.from( BasicEntity.class );
criteria.select( root );
criteria.where( criteriaBuilder.equal( criteriaBuilder.literal( 1 ), criteriaBuilder.literal( 1 ) ) );
inSession(
session -> session.createQuery( criteria ).list()
);
}
@Test
public void testExecutingBasicCriteriaQueryLiteralPredicateInStatelessSession() {
final CriteriaBuilder criteriaBuilder = sessionFactory().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery();
final Root<BasicEntity> root = criteria.from( BasicEntity.class );
criteria.select( root );
criteria.where( criteriaBuilder.equal( criteriaBuilder.literal( 1 ), criteriaBuilder.literal( 1 ) ) );
inStatelessSession(
session -> session.createQuery( criteria ).list()
);
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support comparing parameters against each other")
public void testExecutingBasicCriteriaQueryParameterPredicate() {
final CriteriaBuilder criteriaBuilder = sessionFactory().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery();
final Root<BasicEntity> root = criteria.from( BasicEntity.class );
criteria.select( root );
final ParameterExpression<Integer> param = criteriaBuilder.parameter( Integer.class );
criteria.where( criteriaBuilder.equal( param, param ) );
inSession(
session -> session.createQuery( criteria ).setParameter( param, 1 ).list()
);
}
@Test
@SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't support comparing parameters against each other")
public void testExecutingBasicCriteriaQueryParameterPredicateInStatelessSession() {
final CriteriaBuilder criteriaBuilder = sessionFactory().getCriteriaBuilder();
final CriteriaQuery<Object> criteria = criteriaBuilder.createQuery();
final Root<BasicEntity> root = criteria.from( BasicEntity.class );
criteria.select( root );
final ParameterExpression<Integer> param = criteriaBuilder.parameter( Integer.class );
criteria.where( criteriaBuilder.equal( param, param ) );
inStatelessSession(
session -> session.createQuery( criteria ).setParameter( param, 1 ).list()
);
}
@Entity(name = "BasicEntity")
public static class BasicEntity {
@Id
@GeneratedValue
private Integer id;
}
}
| 29.931507 | 119 | 0.768879 |
b61cb058209e937d9d804efd24d7524edb0894f7 | 1,138 | package com.tbp.crud.services;
import com.tbp.crud.models.entities.User;
import com.tbp.crud.models.requests.UserRequest;
import com.tbp.crud.models.responses.UserResponse;
import com.tbp.crud.repositories.UserRepository;
import com.tbp.crud.services.impl.UserServiceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@InjectMocks private UserServiceImpl userService;
@Mock private UserRepository userRepository;
@Test
void testCreateUser() {
User user = new User();
user.setName("test");
Mockito.when(userRepository.save(ArgumentMatchers.any())).thenReturn(user);
UserRequest userRequest = new UserRequest();
userRequest.setName("test");
UserResponse userResponse = userService.createUser(userRequest);
Assertions.assertEquals(userResponse.getName(), userRequest.getName());
}
}
| 32.514286 | 79 | 0.790861 |
147b3d7e299f4b4a1f32fc1490049a67c03b3515 | 762 | package com.fxn.utility;
import android.net.Uri;
import android.provider.MediaStore;
/**
* Created by akshay on 06/04/18.
*/
public class Constants {
public static final int sScrollbarAnimDuration = 500;
public static String[] PROJECTION = new String[]{
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.DATE_MODIFIED,
};
public static Uri URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
public static String ORDERBY = MediaStore.Images.Media.DATE_TAKEN + " DESC";
}
| 30.48 | 80 | 0.694226 |
0fdd16b0e46519164d2f1caf501ef2cee0facd3a | 1,651 | package com.davidbriglio.foreground;
import android.app.Activity;
import android.content.Intent;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.annotation.TargetApi;
public class ForegroundPlugin extends CordovaPlugin {
@Override
@TargetApi(26)
public boolean execute (final String action, final JSONArray args, final CallbackContext command) throws JSONException {
if (android.os.Build.VERSION.SDK_INT >= 26) {
Activity activity = cordova.getActivity();
Intent intent = new Intent(activity, ForegroundService.class);
if (action.equals("start")) {
// Tell the service we want to start it
intent.setAction("start");
// Pass the notification title/text/icon to the service
intent.putExtra("title", args.getString(0))
.putExtra("text", args.getString(1))
.putExtra("icon", args.getString(2))
.putExtra("importance", args.getString(3))
.putExtra("id", args.getString(4));
// Start the service
activity.getApplicationContext().startForegroundService(intent);
} else if (action.equals("stop")) {
// Tell the service we want to stop it
intent.setAction("stop");
// Stop the service
activity.getApplicationContext().startService(intent);
}
}
command.success();
return true;
}
}
| 36.688889 | 124 | 0.603876 |
1f5cff67cb09ddfc3204ef92c9ae4a824bf61ed1 | 3,374 | /* Annot8 (annot8.io) - Licensed under Apache-2.0. */
package io.annot8.components.gazetteers.processors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import io.annot8.api.components.Processor;
import io.annot8.api.data.Item;
import io.annot8.common.data.bounds.SpanBounds;
import io.annot8.common.data.content.Text;
import io.annot8.common.data.utils.SortUtils;
import io.annot8.conventions.AnnotationTypes;
import io.annot8.testing.testimpl.TestItem;
import io.annot8.testing.testimpl.content.TestStringContent;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class TermsTest {
@Test
public void test() {
Terms.Settings settings = new Terms.Settings();
settings.setType(AnnotationTypes.ANNOTATION_TYPE_PERSON);
settings.setTerms(Arrays.asList("James", "Tom", "Tommy"));
Terms t = new Terms();
Processor p = t.createComponent(null, settings);
Item item = new TestItem();
Text content =
item.createContent(TestStringContent.class)
.withData("James went to visit Tom (also known as TOMMY), in London. Tommy is aged 32.")
.save();
p.process(item);
assertEquals(1, item.getGroups().getAll().count());
assertEquals(4, content.getAnnotations().getAll().count());
List<String> annotations =
content
.getAnnotations()
.getByBoundsAndType(SpanBounds.class, AnnotationTypes.ANNOTATION_TYPE_PERSON)
.sorted(SortUtils.SORT_BY_SPANBOUNDS)
.map(a -> content.getText(a).get())
.collect(Collectors.toList());
assertEquals("James", annotations.get(0));
assertEquals("Tom", annotations.get(1));
assertEquals("TOMMY", annotations.get(2));
assertEquals("Tommy", annotations.get(3));
List<String> group =
content
.getItem()
.getGroups()
.getAll()
.findFirst()
.get()
.getAnnotationsForContent(content)
.map(a -> content.getText(a).get())
.collect(Collectors.toList());
assertTrue(group.contains("TOMMY"));
assertTrue(group.contains("Tommy"));
}
@Test
public void testCaseSensitive() {
Terms.Settings settings = new Terms.Settings();
settings.setType(AnnotationTypes.ANNOTATION_TYPE_PERSON);
settings.setTerms(Arrays.asList("James", "Tom", "Tommy"));
settings.setCaseSensitive(true);
Terms t = new Terms();
Processor p = t.createComponent(null, settings);
Item item = new TestItem();
Text content =
item.createContent(TestStringContent.class)
.withData("James went to visit Tom (also known as TOMMY), in London.")
.save();
p.process(item);
assertEquals(0, item.getGroups().getAll().count());
assertEquals(2, content.getAnnotations().getAll().count());
List<String> annotations =
content
.getAnnotations()
.getByBoundsAndType(SpanBounds.class, AnnotationTypes.ANNOTATION_TYPE_PERSON)
.sorted(SortUtils.SORT_BY_SPANBOUNDS)
.map(a -> content.getText(a).get())
.collect(Collectors.toList());
assertEquals("James", annotations.get(0));
assertEquals("Tom", annotations.get(1));
}
}
| 31.830189 | 100 | 0.666271 |
0f5233bf3d274fc993fe98ac79c323481549a9c0 | 180 | package ru.otus.spring.exception;
public class EntityCreateException extends RuntimeException{
public EntityCreateException(String message) {
super(message);
}
}
| 20 | 60 | 0.75 |
add8e72d2a358e8f05948e3c632efb05084a7999 | 253 | package string;
public class ValueTes1 {
public static void main(String[] args) {
int n1=10;
float n2=1.5f;
String s1=String.valueOf(n1);
String s2=String.valueOf(n2);
System.out.println(s1);
System.out.println(s2);
}
}
| 15.8125 | 42 | 0.640316 |
1739205ce8f418d9fc1f0445ba51a38366426c6e | 333 | package ru.mydesignstudio.database.metadata.extractor.extractors;
import org.springframework.lang.NonNull;
import ru.mydesignstudio.database.metadata.extractor.extractors.model.DatabaseMetadata;
import java.util.List;
public interface DatabaseMetadataExtractor {
List<DatabaseMetadata> extract(@NonNull List<String> schemas);
}
| 30.272727 | 87 | 0.840841 |
5f35b9005199abbd09b788ba97516c33390cfac7 | 2,239 | /*
* 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.polygene.library.sql.generator.grammar.common.datatypes;
/**
* This class represents the {@code INTEGER} type, sometimes abbreviated as {@code INT} (typically 32-bit integer).
*
* @author Stanislav Muhametsin
*/
public interface SQLInterval
extends SQLDataType, ParametrizableDataType
{
/**
* Returns the start field type for this {@code INTERVAL}.
*
* @return The start field type for this {@code INTERVAL}.
*/
IntervalDataType getStartField();
/**
* Return the start field precision for this {@code INTERVAL}. May be {@code null} if none specified.
*
* @return The start field precision for this {@code INTERVAL}.
*/
Integer getStartFieldPrecision();
/**
* Returns the end field precision for this {@code INTERVAL}. Will always be {@code null} for single datetime field
* intervals.
*
* @return The end field precision for this {@code INTERVAL}.
*/
IntervalDataType getEndField();
/**
* Returns the fraction seconds precision for this {@code INTERVAL}. Will always be {@code null} if the end field
* type is not {@link IntervalDataType#SECOND}, or if this is single datetime field interval, and its start type is
* not {@link IntervalDataType#SECOND}.
*
* @return The fraction seconds precision for this {@code INTERVAL}.
*/
Integer getSecondFracs();
} | 36.704918 | 119 | 0.697186 |
792f20d4d987c9f48cd844a3fdf0462318add9ab | 659 | package com.zou.gulimall.product;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 整合Mybatis-Plus
* 1. 导入依赖
* 2. 配置
* 1. 配置数据源
* 1. 导入Mysql驱动依赖
* 2. 在yml中配置数据源信息
* 2. 配置MyBatis-Plus:
* 1. 使用@MapperScan
* 2. yml中 告诉MyBatis-Plus,sql映射文件位置
*/
@SpringBootApplication
@MapperScan("com.zou.gulimall.product.dao")
public class GulimallProductApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallProductApplication.class, args);
}
}
| 24.407407 | 70 | 0.698027 |
0564289ee2d9de0d9f1df4997862b5e4166417f0 | 3,067 | package security.tsg.com.tsgsecurityframwork;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.test.InstrumentationTestCase;
import org.cryptonode.jncryptor.CryptorException;
import org.junit.Assert;
/**
* Created by Rajvanshi on 27-04-2016.
*/
public class AES256JNTest extends InstrumentationTestCase {
private final static String KEY = "bbC2H19lkVbQDfakxcrtNMQdd0FloLyw";
public void testAES256StringConversion() {
String str = "The quick brown fox jumps over the lazy dog.";
AES256JNEncryption aes256JNEncryption = (AES256JNEncryption) DataSecurityFactory.getAlgoUtility(DataSecurity.TYPE.AES256);
String encryptedData = null;
try {
encryptedData = aes256JNEncryption.encrypt(KEY, str);
} catch (CryptorException e) {
e.printStackTrace();
fail("AES256JN String encryption failed with CryptorException " + e.getMessage());
}
String decryptedData = null;
try {
decryptedData = aes256JNEncryption.decryptToString(KEY, encryptedData);
} catch (CryptorException e) {
e.printStackTrace();
}
Assert.assertEquals("AES256JN string encryption and decryption not matched ", str, decryptedData);
}
public void testAES256ByteArrayConversion() {
String str = "The quick brown fox jumps over the lazy dog.";
AES256JNEncryption aes256JNEncryption = (AES256JNEncryption) DataSecurityFactory.getAlgoUtility(DataSecurity.TYPE.AES256);
String encryptedData = null;
try {
encryptedData = aes256JNEncryption.encrypt(KEY, str.getBytes());
} catch (CryptorException e) {
e.printStackTrace();
fail("AES256JN byte array encryption failed with CryptorException " + e.getMessage());
}
String decryptedData = null;
try {
byte[] byt = aes256JNEncryption.decryptToByteArray(KEY, encryptedData);
decryptedData = new String(byt);
} catch (CryptorException e) {
e.printStackTrace();
}
Assert.assertEquals("AES256JN byte Array encryption and decryption not matched ", str, decryptedData);
}
public void testAES256BitmapConversion() {
Context context = this.getInstrumentation().getTargetContext();
Bitmap bitmapOriginal = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
AES256JNEncryption aes256JNEncryption = (AES256JNEncryption) DataSecurityFactory.getAlgoUtility(DataSecurity.TYPE.AES256);
String encryptedData = null;
try {
encryptedData = aes256JNEncryption.encrypt(KEY, bitmapOriginal);
} catch (CryptorException e) {
e.printStackTrace();
}
Bitmap bmpOutput = null;
try {
bmpOutput = aes256JNEncryption.decryptToBitmap(KEY, encryptedData);
} catch (CryptorException e) {
e.printStackTrace();
}
}
}
| 33.703297 | 130 | 0.673948 |
4aab68a1bc7c7b54ec93e283e1b370292394a89a | 515 | package dev.park.e.bookcafemanager;
import dev.park.e.bookcafemanager.properties.SeojiProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(SeojiProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| 34.333333 | 81 | 0.829126 |
29199175c34980f733bff23d55dd6f1fc9fbf1c0 | 7,957 | package sqlite.samples.chat.model;
import com.abubusoft.kripton.KriptonBinder;
import com.abubusoft.kripton.KriptonJsonContext;
import com.abubusoft.kripton.android.sqlite.SQLiteTable;
import com.abubusoft.kripton.common.KriptonByteArrayOutputStream;
import com.abubusoft.kripton.exception.KriptonRuntimeException;
import com.abubusoft.kripton.persistence.JacksonWrapperParser;
import com.abubusoft.kripton.persistence.JacksonWrapperSerializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* <p>
* Entity <code>User</code> is associated to table <code>user</code>
* This class represents table associated to entity.
* </p>
* @see User
*/
public class UserTable implements SQLiteTable {
/**
* Costant represents typeName of table user
*/
public static final String TABLE_NAME = "user";
/**
* <p>
* DDL to create table user
* </p>
*
* <pre>CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, sorted_map BLOB, sorted_set BLOB, username TEXT);</pre>
*/
public static final String CREATE_TABLE_SQL = "CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, sorted_map BLOB, sorted_set BLOB, username TEXT);";
/**
* <p>
* DDL to drop table user
* </p>
*
* <pre>DROP TABLE IF EXISTS user;</pre>
*/
public static final String DROP_TABLE_SQL = "DROP TABLE IF EXISTS user;";
/**
* Entity's property <code>id</code> is associated to table column <code>id</code>. This costant represents column name.
*
* @see User#id
*/
public static final String COLUMN_ID = "id";
/**
* Entity's property <code>sortedMap</code> is associated to table column <code>sorted_map</code>. This costant represents column name.
*
* @see User#sortedMap
*/
public static final String COLUMN_SORTED_MAP = "sorted_map";
/**
* Entity's property <code>sortedSet</code> is associated to table column <code>sorted_set</code>. This costant represents column name.
*
* @see User#sortedSet
*/
public static final String COLUMN_SORTED_SET = "sorted_set";
/**
* Entity's property <code>username</code> is associated to table column <code>username</code>. This costant represents column name.
*
* @see User#username
*/
public static final String COLUMN_USERNAME = "username";
/**
* Columns array
*/
private static final String[] COLUMNS = {COLUMN_ID, COLUMN_SORTED_MAP, COLUMN_SORTED_SET, COLUMN_USERNAME};
/**
* for attribute sortedMap serialization
*/
public static byte[] serializeSortedMap(SortedMap<String, String> value) {
if (value==null) {
return null;
}
KriptonJsonContext context=KriptonBinder.jsonBind();
try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
jacksonSerializer.writeStartObject();
int fieldCount=0;
if (value!=null) {
fieldCount++;
// write wrapper tag
if (value.size()>0) {
jacksonSerializer.writeFieldName("element");
jacksonSerializer.writeStartArray();
for (Map.Entry<String, String> item: value.entrySet()) {
jacksonSerializer.writeStartObject();
jacksonSerializer.writeStringField("key", item.getKey());
if (item.getValue()==null) {
jacksonSerializer.writeNullField("value");
} else {
jacksonSerializer.writeStringField("value", item.getValue());
}
jacksonSerializer.writeEndObject();
}
jacksonSerializer.writeEndArray();
} else {
jacksonSerializer.writeNullField("element");
}
}
jacksonSerializer.writeEndObject();
jacksonSerializer.flush();
return stream.toByteArray();
} catch(Exception e) {
e.printStackTrace();
throw(new KriptonRuntimeException(e.getMessage()));
}
}
/**
* for attribute sortedMap parsing
*/
public static SortedMap<String, String> parseSortedMap(byte[] input) {
if (input==null) {
return null;
}
KriptonJsonContext context=KriptonBinder.jsonBind();
try (JacksonWrapperParser wrapper=context.createParser(input)) {
JsonParser jacksonParser=wrapper.jacksonParser;
// START_OBJECT
jacksonParser.nextToken();
// value of "element"
jacksonParser.nextValue();
SortedMap<String, String> result=null;
if (jacksonParser.currentToken()==JsonToken.START_ARRAY) {
TreeMap<String, String> collection=new TreeMap<>();
String key=null;
String value=null;
while (jacksonParser.nextToken() != JsonToken.END_ARRAY) {
jacksonParser.nextValue();
key=jacksonParser.getText();
jacksonParser.nextValue();
if (jacksonParser.currentToken()!=JsonToken.VALUE_NULL) {
value=jacksonParser.getText();
}
collection.put(key, value);
key=null;
value=null;
jacksonParser.nextToken();
}
result=collection;
}
return result;
} catch(Exception e) {
e.printStackTrace();
throw(new KriptonRuntimeException(e.getMessage()));
}
}
/**
* for attribute sortedSet serialization
*/
public static byte[] serializeSortedSet(SortedSet<String> value) {
if (value==null) {
return null;
}
KriptonJsonContext context=KriptonBinder.jsonBind();
try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
jacksonSerializer.writeStartObject();
int fieldCount=0;
if (value!=null) {
fieldCount++;
// write wrapper tag
jacksonSerializer.writeFieldName("element");
jacksonSerializer.writeStartArray();
for (String item: value) {
if (item==null) {
jacksonSerializer.writeNull();
} else {
jacksonSerializer.writeString(item);
}
}
jacksonSerializer.writeEndArray();
}
jacksonSerializer.writeEndObject();
jacksonSerializer.flush();
return stream.toByteArray();
} catch(Exception e) {
e.printStackTrace();
throw(new KriptonRuntimeException(e.getMessage()));
}
}
/**
* for attribute sortedSet parsing
*/
public static SortedSet<String> parseSortedSet(byte[] input) {
if (input==null) {
return null;
}
KriptonJsonContext context=KriptonBinder.jsonBind();
try (JacksonWrapperParser wrapper=context.createParser(input)) {
JsonParser jacksonParser=wrapper.jacksonParser;
// START_OBJECT
jacksonParser.nextToken();
// value of "element"
jacksonParser.nextValue();
SortedSet<String> result=null;
if (jacksonParser.currentToken()==JsonToken.START_ARRAY) {
TreeSet<String> collection=new TreeSet<>();
String item=null;
while (jacksonParser.nextToken() != JsonToken.END_ARRAY) {
if (jacksonParser.currentToken()==JsonToken.VALUE_NULL) {
item=null;
} else {
item=jacksonParser.getText();
}
collection.add(item);
}
result=collection;
}
return result;
} catch(Exception e) {
e.printStackTrace();
throw(new KriptonRuntimeException(e.getMessage()));
}
}
/**
* Columns array
*/
@Override
public String[] columns() {
return COLUMNS;
}
/**
* table name
*/
@Override
public String name() {
return TABLE_NAME;
}
}
| 31.701195 | 166 | 0.660927 |
06d5def131ed9bbe4adbb90987d9c5eee562328a | 555 | package app.dao.api;
import app.model.BasicShampoo;
import app.model.ProductionBatch;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
@Repository
public interface ProductionBatchDao extends JpaRepository<ProductionBatch, Long> {
List<ProductionBatch> findByName (String name);
List<ProductionBatch> findByDateAfter (Date date);
List<ProductionBatch> findByShampoosIsNull();
List<ProductionBatch> findByDate(Date date);
}
| 24.130435 | 83 | 0.8 |
be2d12c270b2a5264966d07590987c74c87ebda6 | 668 | package com.tutorial;
import java.util.*;
public class LotteryOdds {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers do you need to draw? ");
int k = input.nextInt();
System.out.println("What is the highest number you can draw");
int n = input.nextInt();
/**
* Compute Binomial Coefficient = n*(n-1)*(n-2)*...*(n-k+1) / 1*2*3..*k
*/
int lotteryOdds = 1;
for (int i = 1; i <= k; i++) {
lotteryOdds = lotteryOdds * (n - i + 1) / i;
System.out.printf("Your odds are 1 in %d. Good Luck!\n", lotteryOdds);
}
}
} | 26.72 | 77 | 0.567365 |
b1c1bb1092ef5396ad4af9cbd9768f9a9ac87d56 | 1,791 | package traffic_domain.bean;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TrafficCondition {
private int id;
private String name;
private String description;
private TrafficCondition parentCondition;
private List<TrafficCondition> subConditions = new ArrayList<TrafficCondition>();
private Set<PostalCode> postalCodes = new HashSet<PostalCode>();
public TrafficCondition() {
}
@SuppressWarnings("unused")
private void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setParentCondition(TrafficCondition parentCondition) {
this.parentCondition = parentCondition;
}
public TrafficCondition getParentCondition() {
return parentCondition;
}
public void setSubConditions(List<TrafficCondition> subConditions) {
this.subConditions = subConditions;
}
public List<TrafficCondition> getSubConditions() {
return subConditions;
}
public void setPostalCodes(Set<PostalCode> postalCodes) {
this.postalCodes = postalCodes;
}
public Set<PostalCode> getPostalCodes() {
return postalCodes;
}
public void addToPostalCode(PostalCode entity) {
this.getPostalCodes().add(entity);
entity.getTrafficConditions().add(this);
}
public void removeFromPostalCode(PostalCode entity) {
this.getPostalCodes().remove(entity);
entity.getTrafficConditions().remove(this);
}
}
| 22.670886 | 83 | 0.700726 |
af925804339893fa7a3d8fd859e65e45e9b2d913 | 2,452 | /*
* Copyright (c) 2017 Frederik Ar. Mikkelsen & NoobLance
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package lavalink.server.io;
import net.dv8tion.jda.CoreClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CoreClientImpl implements CoreClient {
private static final Logger log = LoggerFactory.getLogger(CoreClientImpl.class);
@Override
public void sendWS(String message) {
}
@Override
public boolean isConnected() {
log.warn("isConnected was requested, this shouldn't happen", new RuntimeException());
return true;
}
@Override
public boolean inGuild(String guildId) {
log.warn("inGuild was requested, this shouldn't happen, guildId:" + guildId, new RuntimeException());
return true;
}
@Override
public boolean voiceChannelExists(String guildId, String channelId) {
log.warn("voiceChannelExists was requested, this shouldn't happen, guildId:" + guildId + " channelId:" + channelId, new RuntimeException());
return true;
}
@Override
public boolean hasPermissionInChannel(String guildId, String channelId, long l) {
log.warn("hasPermissionInChannel was requested, this shouldn't happen, guildId:" + guildId + " channelId:" + channelId + " l:" + l, new RuntimeException());
return true;
}
}
| 39.548387 | 165 | 0.707586 |
4ccb8f3c7bc0b063c42c1e13d40c2ad8ec70c742 | 2,485 | package com.routon.plcloud.device.data.entity;
import com.alibaba.fastjson.JSON;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author FireWang
* @date 2020/4/30 11:11
*/
public class Syslog {
private Object id;
private String option;
private Object type;
private String loginfo;
private Date timestamp;
private Object userid;
private String userip;
private String remark;
public static final Map<Integer, String> SYS_TYPE = new LinkedHashMap<Integer, String>();
static {
/*用户操作*/
SYS_TYPE.put(10, "用户登录");
SYS_TYPE.put(11, "修改密码");
SYS_TYPE.put(12, "添加用户");
SYS_TYPE.put(13, "删除用户");
SYS_TYPE.put(14, "重置密码");
/*软件管理操作*/
SYS_TYPE.put(20, "软件上传");
SYS_TYPE.put(21, "软件下载");
SYS_TYPE.put(22, "软件删除");
/*设备管理操作*/
SYS_TYPE.put(30, "设备升级");
SYS_TYPE.put(31, "设备消息");
/*分组操作*/
SYS_TYPE.put(40, "添加公司");
SYS_TYPE.put(41, "删除公司");
SYS_TYPE.put(42, "添加分组");
SYS_TYPE.put(43, "删除分组");
/*文件管理操作*/
SYS_TYPE.put(50, "文件上传");
SYS_TYPE.put(51, "文件下载");
SYS_TYPE.put(52, "文件删除");
SYS_TYPE.put(53, "发布节目单");
}
public void setId(Object id) {
this.id = id;
}
public Object getId() {
return id;
}
public void setOption(String option) {
this.option = option;
}
public String getOption() {
return option;
}
public void setType(Object type) {
this.type = type;
}
public Object getType() {
return type;
}
public void setLoginfo(String loginfo) {
this.loginfo = loginfo;
}
public String getLoginfo() {
return loginfo;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public Date getTimestamp() {
return timestamp;
}
public void setUserid(Object userid) {
this.userid = userid;
}
public Object getUserid() {
return userid;
}
public void setUserip(String userip) {
this.userip = userip;
}
public String getUserip() {
return userip;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getRemark() {
return remark;
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
}
| 20.040323 | 93 | 0.567404 |
dffbb143b5b8c8a65b8bb9ca049c49294db6c500 | 287 | package com.macpi.initializer;
import com.macpi.initializer.tags.Integration;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@Integration
@SpringBootTest
class InitializerApplicationTests {
@Test
void contextLoads() {
}
}
| 17.9375 | 60 | 0.780488 |
2d1b60339bbe154bfde20c762965b0d958372f31 | 1,728 | package gerald1248.hollows;
import android.content.Context;
import android.content.res.Resources;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
* Ensures that all levels given are valid (dimensions, required tiles are present, etc.)
*/
@RunWith(AndroidJUnit4.class)
public class LevelsTest {
@Test
public void useAppContext() throws Exception {
Context appContext = InstrumentationRegistry.getTargetContext();
Resources resources = appContext.getResources();
String[] levels = resources.getStringArray(R.array.levels);
for (String level : levels) {
level = level.trim();
requiredTiles(level);
String[] lines = level.split("\\s+");
dimensions(lines);
validTiles(lines);
}
}
public void requiredTiles(String level) {
boolean b = level.contains("e") && level.contains("s");
assertThat(b, is(true));
}
public void dimensions(String[] lines) {
assertThat(lines.length, is(Constants.CHARMAP_LENGTH));
for (String line : lines) {
assertThat(line.length(), is(Constants.CHARMAP_LENGTH));
}
}
public void validTiles(String[] lines) {
for (String line : lines) {
Pattern p = Pattern.compile("^[\\.|/+^v\u00b4`seatpnr1-9mw]{50}$");
Matcher m = p.matcher(line);
boolean b = m.matches();
assertThat(b, is(true));
}
}
} | 29.793103 | 89 | 0.640625 |
c55f237e5d208842b2f194b290b9ac93b20f37f5 | 584 | package br.com.caelum.stella.example.validator;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Validator;
/**
* @author Mario Amaral
*/
@Resource
public class UsuarioController {
private Validator validator;
public UsuarioController(Validator validator) {
super();
this.validator = validator;
}
public void formulario(){
}
public void cadastra(Usuario usuario) {
validator.validate(usuario);
validator.onErrorUsePageOf(UsuarioController.class).formulario();
//adiciona o usuario
}
}
| 16.685714 | 70 | 0.684932 |
fb3a4e5a0b6a5cc604fdf7da2323ee9d29eceefe | 228 | package com.robsonbittencourt.demoacmeap;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoAcmeApApplicationTests {
@Test
void contextLoads() {
}
}
| 16.285714 | 60 | 0.802632 |
84bedd1097de305a82e8e5709cc04687b477bdfe | 160 | package command.remotecontrol;
/**
* lambda 功能接口下使用,接口仅有一个方法
* 需要有撤销 undo() 就不能用 lambda
*
*/
public interface CommandLambda {
public void execute();
}
| 14.545455 | 32 | 0.7 |
910eb90bdcd0a47a30ccf71c1365c03ee5c09b6a | 215 | package pl.edu.pwr.raven.flightproducer.acquisition;
/**
* @author <a href="mailto:226154@student.pwr.edu.pl">Hanna Grodzicka</a>
*/
public interface FileMonitorListener {
void handleNewLine(String line);
}
| 21.5 | 73 | 0.739535 |
f5862334b1468ca044698195b2e8a017fc516527 | 1,837 | /*
* Copyright 2010-2019 Miyamoto Daisuke.
*
* 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 jp.xet.baseunits.time.spec;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import jp.xet.baseunits.time.CalendarDate;
import jp.xet.baseunits.time.CalendarInterval;
import jp.xet.baseunits.time.DayOfWeek;
import org.junit.Ignore;
import org.junit.Test;
/**
* {@link AndDateSpecification}のテストクラス。
*/
public class AndDateSpecificationTest {
/**
* 無限ループする。。。
*
* @see <a href="http://dragon.xet.jp/jira/browse/BU-5">BU-5</a>
*/
@Ignore("BU-5")
@Test(timeout = 5000L)
public void test() {
CalendarInterval interval =
CalendarInterval.inclusive(CalendarDate.from(2012, 3, 12), CalendarDate.from(2012, 3, 25));
DateSpecification intervalSpec = DateSpecifications.calendarInterval(interval);
DateSpecification dayOfWeekSpec = DateSpecifications.dayOfWeek(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY);
DateSpecification andSpec = new AndDateSpecification(intervalSpec, dayOfWeekSpec);
CalendarInterval investigateInterval = CalendarInterval.everFrom(CalendarDate.from(2012, 3, 23));
assertThat(andSpec.firstOccurrenceIn(investigateInterval), is(nullValue()));
}
}
| 36.019608 | 105 | 0.739793 |
9213a7026e38873db756d2212f8a168d773dbe3a | 2,030 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.coinlab.sampleapp;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.statistics.HistogramDataset;
import org.jfree.data.statistics.HistogramType;
/**
*
* @author seadahai
*/
public class MainClass {
public static void main(String[] args) {
plotNormalDistHist();
}
public static void plotNormalDistHist() throws NotStrictlyPositiveException {
System.out.println("Hello Maven World!");
NormalDistribution normal = new NormalDistribution(0, 1);
double[] value = new double[1000];
for (int i = 1; i < value.length; i++) {
value[i] = normal.sample();
}
int number = 20;
HistogramDataset dataset = new HistogramDataset();
dataset.setType(HistogramType.FREQUENCY);
dataset.addSeries("Histogram", value, number, -3, 3);
String plotTitle = "Histogram";
String xaxis = "number";
String yaxis = "value";
PlotOrientation orientation = PlotOrientation.VERTICAL;
boolean show = false;
boolean toolTips = false;
boolean urls = false;
JFreeChart chart = ChartFactory.createHistogram(plotTitle, xaxis, yaxis,
dataset, orientation, show, toolTips, urls);
int width = 300;
int height = 300;
try {
ChartUtilities.saveChartAsPNG(new File("histogram.png"), chart, width, height);
} catch (IOException e) {
}
}
}
| 35 | 92 | 0.658128 |
89068b0d9d1c1ea1df1c697e0bb122a6adce8486 | 1,074 | package com.princess.android.cryptonews.settings.viewmodel;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import com.princess.android.cryptonews.AppController;
import com.princess.android.cryptonews.injection.CryptoNewsComponents;
import com.princess.android.cryptonews.model.News;
import com.princess.android.cryptonews.settings.repository.CheckValidUrlRepository;
import java.util.List;
import javax.inject.Inject;
/**
* Created by numb3rs on 3/7/18.
*/
public class ValidUrlViewModel extends AndroidViewModel implements CryptoNewsComponents.Injectable {
private CheckValidUrlRepository checkValidUrlRepository;
@Inject
public ValidUrlViewModel() {
super(AppController.getInstance());
}
public LiveData<List<News>> isValidUrl(){
checkValidUrlRepository = new CheckValidUrlRepository();
return checkValidUrlRepository.isValidUrl();
}
@Override
public void inject(CryptoNewsComponents cryptoNewsComponents) {
cryptoNewsComponents.inject(this);
}
}
| 26.85 | 100 | 0.777467 |
eeec5bd12d96fdc6a0871b9f0480c533e559a826 | 4,115 | package com.github.TKnudsen.DMandML.model.evaluation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.github.TKnudsen.ComplexDataObject.data.features.Feature;
import com.github.TKnudsen.ComplexDataObject.data.interfaces.IFeatureVectorObject;
import com.github.TKnudsen.DMandML.model.evaluation.performanceMeasure.IPerformanceMeasure;
import com.github.TKnudsen.DMandML.model.supervised.ILearningModel;
import com.github.TKnudsen.DMandML.model.supervised.classifier.Classifiers;
/**
* <p>
* Title: RandomIterationsEvaluation
* </p>
*
* <p>
* Description:
* </p>
*
* <p>
* Copyright: (c) 2016-2018 Juergen Bernard, https://github.com/TKnudsen/DMandML
* </p>
*
* @author Christian Ritter, Juergen Bernard
* @version 1.04
*/
public class RandomIterationsEvaluation<O, X extends IFeatureVectorObject<O, ? extends Feature<O>>, Y, L extends ILearningModel<X, Y>>
extends AbstractModelEvaluation<X, Y, L> {
private int iterations;
private double split = 0.66;
private List<X> trainset;
private List<X> testset;
private List<Y> trainTruth;
private List<Y> testTruth;
public RandomIterationsEvaluation(List<? extends IPerformanceMeasure<Y>> performanceMeasures, int iterations) {
super(performanceMeasures);
this.iterations = iterations;
}
public RandomIterationsEvaluation(List<? extends IPerformanceMeasure<Y>> performanceMeasures, int iterations,
double split) {
super(performanceMeasures);
this.iterations = iterations;
this.split = split;
}
@Override
public void evaluate(L learner, List<X> featureVectors, List<Y> groundTruth) {
if (learner == null)
throw new IllegalArgumentException("Learning Model must not be null");
if (featureVectors == null || groundTruth == null || featureVectors.size() != groundTruth.size())
throw new IllegalArgumentException("Lists are null or of unequal size!");
performanceValues = new HashMap<>();
for (IPerformanceMeasure<Y> pm : getPerformanceMeasures()) {
performanceValues.put(pm, new ArrayList<>());
}
for (int i = 0; i < iterations; i++) {
trainset = new ArrayList<>();
testset = new ArrayList<>();
trainTruth = new ArrayList<>();
testTruth = new ArrayList<>();
calcRandomTrainAndTestSets(featureVectors, groundTruth);
Classifiers.setAttribute("class", trainset, trainTruth);
learner.train(trainset);
calculatePerformances(learner.test(testset), testTruth);
}
}
private void calcRandomTrainAndTestSets(List<X> featureVectors, List<Y> groundTruth) {
trainset = new ArrayList<>();
testset = new ArrayList<>();
trainTruth = new ArrayList<>();
testTruth = new ArrayList<>();
List<Integer> indices = new ArrayList<>();
for (int i = 0; i < featureVectors.size(); i++) {
indices.add(i);
}
int s = (int) Math.round(split * featureVectors.size());
while (trainset.size() <= s) {
int r = (int) (Math.random() * indices.size());
int ind = indices.remove(r);
trainset.add(featureVectors.get(ind));
trainTruth.add(groundTruth.get(ind));
}
// a bit sloppy. check whether all possible labels are covered in a
// classification task
if (groundTruth.get(0) instanceof String) {
Set<Y> all = new HashSet<>(groundTruth);
Set<Y> train = new HashSet<>(trainTruth);
if (all.size() != train.size()) {
calcRandomTrainAndTestSets(featureVectors, groundTruth);
}
}
for (int i : indices) {
testset.add(featureVectors.get(i));
testTruth.add(groundTruth.get(i));
}
}
@Override
protected void initDefaultPerformanceMeasures() {
throw new UnsupportedOperationException(
"RandomIterationsEvaluation: Empty performance measures are not supported yet.");
}
@Override
protected Double cumulate(List<Double> values) {
return values.stream().reduce(0.0, (x, y) -> x + y) / values.size();
}
@Override
public String getName() {
return "Random Iterations Evaluation";
}
@Override
public String getDescription() {
return "Performs several iterations of evaluation with random training instances chosen at each iteration.";
}
} | 31.412214 | 134 | 0.72175 |
9f39ddcfdaa6c1b9b3832d6a94f24752b6b5149c | 913 | package com.arjuna.webservices11.wsarj.processor;
import com.arjuna.webservices.base.processors.BaseProcessor;
import com.arjuna.webservices11.wsarj.ArjunaContext;
import com.arjuna.webservices11.wsarj.InstanceIdentifier;
/**
* Utility class handling common response functionality.
* @author kevin
*/
public abstract class BaseNotificationProcessor extends BaseProcessor
{
/**
* Get the callback ids.
* @param arjunaContext The arjuna context.
* @return The callback ids.
*/
protected String[] getIDs(final ArjunaContext arjunaContext)
{
if (arjunaContext != null)
{
final InstanceIdentifier instanceIdentifier = arjunaContext.getInstanceIdentifier() ;
if (instanceIdentifier != null)
{
return new String[] {instanceIdentifier.getInstanceIdentifier()} ;
}
}
return null ;
}
}
| 29.451613 | 97 | 0.67908 |
08f3f75ab4f4ebf200431e0159abbb966cdad1c2 | 841 | package org.stonlexx.packetwrapper.api.packet.client;
import com.comphenix.protocol.PacketType;
import org.bukkit.inventory.ItemStack;
import org.stonlexx.packetwrapper.api.packet.WrapperPacket;
public interface WrapperPlayClientSetCreativeSlot extends WrapperPacket {
PacketType TYPE =
PacketType.Play.Client.SET_CREATIVE_SLOT;
/**
* Retrieve Slot.
* <p>
* Notes: inventory slot
*
* @return The current Slot
*/
int getSlot();
/**
* Set Slot.
*
* @param value - new value.
*/
void setSlot(int value);
/**
* Retrieve Clicked item.
*
* @return The current Clicked item
*/
ItemStack getClickedItem();
/**
* Set Clicked item.
*
* @param value - new value.
*/
void setClickedItem(ItemStack value);
}
| 19.55814 | 73 | 0.621879 |
87390e1b1868ce91a761c998ead50c961bdd6029 | 770 | package nyla.solutions.spring.batch;
import static org.junit.Assert.fail;
import org.junit.Ignore;
import org.junit.Test;
import nyla.solutions.core.data.DataRow;
import nyla.solutions.spring.batch.CsvArrayableSkipListener;
@Ignore
public class CsvSkipListenerTest
{
@Test
public void testOnSkipInProcess()
{
CsvArrayableSkipListener skipper = new CsvArrayableSkipListener();
skipper.setSkipInProcessFilePath("${inReadFile}");
Exception exception = new Exception("error");
Object[] inputs = {};
DataRow dataRow = new DataRow(inputs);
skipper.onSkipInProcess(dataRow, exception);
}
@Test
public void testOnSkipInRead()
{
fail("Not yet implemented");
}
@Test
public void testOnSkipInWrite()
{
fail("Not yet implemented");
}
}
| 17.906977 | 68 | 0.744156 |
cf52e0849537f5d46b1a9659bcc694ebbb3b2f6f | 553 | package code.components.behaviour.hit;
import code.components.storage.projectile.ProjectileStorage;
import code.entity.Entity;
/**
* Created by theo on 8/07/17.
*/
public class HackingMissileProjectile extends ProjectileHandler {
// TODO private static final int PARTICLE_SIZE = 4;
public HackingMissileProjectile() {
super(HitType.HACKING_MISSILE);
}
public void payload(Entity entity, Entity victim, ProjectileStorage projStore) {
addEffect(victim, projStore.getOnHitEffect());
entity.destroy();
}
}
| 25.136364 | 84 | 0.726944 |
67e072dbc5f8e7374fade9de290e17e1d06d7515 | 342 | package translation;
public interface Translatable {
/**
* 한국어를 외국어로 변환
* @param korean 한국어 문장
* @return 번역된 외국어 문장
*/
public String translate(String korean);
/**
* 외국어를 한국어로 변환
* @param foreignLang 외국어 문장
* @return 번역된 한국어 문장
*/
public String inverseTranslate(String foreignLang);
}
| 19 | 55 | 0.608187 |
be0e434bcad51a61d08687daa8fa86bdc9a2213c | 987 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See the LICENSE file in the project root for full license information.
package com.microsoft.store.partnercenter.models.users;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PasswordProfile {
/**
* Gets or sets a value indicating whether force change password on first login is required or not.
*/
@JsonProperty("ForceChangePassword")
private boolean __ForceChangePassword;
public boolean getForceChangePassword()
{
return __ForceChangePassword;
}
public void setForceChangePassword(boolean value)
{
__ForceChangePassword = value;
}
/**
* Gets or sets the password.
*/
@JsonProperty("Password")
private String __Password;
public String getPassword()
{
return __Password;
}
public void setPassword(String value)
{
__Password = value;
}
}
| 22.953488 | 105 | 0.687943 |
e8ef26f0c67569f41cc533d576ed200bdc3da7ee | 4,520 | package com.lifeweb.dao.impl;
import com.lifeweb.dao.MarkalarDao;
import com.lifeweb.dao.pojo.Markalar;
import com.lifeweb.enitity.helper.DaoHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Life
*/
public class MarkalarDaoImpl implements MarkalarDao {
private final static Logger LOGGER = Logger.getLogger(MarkalarDaoImpl.class
.getName());
@Override
public int createMarkalar(Markalar markalar) {
Connection con;
PreparedStatement pstmt;
try {
con = DaoHelper.instance().getConnection();
pstmt = con.prepareStatement("INSERT INTO markalar ( MARKA_ADI, MARKA_DURUM)"
+ " VALUES (?, ?)");
pstmt.setString(1, markalar.getMarkaAdi());
pstmt.setString(2, markalar.getMarkaDurum());
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException e) {
LOGGER.logp(Level.SEVERE, LOGGER.getName(), IndirimlerDaoImpl.class.getEnclosingMethod().getName(), e.getLocalizedMessage(),e);
}
return -1;
}
@Override
public List<Markalar> getMarkalarList() {
Connection con;
PreparedStatement pstmt;
ResultSet rs;
ArrayList<Markalar> list = new ArrayList<>();
try {
con = DaoHelper.instance().getConnection();
pstmt = con.prepareStatement("SELECT MARKA_ID,MARKA_ADI,MARKA_DURUM FROM markalar ORDER BY MARKA_ADI ASC ");
rs = pstmt.executeQuery();
while (rs.next()) {
Markalar data = new Markalar();
data.setMarkaId(rs.getInt(1));
data.setMarkaAdi(rs.getString(2));
data.setMarkaDurum(rs.getString(3));
list.add(data);
}
rs.close();
pstmt.close();
} catch (SQLException e) {
LOGGER.logp(Level.SEVERE, LOGGER.getName(), IndirimlerDaoImpl.class.getEnclosingMethod().getName(), e.getLocalizedMessage(),e);
}
return list;
}
@Override
public Markalar getMarkalar(int id) {
Connection con;
PreparedStatement pstmt;
ResultSet rs;
Markalar data = null;
try {
con = DaoHelper.instance().getConnection();
pstmt = con.prepareStatement("SELECT MARKA_ID,MARKA_ADI,MARKA_DURUM "
+ "FROM markalar where MARKA_ID=?");
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
data = new Markalar();
data.setMarkaId(rs.getInt(1));
data.setMarkaAdi(rs.getString(2));
data.setMarkaDurum(rs.getString(3));
}
rs.close();
pstmt.close();
} catch (SQLException e) {
LOGGER.logp(Level.SEVERE, LOGGER.getName(), IndirimlerDaoImpl.class.getEnclosingMethod().getName(), e.getLocalizedMessage(),e);
}
return data;
}
@Override
public Markalar editMarkalar(Markalar markalar) {
Connection con;
PreparedStatement pstmt;
try {
con = DaoHelper.instance().getConnection();
pstmt = con.prepareStatement("UPDATE markalar MARKA_ADI=?,MARKA_DURUM=? WHERE MARKA_ID=?");
pstmt.setString(1, markalar.getMarkaAdi());
pstmt.setString(2, markalar.getMarkaDurum());
pstmt.setInt(3, markalar.getMarkaId());
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException e) {
LOGGER.logp(Level.SEVERE, LOGGER.getName(), IndirimlerDaoImpl.class.getEnclosingMethod().getName(), e.getLocalizedMessage(),e);
}
return markalar;
}
@Override
public void removeMarkalar(Markalar markalar) {
Connection con;
PreparedStatement pstmt;
try {
con = DaoHelper.instance().getConnection();
pstmt = con.prepareStatement("delete from markalar WHERE MARKA_ID=?");
pstmt.setInt(1, markalar.getMarkaId());
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException e) {
LOGGER.logp(Level.SEVERE, LOGGER.getName(), IndirimlerDaoImpl.class.getEnclosingMethod().getName(), e.getLocalizedMessage(),e);
}
}
}
| 33.481481 | 136 | 0.597124 |
5cbd9ccd330315a26a65c2723f551ba36df07e1c | 1,703 | package com.manulaiko.renashit.launcher;
import java.io.File;
import java.security.MessageDigest;
import java.util.regex.Pattern;
import com.manulaiko.tabitha.Console;
/**
* Settings class.
* ===============
*
* Application settings.
*
* @author Manulaiko <manulaiko@gmail.com>
*/
public class Settings
{
///////////////////////////////
// Start Constant Definition //
///////////////////////////////
public static final String MD5 = "md5";
public static final String SHA1 = "sha-1";
public static final String SHA256 = "sha-256";
/**
* Whether we're running in debug mode or not.
*/
public static boolean debug = false;
/**
* Whether we're running in recursive mode or not.
*/
public static boolean recursive = false;
/**
* Whether we're running in unique mode or not.
*/
public static boolean unique = false;
/**
* Hashing algorithm.
*/
public static MessageDigest algorithm = Settings.getAlgorithm(Settings.MD5);
/**
* Path to parse.
*/
public static File path = new File("./");
/**
* Regular expression.
*/
public static Pattern pattern = Pattern.compile("(.*)");
/**
* Returns an instance of a MessageDigest algorithm.
*
* @param algo Algorithm to instance.
*
* @return MessageDigest instance.
*/
public static MessageDigest getAlgorithm(String algo)
{
try {
return MessageDigest.getInstance(algo.toUpperCase());
} catch(Exception e) {
Console.println(algo +" is not a supported algorithm!");
System.exit(0);
}
return null;
}
}
| 22.407895 | 80 | 0.578978 |
40383cd57ea1f3d39b4ccb5c3538dc36d8a0b991 | 1,271 | package fr.idarkay.morefeatures.options.screen;
import fr.idarkay.morefeatures.options.FeaturesGameOptions;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.ClickableWidget;
import net.minecraft.text.Text;
import org.jetbrains.annotations.Nullable;
import java.util.function.BiFunction;
/**
* File <b>SubMenueButton</b> located on fr.idarkay.morefeatures.options.screen
* SubMenueButton is a part of Features-mod_1.17.1.
* <p>
* Copyright (c) 2021 Features-mod_1.17.1.
* <p>
*
* @author Alois. B. (IDarKay),
* Created the 26/07/2021 at 21:46
*/
public class MenuButton {
private final Text name;
private final BiFunction<Screen, FeaturesGameOptions, Screen> creator;
public MenuButton(Text name, BiFunction<Screen, FeaturesGameOptions, Screen> creator) {
this.name = name;
this.creator = creator;
}
public ClickableWidget createButton(@Nullable Screen parent, FeaturesGameOptions options, int x, int y, int width) {
return new ButtonWidget(x, y, width, 20, this.name,
button -> MinecraftClient.getInstance().setScreen(creator.apply(parent, options)));
}
}
| 32.589744 | 120 | 0.738788 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.