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
|
---|---|---|---|---|---|
d003aed441bb95f9c4208f29b0ffe65e1f1ec814 | 806 | import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class File1 {
public static void main(String[] args) throws IOException {
File f = new File("test.txt");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
dos.writeInt(2019);
dos.writeBoolean(true);
dos.writeChar('S');
dos.writeDouble(99.95);
dos.close();
DataInputStream dis = new DataInputStream(new FileInputStream(f));
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
System.out.println(dis.readDouble());
dis.close();
}
} | 33.583333 | 77 | 0.666253 |
757ee9ff8dcd3c363e31d60eb62bcd79ec62d06a | 424 | package com.quorum.tessera.enclave;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class DefaultPayloadDigestTest {
@Test
public void digest() {
PayloadDigest digest = new DefaultPayloadDigest();
String cipherText = "cipherText";
byte[] result = digest.digest(cipherText.getBytes());
assertThat(result).isNotNull();
assertThat(result).hasSize(64);
}
}
| 22.315789 | 57 | 0.731132 |
025ef41ab39da74fbce6bf5ef4fef395ae1e4f71 | 751 | package com.mhuang.kafka.common.producer.event;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationEvent;
import lombok.Getter;
import lombok.Setter;
/**
*
* @ClassName: ProducerEvent
* @Description:生产者通知事件
* @author: mhuang
* @date: 2017年9月15日 下午4:16:27
*/
public class ProducerEvent extends ApplicationEvent{
private static final long serialVersionUID = 1L;
@Setter
@Getter
private Map<String, Object> map;
public ProducerEvent(Object source,Map<String, Object> map) {
super(source);
this.map = map;
}
public ProducerEvent(Object source,String key,Object value) {
super(source);
map = new HashMap<>(1);
map.put(key, value);
}
}
| 20.297297 | 63 | 0.689747 |
7253c61448070cf822b32e1748ae7106505f803e | 1,110 | package com.chii.www.service;
import com.chii.www.pojo.Admin;
import com.chii.www.pojo.PageBean;
import com.chii.www.pojo.Student;
import com.chii.www.pojo.Teacher;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import java.io.InputStream;
import java.util.List;
public interface UserService {
Student getStuInfoById(String userno);
List<Student> getAllStuInfoByTeaId(String userno);
PageInfo<Student> getAllStuInfo(PageBean pageBean);
Teacher getTeaInfoById(String userno);
List<Teacher> getAllTeaInfo();
PageInfo<Teacher> getAllTeaInfoByPage(PageBean pageBean);
Admin getAdminInfoById(String userno);
void insertStuInfo(Student student);
void updateStuLoginPass(Student student);
void updateTeaLoginPass(Teacher teacher);
void updateAdmLoginPass(Admin admin);
void updateStuInfo(Student student);
void deleteStuInfo(String userno);
void insertTeaInfo(Teacher teacher);
void updateTeaInfo(Teacher teacher);
void dateleTeaInfo(String userno);
InputStream getInputStream() throws Exception;
}
| 21.346154 | 61 | 0.762162 |
4ff9cfe74ca7ad74d3d04d9308ca05142d4774ac | 6,201 | package com.kaqi.niuniu.ireader.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gyf.barlibrary.ImmersionBar;
import com.kaqi.niuniu.ireader.R;
import com.kaqi.niuniu.ireader.ui.base.BaseActivity;
import com.kaqi.niuniu.ireader.utils.Constant;
import com.kaqi.niuniu.ireader.utils.SharedPreUtils;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by niqiao on .
*/
public class SplashActivity extends BaseActivity {
public static final int SHOW_TIME = 0x01;
public static final int GO_HOME = 0x02;
private int countDownTime = 4 * 1000;
@BindView(R.id.tvSkip)
TextView tvSkip;
@BindView(R.id.mIvGender)
ImageView mIvGender;
@BindView(R.id.mTvContent)
TextView mTvContent;
@BindView(R.id.mTvSelect)
TextView mTvSelect;
@BindView(R.id.mBtnMale)
Button mBtnMale;
@BindView(R.id.mBtnFemale)
Button mBtnFemale;
@BindView(R.id.choose_sex_rl)
RelativeLayout chooseSexRl;
@BindView(R.id.splash_ad_fl)
FrameLayout splashAdFl;
private boolean flag = false;
private SplashCountDownTimer mCountDownTimer;
private synchronized void goHome() {
if (!flag) {
flag = true;
mCountDownTimer = null;
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
}
@Override
protected int getContentId() {
return R.layout.activity_splash;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreUtils.getInstance()
.putBoolean(Constant.FITST_APP, false);
mCountDownTimer = new SplashCountDownTimer(countDownTime, 1000);
mCountDownTimer.start();
ImmersionBar.with(this)
.fitsSystemWindows(true)
.fullScreen(true)
.statusBarDarkFont(true, 0.2f) //原理:如果当前设备支持状态栏字体变色,会设置状态栏字体为黑色,如果当前设备不支持状态栏字体变色,会使当前状态栏加上透明度,否则不执行透明度
.init();
}
@Override
protected void initData(Bundle savedInstanceState) {
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mHandler.removeCallbacksAndMessages(null);
flag = true;
}
@Override
protected void dispatchHandler(Message msg) {
switch (msg.what) {
case SHOW_TIME:
mCountDownTimer = new SplashCountDownTimer(countDownTime, 1000);
mCountDownTimer.start();
break;
case GO_HOME:
goHome();
break;
}
}
@OnClick({R.id.mTvContent, R.id.mTvSelect, R.id.mBtnMale, R.id.mBtnFemale, R.id.tvSkip})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.mTvContent:
break;
case R.id.mTvSelect:
break;
case R.id.mBtnMale:
SharedPreUtils.getInstance()
.putString(Constant.SHARED_SEX, Constant.SEX_BOY);
SharedPreUtils.getInstance()
.putBoolean(Constant.FITST_APP, true);
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mHandler.sendEmptyMessageDelayed(GO_HOME, 100);
break;
case R.id.mBtnFemale:
SharedPreUtils.getInstance()
.putBoolean(Constant.FITST_APP, true);
SharedPreUtils.getInstance()
.putString(Constant.SHARED_SEX, Constant.SEX_GIRL);
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mHandler.sendEmptyMessageDelayed(GO_HOME, 100);
break;
case R.id.tvSkip:
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
if ("".equals(SharedPreUtils.getInstance()
.getString(Constant.SHARED_SEX))) {
tvSkip.setVisibility(View.GONE);
splashAdFl.setVisibility(View.GONE);
chooseSexRl.setVisibility(View.VISIBLE);
} else {
mHandler.sendEmptyMessageDelayed(GO_HOME, 100);
}
break;
}
}
/**
* 倒计时
*/
private class SplashCountDownTimer extends CountDownTimer {
/**
* @param millisInFuture 表示以「 毫秒 」为单位倒计时的总数
* 例如 millisInFuture = 1000 表示1秒
* @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick()
* 例如: countDownInterval = 1000 ; 表示每 1000 毫秒调用一次 onTick()
*/
public SplashCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
this.cancel();
if (tvSkip == null) {
tvSkip = (TextView) findViewById(R.id.tvSkip);
}
tvSkip.setText("0s 跳过");
if ("".equals(SharedPreUtils.getInstance()
.getString(Constant.SHARED_SEX))) {
tvSkip.setVisibility(View.GONE);
splashAdFl.setVisibility(View.GONE);
chooseSexRl.setVisibility(View.VISIBLE);
} else {
mHandler.sendEmptyMessageDelayed(GO_HOME, 100);
}
}
public void onTick(final long millisUntilFinished) {
try {
tvSkip.setText(millisUntilFinished / 1000 + "s 跳过");
} catch (Exception e) {
e.printStackTrace();
}
}
}
} | 31.477157 | 118 | 0.578294 |
4cd17e6c3bc27fe34518b6fafc696897b1c5cf6e | 6,905 | package sdk.jassinaturas.clients;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.List;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import sdk.jassinaturas.Assinaturas;
import sdk.jassinaturas.clients.attributes.Authentication;
import sdk.jassinaturas.clients.attributes.Interval;
import sdk.jassinaturas.clients.attributes.Plan;
import sdk.jassinaturas.clients.attributes.PlanStatus;
import sdk.jassinaturas.clients.attributes.Trial;
import sdk.jassinaturas.clients.attributes.Unit;
import sdk.jassinaturas.communicators.ProductionCommunicator;
import sdk.jassinaturas.communicators.SandboxCommunicator;
import sdk.jassinaturas.exceptions.ApiResponseErrorException;
import co.freeside.betamax.Betamax;
import co.freeside.betamax.MatchRule;
import co.freeside.betamax.Recorder;
public class PlanClientTest {
private final Assinaturas assinaturas = new Assinaturas(new Authentication("SGPA0K0R7O0IVLRPOVLJDKAWYBO1DZF3",
"QUJESGM9JU175OGXRFRJIYM0SIFOMIFUYCBWH9WA"), new SandboxCommunicator());
@Rule
public Recorder recorder = new Recorder();
@Betamax(tape = "ACTIVATE_PLAN", match = { MatchRule.method, MatchRule.uri })
@Test
public void shouldActivateAPlan() {
Plan plan = assinaturas.plans().active("plan01");
// There isn't any response from Moip Assinaturas when plan is activated
// So, I didn't do any assert
}
@Betamax(tape = "CREATE_PLAN", match = { MatchRule.body, MatchRule.method, MatchRule.uri })
@Test
public void shouldCreateANewPlan() {
Plan toCreate = new Plan();
toCreate.withCode("plan001").withDescription("Plano de Teste").withName("Plano de Teste").withAmount(1000)
.withSetupFee(100).withBillingCycles(1).withPlanStatus(PlanStatus.ACTIVE).withMaxQty(10)
.withInterval(new Interval().withLength(10).withUnit(Unit.MONTH))
.withTrial(new Trial().withDays(10).enabled());
Plan created = assinaturas.plans().create(toCreate);
assertEquals("Plano criado com sucesso", created.getMessage());
}
@Betamax(tape = "INACTIVATE_PLAN", match = { MatchRule.method, MatchRule.uri })
@Test
public void shouldInactivateAPlan() {
Plan plan = assinaturas.plans().inactive("plan001");
// There isn't any response from Moip Assinaturas when plan is
// inactivated
// So, I didn't do any assert
}
@Betamax(tape = "LIST_ALL_PLANS", match = { MatchRule.method, MatchRule.uri })
@Test
public void shouldListAllPlans() {
List<Plan> plans = assinaturas.plans().list();
assertEquals(7, plans.size());
}
@Betamax(tape = "CREATE_PLAN_RETURNED_ERROR")
@Test
public void shouldReturnErrors() {
Plan toCreate = new Plan();
toCreate.withCode("plan001").withDescription("Plano de Teste").withName("Plano de Teste").withAmount(1000)
.withSetupFee(100).withBillingCycles(1).withPlanStatus(PlanStatus.ACTIVE).withMaxQty(10)
.withInterval(new Interval().withLength(10).withUnit(Unit.MONTH))
.withTrial(new Trial().withDays(10).enabled());
try {
Plan created = assinaturas.plans().create(toCreate);
Assert.fail("Should return error");
} catch (ApiResponseErrorException e) {
assertEquals("Erro na requisição", e.getApiResponseError().getMessage());
assertEquals("Código do plano já utilizado. Escolha outro código",
e.getApiResponseError().getErrors().get(0).getDescription());
assertEquals("MA6", e.getApiResponseError().getErrors().get(0).getCode());
}
}
@Betamax(tape = "GET_SINGLE_PLAN", match = { MatchRule.method, MatchRule.uri })
@Test
public void shouldShowAPlan() {
Plan plan = assinaturas.plans().show("plan001");
assertEquals("plan001", plan.getCode());
assertEquals("Plano de Teste Atualizado", plan.getDescription());
assertEquals("Plano de Teste Atualizado", plan.getName());
assertEquals(10000, plan.getAmount());
assertEquals(1000, plan.getSetupFee());
assertEquals(10, plan.getBillingCycles());
assertEquals(PlanStatus.INACTIVE, plan.getStatus());
assertEquals(100, plan.getMaxQuantity());
assertEquals(100, plan.getInterval().getLength());
assertEquals(Unit.DAY, plan.getInterval().getUnit());
assertFalse(plan.getTrial().isEnabled());
assertEquals(5, plan.getTrial().getDays());
}
@Betamax(tape = "UPDATE_PLAN", match = { MatchRule.body, MatchRule.method, MatchRule.uri })
@Test
public void shouldUpdateAPlan() {
Plan toUpdate = new Plan();
toUpdate.withCode("plan001").withDescription("Plano de Teste Atualizado").withName("Plano de Teste Atualizado")
.withAmount(10000).withSetupFee(1000).withBillingCycles(10).withPlanStatus(PlanStatus.INACTIVE)
.withMaxQty(100).withInterval(new Interval().withLength(100).withUnit(Unit.DAY))
.withTrial(new Trial().withDays(5).disabled());
Plan plan = assinaturas.plans().update(toUpdate);
// There isn't any response from Moip Assinaturas when plan is updated
// So, I didn't do any assert
}
@Betamax(tape = "CREATE_PLAN_PRODUCTION", match = { MatchRule.body, MatchRule.uri })
@Test
public void shouldCreateANewPlanInProductionEnvironment() {
Assinaturas assinaturas = new Assinaturas(new Authentication("SGPA0K0R7O0IVLRPOVLJDKAWYBO1DZF3",
"QUJESGM9JU175OGXRFRJIYM0SIFOMIFUYCBWH9WA"), new ProductionCommunicator());
Plan toCreate = new Plan();
toCreate.withCode("plan_jassinaturas_production_01").withDescription("Plano de Teste")
.withName("Plano de Teste").withAmount(1000).withSetupFee(100).withBillingCycles(1)
.withPlanStatus(PlanStatus.ACTIVE).withMaxQty(10)
.withInterval(new Interval().withLength(10).withUnit(Unit.MONTH))
.withTrial(new Trial().withDays(10).enabled());
Plan created = assinaturas.plans().create(toCreate);
assertEquals("Plano criado com sucesso", created.getMessage());
}
@Betamax(tape = "GET_SINGLE_PLAN", match = { MatchRule.method, MatchRule.uri })
@Test
public void shouldGetResultFromToString() {
String plan = assinaturas.plans().show("plan001").toString();
assertEquals(
"Plan [alerts=null, amount=10000, billingCycles=10, code=plan001, description=Plano de Teste Atualizado, interval=Interval [unit=DAY, length=100], maxQty=100, message=null, name=Plano de Teste Atualizado, plans=null, setupFee=1000, status=INACTIVE, trial=Trial [days=5, enabled=false]]",
plan);
}
}
| 43.427673 | 303 | 0.683707 |
ea3f66003fc80dd7fdbd11a1359ded6495a6976f | 4,371 | package io.fizz.analytics.jobs.metricsRollup.aggregator;
import io.fizz.analytics.common.AbstractTransformer;
import io.fizz.analytics.common.HiveTime;
import io.fizz.analytics.common.source.hive.HiveDefines;
import io.fizz.analytics.common.source.hive.HiveEventFields;
import io.fizz.analytics.common.source.hive.HiveProfileEnrichedEventTableSchema;
import io.fizz.analytics.common.source.hive.HiveMetricTableSchema;
import io.fizz.common.domain.EventType;
import org.apache.spark.api.java.function.FilterFunction;
import org.apache.spark.sql.*;
import org.apache.spark.sql.api.java.UDF1;
import org.apache.spark.sql.catalyst.encoders.RowEncoder;
import org.apache.spark.sql.types.DataTypes;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.Objects;
public class SentimentAggregator implements AbstractTransformer<Row,Row>, Serializable {
private static UDF1 extractSentiment = new UDF1<String,Double>() {
public Double call(final String fieldsStr){
final JSONObject fields = new JSONObject(fieldsStr);
return fields.has(HiveEventFields.SENTIMENT_SCORE.value())
? fields.getDouble(HiveEventFields.SENTIMENT_SCORE.value()) : 0.0;
}
};
private static final String COL_SENTIMENT_SCORE = "sentimentScore";
private final String segment;
private final HiveDefines.MetricId actionMetricId;
public SentimentAggregator(final SparkSession aSpark, final HiveDefines.MetricId aActionMetricId, String aSegment) {
if (Objects.isNull(aActionMetricId)) {
throw new IllegalArgumentException("Invalid action metric id specified.");
}
if (Objects.isNull(aSpark)) {
throw new IllegalArgumentException("Invalid spark session specified.");
}
actionMetricId = aActionMetricId;
segment = aSegment;
aSpark.udf().register("extractSentiment", extractSentiment, DataTypes.DoubleType);
}
@Override
public Dataset<Row> transform(Dataset<Row> aSourceDS, HiveTime aTime) {
if (Objects.isNull(aSourceDS)) {
throw new IllegalArgumentException("invalid data set provided");
}
if (Objects.isNull(aTime)) {
throw new IllegalArgumentException("invalid time provided");
}
final Dataset<Row> scoredMsgDS = mapSentimentScoredMessageEvents(aSourceDS);
return Objects.isNull(segment)
? aggregateSentimentMetrics(scoredMsgDS, aTime)
: aggregateSentimentMetrics(scoredMsgDS, segment, aTime);
}
private Dataset<Row> mapSentimentScoredMessageEvents(Dataset<Row> aSourceDS) {
return aSourceDS.filter((FilterFunction<Row>) row -> HiveProfileEnrichedEventTableSchema.eventType(row) == EventType.TEXT_MESSAGE_SENT.value())
.withColumn(COL_SENTIMENT_SCORE, functions.callUDF("extractSentiment", aSourceDS.col(HiveProfileEnrichedEventTableSchema.COL_FIELDS.title())));
}
private Dataset<Row> aggregateSentimentMetrics(final Dataset<Row> aActionDS, final HiveTime aTime) {
RelationalGroupedDataset groupDS = aActionDS.groupBy(HiveProfileEnrichedEventTableSchema.COL_APP_ID.title());
return aggregateSentimentMetrics(groupDS, null, aTime);
}
private Dataset<Row> aggregateSentimentMetrics(final Dataset<Row> aActionDS, String segment, final HiveTime aTime) {
RelationalGroupedDataset groupDS = aActionDS.groupBy(HiveProfileEnrichedEventTableSchema.COL_APP_ID.title(), segment);
return aggregateSentimentMetrics(groupDS, segment, aTime);
}
private Dataset<Row> aggregateSentimentMetrics(RelationalGroupedDataset groupDS, String segment, final HiveTime aTime) {
return groupDS
.agg(
functions.mean(COL_SENTIMENT_SCORE).cast("string").as(HiveDefines.ValueTag.MEAN),
functions.max(COL_SENTIMENT_SCORE).cast("string").as(HiveDefines.ValueTag.MAX),
functions.min(COL_SENTIMENT_SCORE).cast("string").as(HiveDefines.ValueTag.MIN)
)
.map(
new AggregateToMetricRowMapper(AggregateType.MIN | AggregateType.MAX | AggregateType.MEAN, actionMetricId, aTime, segment, true),
RowEncoder.apply(new HiveMetricTableSchema().schema())
);
}
} | 48.032967 | 159 | 0.716541 |
4013fdef95af97d09f8165e88417b007419f4e6e | 2,853 | package ru.iopump.qa.exception;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class PumpExceptionTest {
@Test
public void create() {
assertThat(new PumpException("", null, ""))
.isInstanceOf(PumpException.class)
.hasMessage("")
.hasNoCause();
assertThat(new PumpException(new RuntimeException()))
.isInstanceOf(PumpException.class)
.hasMessage("java.lang.RuntimeException")
.hasCauseInstanceOf(RuntimeException.class);
assertThat(PumpException.of(new RuntimeException()))
.isInstanceOf(PumpException.class)
.hasMessage("java.lang.RuntimeException")
.hasCauseInstanceOf(RuntimeException.class);
assertThat(PumpException.of().initCause(new RuntimeException()))
.isInstanceOf(PumpException.class)
.hasMessage(null)
.hasCauseInstanceOf(RuntimeException.class);
}
@Test
public void ofCause() {
assertThat(PumpException.of(new Exception()))
.isInstanceOf(PumpException.class)
.hasMessage("java.lang.Exception")
.hasCauseInstanceOf(Exception.class);
assertThat(PumpException.of(null))
.isInstanceOf(PumpException.class)
.hasMessage(null)
.hasNoCause();
}
@Test
public void of() {
assertThat(PumpException.of())
.isInstanceOf(PumpException.class)
.hasMessage(null)
.hasNoCause();
}
@Test
public void ofWithArgs() {
assertThat(PumpException.of("{}", "test"))
.isInstanceOf(PumpException.class)
.hasMessage("test")
.hasNoCause();
assertThat(PumpException.of(null, "test"))
.isInstanceOf(PumpException.class)
.hasMessage("null")
.hasNoCause();
assertThat(PumpException.of(null, (Object[]) null))
.isInstanceOf(PumpException.class)
.hasMessage("null")
.hasNoCause();
}
@Test
public void withCause() {
assertThat(PumpException.of().withCause(new IllegalArgumentException()))
.isInstanceOf(PumpException.class)
.hasMessage("java.lang.IllegalArgumentException")
.hasCauseInstanceOf(IllegalArgumentException.class);
assertThat(PumpException.of().withCause(null))
.isInstanceOf(PumpException.class)
.hasMessage("null")
.hasNoCause();
}
@Test
public void withMsg() {
assertThat(PumpException.of("no").withCause(new IllegalArgumentException()).withMsg("new"))
.isInstanceOf(PumpException.class)
.hasMessage("new")
.hasCauseInstanceOf(IllegalArgumentException.class);
}
} | 31.351648 | 99 | 0.610936 |
b49333930e335b4ec8bde6f06e5344b81aa2cc4c | 3,518 | /*
* Copyright 2017 Palantir Technologies, Inc. All rights reserved.
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.http;
import com.palantir.atlasdb.http.errors.AtlasDbRemoteException;
import com.palantir.lock.remoting.BlockingTimeoutException;
import feign.RetryableException;
public enum ExceptionRetryBehaviour {
RETRY_ON_OTHER_NODE(true, true),
RETRY_INDEFINITELY_ON_SAME_NODE(true, false),
RETRY_ON_SAME_NODE(false, false);
private final boolean shouldRetryInfinitelyManyTimes;
private final boolean shouldBackoffAndTryOtherNodes;
ExceptionRetryBehaviour(boolean shouldRetryInfinitelyManyTimes, boolean shouldBackoffAndTryOtherNodes) {
this.shouldRetryInfinitelyManyTimes = shouldRetryInfinitelyManyTimes;
this.shouldBackoffAndTryOtherNodes = shouldBackoffAndTryOtherNodes;
}
public static ExceptionRetryBehaviour getRetryBehaviourForException(RetryableException retryableException) {
if (isCausedByBlockingTimeout(retryableException)) {
// This is the case where we have a network request that failed because it blocked too long on a lock.
// Since it is still the leader, we want to try again on the same node.
return RETRY_INDEFINITELY_ON_SAME_NODE;
}
if (retryableException.retryAfter() != null) {
// This is the case where the server has returned a 503.
// This is done when we want to do fast failover because we aren't the leader or we are shutting down.
return RETRY_ON_OTHER_NODE;
}
// This is the case where we have failed due to networking or other IOException.
return RETRY_ON_SAME_NODE;
}
/**
* Returns true if and only if clients which have defined a finite limit for the number
* of retries should retry infinitely many times. Typically, this implies that the failure of the
* node in question is not reflective of a failing condition of the cluster in general (such as the node
* in question shutting down, or it not being the leader.)
*/
public boolean shouldRetryInfinitelyManyTimes() {
return shouldRetryInfinitelyManyTimes;
}
/**
* Returns true if clients should, where possible, retry on other nodes before retrying on this
* node. Note that a value of false here does not necessarily mean that clients should not retry on other nodes.
*/
public boolean shouldBackoffAndTryOtherNodes() {
return shouldBackoffAndTryOtherNodes;
}
private static boolean isCausedByBlockingTimeout(RetryableException retryableException) {
return retryableException.getCause() instanceof AtlasDbRemoteException
&& getCausingErrorName(retryableException).equals(BlockingTimeoutException.class.getName());
}
private static String getCausingErrorName(RetryableException retryableException) {
return ((AtlasDbRemoteException) retryableException.getCause()).getErrorName();
}
}
| 43.975 | 116 | 0.741615 |
9793f9439e16b2a4a8266959fb2841e2be92a1bb | 22,764 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.optimizer.core.planner.rule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppBKAJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppCorrelateConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppDynamicValuesConverRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppExpandConversionRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppExpandConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppFilterConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppHashAggConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppHashGroupJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppHashJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppLimitConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppLogicalViewConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppMaterializedSemiJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppMemSortConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppMergeSortConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppNLJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppProjectConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppSemiBKAJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppSemiHashJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppSemiNLJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppSemiSortMergeJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppSortAggConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppSortMergeJoinConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppSortWindowConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppTopNConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppUnionConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppValuesConverRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.MppVirtualViewConvertRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.FilterExchangeTransposeRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.FilterRFBuilderTransposeRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.JoinToRuntimeFilterJoinRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.RFBuilderExchangeTransposeRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.RFBuilderJoinTransposeRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.RFBuilderMergeRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.RFBuilderProjectTransposeRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.RFilterJoinTransposeRule;
import com.alibaba.polardbx.optimizer.core.planner.rule.mpp.runtimefilter.RFilterProjectTransposeRule;
import com.google.common.collect.ImmutableList;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.rel.rules.AggregateProjectMergeRule;
import org.apache.calcite.rel.rules.AggregateReduceFunctionsRule;
import org.apache.calcite.rel.rules.CorrelateProjectRule;
import org.apache.calcite.rel.rules.FilterAggregateTransposeRule;
import org.apache.calcite.rel.rules.FilterCorrelateRule;
import org.apache.calcite.rel.rules.FilterJoinRule;
import org.apache.calcite.rel.rules.FilterProjectTransposeRule;
import org.apache.calcite.rel.rules.FilterSortTransposeRule;
import org.apache.calcite.rel.rules.FilterWindowTransposeRule;
import org.apache.calcite.rel.rules.JoinCommuteRule;
import org.apache.calcite.rel.rules.JoinProjectTransposeRule;
import org.apache.calcite.rel.rules.JoinPushTransitivePredicatesRule;
import org.apache.calcite.rel.rules.ProjectFilterTransposeRule;
import org.apache.calcite.rel.rules.ProjectJoinTransposeRule;
import org.apache.calcite.rel.rules.ProjectMergeRule;
import org.apache.calcite.rel.rules.ProjectRemoveRule;
import org.apache.calcite.rel.rules.ProjectToWindowRule;
import org.apache.calcite.rel.rules.ProjectWindowTransposeRule;
import org.apache.calcite.rel.rules.PruneEmptyRules;
import org.apache.calcite.rel.rules.SemiJoinProjectTransposeRule;
import org.apache.calcite.rel.rules.SortProjectTransposeRule;
import org.apache.calcite.rel.rules.UnionMergeRule;
import java.util.List;
/**
* Rules TDDL used.
*
* @author lingce.ldm
*/
public class RuleToUse {
public static final ImmutableList<RelOptRule> PRE_PUSH_TRANSFORMER_RULE = ImmutableList.of(
PushJoinRule.INSTANCE,
PushProjectRule.INSTANCE,
// PushCorrelateRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
ProjectTableLookupTransposeRule.INSTANCE,
AggregatePruningRule.INSTANCE,
TableLookupRemoveRule.INSTANCE,
PushFilterRule.LOGICALVIEW,
FilterCorrelateRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
OptimizeLogicalTableLookupRule.INSTANCE,
FilterTableLookupTransposeRule.INSTANCE
);
public static final ImmutableList<RelOptRule> SQL_REWRITE_CALCITE_RULE_PRE = ImmutableList.of(
FilterAggregateTransposeRule.INSTANCE,
FilterWindowTransposeRule.INSTANCE,
ProjectRemoveRule.INSTANCE,
ProjectTableLookupTransposeRule.INSTANCE,
TableLookupRemoveRule.INSTANCE,
PruneEmptyRules.FILTER_INSTANCE,
PruneEmptyRules.PROJECT_INSTANCE,
PruneEmptyRules.SORT_INSTANCE,
PruneEmptyRules.SORT_FETCH_ZERO_INSTANCE,
PruneEmptyRules.AGGREGATE_INSTANCE,
PruneEmptyRules.JOIN_LEFT_INSTANCE,
PruneEmptyRules.JOIN_RIGHT_INSTANCE,
PruneEmptyRules.MINUS_INSTANCE,
PruneEmptyRules.UNION_INSTANCE,
PruneEmptyRules.INTERSECT_INSTANCE,
LogicalSemiJoinRule.PROJECT,
LogicalSemiJoinRule.JOIN,
PruneEmptyRules.INTERSECT_INSTANCE,
MergeUnionValuesRule.UNION_VALUES_INSTANCE,
MergeUnionValuesRule.REMOVE_PROJECT_INSTANCE,
UnionMergeRule.INSTANCE,
AggregateReduceFunctionsRule.INSTANCE,
DrdsAggregateRemoveRule.INSTANCE
);
/**
* 下推 Filter
*/
private static final ImmutableList<RelOptRule> CALCITE_PUSH_FILTER_BASE = ImmutableList.of(
FilterJoinRule.FILTER_ON_JOIN,
FilterJoinRule.JOIN,
PushFilterRule.LOGICALUNION,
FilterCorrelateRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
SortProjectTransposeRule.INSTANCE,
FilterWindowTransposeRule.INSTANCE,
LogicalSemiJoinRule.PROJECT,
LogicalSemiJoinRule.JOIN
);
public static final ImmutableList<RelOptRule> CALCITE_PUSH_FILTER_PRE = ImmutableList
.<RelOptRule>builder()
.addAll(CALCITE_PUSH_FILTER_BASE)
.add(JoinPushTransitivePredicatesRule.INSTANCE)
.build();
public static final ImmutableList<RelOptRule> CALCITE_PUSH_FILTER_POST = ImmutableList
.<RelOptRule>builder()
.addAll(CALCITE_PUSH_FILTER_BASE)
.add(FilterProjectTransposeRule.INSTANCE)
.build();
public static final ImmutableList<RelOptRule> PUSH_FILTER_PROJECT_SORT = ImmutableList.of(
FilterProjectTransposeRule.INSTANCE,
PushFilterRule.LOGICALVIEW,
FilterCorrelateRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
FilterTableLookupTransposeRule.INSTANCE,
ProjectTableLookupTransposeRule.INSTANCE,
TableLookupRemoveRule.INSTANCE,
PushProjectRule.INSTANCE,
PushCorrelateRule.INSTANCE,
TddlFilterJoinRule.TDDL_FILTER_ON_JOIN,
FilterSortTransposeRule.INSTANCE
);
public static final ImmutableList<RelOptRule> PUSH_AFTER_JOIN = ImmutableList.of(
ProjectMergeRule.INSTANCE,
ProjectRemoveRule.INSTANCE,
ProjectTableLookupTransposeRule.INSTANCE,
ProjectSortTransitiveRule.TABLELOOKUP,
TableLookupRemoveRule.INSTANCE,
ProjectJoinTransposeRule.INSTANCE,
ProjectCorrelateTransposeRule.INSTANCE,
PushFilterRule.LOGICALVIEW,
FilterCorrelateRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
FilterTableLookupTransposeRule.INSTANCE,
OptimizeLogicalTableLookupRule.INSTANCE,
// Limit Union Transpose
LimitUnionTransposeRule.INSTANCE,
PushProjectRule.INSTANCE,
PushCorrelateRule.INSTANCE,
TddlFilterJoinRule.TDDL_FILTER_ON_JOIN,
PushAggRule.SINGLE_GROUP_VIEW,
PushAggRule.NOT_SINGLE_GROUP_VIEW,
PushSemiJoinRule.INSTANCE,
PushJoinRule.INSTANCE,
PushFilterRule.VIRTUALVIEW);
/**
* <pre>
* 1. 将Filter下推至JOIN的ON条件中
* 2. JOIN 下推
* </pre>
*/
public static final ImmutableList<RelOptRule> TDDL_PUSH_JOIN = ImmutableList.of(
JoinConditionSimplifyRule.INSTANCE,
TddlFilterJoinRule.TDDL_FILTER_ON_JOIN,
PushFilterRule.LOGICALVIEW,
FilterCorrelateRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
FilterTableLookupTransposeRule.INSTANCE,
OptimizeLogicalTableLookupRule.INSTANCE,
PushProjectRule.INSTANCE,
PushCorrelateRule.INSTANCE,
PushJoinRule.INSTANCE,
PushSemiJoinRule.INSTANCE
);
/**
* SUBQUERY 的处理
*/
public static final ImmutableList<RelOptRule> SUBQUERY = ImmutableList.of(
SubQueryToSemiJoinRule.FILTER,
SubQueryToSemiJoinRule.JOIN,
SubQueryToSemiJoinRule.PROJECT,
CorrelateProjectRule.INSTANCE,
FilterConditionSimplifyRule.INSTANCE,
ProjectToWindowRule.PROJECT,
ProjectToWindowRule.INSTANCE
);
public static ImmutableList<RelOptRule> PUSH_INTO_LOGICALVIEW = ImmutableList.of(
// Push Agg
PushAggRule.SINGLE_GROUP_VIEW,
PushAggRule.NOT_SINGLE_GROUP_VIEW,
// Push Join
PushJoinRule.INSTANCE,
PushSemiJoinRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
// PushFilter, because Push Sort move to CBO, so we should transpose, let filter down
// FIXME: sharding calculation dose not satisfying monotonicity
FilterSortTransposeRule.INSTANCE,
FilterProjectTransposeRule.INSTANCE,
PushFilterRule.LOGICALVIEW,
FilterMergeRule.INSTANCE,
FilterConditionSimplifyRule.INSTANCE,
// Push Project
PushProjectRule.INSTANCE,
PushCorrelateRule.INSTANCE,
// Project Merge
ProjectMergeRule.INSTANCE,
// TableLookup Related
FilterTableLookupTransposeRule.INSTANCE,
ProjectTableLookupTransposeRule.INSTANCE,
OptimizeLogicalTableLookupRule.INSTANCE,
TableLookupRemoveRule.INSTANCE
);
public static final ImmutableList<RelOptRule> CONVERT_MODIFY = ImmutableList.of(
LogicalModifyToLogicalRelocateRule.INSTANCE,
RemoveProjectRule.INSTANCE,
RemoveUnionProjectRule.INSTANCE,
LogicalValuesToLogicalDynamicValuesRule.INSTANCE);
public static final List RULE_FOR_NATIVE_SQL = ImmutableList.of(
FilterProjectTransposeRule.INSTANCE,
//SortProjectTransposeRule.INSTANCE,
ProjectRemoveRule.INSTANCE
);
public static final ImmutableList<RelOptRule> TDDL_SHARDING_RULE = ImmutableList.of(
ShardLogicalViewRule.INSTANCE,
MergeSortRemoveGatherRule.INSTANCE
);
public static final ImmutableList<RelOptRule> EXPAND_VIEW_PLAN = ImmutableList.of(
ExpandViewPlanRule.INSTANCE
);
/**
* the following two rules are aimed to reorder the joins
*/
public static ImmutableList<RelOptRule> JOIN_TO_MULTIJOIN = ImmutableList.of(
LogicalJoinToMultiJoinRule.INSTANCE
);
public static ImmutableList<RelOptRule> MULTIJOIN_REORDER_TO_JOIN = ImmutableList.of(
MultiJoinToLogicalJoinRule.INSTANCE
);
/**
* 将多次join转换为bushy join的结构,随后下推
*/
public static final ImmutableList<RelOptRule> TDDL_PRE_BUSHY_JOIN_SHALLOW_PUSH_FILTER = ImmutableList.of(
TddlPreBushyJoinShallowPushFilterRule.INSTANCE,
FilterJoinRule.SEMI_JOIN
);
public static final ImmutableList<RelOptRule> LOGICAL_JOIN_TO_BUSHY_JOIN = ImmutableList.of(
LogicalJoinToBushyJoinRule.INSTANCE
);
public static final ImmutableList<RelOptRule> BUSHY_JOIN_CLUSTERING = ImmutableList.of(
BushyJoinClusteringRule.INSTANCE
);
public static final ImmutableList<RelOptRule> BUSHY_JOIN_TO_LOGICAL_JOIN = ImmutableList.of(
BushyJoinToLogicalJoinRule.INSTANCE
);
public static final ImmutableList<RelOptRule> CALCITE_NO_FILTER_JOIN_RULE = ImmutableList.of(
FilterJoinRule.JOIN
);
public static final ImmutableList<RelOptRule> PUSH_PROJECT_RULE = ImmutableList.of(
ProjectJoinTransposeRule.INSTANCE,
ProjectCorrelateTransposeRule.INSTANCE,
ProjectFilterTransposeRule.INSTANCE,
ProjectWindowTransposeRule.INSTANCE,
ProjectSortTransitiveRule.INSTANCE,
PushProjectRule.INSTANCE,
PushCorrelateRule.INSTANCE,
ProjectMergeRule.INSTANCE
);
public static final ImmutableList<RelOptRule> PULL_PROJECT_RULE = ImmutableList.of(
JoinProjectTransposeRule.LEFT_PROJECT,
JoinProjectTransposeRule.RIGHT_PROJECT,
SemiJoinProjectTransposeRule.INSTANCE,
ProjectMergeRule.INSTANCE,
PushCorrelateRule.INSTANCE,
ProjectRemoveRule.INSTANCE,
FilterProjectTransposeRule.INSTANCE,
AggregateProjectMergeRule.INSTANCE
);
public static final ImmutableList<RelOptRule> EXPAND_TABLE_LOOKUP = ImmutableList.of(
PushProjectRule.INSTANCE,
// PushCorrelateRule.INSTANCE,
ProjectSortTransitiveRule.LOGICALVIEW,
ProjectRemoveRule.INSTANCE,
TableLookupExpandRule.INSTANCE);
public static final ImmutableList<RelOptRule> OPTIMIZE_MODIFY = ImmutableList.of(
OptimizeLogicalModifyRule.INSTANCE,
OptimizeLogicalInsertRule.INSTANCE
);
public static final ImmutableList<RelOptRule> OPTIMIZE_LOGICAL_VIEW = ImmutableList.of(
OptimizeLogicalViewRule.INSTANCE
);
public static final ImmutableList<RelOptRule> OPTIMIZE_AGGREGATE = ImmutableList.of(
// remove aggregation if it does not aggregate and input is already distinct
DrdsAggregateRemoveRule.INSTANCE,
// expand distinct aggregate to normal aggregate with groupby
DrdsAggregateExpandDistinctAggregatesRule.INSTANCE,
// expand grouping sets
GroupingSetsToExpandRule.INSTANCE,
ProjectMergeRule.INSTANCE
);
public static final ImmutableList<RelOptRule> CBO_TOO_MANY_JOIN_REORDER_RULE = ImmutableList.of(
JoinCommuteRule.SWAP_OUTER
);
public static final ImmutableList<RelOptRule> CBO_LEFT_DEEP_TREE_JOIN_REORDER_RULE = ImmutableList.of(
JoinCommuteRule.SWAP_OUTER_SWAP_BOTTOM_JOIN,
InnerJoinLAsscomRule.INSTANCE,
InnerJoinLAsscomRule.PROJECT_INSTANCE,
OuterJoinLAsscomRule.INSTANCE,
OuterJoinLAsscomRule.PROJECT_INSTANCE,
SemiJoinSemiJoinTransposeRule.INSTANCE,
CBOLogicalSemiJoinLogicalJoinTransposeRule.LASSCOM,
CBOLogicalSemiJoinLogicalJoinTransposeRule.PROJECT_LASSCOM
);
public static final ImmutableList<RelOptRule> CBO_ZIG_ZAG_TREE_JOIN_REORDER_RULE = ImmutableList.of(
JoinCommuteRule.SWAP_OUTER_SWAP_ZIG_ZAG,
InnerJoinLAsscomRule.INSTANCE,
InnerJoinLAsscomRule.PROJECT_INSTANCE,
OuterJoinLAsscomRule.INSTANCE,
OuterJoinLAsscomRule.PROJECT_INSTANCE,
SemiJoinSemiJoinTransposeRule.INSTANCE,
CBOLogicalSemiJoinLogicalJoinTransposeRule.LASSCOM,
CBOLogicalSemiJoinLogicalJoinTransposeRule.PROJECT_LASSCOM
);
public static final ImmutableList<RelOptRule> CBO_BUSHY_TREE_JOIN_REORDER_RULE = ImmutableList.of(
JoinCommuteRule.SWAP_OUTER,
ProjectJoinCommuteRule.SWAP_OUTER,
InnerJoinLeftAssociateRule.INSTANCE,
InnerJoinLeftAssociateRule.PROJECT_INSTANCE,
InnerJoinRightAssociateRule.INSTANCE,
InnerJoinRightAssociateRule.PROJECT_INSTANCE,
JoinExchangeRule.INSTANCE,
JoinExchangeRule.BOTH_PROJECT,
JoinExchangeRule.LEFT_PROJECT,
JoinExchangeRule.RIGHT_PROJECT,
OuterJoinAssocRule.INSTANCE,
OuterJoinLAsscomRule.INSTANCE,
CBOLogicalSemiJoinLogicalJoinTransposeRule.INSTANCE,
SemiJoinSemiJoinTransposeRule.INSTANCE,
SemiJoinProjectTransposeRule.INSTANCE
);
public static final ImmutableList<RelOptRule> CBO_JOIN_TABLELOOKUP_REORDER_RULE = ImmutableList.of(
JoinTableLookupTransposeRule.INSTANCE_RIGHT
);
public static final ImmutableList<RelOptRule> CBO_BASE_RULE = ImmutableList.of(
// Join Algorithm
LogicalJoinToBKAJoinRule.LOGICALVIEW_NOT_RIGHT,
LogicalJoinToBKAJoinRule.LOGICALVIEW_RIGHT,
LogicalJoinToBKAJoinRule.TABLELOOKUP_NOT_RIGHT,
LogicalJoinToBKAJoinRule.TABLELOOKUP_RIGHT,
LogicalJoinToNLJoinRule.INSTANCE,
LogicalJoinToHashJoinRule.INSTANCE,
LogicalJoinToHashJoinRule.OUTER_INSTANCE,
LogicalJoinToSortMergeJoinRule.INSTANCE,
LogicalSemiJoinToMaterializedSemiJoinRule.INSTANCE,
LogicalSemiJoinToMaterializedSemiJoinRule.TABLELOOKUP,
LogicalSemiJoinToSemiNLJoinRule.INSTANCE,
LogicalSemiJoinToSemiHashJoinRule.INSTANCE,
LogicalSemiJoinToSemiSortMergeJoinRule.INSTANCE,
LogicalSemiJoinToSemiBKAJoinRule.INSTANCE,
LogicalSemiJoinToSemiBKAJoinRule.TABLELOOKUP,
// Agg Algorithm
LogicalAggToSortAggRule.INSTANCE,
LogicalAggToHashAggRule.INSTANCE,
AggJoinToToHashGroupJoinRule.INSTANCE,
// window
LogicalWindowToSortWindowRule.INSTANCE,
// Push Sort
PushSortRule.PLAN_ENUERATE,
// Push Filter
PushFilterRule.LOGICALVIEW,
PushFilterRule.MERGE_SORT,
PushFilterRule.PROJECT_FILTER_LOGICALVIEW,
// Push Join
CBOPushSemiJoinRule.INSTANCE,
CBOPushJoinRule.INSTANCE,
// Push Agg
CBOPushAggRule.LOGICALVIEW,
// Join Window Transpose
CBOJoinWindowTransposeRule.INSTANCE,
// Agg Join Transpose
DrdsAggregateJoinTransposeRule.EXTENDED,
DrdsAggregateJoinTransposeRule.PROJECT_EXTENDED,
// Access Path
AccessPathRule.LOGICALVIEW,
// Sort TableLookup Transpose
SortTableLookupTransposeRule.INSTANCE,
// Sort Join Transpose
DrdsSortJoinTransposeRule.INSTANCE,
DrdsSortProjectTransposeRule.INSTANCE,
// Push Modify
PushModifyRule.VIEW,
PushModifyRule.MERGESORT,
PushModifyRule.SORT_VIEW,
// Convert
DrdsExpandConvertRule.INSTANCE,
DrdsProjectConvertRule.INSTANCE,
DrdsFilterConvertRule.INSTANCE,
DrdsCorrelateConvertRule.INSTANCE,
DrdsSortConvertRule.INSTANCE,
DrdsSortConvertRule.TOPN,
DrdsMergeSortConvertRule.INSTANCE,
DrdsValuesConvertRule.INSTANCE,
DrdsUnionConvertRule.INSTANCE,
DrdsModifyConvertRule.INSTANCE,
DrdsInsertConvertRule.INSTANCE,
DrdsRelocateConvertRule.INSTANCE,
DrdsRecyclebinConvertRule.INSTANCE,
DrdsLogicalViewConvertRule.INSTANCE,
DrdsLogicalTableLookupConvertRule.INSTANCE,
DrdsVirtualViewConvertRule.INSTANCE,
DrdsDynamicConvertRule.INSTANCE,
DrdsOutFileConvertRule.INSTANCE
);
public static final ImmutableList<RelOptRule> MPP_CBO_RULE = ImmutableList.of(
// Exchange
MppExpandConversionRule.INSTANCE,
// Join Convert
MppNLJoinConvertRule.INSTANCE,
MppHashGroupJoinConvertRule.INSTANCE,
MppHashJoinConvertRule.INSTANCE,
MppBKAJoinConvertRule.INSTANCE,
MppSortMergeJoinConvertRule.INSTANCE,
// Semi Join Convert
MppSemiHashJoinConvertRule.INSTANCE,
MppSemiBKAJoinConvertRule.INSTANCE,
MppSemiNLJoinConvertRule.INSTANCE,
MppMaterializedSemiJoinConvertRule.INSTANCE,
MppSemiSortMergeJoinConvertRule.INSTANCE,
// Agg Convert
MppHashAggConvertRule.INSTANCE,
MppSortAggConvertRule.INSTANCE,
// Window Convert
MppSortWindowConvertRule.INSTANCE,
// Sort Convert
MppMemSortConvertRule.INSTANCE,
MppLimitConvertRule.INSTANCE,
MppTopNConvertRule.INSTANCE,
// Merge Sort
MppMergeSortConvertRule.INSTANCE,
// Others Convert
MppExpandConvertRule.INSTANCE,
MppUnionConvertRule.INSTANCE,
MppValuesConverRule.INSTANCE,
MppDynamicValuesConverRule.INSTANCE,
MppProjectConvertRule.INSTANCE,
MppCorrelateConvertRule.INSTANCE,
MppFilterConvertRule.INSTANCE,
MppLogicalViewConvertRule.INSTANCE,
MppVirtualViewConvertRule.INSTANCE
);
public static final ImmutableList<RelOptRule> RUNTIME_FILTER = ImmutableList.of(
JoinToRuntimeFilterJoinRule.HASHJOIN_INSTANCE,
JoinToRuntimeFilterJoinRule.SEMIJOIN_INSTANCE,
RFBuilderExchangeTransposeRule.INSTANCE,
RFBuilderJoinTransposeRule.INSTANCE,
RFBuilderProjectTransposeRule.INSTANCE,
RFBuilderMergeRule.INSTANCE,
FilterExchangeTransposeRule.INSTANCE,
RFilterProjectTransposeRule.INSTANCE,
FilterMergeRule.INSTANCE,
PushFilterRule.LOGICALUNION,
FilterCorrelateRule.INSTANCE,
CorrelateProjectRule.INSTANCE,
FilterAggregateTransposeRule.INSTANCE,
RFilterJoinTransposeRule.HASHJOIN_INSTANCE,
RFilterJoinTransposeRule.SEMI_HASHJOIN_INSTANCE,
FilterRFBuilderTransposeRule.INSTANCE
);
}
| 42.391061 | 109 | 0.759225 |
94797020dcdefa5d2357776f3b15b03bd1b0b4ba | 883 | package com.ebanswers.kitchendiary.bean;
import android.content.Context;
import android.graphics.Bitmap;
import com.umeng.socialize.media.UMImage;
import java.io.File;
/**
* @author
* Created by lishihui on 2017/3/13.
*/
public class ShareImage extends UMImage {
private File imgFile;
private String imgUrl;
private Bitmap imgBitmap;
public ShareImage(Context context, File file) {
super(context, file);
imgFile = file;
}
public ShareImage(Context context,String s){
super(context,s);
imgUrl = s;
}
public ShareImage(Context context,Bitmap bitmap){
super(context,bitmap);
imgBitmap = bitmap;
}
public File getImgFile() {
return imgFile;
}
public String getImgUrl() {
return imgUrl;
}
public Bitmap getImgBitmap() {
return imgBitmap;
}
}
| 18.787234 | 53 | 0.643262 |
648ff45018bf9737b516f8ca3c594a539f0a14a3 | 1,772 | package ru.job4j.search;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Class for testing the "PriorityQueue" class.
*
* @author Dmitrii Eskov ([email protected])
* @since 20.01.2019
* @version 1.0
*/
public class PriorityQueueTest {
/**
* When it needs to get an element with the highest priority.
*/
@Test
public void whenHigherPriority() {
var queue = new PriorityQueue();
queue.put(new Task("low", 5));
queue.put(new Task("urgent", 1));
queue.put(new Task("middle", 3));
Task result = queue.take();
assertThat(result.getDesc(), is("urgent"));
}
/**
* When it needs to get an element with the highest priority.
*/
@Test
public void whenHigherPriority2() {
var queue = new PriorityQueue();
queue.put(new Task("low", 5));
queue.put(new Task("urgent", 1));
queue.put(new Task("middle", 3));
queue.take();
var result = queue.take();
assertThat(result.getDesc(), is("middle"));
}
/**
* When it needs to get all the elements.
*/
@Test
public void whenHigherPriority4() {
var queue = new PriorityQueue();
queue.put(new Task("middle2", 5));
queue.put(new Task("urgent", 1));
queue.put(new Task("middle1", 3));
queue.put(new Task("low", 8));
var result = queue.take();
assertThat(result.getDesc(), is("urgent"));
result = queue.take();
assertThat(result.getDesc(), is("middle1"));
result = queue.take();
assertThat(result.getDesc(), is("middle2"));
result = queue.take();
assertThat(result.getDesc(), is("low"));
}
} | 28.580645 | 65 | 0.579007 |
ac714bbb5c278197e939789989fea7cfc9a53931 | 15,934 | package com.cognition.android.mailboxapp;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import com.cognition.android.mailboxapp.Summary_Utils.Summary;
import com.cognition.android.mailboxapp.activities.MainActivity;
import com.cognition.android.mailboxapp.models.Message;
import com.cognition.android.mailboxapp.utils.MessagesAdapter;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Base64;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.client.util.StringUtils;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.ListMessagesResponse;
import com.google.api.services.gmail.model.MessagePart;
import com.google.api.services.gmail.model.MessagePartHeader;
import com.mindorks.placeholderview.SwipeDecor;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import pub.devrel.easypermissions.EasyPermissions;
import static com.cognition.android.mailboxapp.activities.MainActivity.PREF_ACCOUNT_NAME;
import static com.cognition.android.mailboxapp.activities.MainActivity.REQUEST_AUTHORIZATION;
import static com.cognition.android.mailboxapp.activities.MainActivity.SCOPES;
import static com.cognition.android.mailboxapp.activities.MainActivity.TAG;
public class activity_swipe extends AppCompatActivity {
List<Message> messageList;
MessagesAdapter messagesAdapter;
List<String> ID = new ArrayList<>();
GoogleAccountCredential mCredential;
Gmail mService;
SharedPreferences sharedPref;
com.cognition.android.mailboxapp.utils.Utils mUtils;
String pageToken = null;
boolean isFetching = false;
FrameLayout lytParent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
mService = null;
sharedPref = activity_swipe.this.getSharedPreferences(getString(R.string.preferences_file_name), Context.MODE_PRIVATE);
mUtils = new com.cognition.android.mailboxapp.utils.Utils(activity_swipe.this);
String accountName = sharedPref.getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
mService = new com.google.api.services.gmail.Gmail.Builder(
transport, jsonFactory, mCredential)
.setApplicationName("MailBox App")
.build();
} else {
startActivity(new Intent(activity_swipe.this, MainActivity.class));
ActivityCompat.finishAffinity(activity_swipe.this);
}
messageList = new ArrayList<>();
messagesAdapter = new MessagesAdapter(activity_swipe.this, messageList);
getMessagesFromDB();
lytParent = findViewById(R.id.lytParent);
SwipePlaceHolderView mSwipeView = findViewById(R.id.swipeView);
Context mContext = getApplicationContext();
mSwipeView.getBuilder()
.setDisplayViewCount(3)
.setSwipeDecor(new SwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
.setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
/*for(com.cognition.android.mailboxapp.Profile profile : Utils.loadProfiles(this.getApplicationContext())){
mSwipeView.addView(new TinderCard(mContext, profile, mSwipeView));
}
if(done==true) {
for (String id : ID) {
Message message = SQLite.select().from(Message.class).where(Message_Table.id.eq(Integer.valueOf(id))).querySingle();
Profile profile = new Profile();
profile.setId(message.getId());
profile.setSubject(message.getSubject());
profile.setMessage(message.getSnippet());
profile.setSender(message.getFrom());
mSwipeView.addView(new TinderCard(mContext, profile, mSwipeView));
}
}
*/
List<Message> messages = SQLite.select().from(Message.class).queryList();
for(Message message: messages) {
Profile profile = new Profile();
profile.setId(String.valueOf(message.getId()));
profile.setSubject(message.getSubject());
profile.setSender(message.getFrom());
profile.setMessage(message.getSnippet());
mSwipeView.addView(new TinderCard(mContext, profile, mSwipeView));
}
/*findViewById(R.id.rejectBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSwipeView.doSwipe(false);
}
});
findViewById(R.id.acceptBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSwipeView.doSwipe(true);
}
});
*/
findViewById(R.id.floatingActionButton2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(activity_swipe.this, View_type.class));
ActivityCompat.finishAffinity(activity_swipe.this);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_AUTHORIZATION) {
if (resultCode == RESULT_OK) {
if (!isFetching && mUtils.isDeviceOnline()) {
getMessagesFromDB();
} else
mUtils.showSnackbar(lytParent, getString(R.string.device_is_offline));
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(activity_swipe.this);
builder.setMessage(R.string.app_requires_auth);
builder.setPositiveButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActivityCompat.finishAffinity(activity_swipe.this);
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(
requestCode, permissions, grantResults, this);
}
private void getMessagesFromDB() {
if (mUtils.isDeviceOnline())
new GetEmailsTask(true).execute();
else
mUtils.showSnackbar(lytParent, getString(R.string.device_is_offline));
}
private String[] getData(JSONArray parts) throws JSONException {
for (int i = 0; i < parts.length(); i++) {
JSONObject part = new JSONObject(parts.getString(i));
if (part.has("parts"))
return getData(new JSONArray(part.getString("parts")));
else {
if (part.getString("mimeType").equals("text/html"))
return new String[]{
part.getString("mimeType"),
new String(
Base64.decodeBase64(part.getJSONObject("body").getString("data")),
StandardCharsets.UTF_8
)
};
}
}
for (int i = 0; i < parts.length(); i++) {
JSONObject part = new JSONObject(parts.getString(i));
if (part.getString("mimeType").equals("text/plain"))
return new String[]{
part.getString("mimeType"),
new String(
Base64.decodeBase64(part.getJSONObject("body").getString("data")),
StandardCharsets.UTF_8
)
};
}
return new String[]{null, null};
}
@SuppressLint("StaticFieldLeak")
private class GetEmailsTask extends AsyncTask<Void, Void, List<Message>> {
private int itemCount = 0;
private boolean clear;
private Exception mLastError = null;
GetEmailsTask(boolean clear) {
this.clear = clear;
}
@Override
protected List<Message> doInBackground(Void... voids) {
isFetching = true;
List<Message> messageListReceived = null;
if (clear) {
//Delete.table(Message.class);
activity_swipe.this.pageToken = null;
}
try {
String user = "me";
String query = "in:inbox";
ListMessagesResponse messageResponse = mService.users().messages().list(user).setQ(query).setMaxResults(100L).setPageToken(activity_swipe.this.pageToken).execute();
messageListReceived = new ArrayList<>();
List<com.google.api.services.gmail.model.Message> receivedMessages = messageResponse.getMessages();
for (com.google.api.services.gmail.model.Message message : receivedMessages) {
com.google.api.services.gmail.model.Message actualMessage = mService.users().messages().get(user, message.getId()).execute();
Map<String, String> headers = new HashMap<>();
for (MessagePartHeader messagePartHeader : actualMessage.getPayload().getHeaders())
headers.put(
messagePartHeader.getName(), messagePartHeader.getValue()
);
//FirebaseDatabase database = FirebaseDatabase.getInstance();
//DatabaseReference myRef = database.getReference("messages");
//myRef.setValue(actualMessage.getRaw());
MessagePart msg = actualMessage.getPayload();
String body = StringUtils.newStringUtf8(Base64.decodeBase64(msg.getBody().getData()));
//String summary = Summary.summarize(body, headers.get("Subject"), getApplicationContext());
Message newMessage = new Message(
actualMessage.getLabelIds(),
actualMessage.getSnippet(),
actualMessage.getPayload().getMimeType(),
headers,
actualMessage.getPayload().getParts(),
actualMessage.getInternalDate(),
activity_swipe.this.mUtils.getRandomMaterialColor(),
actualMessage.getPayload(),
body);
/*
try {
JSONObject parentPart = new JSONObject(newMessage.getParentPartJson());
if (parentPart.getJSONObject("body").getInt("size") != 0) {
byte[] dataBytes = Base64.decodeBase64(parentPart.getJSONObject("body").getString("data"));
String data = new String(dataBytes, StandardCharsets.UTF_8);
Document document = Jsoup.parse(data);
Elements el = document.getAllElements();
for (Element e : el) {
Attributes at = e.attributes();
for (Attribute a : at) {
e.removeAttr(a.getKey());
}
}
document.getElementsByTag("style").remove();
document.select("[style]").removeAttr("style");
//Log.d("DOCUMENT TEXT IS::",document.body());
data = data.replaceAll("\\<.*?>", "");
newMessage.setSummary(Summary.summarize(document.text(), newMessage.getSubject(),getApplicationContext()));
//System.out.println("THE DATA::::" + data);
//Log.d(MainActivity.TAG, newMessage.getMimetype());
} else {
JSONArray partsArray = new JSONArray(newMessage.getPartsJson());
String[] result = getData(partsArray);
if (result[0] != null && result[1] != null) {
//(data,mimeType,encoding)
result[1] = result[1].replaceAll("\\<.*?>", "");
//System.out.println("THE DATA IS::::" + result[1]);
Document document = Jsoup.parse(result[1]);
//Log.d("DOCUMENT TEXT IS::", document.text());
document.getElementsByTag("style").remove();
document.select("[style]").removeAttr("style");
newMessage.setSummary(Summary.summarize(document.text(), newMessage.getSubject(),getApplicationContext()));
//Log.d(MainActivity.TAG, result[0]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
*/
ID.add(actualMessage.getId());
newMessage.save();
messageListReceived.add(newMessage);
itemCount++;
}
} catch (Exception e) {
Log.w(TAG, e);
mLastError = e;
cancel(true);
}
return messageListReceived;
}
}
} | 43.416894 | 180 | 0.58303 |
e209e954bdbbef3f02a9063950f160dab98783b0 | 442 | package profile;
import firebase4j.error.FirebaseException;
import firebase4j.error.JacksonUtilityException;
import firebase4j.model.FirebaseResponse;
import firebase4j.service.Firebase;
import java.io.UnsupportedEncodingException;
public interface IProfile {
FirebaseResponse create(String id, String email) throws JacksonUtilityException, UnsupportedEncodingException, FirebaseException;
FirebaseResponse delete(String email);
}
| 31.571429 | 133 | 0.848416 |
ee0731542c98f352800b4faed97e6390fc693d70 | 1,237 | package org.companion.inquisitor;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class ValidateFromMapTest {
private final ValidationRule validationRule;
public ValidateFromMapTest() throws IOException {
File metaResource = new File("src/test/resources/meta_validator.xml");
File configResource = new File("src/test/resources/validator_from_map.xml");
MetaData metaData = new MetaValidatorFactory().compile(metaResource);
ValidatorFactory validatorFactory = new ValidatorFactory(metaData);
Map<String, ValidationRule> validators = validatorFactory.compile(configResource);
Assert.assertNotNull(validators);
validationRule = validators.get("POSTAL_CODE_LENGTH");
}
@Test
public void canValidateValueFromMap() {
Map<String, Object> data = new HashMap<String, Object>() {{
put("postalCode", "12345");
}};
Assert.assertTrue(validationRule.validate(data));
}
@Test
public void failIfMapHasNoDataButExpectData() {
Assert.assertFalse(validationRule.validate(new HashMap<String, Object>()));
}
}
| 31.717949 | 90 | 0.71059 |
3250e52dada922bedc90ff1bb439f519bf29cd91 | 314 | package main.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
/**
* Created by cipriach on 07.12.2015.
*/
@NoArgsConstructor
@Getter
@Setter
public class User implements Serializable {
private String userName;
private String password;
}
| 16.526316 | 43 | 0.764331 |
85caa2c645ebc1deb8bbd42895528167746ad6e2 | 3,676 | /*
* <!--
* ~ Copyright (c) 2017. ThanksMister 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.thanksmister.btcblue.ui.spinner;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.thanksmister.btcblue.R;
import com.thanksmister.btcblue.data.api.model.DisplayExchange;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class ExchangeAdapter extends ArrayAdapter<DisplayExchange> {
private LayoutInflater inflater;
private List<DisplayExchange> values;
public ExchangeAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<DisplayExchange> values) {
this.values = values;
notifyDataSetInvalidated();
}
public int getCount() {
if (values == null)
return 0;
return values.size();
}
public DisplayExchange getItem(int position) {
if (values == null)
return null;
return values.get(position);
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view != null) {
holder = (ViewHolder) view.getTag();
} else {
view = inflater.inflate(R.layout.spinner_header, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
}
// Fix for exchange being removed from BitcoinAverage list after
// previously been available (Coinbase)
if (!values.isEmpty()) {
DisplayExchange exchange = null;
try {
exchange = values.get(position);
holder.displayName.setText(exchange.getDisplayName());
} catch (IndexOutOfBoundsException e) {
exchange = values.get(0);
holder.displayName.setText(exchange.getDisplayName());
}
} else {
holder.displayName.setText(R.string.spinner_no_exchange_data);
}
return view;
}
@Override
public View getDropDownView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view != null) {
holder = (ViewHolder) view.getTag();
} else {
view = inflater.inflate(R.layout.spinner_dropdown, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
}
DisplayExchange exchange = values.get(position);
holder.displayName.setText(exchange.getDisplayName());
return view;
}
class ViewHolder {
@InjectView(R.id.displayName)
TextView displayName;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
} | 30.380165 | 99 | 0.636017 |
91ba7f777580ecf7b4edb1036dc4154bb45ae0ff | 2,965 | package com.decipherx.fingerprint.idp.entities;
import javax.persistence.*;
@Entity
@Table(name = "user_device")
public class UserDevice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column (nullable = false, unique = true)
private String username;
@Column (nullable = true)
private String fullName;
@Column(nullable = false)
private String emailAddress;
@Column (nullable = true)
private String phoneNumber;
@Column (nullable = false)
private String imei;
@Column (nullable = false)
private String deviceName;
@Column (nullable = false)
private String deviceId;
@Column(nullable = true)
private String publicKey;
@Column(nullable = true)
private String fcmToken;
public UserDevice() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getFcmToken() {
return fcmToken;
}
public void setFcmToken(String fcmToken) {
this.fcmToken = fcmToken;
}
@Override
public String toString() {
return "UserDevice{" +
"id=" + id +
", username='" + username + '\'' +
", fullName='" + fullName + '\'' +
", emailAddress='" + emailAddress + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", imei='" + imei + '\'' +
", deviceName='" + deviceName + '\'' +
", deviceId='" + deviceId + '\'' +
", publicKey='" + publicKey + '\'' +
", fcmToken='" + fcmToken + '\'' +
'}';
}
}
| 21.330935 | 58 | 0.565599 |
22968216f4d500f37629968f079cb171fcdc31a8 | 7,461 | package com.rarchives.ripme.ripper.rippers;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.rarchives.ripme.utils.Utils;
import org.json.JSONObject;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.rarchives.ripme.ripper.AbstractHTMLRipper;
import com.rarchives.ripme.ui.RipStatusMessage.STATUS;
import com.rarchives.ripme.utils.Http;
public class EightmusesRipper extends AbstractHTMLRipper {
private Document albumDoc = null;
private Map<String,String> cookies = new HashMap<>();
// TODO put up a wiki page on using maps to store titles
// the map for storing the title of each album when downloading sub albums
private Map<URL,String> urlTitles = new HashMap<>();
private Boolean rippingSubalbums = false;
public EightmusesRipper(URL url) throws IOException {
super(url);
}
@Override
public boolean hasASAPRipping() {
return true;
}
@Override
public String getHost() {
return "8muses";
}
@Override
public String getDomain() {
return "8muses.com";
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p = Pattern.compile("^https?://(www\\.)?8muses\\.com/(comix|comics)/album/([a-zA-Z0-9\\-_]+).*$");
Matcher m = p.matcher(url.toExternalForm());
if (!m.matches()) {
throw new MalformedURLException("Expected URL format: http://www.8muses.com/index/category/albumname, got: " + url);
}
return m.group(m.groupCount());
}
@Override
public String getAlbumTitle(URL url) throws MalformedURLException {
try {
// Attempt to use album title as GID
Element titleElement = getFirstPage().select("meta[name=description]").first();
String title = titleElement.attr("content");
title = title.replace("A huge collection of free porn comics for adults. Read", "");
title = title.replace("online for free at 8muses.com", "");
return getHost() + "_" + title.trim();
} catch (IOException e) {
// Fall back to default album naming convention
LOGGER.info("Unable to find title at " + url);
}
return super.getAlbumTitle(url);
}
@Override
public Document getFirstPage() throws IOException {
if (albumDoc == null) {
Response resp = Http.url(url).response();
cookies.putAll(resp.cookies());
albumDoc = resp.parse();
}
return albumDoc;
}
@Override
public List<String> getURLsFromPage(Document page) {
List<String> imageURLs = new ArrayList<>();
int x = 1;
// This contains the thumbnails of all images on the page
Elements pageImages = page.getElementsByClass("c-tile");
for (Element thumb : pageImages) {
// If true this link is a sub album
if (thumb.attr("href").contains("/comics/album/")) {
String subUrl = "https://www.8muses.com" + thumb.attr("href");
try {
LOGGER.info("Retrieving " + subUrl);
sendUpdate(STATUS.LOADING_RESOURCE, subUrl);
Document subPage = Http.url(subUrl).get();
// If the page below this one has images this line will download them
List<String> subalbumImages = getURLsFromPage(subPage);
LOGGER.info("Found " + subalbumImages.size() + " images in subalbum");
} catch (IOException e) {
LOGGER.warn("Error while loading subalbum " + subUrl, e);
}
} else if (thumb.attr("href").contains("/comics/picture/")) {
LOGGER.info("This page is a album");
LOGGER.info("Ripping image");
if (super.isStopped()) break;
// Find thumbnail image source
String image = null;
if (thumb.hasAttr("data-cfsrc")) {
image = thumb.attr("data-cfsrc");
} else {
// Deobfustace the json data
String rawJson = deobfuscateJSON(page.select("script#ractive-public").html()
.replaceAll(">", ">").replaceAll("<", "<").replace("&", "&"));
JSONObject json = new JSONObject(rawJson);
try {
for (int i = 0; i != json.getJSONArray("pictures").length(); i++) {
image = "https://www.8muses.com/image/fl/" + json.getJSONArray("pictures").getJSONObject(i).getString("publicUri");
URL imageUrl = new URL(image);
addURLToDownload(imageUrl, getPrefixShort(x), getSubdir(page.select("title").text()), this.url.toExternalForm(), cookies, "", null, true);
// X is our page index
x++;
if (isThisATest()) {
break;
}
}
return imageURLs;
} catch (MalformedURLException e) {
LOGGER.error("\"" + image + "\" is malformed");
}
}
if (!image.contains("8muses.com")) {
// Not hosted on 8muses.
continue;
}
imageURLs.add(image);
if (isThisATest()) break;
}
}
return imageURLs;
}
public String getSubdir(String rawHref) {
LOGGER.info("Raw title: " + rawHref);
String title = rawHref;
title = title.replaceAll("8muses - Sex and Porn Comics", "");
title = title.replaceAll("\\s+", " ");
title = title.replaceAll("\n", "");
title = title.replaceAll("\\| ", "");
title = title.replace(" - ", "-");
title = title.replace(" ", "-");
LOGGER.info(title);
return title;
}
@Override
public void downloadURL(URL url, int index) {
addURLToDownload(url, getPrefix(index), "", this.url.toExternalForm(), cookies);
}
public String getPrefixLong(int index) {
return String.format("%03d_", index);
}
public String getPrefixShort(int index) {
return String.format("%03d", index);
}
private String deobfuscateJSON(String obfuscatedString) {
StringBuilder deobfuscatedString = new StringBuilder();
// The first char in one of 8muses obfuscated strings is always ! so we replace it
for (char ch : obfuscatedString.replaceFirst("!", "").toCharArray()){
deobfuscatedString.append(deobfuscateChar(ch));
}
return deobfuscatedString.toString();
}
private String deobfuscateChar(char c) {
if ((int) c == 32) {
return fromCharCode(32);
}
return fromCharCode(33 + (c + 14) % 94);
}
private static String fromCharCode(int... codePoints) {
return new String(codePoints, 0, codePoints.length);
}
} | 37.873096 | 166 | 0.562525 |
dd7cd79d1731c8731150e3c1ab0f4d96683cece2 | 2,670 | package pl.polsl.webexchange;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import pl.polsl.webexchange.currency.Currency;
import pl.polsl.webexchange.currency.CurrencyRepository;
import pl.polsl.webexchange.currencyrate.CurrencyRateUpdater;
import pl.polsl.webexchange.currencyrate.ExchangeRateApiService;
import pl.polsl.webexchange.user.Role;
import pl.polsl.webexchange.user.User;
import pl.polsl.webexchange.user.UserRepository;
import java.util.List;
@Component
@RequiredArgsConstructor
public class DataInitializer implements ApplicationRunner {
private final CurrencyRepository currencyRepository;
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;
private final CurrencyRateUpdater currencyRateUpdater;
private final ExchangeRateApiService exchangeRateApiService;
private final WebExchangeProperties webExchangeProperties;
@Override
public void run(ApplicationArguments args) {
if (!webExchangeProperties.getInit()) {
return;
}
WebExchangeProperties.UserConfig initialAdmin = webExchangeProperties.getAdmin();
User admin = new User(initialAdmin.getEmail(), initialAdmin.getUsername(), passwordEncoder.encode(initialAdmin.getPassword()), Role.ROLE_ADMIN);
admin.activateAccount();
admin = userRepository.save(admin);
WebExchangeProperties.UserConfig initialUser = webExchangeProperties.getUser();
User user = new User(initialUser.getEmail(), initialUser.getUsername(), passwordEncoder.encode(initialUser.getPassword()), Role.ROLE_USER);
user.activateAccount();
user = userRepository.save(user);
List<WebExchangeProperties.CurrencyConfig> initialCurrencies = webExchangeProperties.getInitialCurrencies();
exchangeRateApiService.getAllValidCurrencyCodes().forEach(currencyCode -> {
Currency currency = new Currency(currencyCode.toUpperCase());
initialCurrencies.stream()
.filter(currencyConfig -> currencyConfig.getCurrencyCode().equals(currencyCode))
.findFirst()
.ifPresent(currencyConfig -> {
currency.setActive(true);
currency.setCountry(currencyConfig.getCountry());
});
currencyRepository.save(currency);
});
this.currencyRateUpdater.updateCurrencyRates();
}
}
| 39.264706 | 152 | 0.738951 |
106fe0e1b7a0d241f3e657d921ecf0b1d4e5a5b7 | 6,574 | package design.aem.models.v2.layout;
import design.aem.components.ComponentProperties;
import design.aem.models.BaseComponent;
import design.aem.utils.components.ComponentsUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import java.util.LinkedHashMap;
import java.util.Map;
import static design.aem.utils.components.ComponentsUtil.*;
import static design.aem.utils.components.ImagesUtil.DEFAULT_BACKGROUND_IMAGE_NODE_NAME;
import static design.aem.utils.components.ImagesUtil.getBackgroundImageRenditions;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
public class ContentBlockMenu extends BaseComponent {
protected static final String DEFAULT_MENUSOURCE_PARENT = "parent";
protected static final String DEFAULT_MENUSOURCE_PAGEPATH = "pagepath";
protected static final String FIELD_MENUSOURCE = "menuSource";
protected static final String FIELD_MENUSOURCEPAGEPATH = "menuSourcePagePath";
protected void ready() throws Exception {
componentProperties = ComponentsUtil.getComponentProperties(
this,
componentFields,
DEFAULT_FIELDS_STYLE,
DEFAULT_FIELDS_ACCESSIBILITY);
Map<String, String> contentBlockList = new LinkedHashMap<>();
Resource menuSource = getResource().getParent();
if (componentProperties.get(FIELD_MENUSOURCE, DEFAULT_MENUSOURCE_PARENT).equals(DEFAULT_MENUSOURCE_PAGEPATH)) {
String menuSourcePagePath = componentProperties.get(FIELD_MENUSOURCEPAGEPATH, StringUtils.EMPTY);
if (isNotEmpty(menuSourcePagePath)) {
Resource menuSourcePagePathRes = getResourceResolver().getResource(menuSourcePagePath);
if (menuSourcePagePathRes != null) {
menuSource = menuSourcePagePathRes;
}
}
}
if (menuSource != null) {
contentBlockList = getContentBlockMenu(menuSource);
}
componentProperties.put("contentBlockList", contentBlockList);
componentProperties.put(DEFAULT_BACKGROUND_IMAGE_NODE_NAME,
getBackgroundImageRenditions(this));
}
@Override
protected void setFields() {
setComponentFields(new Object[][]{
{FIELD_VARIANT, DEFAULT_VARIANT},
{FIELD_MENUSOURCE, DEFAULT_MENUSOURCE_PARENT},
{FIELD_MENUSOURCEPAGEPATH, StringUtils.EMPTY},
});
}
/**
* Checks whether a jcr node is a content block we want to be processing
*
* @param childNode is the childnode
* @return true if this is a content block component
* @throws RepositoryException when can't read content
*/
private static boolean isContentBlockComponent(Node childNode) throws RepositoryException {
return
(childNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY) &&
childNode.getProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY).getString().endsWith("contentblock")) ||
(childNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY) &&
childNode.getProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY).getString().endsWith("contentblocklock"));
}
/**
* Return true if this content block node should be shown in the content menu. This
* is indicated by the avialability of the hideInMenu property. If it's not there, it should
* be visible, if it is set to true, it should be visible, otherwise hide it.
*
* @param childNode is the content block child node to inspect
* @return true if the content block's title should be shown in the menu
* @throws RepositoryException when something weird happens retrieving the properties.
*/
private static boolean isVisibleInMenu(Node childNode) throws RepositoryException {
return
// not been set? it's visible
!childNode.hasProperty(FIELD_HIDEINMENU) ||
// set to true? it's visible.
"true".equals(childNode.getProperty(FIELD_HIDEINMENU).getString());
}
/**
* Get the content block menu for page <code>page</code>
*
* @param parSys is the Resource to
* @return a sequenced map of the content block anchor names and their titles
* @throws RepositoryException when can't read content
*/
@SuppressWarnings({"squid:S3776"})
private static Map<String, String> getContentBlockMenu(Resource parSys) throws RepositoryException {
Map<String, String> contentMenu = new LinkedHashMap<>();
if (parSys != null) {
Node contentResourceNode = parSys.adaptTo(Node.class);
if (contentResourceNode != null) {
NodeIterator nodeIterator = contentResourceNode.getNodes();
// iterate over children
if (nodeIterator != null) {
while (nodeIterator.hasNext()) {
Node childNode = nodeIterator.nextNode();
if (childNode == null) {
continue;
}
if (isContentBlockComponent(childNode) && isVisibleInMenu(childNode)) {
String childTitle = childNode.getName();
String childName = childNode.getName();
if (childNode.hasProperty(FIELD_STYLE_COMPONENT_ID)) {
String componentId = childNode.getProperty(FIELD_STYLE_COMPONENT_ID).getString();
if (isNotEmpty(componentId)) {
childName = componentId;
}
}
if (childNode.hasProperty("title")) {
childTitle = childNode.getProperty("title").getString();
if (isEmpty(childTitle)) {
childTitle = childName;
}
}
contentMenu.put(childName, childTitle);
}
}
return contentMenu;
}
}
}
return contentMenu;
}
}
| 41.345912 | 135 | 0.632187 |
9452025bb9b77bebd2ccc548980927fbe614738c | 2,025 | package com.kunlunsoft.entity;
import java.io.Serializable;
public class User implements Serializable {
/** */
private Integer id;
/** */
private String name;
/** */
private Byte age;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column USER.id
*
* @return the value of USER.id
* @mbg.generated Fri Jul 06 13:45:15 CST 2018
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column USER.id
*
* @param id the value for USER.id
* @mbg.generated Fri Jul 06 13:45:15 CST 2018
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column USER.name
*
* @return the value of USER.name
* @mbg.generated Fri Jul 06 13:45:15 CST 2018
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column USER.name
*
* @param name the value for USER.name
* @mbg.generated Fri Jul 06 13:45:15 CST 2018
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column USER.age
*
* @return the value of USER.age
* @mbg.generated Fri Jul 06 13:45:15 CST 2018
*/
public Byte getAge() {
return age;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column USER.age
*
* @param age the value for USER.age
* @mbg.generated Fri Jul 06 13:45:15 CST 2018
*/
public void setAge(Byte age) {
this.age = age;
}
} | 25.3125 | 69 | 0.600494 |
5bc168fae1d763b81d5a97a130c62e500395780b | 471 | package no.mnemonic.messaging.documentchannel.kafka;
/**
* A transport object representing a document coming from Kafka
*
* @param <T> document type
*/
public class KafkaDocument<T> {
private final T document;
private final String cursor;
public KafkaDocument(T document, String cursor) {
this.document = document;
this.cursor = cursor;
}
public T getDocument() {
return document;
}
public String getCursor() {
return cursor;
}
}
| 18.115385 | 63 | 0.694268 |
109e564634cab4ea6a124adff641ee53231ea993 | 5,109 | package nl.ellipsis.webdav.server;
public interface WebDAVConstants {
public final static String PFX_ACL_PFXDOCUMENT = "PfxDocuments";
public final static String PREFIX_DOMAIN_PERMISSION = "imDomain";
public final static String ENCODING_UTF8 = "UTF-8";
public final static String CONTENTTYPE_XML_UTF8 = "text/xml; charset=utf-8";
// public static final String RESOURCES_ATTR = "nl.ellipsis.webdav.naming.resources";
public interface HttpRequestParam {
public static final String INCLUDE_CONTEXT_PATH = "javax.servlet.include.context_path";
public static final String INCLUDE_PATH_INFO = "javax.servlet.include.path_info";
public static final String INCLUDE_REQUEST_URI = "javax.servlet.include.request_uri";
public static final String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path";
}
public interface Permission {
public final static String PFX_DOCUMENT_METHOD_COPY = "pfxDocumentMethodCopy";
public final static String PFX_DOCUMENT_METHOD_DELETE = "pfxDocumentMethodDelete";
public final static String PFX_DOCUMENT_METHOD_GET = "pfxDocumentMethodGet";
public final static String PFX_DOCUMENT_METHOD_LOCK = "pfxDocumentMethodLock";
public final static String PFX_DOCUMENT_METHOD_MKCOL = "pfxDocumentMethodMkcol";
public final static String PFX_DOCUMENT_METHOD_MOVE = "pfxDocumentMethodMove";
public final static String PFX_DOCUMENT_METHOD_PROPFIND = "pfxDocumentMethodProppatch";
public final static String PFX_DOCUMENT_METHOD_PROPPATCH = "pfxDocumentMethodPropfind";
public final static String PFX_DOCUMENT_METHOD_PUT = "pfxDocumentMethodPut";
public final static String PFX_DOCUMENT_METHOD_UNLOCK = "pfxDocumentMethodUnlock";
public final static String PFX_ACCESS_WEBDAV_ROOTDIR = "pfxAccessWebDAVRootDir";
public final static String PFX_ACCESS_WEBDAV_DOMAINDIR = "pfxAccessWebDAVDomainDir";
public final static String PFX_ACCESS_WEBDAV_DOMAINDIR_SUB1 = "pfxAccessWebDAVDomainDirSub1";
public final static String PFX_ACCESS_WEBDAV_DOMAINDIR_SUB2 = "pfxAccessWebDAVDomainDirSub2";
public final static String PFX_ACCESS_WEBDAV_DIRECTORY_LISTING = "pfxAccessWebDAVDirectoryListing";
public final static String PFX_ACCESS_WEBDAV_METHOD_COPY = "pfxAccessWebDAVMethodCopy";
public final static String PFX_ACCESS_WEBDAV_METHOD_DELETE = "pfxAccessWebDAVMethodDelete";
public final static String PFX_ACCESS_WEBDAV_METHOD_GET = "pfxAccessWebDAVMethodGet";
public final static String PFX_ACCESS_WEBDAV_METHOD_LOCK = "pfxAccessWebDAVMethodLock";
public final static String PFX_ACCESS_WEBDAV_METHOD_MKCOL = "pfxAccessWebDAVMethodMkcol";
public final static String PFX_ACCESS_WEBDAV_METHOD_MOVE = "pfxAccessWebDAVMethodMove";
public final static String PFX_ACCESS_WEBDAV_METHOD_PROPFIND = "pfxAccessWebDAVMethodProppatch";
public final static String PFX_ACCESS_WEBDAV_METHOD_PROPPATCH = "pfxAccessWebDAVMethodPropfind";
public final static String PFX_ACCESS_WEBDAV_METHOD_PUT = "pfxAccessWebDAVMethodPut";
public final static String PFX_ACCESS_WEBDAV_METHOD_UNLOCK = "pfxAccessWebDAVMethodUnlock";
}
public interface XMLTag {
public final static String ACTIVELOCK = "activelock";
public static final String ALLPROP = "allprop";
public final static String COLLECTION = "collection";
public final static String CREATIONDATE = "creationdate";
public final static String DEPTH = "depth";
public final static String DISPLAYNAME = "displayname";
public static final String EXCLUSIVE = "exclusive";
public final static String GET_CONTENTLANGUAGE = "getcontentlanguage";
public final static String GET_CONTENTLENGTH = "getcontentlength";
public final static String GET_CONTENTTYPE = "getcontenttype";
public final static String GET_ETAG = "getetag";
public final static String GET_LASTMODIFIED = "getlastmodified";
public final static String HREF = "href";
public final static String LOCK_NULL = "lock-null";
public final static String LOCKDISCOVERY = "lockdiscovery";
public static final String LOCKENTRY = "lockentry";
public final static String LOCKSCOPE = "lockscope";
public final static String LOCKTOKEN = "locktoken";
public final static String LOCKTYPE = "locktype";
public final static String OWNER = "owner";
public final static String PROP = "prop";
public static final String PROPERTYUPDATE = "propertyupdate";
public static final String PROPNAME = "propname";
public final static String PROPSTAT = "propstat";
public final static String MULTISTATUS = "multistatus";
public final static String RESPONSE = "response";
public final static String RESOURCETYPE = "resourcetype";
public final static String SOURCE = "source";
public static final String SHARED = "shared";
public final static String STATUS = "status";
public final static String SUPPORTEDLOCK = "supportedlock";
public final static String TIMEOUT = "timeout";
public static final String WRITE = "write";
}
}
| 61.554217 | 101 | 0.778626 |
f56a50f293932b53fc50c0850094c0f673f4e645 | 1,379 | /*
* 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.giraph.examples;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation should be used to annotate built-in algorithms.
*/
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Algorithm {
/**
* Name of the algorithm.
*/
String name();
/**
* Short description of algorithm which is going to be presented to the user.
*/
String description() default "";
}
| 32.833333 | 79 | 0.744017 |
c34d93468985bd96291d79d2993028b848bc08ba | 1,821 | package com.student.compete.geeksforgeeks.dp.easy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MobileNumericKeypad {
// study more
// https://www.geeksforgeeks.org/mobile-numeric-keypad-problem/
public int getWaysCount(int num) {
if (num <= 0) {
return 0;
}
Map<Integer, List<Integer>> keypadMap = getKeypadMap();
int[][] waysCountDP = getWaysCountDP(num, keypadMap);
return Arrays.stream(waysCountDP[num - 1])
.sum();
}
private Map<Integer, List<Integer>> getKeypadMap() {
Map<Integer, List<Integer>> keypadMap = new HashMap<>();
keypadMap.put(0, Arrays.asList(0, 8));
keypadMap.put(1, Arrays.asList(1, 2, 4));
keypadMap.put(2, Arrays.asList(2, 1, 3, 5));
keypadMap.put(3, Arrays.asList(3, 2, 6));
keypadMap.put(4, Arrays.asList(4, 1, 5, 7));
keypadMap.put(5, Arrays.asList(5, 2, 4, 6, 8));
keypadMap.put(6, Arrays.asList(6, 3, 5, 9));
keypadMap.put(7, Arrays.asList(7, 4, 8));
keypadMap.put(8, Arrays.asList(8, 0, 5, 7, 9));
keypadMap.put(9, Arrays.asList(9, 6, 8));
return keypadMap;
}
private int[][] getWaysCountDP(int num, Map<Integer, List<Integer>> keypadMap) {
int[][] waysCountDP = new int[num][keypadMap.size()];
Arrays.fill(waysCountDP[0], 1);
for (int step = 1; step <= num - 1; step++) {
for (int key = 0; key <= keypadMap.size() - 1; key++) {
final int s = step;
waysCountDP[step][key] = keypadMap.get(key).stream()
.mapToInt(k -> waysCountDP[s - 1][k])
.sum();
}
}
return waysCountDP;
}
}
| 31.947368 | 84 | 0.556837 |
e280100019f8a69068feba63dfd00a375f7500d8 | 194 | package com.josericardojunior.gitdataminer.buildingblocks;
import javax.swing.JPanel;
public class Block extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 13.857143 | 58 | 0.742268 |
0279d9c3751c21b6409c0b158ff98163021179ad | 3,075 | package com.stl.skipthelibrary.DatabaseAndAPI;
import android.net.Uri;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* This class is used to get the book's description from google's book api
*/
public class BookWebAPIHelper {
private static final String TAG = "BookWebAPIHelper";
private static final String BASE_URL = "https://www.googleapis.com/books/v1/volumes?";
private static final String QUERY_PARAM = "q";
private static final String QUERY_BASE = "=isbn:";
private static final String PRINT_TYPE = "printType";
private static final String PRINT_VALUE = "books";
private static final String METHOD = "GET";
/**
* Empty constructor
*/
public BookWebAPIHelper() {}
/**
* Get the book's JSON info by making an API call.
* Sets up the HTTP connection and then retrieves the response
* @param ISBN: the book's ISBN
* @return the book's details in JSON
*/
public static String getBookInfo(String ISBN){
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader = null;
String bookDescriptionJSON = null;
try {
// construct the URL
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, QUERY_BASE + ISBN)
.appendQueryParameter(PRINT_TYPE, PRINT_VALUE).build();
URL url = new URL(uri.toString());
// start the connection
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(METHOD);
httpURLConnection.connect();
// get the response
InputStream inputStream = httpURLConnection.getInputStream();
StringBuffer stringBuffer = new StringBuffer();
if (inputStream == null){
return null;
}
// format the response
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
stringBuffer.append(line + "\n");
}
if (stringBuffer.length() == 0){
return null;
}
bookDescriptionJSON = stringBuffer.toString();
Log.d(TAG, bookDescriptionJSON);
}
catch (Exception e){
e.printStackTrace();
return null;
}
finally {
// return the response after disconnecting safely
if (httpURLConnection != null){
httpURLConnection.disconnect();
}
if (bufferedReader!=null){
try{
bufferedReader.close();
}
catch (Exception e){
e.printStackTrace();
}
}
return bookDescriptionJSON;
}
}
}
| 30.75 | 90 | 0.587317 |
aee0192ca2e08464094d8523546619abf0f1c657 | 617 | package com.langke.wudimall.coupon;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author LangKe
* @description
* @date 2021/6/26 14:47
*/
@EnableDiscoveryClient //开启服务注册与发现功能
@MapperScan("com.langke.wudimall.coupon.dao")
@SpringBootApplication
public class WudimallCouponApplication {
public static void main(String[] args){
SpringApplication.run(WudimallCouponApplication.class, args);
}
}
| 29.380952 | 72 | 0.795786 |
658fb4f3cf963fb0effaa0a5d0b6bb6acc073420 | 151 | package org.accounting.system.clients.responses.eoscportal;
import java.util.List;
public class Response {
public List<EOSCProvider> results;
}
| 16.777778 | 59 | 0.781457 |
79c583976c85e00dc7c3c0c5794e743ed5887a05 | 2,175 | package com.yuuko.core.modules.utility;
import com.yuuko.core.CommandExecutor;
import com.yuuko.core.modules.Command;
import com.yuuko.core.modules.Module;
import com.yuuko.core.modules.utility.commands.BindCommand;
import com.yuuko.core.modules.utility.commands.ChannelCommand;
import com.yuuko.core.modules.utility.commands.ServerCommand;
import com.yuuko.core.modules.utility.commands.UserCommand;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageReaction;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.core.events.message.react.MessageReactionRemoveEvent;
public class UtilityModule extends Module {
public UtilityModule(MessageReceivedEvent e, String[] command) {
super("Utility", "moduleUtility", false, new Command[]{
new UserCommand(),
new ServerCommand(),
new BindCommand(),
new ChannelCommand()
});
new CommandExecutor(e, command, this);
}
/**
* Module constructor for MessageReactionAddEvents
* @param e MessageReactionAddEvent
*/
public UtilityModule(MessageReactionAddEvent e) {
super("Utility", "moduleUtility", false, null);
if(e.getReaction().getReactionEmote().getName().equals("📌")) {
Message message = e.getTextChannel().getMessageById(e.getMessageId()).complete();
message.pin().queue();
}
}
/**
* Module constructor for MessageReactionRemoveEvents
* @param e MessageReactionRemoveEvent
*/
public UtilityModule(MessageReactionRemoveEvent e) {
super("Utility", "moduleUtility", false, null);
Message message = e.getTextChannel().getMessageById(e.getMessageId()).complete();
if(e.getReactionEmote().getName().equals("📌")) {
for(MessageReaction emote: message.getReactions()) {
if(emote.getReactionEmote().getName().equals("📌")) {
return;
}
}
message.unpin().queue();
}
}
} | 35.655738 | 93 | 0.670345 |
3ce42c1f32f732df8291dd2bdba13e43a79a618c | 4,718 | package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.TemplateCardLevelConfDTO;
import com.alipay.api.domain.TemplateColumnInfoDTO;
import com.alipay.api.domain.TemplateFieldRuleDTO;
import com.alipay.api.domain.TemplateOpenCardConfDTO;
import com.alipay.api.domain.PubChannelDTO;
import com.alipay.api.domain.TemplateBenefitInfoDTO;
import com.alipay.api.domain.TemplateStyleInfoDTO;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.marketing.card.template.query response.
*
* @author auto create
* @since 1.0, 2016-10-18 15:46:32
*/
public class AlipayMarketingCardTemplateQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 8293343182392977652L;
/**
* 业务卡号前缀,由商户自定义
*/
@ApiField("biz_no_prefix")
private String bizNoPrefix;
/**
* 卡号长度
*/
@ApiField("biz_no_suffix_len")
private String bizNoSuffixLen;
/**
* 卡等级配置
*/
@ApiListField("card_level_confs")
@ApiField("template_card_level_conf_d_t_o")
private List<TemplateCardLevelConfDTO> cardLevelConfs;
/**
* 会员卡类型:
OUT_MEMBER_CARD:外部权益卡
*/
@ApiField("card_type")
private String cardType;
/**
* 栏位信息(卡包详情页面展现的栏位)
*/
@ApiListField("column_info_list")
@ApiField("template_column_info_d_t_o")
private List<TemplateColumnInfoDTO> columnInfoList;
/**
* 字段规则列表,会员卡开卡过程中,会员卡信息的生成规则,
例如:卡有效期为开卡后两年内有效,则设置为:DATE_IN_FUTURE
*/
@ApiListField("field_rule_list")
@ApiField("template_field_rule_d_t_o")
private List<TemplateFieldRuleDTO> fieldRuleList;
/**
* 会员卡用户领卡配置,在门店等渠道露出领卡入口时,需要部署的商户领卡H5页面地址
*/
@ApiField("open_card_conf")
private TemplateOpenCardConfDTO openCardConf;
/**
* 卡模板投放渠道
*/
@ApiListField("pub_channels")
@ApiField("pub_channel_d_t_o")
private List<PubChannelDTO> pubChannels;
/**
* 服务标签列表
*/
@ApiListField("service_label_list")
@ApiField("string")
private List<String> serviceLabelList;
/**
* 门店ids
*/
@ApiListField("shop_ids")
@ApiField("string")
private List<String> shopIds;
/**
* 权益信息,
1、在卡包的卡详情页面会自动添加权益栏位,展现会员卡特权,
2、如果添加门店渠道,则可在门店页展现会员卡的权益
*/
@ApiListField("template_benefit_info")
@ApiField("template_benefit_info_d_t_o")
private List<TemplateBenefitInfoDTO> templateBenefitInfo;
/**
* 模板样式信息(钱包展现效果)
*/
@ApiField("template_style_info")
private TemplateStyleInfoDTO templateStyleInfo;
public void setBizNoPrefix(String bizNoPrefix) {
this.bizNoPrefix = bizNoPrefix;
}
public String getBizNoPrefix( ) {
return this.bizNoPrefix;
}
public void setBizNoSuffixLen(String bizNoSuffixLen) {
this.bizNoSuffixLen = bizNoSuffixLen;
}
public String getBizNoSuffixLen( ) {
return this.bizNoSuffixLen;
}
public void setCardLevelConfs(List<TemplateCardLevelConfDTO> cardLevelConfs) {
this.cardLevelConfs = cardLevelConfs;
}
public List<TemplateCardLevelConfDTO> getCardLevelConfs( ) {
return this.cardLevelConfs;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getCardType( ) {
return this.cardType;
}
public void setColumnInfoList(List<TemplateColumnInfoDTO> columnInfoList) {
this.columnInfoList = columnInfoList;
}
public List<TemplateColumnInfoDTO> getColumnInfoList( ) {
return this.columnInfoList;
}
public void setFieldRuleList(List<TemplateFieldRuleDTO> fieldRuleList) {
this.fieldRuleList = fieldRuleList;
}
public List<TemplateFieldRuleDTO> getFieldRuleList( ) {
return this.fieldRuleList;
}
public void setOpenCardConf(TemplateOpenCardConfDTO openCardConf) {
this.openCardConf = openCardConf;
}
public TemplateOpenCardConfDTO getOpenCardConf( ) {
return this.openCardConf;
}
public void setPubChannels(List<PubChannelDTO> pubChannels) {
this.pubChannels = pubChannels;
}
public List<PubChannelDTO> getPubChannels( ) {
return this.pubChannels;
}
public void setServiceLabelList(List<String> serviceLabelList) {
this.serviceLabelList = serviceLabelList;
}
public List<String> getServiceLabelList( ) {
return this.serviceLabelList;
}
public void setShopIds(List<String> shopIds) {
this.shopIds = shopIds;
}
public List<String> getShopIds( ) {
return this.shopIds;
}
public void setTemplateBenefitInfo(List<TemplateBenefitInfoDTO> templateBenefitInfo) {
this.templateBenefitInfo = templateBenefitInfo;
}
public List<TemplateBenefitInfoDTO> getTemplateBenefitInfo( ) {
return this.templateBenefitInfo;
}
public void setTemplateStyleInfo(TemplateStyleInfoDTO templateStyleInfo) {
this.templateStyleInfo = templateStyleInfo;
}
public TemplateStyleInfoDTO getTemplateStyleInfo( ) {
return this.templateStyleInfo;
}
}
| 24.319588 | 87 | 0.770242 |
187c084efac01ee33cc315fd8cceb46d499e6d0a | 2,389 | package com.example.karakoram.parentFragment;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.karakoram.R;
import com.example.karakoram.childFragment.bill.BillChildFragment;
import com.example.karakoram.adapter.PageAdapter;
import com.example.karakoram.resource.Category;
import com.google.android.material.tabs.TabLayout;
public class BillFragment extends Fragment {
private View myfragment;
private ViewPager viewPager;
private TabLayout tabLayout;
public BillFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
myfragment= inflater.inflate(R.layout.fragment_bill, container, false);
viewPager=myfragment.findViewById(R.id.viewpager);
tabLayout=myfragment.findViewById(R.id.tabs);
return myfragment;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setUpViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setUpViewPager(ViewPager viewPager){
PageAdapter adapter=new PageAdapter(getChildFragmentManager());
adapter.addFragment(new BillChildFragment(Category.Maintenance,false),"Maint");
adapter.addFragment(new BillChildFragment(Category.Mess,false),"Mess");
adapter.addFragment(new BillChildFragment(Category.Cultural,false),"Cult");
adapter.addFragment(new BillChildFragment(Category.Sports,false),"Sports");
adapter.addFragment(new BillChildFragment(Category.Others,false),"Others");
viewPager.setAdapter(adapter);
}
}
| 32.283784 | 87 | 0.713688 |
9973a0a98055bdbfa585df1b81b23b5aab9ba029 | 5,338 | package com.arnab.datta.babycare;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class Login extends AppCompatActivity {
private TextView t1;
private Button btl;
private EditText tu,tp;
private ProgressDialog ProgressDialog ;
private FirebaseAuth FirebaseAuth ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
/* if (FirebaseAuth.getCurrentUser() != null){
finish();
// openActivityHome(FirebaseAuth.getCurrentUser());
}*/
ProgressDialog = new ProgressDialog(this);
tu = findViewById(R.id.editTextUser);
tp = findViewById(R.id.editTextPass);
t1 = findViewById(R.id.textViewSignUp);
t1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openActivitySignUp();
}
});
btl = findViewById(R.id.buttonLogin);
btl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
userlogin();
}
});
}
public void openActivitySignUp(){
Intent intent = new Intent(this, Signup.class);
startActivity(intent);
}
public void openActivityHome(User user){
String str = "You have logged in successfully";
Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Home.class);
intent.putExtra("userName",user.getUsername());
intent.putExtra("babyName",user.getBabyname());
startActivity(intent);
}
private void userlogin () {
String Username = tu.getText().toString().trim();
String password = tp.getText().toString().trim();
if (TextUtils.isEmpty(Username)) {
Toast.makeText(this, "please enter email", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "please enter password", Toast.LENGTH_SHORT).show();
return;
}
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersdRef = rootRef.child("baby");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> array=new ArrayList();
List<User> allUsers=new ArrayList();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds.child("email").getValue(String.class);
String babyName = ds.child("babyname").getValue(String.class);
String pasword=ds.child("password").getValue(String.class);
String userName=ds.child("username").getValue(String.class);
User user=new User();
user.setEmail(email);
user.setBabyname(babyName);
user.setPassword(pasword);
user.setUsername(userName);
allUsers.add(user);
array.add(email);
}
for(User u:allUsers){
if((u.getUsername().equals(tu.getText().toString().trim()))&&(u.getPassword().equals(tp.getText().toString().trim()))){
ProgressDialog.dismiss();
User muUser=u;
finish();
openActivityHome(u);
break;
}
}
/* if (task.isSuccessful()) {
finish();
openActivityHome();
} else {
Toast.makeText(Login.this, "login failed please try again", Toast.LENGTH_SHORT).show();
}*/
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
usersdRef.addListenerForSingleValueEvent(eventListener);
}
/* @Override
public void onClick(View v) {
if (v == btl) {
userlogin();
}
if (v == t1)
finish();
openActivitySignUp();
}*/
}
| 32.54878 | 139 | 0.599288 |
689502cfb8bf25e1ecfc47223fcd5eee9c2e3504 | 1,047 | /** @version $Id: ShowTextElement.java,v 1.10 2015/11/30 23:17:08 ist181861 Exp $ */
package edt.textui.main;
import edt.core.Element;
import edt.core.Document;
import edt.core.DocumentEditor;
import edt.core.Paragraph;
import edt.core.Section;
import static ist.po.ui.Dialog.IO;
import ist.po.ui.Command;
import ist.po.ui.DialogException;
import java.util.Iterator;
import java.io.IOException;
/**
* §2.1.5.
*/
public class ShowTextElement extends Command<DocumentEditor> {
public ShowTextElement(DocumentEditor w) {
super(MenuEntry.SHOW_TEXT_ELEMENT, w);
}
@Override
public final void execute() throws DialogException, IOException {
Document recvDoc = _receiver.getCurrentDocument();
String id = IO.readString(Message.requestElementId());
Element target = recvDoc.getElementById(id);
if (target == null) {
IO.println(Message.noSuchTextElement(id));
return;
} else {
ShowerElementVisitor vis = new ShowerElementVisitor();
target.accept(vis);
for (String s: vis.getReturn()) {
IO.println(s);
}
}
}
}
| 25.536585 | 84 | 0.731614 |
fce1da683219cf26f26b526a90a0dec108cc9bc4 | 12,749 | /*
* Copyright (c) 2011, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.color;
import com.twelvemonkeys.lang.Validate;
import com.twelvemonkeys.util.LRUHashMap;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.Map;
import static com.twelvemonkeys.imageio.color.ColorProfiles.*;
/**
* A helper class for working with ICC color profiles and color spaces.
* <p>
* Standard ICC color profiles are read from system-specific locations
* for known operating systems.
* </p>
* <p>
* Color profiles may be configured by placing a property-file
* {@code com/twelvemonkeys/imageio/color/icc_profiles.properties}
* on the classpath, specifying the full path to the profiles.
* ICC color profiles are probably already present on your system, or
* can be downloaded from
* <a href="http://www.color.org/profiles2.xalter">ICC</a>,
* <a href="http://www.adobe.com/downloads/">Adobe</a> or other places.
* * </p>
* <p>
* Example property file:
* </p>
* <pre>
* # icc_profiles.properties
* ADOBE_RGB_1998=/path/to/Adobe RGB 1998.icc
* GENERIC_CMYK=/path/to/Generic CMYK.icc
* </pre>
*
* @author <a href="mailto:[email protected]">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: ColorSpaces.java,v 1.0 24.01.11 17.51 haraldk Exp$
*/
public final class ColorSpaces {
// TODO: Consider creating our own ICC profile class, which just wraps the byte array,
// for easier access and manipulation until creating a "real" ICC_Profile/ColorSpace.
// This will also let us work around the issues in the LCMS implementation.
final static boolean DEBUG = "true".equalsIgnoreCase(System.getProperty("com.twelvemonkeys.imageio.color.debug"));
// NOTE: java.awt.color.ColorSpace.CS_* uses 1000-1004, we'll use 5000+ to not interfere with future additions
/** The Adobe RGB 1998 (or compatible) color space. Either read from disk or built-in. */
@SuppressWarnings("WeakerAccess")
public static final int CS_ADOBE_RGB_1998 = 5000;
/** A best-effort "generic" CMYK color space. Either read from disk or built-in. */
@SuppressWarnings("WeakerAccess")
public static final int CS_GENERIC_CMYK = 5001;
// TODO: Move to ColorProfiles OR cache ICC_ColorSpace instead?
// Weak references to hold the color spaces while cached
private static WeakReference<ICC_Profile> adobeRGB1998 = new WeakReference<>(null);
private static WeakReference<ICC_Profile> genericCMYK = new WeakReference<>(null);
// Cache for the latest used color spaces
private static final Map<Key, ICC_ColorSpace> cache = new LRUHashMap<>(16);
static {
// In case we didn't activate through SPI already
ProfileDeferralActivator.activateProfiles();
}
private ColorSpaces() {}
/**
* Creates an ICC color space from the given ICC color profile.
* <p>
* For standard Java color spaces, the built-in instance is returned.
* Otherwise, color spaces are looked up from cache and created on demand.
* </p>
*
* @param profile the ICC color profile. May not be {@code null}.
* @return an ICC color space
* @throws IllegalArgumentException if {@code profile} is {@code null}.
* @throws java.awt.color.CMMException if {@code profile} is invalid.
*/
public static ICC_ColorSpace createColorSpace(final ICC_Profile profile) {
Validate.notNull(profile, "profile");
// Fix profile before lookup/create
fixProfile(profile);
byte[] profileHeader = getProfileHeaderWithProfileId(profile);
ICC_ColorSpace cs = getInternalCS(profile.getColorSpaceType(), profileHeader);
if (cs != null) {
return cs;
}
return getCachedOrCreateCS(profile, profileHeader);
}
static ICC_ColorSpace getInternalCS(final int profileCSType, final byte[] profileHeader) {
if (profileCSType == ColorSpace.TYPE_RGB && Arrays.equals(profileHeader, ColorProfiles.sRGB.header)) {
return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_sRGB);
}
else if (profileCSType == ColorSpace.TYPE_GRAY && Arrays.equals(profileHeader, ColorProfiles.GRAY.header)) {
return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_GRAY);
}
else if (profileCSType == ColorSpace.TYPE_3CLR && Arrays.equals(profileHeader, ColorProfiles.PYCC.header)) {
return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_PYCC);
}
else if (profileCSType == ColorSpace.TYPE_RGB && Arrays.equals(profileHeader, ColorProfiles.LINEAR_RGB.header)) {
return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
}
else if (profileCSType == ColorSpace.TYPE_XYZ && Arrays.equals(profileHeader, ColorProfiles.CIEXYZ.header)) {
return (ICC_ColorSpace) ColorSpace.getInstance(ColorSpace.CS_CIEXYZ);
}
return null;
}
private static ICC_ColorSpace getCachedOrCreateCS(final ICC_Profile profile, final byte[] profileHeader) {
Key key = new Key(profileHeader);
synchronized (cache) {
ICC_ColorSpace cs = getCachedCS(key);
if (cs == null) {
cs = new ICC_ColorSpace(profile);
validateColorSpace(cs);
cache.put(key, cs);
// On LCMS, validation *alters* the profile header, need to re-generate key
if (ColorProfiles.validationAltersProfileHeader()) {
cache.put(new Key(getProfileHeaderWithProfileId(cs.getProfile())), cs);
}
}
return cs;
}
}
private static ICC_ColorSpace getCachedCS(Key profileKey) {
synchronized (cache) {
return cache.get(profileKey);
}
}
static ICC_ColorSpace getCachedCS(final byte[] profileHeader) {
return getCachedCS(new Key(profileHeader));
}
static void validateColorSpace(final ICC_ColorSpace cs) {
// Validate the color space, to avoid caching bad profiles/color spaces
// Will throw IllegalArgumentException or CMMException if the profile is bad
cs.fromRGB(new float[] {0.999f, 0.5f, 0.001f});
// This breaks *some times* after validation of bad profiles,
// we'll let it blow up early in this case
cs.getProfile().getData();
}
/**
* @deprecated Use {@link ColorProfiles#isCS_sRGB(ICC_Profile)} instead.
*/
@Deprecated
public static boolean isCS_sRGB(final ICC_Profile profile) {
return ColorProfiles.isCS_sRGB(profile);
}
/**
* @deprecated Use {@link ColorProfiles#isCS_GRAY(ICC_Profile)} instead.
*/
@Deprecated
public static boolean isCS_GRAY(final ICC_Profile profile) {
return ColorProfiles.isCS_GRAY(profile);
}
/**
* @deprecated Use {@link ColorProfiles#validateProfile(ICC_Profile)} instead.
*/
@Deprecated
public static ICC_Profile validateProfile(final ICC_Profile profile) {
return ColorProfiles.validateProfile(profile);
}
/**
* Returns the color space specified by the given color space constant.
* <p>
* For standard Java color spaces, the built-in instance is returned.
* Otherwise, color spaces are looked up from cache and created on demand.
* </p>
*
* @param colorSpace the color space constant.
* @return the {@link ColorSpace} specified by the color space constant.
* @throws IllegalArgumentException if {@code colorSpace} is not one of the defined color spaces ({@code CS_*}).
* @see ColorSpace
* @see ColorSpaces#CS_ADOBE_RGB_1998
* @see ColorSpaces#CS_GENERIC_CMYK
*/
public static ColorSpace getColorSpace(int colorSpace) {
ICC_Profile profile;
switch (colorSpace) {
case CS_ADOBE_RGB_1998:
synchronized (ColorSpaces.class) {
profile = adobeRGB1998.get();
if (profile == null) {
// Try to get system default or user-defined profile
profile = readProfileFromPath(Profiles.getPath("ADOBE_RGB_1998"));
if (profile == null) {
// Fall back to the bundled ClayRGB1998 public domain Adobe RGB 1998 compatible profile,
// which is identical for all practical purposes
profile = readProfileFromClasspathResource("/profiles/ClayRGB1998.icc");
if (profile == null) {
// Should never happen given we now bundle fallback profile...
throw new IllegalStateException("Could not read AdobeRGB1998 profile");
}
}
if (profile.getColorSpaceType() != ColorSpace.TYPE_RGB) {
throw new IllegalStateException("Configured AdobeRGB1998 profile is not TYPE_RGB");
}
adobeRGB1998 = new WeakReference<>(profile);
}
}
return createColorSpace(profile);
case CS_GENERIC_CMYK:
synchronized (ColorSpaces.class) {
profile = genericCMYK.get();
if (profile == null) {
// Try to get system default or user-defined profile
profile = readProfileFromPath(Profiles.getPath("GENERIC_CMYK"));
if (profile == null) {
if (DEBUG) {
System.out.println("Using fallback profile");
}
// Fall back to generic CMYK ColorSpace, which is *insanely slow* using ColorConvertOp... :-P
return CMYKColorSpace.getInstance();
}
if (profile.getColorSpaceType() != ColorSpace.TYPE_CMYK) {
throw new IllegalStateException("Configured Generic CMYK profile is not TYPE_CMYK");
}
genericCMYK = new WeakReference<>(profile);
}
}
return createColorSpace(profile);
default:
// Default cases for convenience
return ColorSpace.getInstance(colorSpace);
}
}
private static final class Key {
private final byte[] data;
Key(byte[] data) {
this.data = data;
}
@Override
public boolean equals(Object other) {
return other instanceof Key && Arrays.equals(data, ((Key) other).data);
}
@Override
public int hashCode() {
return Arrays.hashCode(data);
}
@Override
public String toString() {
return getClass().getSimpleName() + "@" + Integer.toHexString(hashCode());
}
}
}
| 39.470588 | 121 | 0.640207 |
847c7326b2210a37ef5dccc9614d7b6bdae2376d | 2,317 | package pp.facerecognizer;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class Show_Attendance_Adapter extends RecyclerView.Adapter<Show_Attendance_Adapter.ViewHolder> {
private List<Model_Attendance> itemList;
private Context context;
private ItemClickListener clickListener;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView date_txt,Status_txt,Name_txt;
public ViewHolder(View itemView) {
super(itemView);
Name_txt = itemView.findViewById (R.id.itemlist_name);
date_txt = itemView.findViewById(R.id.itemlist_date);
Status_txt = itemView.findViewById(R.id.itemlist_status);
}
}
public Show_Attendance_Adapter(Context context, List<Model_Attendance> itemList) {
this.itemList = itemList;
this.context = context;
}
@Override
public Show_Attendance_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemlist_show_attendance, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(Show_Attendance_Adapter.ViewHolder holder, final int position) {
holder.date_txt.setText(itemList.get(position).getDate ());
holder.Name_txt.setText (itemList.get (position).getStudent ());
if(itemList.get (position).getStatus () == "A"){
holder.Status_txt.setTextColor(ContextCompat.getColor(context, R.color.Red));
holder.Status_txt.setText(itemList.get(position).getStatus ());
}
else{
holder.Status_txt.setText(itemList.get(position).getStatus ());
}
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
@Override
public int getItemCount() {
return this.itemList.size();
}
public interface ItemClickListener {
public void itemClick(View view, int position);
}
}
| 29.329114 | 116 | 0.702201 |
c72fabc7fe91fad0013fa28701a5a3d15791db0c | 1,919 | /*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
package com.arangodb.velocypack.module.joda.internal.util;
import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.format.ISODateTimeFormat;
public final class JodaTimeUtil {
private JodaTimeUtil() {
}
public static String format(final Instant source) {
return ISODateTimeFormat.dateTime().print(source);
}
public static String format(final DateTime source) {
return ISODateTimeFormat.dateTime().print(source);
}
public static String format(final LocalDate source) {
return ISODateTimeFormat.yearMonthDay().print(source);
}
public static String format(final LocalDateTime source) {
return ISODateTimeFormat.dateTime().print(source);
}
public static Instant parseInstant(final String source) {
return Instant.parse(source);
}
public static DateTime parseDateTime(final String source) {
return DateTime.parse(source);
}
public static LocalDate parseLocalDate(final String source) {
return LocalDate.parse(source);
}
public static LocalDateTime parseLocalDateTime(final String source) {
return LocalDateTime.parse(source);
}
} | 29.075758 | 76 | 0.736842 |
b984c48347ed97366a34ef00a92936265a78020d | 10,943 | package com.fitpay.android.webview.impl.webclients;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import com.fitpay.android.utils.Constants;
import java.io.File;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Default Fitpay web chrome client.
*/
public class FitpayWebChromeClient extends WebChromeClient {
public static final String CAPTURE_IMAGE_FILE_PROVIDER = "fitpay.pagare.fileprovider";
private Activity mActivity;
private Handler mHandler = new Handler();
private Runnable deletePrivatePhotoRunnable;
private boolean takingPhoto = false;
private long mImageTakenTime = -1;
/**
* File upload callback for platform versions prior to Android 5.0
*/
protected ValueCallback<Uri> mFileUploadCallbackFirst;
/**
* File upload callback for Android 5.0+
*/
protected ValueCallback<Uri[]> mFileUploadCallbackSecond;
public FitpayWebChromeClient(Activity activity) {
mActivity = activity;
}
public boolean isTakingPhoto() {
return takingPhoto;
}
public void updateTakingPhotoStatus() {
if (mFileUploadCallbackFirst == null && mFileUploadCallbackSecond == null) {
takingPhoto = false;
}
}
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
switch (requestCode) {
case Constants.INTENT_TAKE_PHOTO_REQUEST: {
if (resultCode == Activity.RESULT_OK) {
deletePublicPhoto();
if (mFileUploadCallbackFirst != null) {
mFileUploadCallbackFirst.onReceiveValue(getFileUri());
mFileUploadCallbackFirst = null;
} else if (mFileUploadCallbackSecond != null) {
mFileUploadCallbackSecond.onReceiveValue(new Uri[]{getFileUri()});
mFileUploadCallbackSecond = null;
}
deletePrivatePhoto();
} else {
dismissPhotoAction(false);
}
break;
}
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == Constants.INTENT_TAKE_PHOTO_PERMISSION_REQUEST) {
if (grantResults.length == 0) {
dismissPhotoAction(true);
} else {
boolean canTakePhoto = true;
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
canTakePhoto = false;
break;
}
}
if (canTakePhoto) {
takePhoto();
} else {
dismissPhotoAction(true);
}
}
}
}
// file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method)
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, null);
}
// file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method)
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
openFileChooser(uploadMsg, acceptType, null);
}
// file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method)
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileInput(uploadMsg, null, false);
}
// file upload callback (Android 5.0 (API level 21) -- current) (public method)
@SuppressWarnings("all")
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (Build.VERSION.SDK_INT >= 21) {
final boolean allowMultiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE;
openFileInput(null, filePathCallback, allowMultiple);
return true;
} else {
return false;
}
}
@SuppressLint("NewApi")
protected void openFileInput(final ValueCallback<Uri> fileUploadCallbackFirst, final ValueCallback<Uri[]> fileUploadCallbackSecond, final boolean allowMultiple) {
takingPhoto = true;
if (mFileUploadCallbackFirst != null) {
mFileUploadCallbackFirst.onReceiveValue(null);
}
mFileUploadCallbackFirst = fileUploadCallbackFirst;
if (mFileUploadCallbackSecond != null) {
mFileUploadCallbackSecond.onReceiveValue(null);
}
mFileUploadCallbackSecond = fileUploadCallbackSecond;
takePhoto();
}
private File getFile() {
File path = new File(mActivity.getFilesDir(), "/secured/");
if (!path.exists()) path.mkdirs();
return new File(path, "image.jpg");
}
private Uri getFileUri() {
return FileProvider.getUriForFile(mActivity, CAPTURE_IMAGE_FILE_PROVIDER, getFile());
}
private void takePhoto() {
boolean readPermissionGranted = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
boolean cameraPermissionGranted = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
if (readPermissionGranted && cameraPermissionGranted) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(mActivity.getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFileUri());
mImageTakenTime = System.currentTimeMillis();
mHandler.removeCallbacks(deletePrivatePhotoRunnable);
List<ResolveInfo> resInfoList = mActivity.getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
mActivity.grantUriPermission(packageName, getFileUri(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
mActivity.startActivityForResult(takePictureIntent, Constants.INTENT_TAKE_PHOTO_REQUEST);
}
} else {
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
Constants.INTENT_TAKE_PHOTO_PERMISSION_REQUEST);
}
}
//hack. some devices creates duplicate of a photo in a public directory
private void deletePublicPhoto() {
if (mImageTakenTime == -1) {
return;
}
String[] projection = {
BaseColumns._ID,
MediaStore.Images.ImageColumns.SIZE,
MediaStore.Images.ImageColumns.DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DATE_ADDED};
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
final String selection = MediaStore.Images.Media.DATE_TAKEN + " > " + mImageTakenTime;
//// intialize the Uri and the Cursor, and the current expected size.
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor c = mActivity.getContentResolver().query(u, projection, selection, null, imageOrderBy);
if (null != c && c.moveToFirst()) {
ContentResolver cr = mActivity.getContentResolver();
try {
cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, BaseColumns._ID + "=" + c.getString(3), null);
} catch (Exception ex) {
}
try {
int column_index_data = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
final String image_path = c.getString(column_index_data);
final AtomicInteger repeat = new AtomicInteger(0);
final Runnable deleteFileRunnable = new Runnable() {
@Override
public void run() {
if (repeat.get() == 5) {
return;
}
File nFile = new File(image_path);
if (nFile.exists()) {
nFile.delete();
MediaScannerConnection.scanFile(mActivity,
new String[]{image_path}, new String[]{"image/*"},
(path, uri) -> {
});
}
repeat.set(repeat.get() + 1);
mHandler.postDelayed(this, 2000);
}
};
mHandler.postDelayed(deleteFileRunnable, 5000);
} catch (Exception e) {
}
}
mImageTakenTime = -1;
}
private void deletePrivatePhoto() {
if (deletePrivatePhotoRunnable == null) {
deletePrivatePhotoRunnable = () -> {
File fdelete = getFile();
if (fdelete.exists()) {
fdelete.delete();
}
};
}
mHandler.postDelayed(deletePrivatePhotoRunnable, 30000);
}
private void dismissPhotoAction(boolean showMsg) {
if (mFileUploadCallbackFirst != null) {
mFileUploadCallbackFirst.onReceiveValue(null);
mFileUploadCallbackFirst = null;
} else if (mFileUploadCallbackSecond != null) {
mFileUploadCallbackSecond.onReceiveValue(null);
mFileUploadCallbackSecond = null;
}
if (showMsg) {
Toast.makeText(mActivity, "Photo can't be taken. Please check your application permissions", Toast.LENGTH_SHORT).show();
}
}
} | 38.396491 | 166 | 0.618752 |
323a92746a98a4e6ac795aa0bfc0b1188426927a | 861 | package net.algorithm.answer;
/**
* @Author TieJianKuDan
* @Date 2021/12/19 14:44
* @Description 997. 找到小镇的法官
* @Since version-1.0
*/
public class FindJudge {
public static void main(String[] args) {
}
public int findJudge(int n, int[][] trust) {
int[] records = new int[n + 1];
int candidate = -1;
for (int i = 0; i < trust.length; i++) {
records[trust[i][0]] = -1;
if (records[trust[i][1]] == -1) {
continue;
}
records[trust[i][1]]++;
}
for (int i = 1; i < records.length; i++) {
if (records[i] == n - 1 && candidate != -1) {
candidate = -1;
break;
}
if (records[i] == n - 1) {
candidate = i;
}
}
return candidate;
}
}
| 23.916667 | 57 | 0.437863 |
b843d32349de837dd06306cc376b025f835f0bb0 | 647 | package klay.common.dictionary.structure;
import lombok.Data;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
@Data
public class ItemData {
private CharSequence word;
private CharSequence pos;
public ItemData(CharSequence word,
CharSequence pos) {
this.word = word;
this.pos = pos;
}
public void store(DataOutput os) throws IOException {
os.writeUTF(word.toString());
os.writeUTF(pos.toString());
}
public static ItemData read(DataInput is) throws IOException {
return new ItemData(is.readUTF(), is.readUTF());
}
}
| 21.566667 | 66 | 0.659969 |
4d664998157f9aecf65f3769f48a1d432358aaf5 | 2,018 | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.example.photoz.album;
import org.keycloak.example.photoz.CustomDatabase;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.security.Principal;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">Pedro Igor</a>
*/
@Path("/profile")
public class ProfileService {
private static final String PROFILE_VIEW = "profile:view";
private CustomDatabase customDatabase = CustomDatabase.create();
@GET
@Produces("application/json")
public Response view(@Context HttpServletRequest request) {
Principal userPrincipal = request.getUserPrincipal();
List albums = this.customDatabase.findByUserId(userPrincipal.getName());
return Response.ok(new Profile(userPrincipal.getName(), albums.size())).build();
}
public static class Profile {
private String userName;
private int totalAlbums;
public Profile(String name, int totalAlbums) {
this.userName = name;
this.totalAlbums = totalAlbums;
}
public String getUserName() {
return userName;
}
public int getTotalAlbums() {
return totalAlbums;
}
}
}
| 30.119403 | 88 | 0.699207 |
e88764dc2787e8faad50f7d43bf7c5180c77187b | 185 | package p;
class SuperA{
public void m() {
}
}
class A extends SuperA{
public void m() {
}
}
class B extends A{
}
class B1 extends A{
public void foo(){
A a= null;
a.m();
}
} | 10.277778 | 23 | 0.594595 |
dd8acf7274f44e540586232578821e1de83dac33 | 2,241 | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/jdbc4/Jdbc4ResultSet.java,v 1.5 2008/01/08 06:56:30 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc4;
import java.sql.*;
import java.util.Map;
import java.util.Vector;
import org.postgresql.core.*;
/**
* This class implements the java.sql.ResultSet interface for JDBC4.
* However most of the implementation is really done in
* org.postgresql.jdbc4.AbstractJdbc4ResultSet or one of it's parents
*/
public class Jdbc4ResultSet extends AbstractJdbc4ResultSet implements java.sql.ResultSet
{
Jdbc4ResultSet(Query originalQuery, BaseStatement statement, Field[] fields, Vector tuples, ResultCursor cursor,
int maxRows, int maxFieldSize, int rsType, int rsConcurrency, int rsHoldability) throws SQLException
{
super(originalQuery, statement, fields, tuples, cursor, maxRows, maxFieldSize, rsType, rsConcurrency, rsHoldability);
}
public java.sql.ResultSetMetaData getMetaData() throws SQLException
{
checkClosed();
return new Jdbc4ResultSetMetaData(connection, fields);
}
public java.sql.Clob getClob(int i) throws SQLException
{
checkResultSet(i);
if (wasNullFlag)
return null;
return new Jdbc4Clob(connection, getLong(i));
}
public java.sql.Blob getBlob(int i) throws SQLException
{
checkResultSet(i);
if (wasNullFlag)
return null;
return new Jdbc4Blob(connection, getLong(i));
}
public Array createArray(int i) throws SQLException
{
checkResultSet(i);
int oid = fields[i - 1].getOID();
String value = getFixedString(i);
return new Jdbc4Array(connection, oid, value);
}
public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException
{
return getObjectImpl(s, map);
}
public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException
{
return getObjectImpl(i, map);
}
}
| 29.88 | 125 | 0.632753 |
c4bd99ed1302355373e573ae7c1d4e09652460d0 | 1,088 | package com.frontcamera.zhousong.frontcamera;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.SurfaceView;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
Context context = MainActivity.this;
SurfaceView surfaceView;
CameraSurfaceHolder mCameraSurfaceHolder = new CameraSurfaceHolder();
private final Timer timer = new Timer();
private int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
timer.schedule(task,0,1000);
}
public void initView()
{
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
mCameraSurfaceHolder.setCameraSurfaceHolder(context,surfaceView);
}
TimerTask task= new TimerTask() {
@Override
public void run() {
if(count==10){
finish();
}
count++;
}
};
}
| 23.148936 | 73 | 0.661765 |
093beece37a83e05c143f0cd76a281577d165539 | 1,219 | package com.verdantartifice.primalmagick.common.concoctions;
import javax.annotation.Nullable;
import net.minecraft.util.StringRepresentable;
/**
* Definition of a type of alchemical concoction. Determines the maximum dosage of the vial.
*
* @author Daedalus4096
*/
public enum ConcoctionType implements StringRepresentable {
WATER(1, "water"),
TINCTURE(3, "tincture"),
PHILTER(6, "philter"),
ELIXIR(9, "elixir"),
BOMB(6, "bomb");
private final int maxDoses;
private final String tag;
private ConcoctionType(int maxDoses, String tag) {
this.maxDoses = maxDoses;
this.tag = tag;
}
public int getMaxDoses() {
return this.maxDoses;
}
@Override
public String getSerializedName() {
return this.tag;
}
public boolean hasDrinkablePotion() {
return this == TINCTURE || this == PHILTER || this == ELIXIR;
}
@Nullable
public static ConcoctionType fromName(@Nullable String name) {
for (ConcoctionType type : ConcoctionType.values()) {
if (type.getSerializedName().equals(name)) {
return type;
}
}
return null;
}
}
| 24.38 | 93 | 0.624282 |
4f1e01aab94662d8681f255fd8458cb0fae51c1f | 118 | package edu.illinois.cs.cs125.answerable.classdesignanalysis.fixtures.typeparameters.reference;
public class T<T> {}
| 29.5 | 95 | 0.830508 |
adbd1e8deed7eacdd6f83bd278c6b57184fca658 | 264 | package com.alphagfx.http.transform.util.json;
import org.json.JSONObject;
import java.util.function.Function;
public class AsJsonObject implements Function<String, JSONObject> {
@Override
public JSONObject apply(String s) {
return new JSONObject(s);
}
}
| 18.857143 | 67 | 0.776515 |
8cc8d110e806f90d7a7e1d335cd6e42eea107645 | 5,800 | /*
* Copyright (c) 2019 Greg Hoffman
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.epaga.particles;
import com.jme3.export.*;
import com.jme3.material.Material;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;
import java.io.IOException;
/**
* Emitter Shape
* This abstract class defines some base attributes that all emitter shapes use.
*
* @author Jeddic
*/
public abstract class EmitterShape implements Savable, Cloneable {
protected float randomDirection = 0.0f;
protected float originDirection = 0.0f;
protected float randomizePosition = 0.0f;
protected transient Vector3f nextDirection = new Vector3f();
protected transient Vector3f nextPosition = new Vector3f();
protected transient Vector3f tempVec = new Vector3f();
public abstract void setNext();
public abstract void setNext(int index);
public abstract int getIndex();
public abstract Vector3f getNextTranslation();
public abstract Vector3f getRandomTranslation();
public abstract Vector3f getNextDirection();
public abstract Spatial getDebugShape(Material mat, boolean ignoreTransforms);
public float getRandomDirection() {
return randomDirection;
}
public void setRandomDirection(float randomDirection) {
this.randomDirection = randomDirection;
if (randomDirection < 0) randomDirection = 0.0f;
if (randomDirection > 1.0f) randomDirection = 1.0f;
}
public float getOriginDirection() {
return originDirection;
}
public void setOriginDirection(float originDirection) {
this.originDirection = originDirection;
if (originDirection < 0) originDirection = 0.0f;
if (originDirection > 1.0f) originDirection = 1.0f;
}
public float getRandomizePosition() {
return randomizePosition;
}
public void setRandomizePosition(float randomizePosition) {
this.randomizePosition = randomizePosition;
}
protected void applyRootBehaviors() {
if (randomizePosition > 0) {
nextPosition.add((randomizePosition * 2.0f * (FastMath.nextRandomFloat() - 0.5f)),
(randomizePosition * 2.0f * (FastMath.nextRandomFloat() - 0.5f)),
(randomizePosition * 2.0f * (FastMath.nextRandomFloat() - 0.5f)));
}
if (randomDirection > 0) {
tempVec.set((2.0f * (FastMath.nextRandomFloat() - 0.5f)),
(2.0f * (FastMath.nextRandomFloat() - 0.5f)),
(2.0f * (FastMath.nextRandomFloat() - 0.5f)));
nextDirection.x = nextDirection.x * (1.0f - randomDirection) + randomDirection * tempVec.x;
nextDirection.y = nextDirection.y * (1.0f - randomDirection) + randomDirection * tempVec.y;
nextDirection.z = nextDirection.z * (1.0f - randomDirection) + randomDirection * tempVec.z;
}
if (originDirection > 0) {
tempVec.set(nextPosition);
tempVec.normalizeLocal();
nextDirection.x = nextDirection.x * (1.0f - originDirection) + originDirection * tempVec.x;
nextDirection.y = nextDirection.y * (1.0f - originDirection) + originDirection * tempVec.y;
nextDirection.z = nextDirection.z * (1.0f - originDirection) + originDirection * tempVec.z;
}
}
@Override
public void write(JmeExporter ex) throws IOException {
OutputCapsule oc = ex.getCapsule(this);
oc.write(randomDirection, "randomdirection", 0.0f);
oc.write(originDirection, "orgindirection", 0.0f);
oc.write(randomizePosition, "randomizeposition", 0.0f);
}
@Override
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
randomDirection = ic.readFloat("randomdirection", 0.0f);
originDirection = ic.readFloat("orgindirection", 0.0f);
randomizePosition = ic.readFloat("randomizeposition", 0.0f);
}
@Override
public EmitterShape clone() {
try {
EmitterShape clone = (EmitterShape) super.clone();
return clone;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
public boolean equals(Object o) {
if (!(o instanceof EmitterShape)) return false;
EmitterShape check = (EmitterShape)o;
if (randomDirection != check.randomDirection) return false;
if (originDirection != check.originDirection) return false;
if (randomizePosition != check.randomizePosition) return false;
return true;
}
}
| 35.365854 | 97 | 0.722931 |
36cbe106a07d96ab00a82e8ffef0ff583d3d025f | 4,182 | package com.pratamawijaya.blog.presentation.ui.home.fragment.list;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.pratamawijaya.blog.R;
import com.pratamawijaya.blog.app.AppComponent;
import com.pratamawijaya.blog.domain.entity.Post;
import com.pratamawijaya.blog.presentation.BaseFragment;
import com.pratamawijaya.blog.presentation.pojo.event.ShowMessageEvent;
import com.pratamawijaya.blog.presentation.ui.home.di.DaggerHomeComponent;
import com.pratamawijaya.blog.presentation.ui.home.di.HomeModule;
import com.pratamawijaya.blog.presentation.ui.home.fragment.list.adapter.ListArticleAdapter;
import com.pratamawijaya.blog.presentation.ui.home.presenter.ListPresenter;
import com.pratamawijaya.blog.presentation.utils.SimpleDividerItemDecoration;
import com.pratamawijaya.blog.utils.EndlessRecyclerOnScrollListener;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.greenrobot.eventbus.EventBus;
/**
* A simple {@link Fragment} subclass.
*/
public class ListArticleFragment extends BaseFragment implements ListArcticleView {
@Bind(R.id.contentView) SwipeRefreshLayout contentView;
@Bind(R.id.errorView) TextView errorView;
@Bind(R.id.rvListArctile) RecyclerView recyclerView;
@Inject ListPresenter presenter;
private ListArticleAdapter adapter;
private List<Post> posts;
private EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener;
public ListArticleFragment() {
// Required empty public constructor
}
public static ListArticleFragment newInstance() {
Bundle args = new Bundle();
ListArticleFragment fragment = new ListArticleFragment();
fragment.setArguments(args);
return fragment;
}
@Override public void onDestroy() {
super.onDestroy();
presenter.detachView();
}
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list_article, container, false);
}
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
presenter.attachView(this);
setupRecyclerView();
presenter.getPosts(1, false);
}
private void setupRecyclerView() {
posts = new ArrayList<>();
adapter = new ListArticleAdapter(posts, getActivity());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
ContextCompat.getDrawable(getActivity(), R.drawable.line_divider)));
endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(linearLayoutManager) {
@Override public void onLoadMore(int current_page) {
presenter.getPosts(current_page, false);
}
};
recyclerView.addOnScrollListener(endlessRecyclerOnScrollListener);
}
@Override public void showLoading() {
contentView.setRefreshing(true);
}
@Override public void hideLoading() {
contentView.setRefreshing(false);
}
@Override public void showMessage(String msg) {
EventBus.getDefault().post(new ShowMessageEvent.Builder().message(msg).build());
}
@Override protected void buildComponent(AppComponent appComponent) {
DaggerHomeComponent.builder()
.appComponent(appComponent)
.homeModule(new HomeModule(getActivity()))
.build()
.inject(this);
}
@Override public void setData(List<Post> posts) {
this.posts.addAll(posts);
adapter.notifyDataSetChanged();
}
}
| 34 | 96 | 0.778575 |
0173e3cb63aba80a57833960f2603826f192e86b | 762 | package io.github.xinshepherd.excel.core;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.List;
/**
* @author Fuxin
* @since 1.1.0
*/
public class ExcelSheetBuilder<T> {
private Class<T> modelClass;
private List<T> data;
private Workbook workbook;
private String sheetName;
public ExcelSheetBuilder(Class<T> modelClass, List<T> data, Workbook workbook) {
this.modelClass = modelClass;
this.data = data;
this.workbook = workbook;
}
public ExcelSheetBuilder<T> sheetName(String sheetName) {
this.sheetName = sheetName;
return this;
}
public ExcelSheetMetadata<T> build() {
return new ExcelSheetMetadata<>(modelClass, data, workbook, sheetName);
}
}
| 21.166667 | 84 | 0.669291 |
11af51c2485dd4a35fd4693eb7d5f6ab4da48ede | 4,266 | package org.tec.datos1.eclipse.grapher.debugger;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.debug.core.model.IStackFrame;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.tec.datos1.eclipse.grapher.CodeParser;
import org.tec.datos1.eclipse.grapher.Roger.DiagramView2;
import org.tec.datos1.eclipse.grapher.Roger.Methods;
import org.tec.datos1.eclipse.grapher.data.ASTData;
public class DebugStepIO {
private static IJavaThread debugThread;
public static IJavaThread getDebugThread() {
return debugThread;
}
public static void setDebugThread(IJavaThread DebugThread) {
debugThread = DebugThread;
}
//Se encarga de ejecutar un stepinto del debugger de eclipse
//ASTData step = ASTData.getRoot().findLine(update());
//if (step.getElement() instanceof MethodInvocation) {
//MAE VE PORQUE NO EN LUGAR DE BUSCAR LA LINEA DEL BREACKPOINT EN CODEPARSER LO HACEMOS DIRECTAMENTE EN EL DiagramView2?
//LE ACABO DE AGREGAR UN ATRIBUTO QUE ES LITERALMENTE lineNumber, entonces podriamos guardar eso ahi ya que a la hora de hacer un stepinto/over esto se deberia volver a instanciar, no?
//Entonces no ocupariamos resume
//fijate como es el stepover seria muy parecido
//y lo ultimo seria que como arriba hay un if que valida si es una instancia de algun metodo, que si no lo es que se lo salte con stepover
public static void stepInto() {
try {
ASTData step = ASTData.getRoot().findLine(update());
if (step.getElement() instanceof MethodInvocation) {
debugThread.stepInto();
int currentLine = update();
DiagramView2.setLineNumber(currentLine);
try {
MethodInvocation methodInvocation = (MethodInvocation) step.getElement();
ICompilationUnit newUnit = Methods.findClass(methodInvocation.resolveMethodBinding().getDeclaringClass().getQualifiedName());
if (!ASTData.getCompUnit().getJavaElement().getElementName()
.equals(newUnit.getElementName())){
CodeParser.executeSingular(newUnit);
}
List<String> methods = ASTData.getMethods();
String[] array = new String[methods.size()];
int cont = 0;
for(String method : methods) {
array[cont] = method;
cont++;
}
DiagramView2.setMethods(array);
DiagramView2.selectMethod(methodInvocation.getName().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
else {
stepOver();
}
} catch (Exception e) {
stepOver();
}
}
//Se encarga de ejecutar un stepover del debugger de eclipse
//ENTONCES PORQUE NO USAS DEBUGTHREAD.STEPOVER y tambien llamas a DiagramView2.setlinenumber(current) current seria la linea actual entonces deberia ir ligado con el update
public static void stepOver() {
try {
debugThread.stepOver();
int currentLine = update();
DiagramView2.setLineNumber(currentLine);
if ( !DiagramView2.getMethodSelector().getText().equalsIgnoreCase(
((MethodDeclaration)ASTData.getMethodByLine(currentLine).getElement()) //Null pointer exception al hacer step into o over a println
.getName().toString())) {
DiagramView2.Select();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Se encarga de conseguir la linea actual del debugger
public static int update(){
try {
IStackFrame Frame = null;
while (Frame == null) {
Frame = debugThread.getTopStackFrame();
}
IWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
ICompilationUnit IcUnit = (ICompilationUnit) JavaCore.create(file);
if(!IcUnit.getElementName().equalsIgnoreCase(ASTData.getCompUnit().getJavaElement().getElementName())) {
CodeParser.executeSingular(IcUnit);
}
return Frame.getLineNumber();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
| 33.590551 | 185 | 0.72691 |
5594f81ad124d47ffc42b83d36f9336dbd98feee | 7,398 | /*
* Copyright 2021 Red Hat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apicurio.tests.serdes.apicurio;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.apache.avro.generic.GenericRecord;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import io.apicurio.registry.rest.client.RegistryClient;
import io.apicurio.registry.rest.client.RegistryClientFactory;
import io.apicurio.registry.rest.client.exception.RateLimitedClientException;
import io.apicurio.registry.rest.v2.beans.ArtifactMetaData;
import io.apicurio.registry.serde.SerdeConfig;
import io.apicurio.registry.serde.avro.AvroKafkaDeserializer;
import io.apicurio.registry.serde.avro.AvroKafkaSerializer;
import io.apicurio.registry.serde.strategy.SimpleTopicIdStrategy;
import io.apicurio.registry.serde.strategy.TopicIdStrategy;
import io.apicurio.registry.types.ArtifactType;
import io.apicurio.registry.utils.IoUtil;
import io.apicurio.registry.utils.tests.TestUtils;
import io.apicurio.tests.ApicurioV2BaseIT;
import io.apicurio.tests.common.Constants;
import io.apicurio.tests.common.KafkaFacade;
import io.apicurio.tests.utils.RateLimitingProxy;
import io.apicurio.tests.utils.TooManyRequestsMock;
/**
* @author Fabian Martinez
*/
@Tag(Constants.SERDES)
public class RateLimitedRegistrySerdeIT extends ApicurioV2BaseIT {
private KafkaFacade kafkaCluster = KafkaFacade.getInstance();
private TooManyRequestsMock mock = new TooManyRequestsMock();
@BeforeAll
void setupEnvironment() {
kafkaCluster.startIfNeeded();
mock.start();
}
@AfterAll
public void teardown() throws Exception {
kafkaCluster.stopIfPossible();
mock.stop();
}
@Test
public void testClientRateLimitError() {
RegistryClient client = RegistryClientFactory.create(mock.getMockUrl());
Assertions.assertThrows(RateLimitedClientException.class, () -> client.getLatestArtifact("test", "test"));
Assertions.assertThrows(RateLimitedClientException.class, () -> client.createArtifact(null, "aaa", IoUtil.toStream("{}")));
Assertions.assertThrows(RateLimitedClientException.class, () -> client.getContentByGlobalId(5));
}
@Test
void testFindLatestRateLimited() throws Exception {
RateLimitingProxy proxy = new RateLimitingProxy(2, TestUtils.getRegistryHost(), TestUtils.getRegistryPort());
try {
proxy.start();
String topicName = TestUtils.generateTopic();
String artifactId = topicName;
kafkaCluster.createTopic(topicName, 1, 1);
AvroGenericRecordSchemaFactory avroSchema = new AvroGenericRecordSchemaFactory("myrecordapicurio1", List.of("key1"));
createArtifact(topicName, artifactId, ArtifactType.AVRO, avroSchema.generateSchemaStream());
new SimpleSerdesTesterBuilder<GenericRecord, GenericRecord>()
.withTopic(topicName)
//url of the proxy
.withCommonProperty(SerdeConfig.REGISTRY_URL, proxy.getServerUrl())
.withSerializer(AvroKafkaSerializer.class)
.withDeserializer(AvroKafkaDeserializer.class)
.withStrategy(SimpleTopicIdStrategy.class)
.withDataGenerator(avroSchema::generateRecord)
.withDataValidator(avroSchema::validateRecord)
.withProducerProperty(SerdeConfig.EXPLICIT_ARTIFACT_GROUP_ID, topicName)
// make serdes tester send multiple message batches, that will test that the cache is used when loaded
.withMessages(4, 5)
.build()
.test();
} finally {
proxy.stop();
}
}
@Test
void testAutoRegisterRateLimited() throws Exception {
RateLimitingProxy proxy = new RateLimitingProxy(2, TestUtils.getRegistryHost(), TestUtils.getRegistryPort());
try {
proxy.start();
String topicName = TestUtils.generateTopic();
//because of using TopicIdStrategy
String artifactId = topicName + "-value";
kafkaCluster.createTopic(topicName, 1, 1);
AvroGenericRecordSchemaFactory avroSchema = new AvroGenericRecordSchemaFactory("myrecordapicurio1", List.of("key1"));
new SimpleSerdesTesterBuilder<GenericRecord, GenericRecord>()
.withTopic(topicName)
//url of the proxy
.withCommonProperty(SerdeConfig.REGISTRY_URL, proxy.getServerUrl())
.withSerializer(AvroKafkaSerializer.class)
.withDeserializer(AvroKafkaDeserializer.class)
.withStrategy(TopicIdStrategy.class)
.withDataGenerator(avroSchema::generateRecord)
.withDataValidator(avroSchema::validateRecord)
.withProducerProperty(SerdeConfig.AUTO_REGISTER_ARTIFACT, "true")
.withAfterProduceValidator(() -> {
return TestUtils.retry(() -> {
ArtifactMetaData meta = registryClient.getArtifactMetaData(null, artifactId);
registryClient.getContentByGlobalId(meta.getGlobalId());
return true;
});
})
// make serdes tester send multiple message batches, that will test that the cache is used when loaded
.withMessages(4, 5)
.build()
.test();
//TODO make serdes tester send a second batch, that will test that the cache is used when loaded
ArtifactMetaData meta = registryClient.getArtifactMetaData(null, artifactId);
byte[] rawSchema = IoUtil.toBytes(registryClient.getContentByGlobalId(meta.getGlobalId()));
assertEquals(new String(avroSchema.generateSchemaBytes()), new String(rawSchema));
} finally {
proxy.stop();
}
}
@Test
void testFirstRequestFailsRateLimited() throws Exception {
String topicName = TestUtils.generateSubject();
kafkaCluster.createTopic(topicName, 1, 1);
AvroGenericRecordSchemaFactory avroSchema = new AvroGenericRecordSchemaFactory("mygroup", "myrecord", List.of("keyB"));
new WrongConfiguredSerdesTesterBuilder<GenericRecord>()
.withTopic(topicName)
//mock url that will return 429 status always
.withProducerProperty(SerdeConfig.REGISTRY_URL, mock.getMockUrl())
.withSerializer(AvroKafkaSerializer.class)
.withStrategy(TopicIdStrategy.class)
.withDataGenerator(avroSchema::generateRecord)
.build()
.test();
}
}
| 37.363636 | 131 | 0.682347 |
c42e7aa4d03e673d4b0b801f4316635f90e72755 | 507 | package fr.gustaveroussy.AdvancedQC.model;
//public class SampleValue {
// String sampleName;
// Double sampleValue;
// public SampleValue(String sampleName, Double sampleValue) {
// super();
// this.sampleName = sampleName;
// this.sampleValue = sampleValue;
// }
// public String getSampleName() {
// return sampleName;
// }
// public Double getSampleValue() {
// return sampleValue;
// }
// @Override
// public String toString() {
// return this.sampleName + " " + this.sampleValue ;
// }
//
//}
| 22.043478 | 62 | 0.678501 |
ad4bed6851143c827cd61d19ed8c1a5802ebb00e | 1,040 | package si.bismuth.mixins;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.Scoreboard;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Score.class)
public class MixinScore {
@Shadow @Final private Scoreboard scoreboard;
@Shadow @Final private ScoreObjective objective;
@Shadow @Final private String scorePlayerName;
@Inject(method="increaseScore", at = @At("RETURN"))
public void increaseTotal(int amount, CallbackInfo ci){
if (!"Total".equals(scorePlayerName)){
final Score totalScore = scoreboard.getOrCreateScore("Total", objective);
if (totalScore.getScorePoints() > -1){
totalScore.increaseScore(amount);
}
}
}
}
| 35.862069 | 85 | 0.735577 |
f5dafbf8dbaadbaabd277774f58d236e004dce54 | 544 | package graphicsassignment4;
import org.lwjgl.util.vector.Vector3f;
/**
*
* @author tushariyer
*/
public interface BlenderMethodInterface {
void setS(float x, float y, float z);
void setS(Vector3f updateScale);
void setRA(double angle);
void setRV(Vector3f updateRotation);
void setRV(float x, float y, float z);
void setG(Vector3f updateTranslation);
void setG(float x, float y, float z);
Vector3f getS();
double getRA();
Vector3f getRV();
Vector3f getG();
String toString();
}
| 15.542857 | 42 | 0.667279 |
b85701b3c8701888da4c280da9bafd160b47e12a | 6,131 | /*******************************************************************************
* Copyright (c) 2013 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* 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 gov.nasa.arc.verve.common.ardor3d.shape.grid;
import java.nio.FloatBuffer;
import com.ardor3d.bounding.BoundingBox;
import com.ardor3d.bounding.BoundingVolume;
import com.ardor3d.image.Texture2D;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.type.ReadOnlyColorRGBA;
import com.ardor3d.renderer.IndexMode;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.RenderState.StateType;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.scenegraph.FloatBufferData;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.util.geom.BufferUtils;
/**
* Utility geometry for a ground plane grid. TexCoord set
* 0 is 0,0 to w,h and TexCoord set 1 is 0,0 to 1,1
* i.e. texture 0 should be the grid texture, and the (optional)
* texture 1 should be the satellite image
* @author mallan
*
*/
public class FlatGridQuad extends Mesh {
protected float[] m_size = new float[] { 0,0 };
protected Texture2D[] m_tex = new Texture2D[] { null, null };
protected MaterialState m_mat = new MaterialState();
/**
*
*/
public FlatGridQuad(String name, float size, ColorRGBA color, Texture2D gridTex, Texture2D baseTex) {
super(name);
initialize(size, size, color, gridTex, baseTex);
}
public void setColor(ReadOnlyColorRGBA color) {
m_mat.setDiffuse(color);
m_mat.setSpecular(ColorRGBA.BLACK);
m_mat.setEmissive(ColorRGBA.BLACK);
m_mat.setAmbient(ColorRGBA.BLACK);
if(getSceneHints().getLightCombineMode() == LightCombineMode.Off) {
setDefaultColor(color);
}
else {
setRenderState(m_mat);
}
}
/**
*
*/
public void resize(float width, float height) {
m_size[0] = width;
m_size[1] = height;
FloatBuffer vertBuf = this.getMeshData().getVertexBuffer();
FloatBuffer normBuf = this.getMeshData().getNormalBuffer();
FloatBuffer texBuf0 = this.getMeshData().getTextureCoords(0).getBuffer();
FloatBuffer texBuf1 = this.getMeshData().getTextureCoords(1).getBuffer();
vertBuf.clear();
if(width > 0) {
vertBuf.put( 0.0f).put(height).put(0);
vertBuf.put( 0.0f).put( 0.0f).put(0);
vertBuf.put(width).put(height).put(0);
vertBuf.put(width).put( 0.0f).put(0);
}
else {
vertBuf.put( 0.0f).put( 0.0f).put(0);
vertBuf.put( 0.0f).put(height).put(0);
vertBuf.put(width).put( 0.0f).put(0);
vertBuf.put(width).put(height).put(0);
}
float up = width > 0 ? 1 : -1;
normBuf.clear();
normBuf.put(0).put(0).put(up);
normBuf.put(0).put(0).put(up);
normBuf.put(0).put(0).put(up);
normBuf.put(0).put(0).put(up);
texBuf0.clear();
texBuf0.put( 0.0f).put(height);
texBuf0.put( 0.0f).put( 0.0f);
texBuf0.put(width).put(height);
texBuf0.put(width).put( 0.0f);
texBuf1.clear();
texBuf1.put(0).put(0);
texBuf1.put(0).put(1);
texBuf1.put(1).put(0);
texBuf1.put(1).put(1);
updateModelBound();
}
/**
*
*/
public void setGridTexture(Texture2D gridTex) {
TextureState ts = (TextureState)this.getLocalRenderState(StateType.Texture);
ts.setTexture(gridTex, 0);
}
/**
*
*/
public void setBaseTexture(Texture2D baseTex) {
TextureState ts = (TextureState)this.getLocalRenderState(StateType.Texture);
ts.setTexture(baseTex, 1);
}
/**
*
*/
public void initialize(float width, float height, ColorRGBA color, Texture2D gridTex, Texture2D baseTex) {
//-- texture state ----------------------
TextureState ts = new TextureState();
ts.setTexture(null);
setRenderState(ts);
getSceneHints().setLightCombineMode(LightCombineMode.Off);
setGridTexture(gridTex);
setBaseTexture(baseTex);
m_size[0] = width;
m_size[1] = height;
setColor(color);
getMeshData().setIndexMode(IndexMode.TriangleStrip);
int vertexCount = 4;
FloatBuffer vertBuf = BufferUtils.createVector3Buffer(vertexCount);
FloatBuffer normBuf = BufferUtils.createVector3Buffer(vertexCount);
FloatBuffer texBuf0 = BufferUtils.createVector2Buffer(vertexCount);
FloatBuffer texBuf1 = BufferUtils.createVector2Buffer(vertexCount);
getMeshData().setVertexBuffer(vertBuf);
getMeshData().setNormalBuffer(normBuf);
getMeshData().setTextureCoords(new FloatBufferData(texBuf0,2), 0);
getMeshData().setTextureCoords(new FloatBufferData(texBuf1,2), 1);
BoundingVolume bound = new BoundingBox();
setModelBound(bound);
resize(width, height);
}
public float getWidth() {
return m_size[0];
}
public float getHeight() {
return m_size[1];
}
}
| 34.44382 | 111 | 0.609525 |
6a6abf041392d240db3cc2226ca0ae845826dc66 | 877 | package android.zou.com.viewpagerdemo.gson;
/**
* Created by Administrator on 2017/8/8.
*/
public class JokeImg {
private String img;
private String title;
private int width;
private int height;
public JokeImg(String img, String title) {
this.img = img;
this.title = title;
}
public JokeImg(){
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
| 16.865385 | 46 | 0.567845 |
6c7649d7f83a432e43d06fbcf353200cf34bb68b | 17,081 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.app;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.wearable.provider.WearableCalendarContract;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.WindowInsets;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Wearable;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* Digital watch face with seconds. In ambient mode, the seconds aren't displayed. On devices with
* low-bit ambient mode, the text is drawn without anti-aliasing in ambient mode.
*/
public class MyWatchFace extends CanvasWatchFaceService {
private static final Typeface NORMAL_TYPEFACE =
Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
/**
* Update rate in milliseconds for interactive mode. We update once a second since seconds are
* displayed in interactive mode.
*/
private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1);
/**
* Handler message id for updating the time periodically in interactive mode.
*/
private static final int MSG_UPDATE_TIME = 0;
MyWatchFace mMyWatchFace;
@Override
public void onCreate() {
//REMOVE THIS OR IT WILL FREEZE ON STARTUP
//android.os.Debug.waitForDebugger();
super.onCreate();
}
@Override
public Engine onCreateEngine() {
return new Engine();
}
private class Engine extends CanvasWatchFaceService.Engine {
final Handler mUpdateTimeHandler = new EngineHandler(this);
final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mTime.clear(intent.getStringExtra("time-zone"));
mTime.setToNow();
}
};
boolean mRegisteredTimeZoneReceiver = false;
Paint mBackgroundPaint;
Paint mTextPaint;
Paint mTextSecondaryPaint;
Paint mLinePaint;
Paint mHighTempPaint;
Paint mLowTempPaint;
boolean mAmbient;
Time mTime;
float mXOffset;
float mYOffset;
float mDateXOffset;
float mDateYOffset;
float mLineLength;
float mLineY;
long mLowTemp;
long mHighTemp;
int mWeatherId;
float mTempYOffset;
float mLowTempXOffset;
float mWeatherXOffset;
boolean mHasWeatherData;
/**
* Whether the display supports fewer bits for each color in ambient mode. When true, we
* disable anti-aliasing in ambient mode.
*/
boolean mLowBitAmbient;
GoogleApiClient mGoogleApiClient;
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(MyWatchFace.this)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setShowSystemUiTime(false)
.build());
Resources resources = MyWatchFace.this.getResources();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
mDateYOffset = resources.getDimension(R.dimen.date_y_offset);
mTempYOffset = resources.getDimension(R.dimen.tempYOffset);
mBackgroundPaint = new Paint();
mBackgroundPaint.setColor(resources.getColor(R.color.background));
mTextPaint = new Paint();
mTextPaint = createTextPaint(resources.getColor(R.color.digital_text));
mTextSecondaryPaint = new Paint();
mTextSecondaryPaint = createTextPaint(resources.getColor(R.color.text_secondary));
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.line_color));
mLowTempPaint = createTextPaint(resources.getColor(R.color.text_secondary));
mHighTempPaint= createTextPaint(resources.getColor(R.color.digital_text));
mTime = new Time();
mLineLength = resources.getDimension(R.dimen.line_length);
mLineY = resources.getDimension(R.dimen.line_y);
mLowTemp = -1;
mHighTemp = -1;
mWeatherId = -1;
mHasWeatherData = false;
startService(new Intent(getBaseContext(), WatchListenerService.class));
LocalBroadcastManager.getInstance(getBaseContext()).registerReceiver(mReceiver,
new IntentFilter("weather_data"));
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
long low = intent.getLongExtra("LowTemp", 0);
long high = intent.getLongExtra("HighTemp", 0);
int weatherId = intent.getIntExtra("WeatherId", 0);
mHasWeatherData = true;
updateWeather(low, high, weatherId);
}
};
//taken from app/Utility.java
public int getIconResourceForWeatherCondition(int weatherId) {
// Based on weather code data found at:
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
if (weatherId >= 200 && weatherId <= 232) {
return R.drawable.ic_storm;
} else if (weatherId >= 300 && weatherId <= 321) {
return R.drawable.ic_light_rain;
} else if (weatherId >= 500 && weatherId <= 504) {
return R.drawable.ic_rain;
} else if (weatherId == 511) {
return R.drawable.ic_snow;
} else if (weatherId >= 520 && weatherId <= 531) {
return R.drawable.ic_rain;
} else if (weatherId >= 600 && weatherId <= 622) {
return R.drawable.ic_snow;
} else if (weatherId >= 701 && weatherId <= 761) {
return R.drawable.ic_fog;
} else if (weatherId == 761 || weatherId == 781) {
return R.drawable.ic_storm;
} else if (weatherId == 800) {
return R.drawable.ic_clear;
} else if (weatherId == 801) {
return R.drawable.ic_light_clouds;
} else if (weatherId >= 802 && weatherId <= 804) {
return R.drawable.ic_cloudy;
}
return -1;
}
private void updateWeather(long low, long high, int weather) {
mLowTemp = low;
mHighTemp = high;
mWeatherId = weather;
invalidate();
}
@Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
super.onDestroy();
}
private Paint createTextPaint(int textColor) {
Paint paint = new Paint();
paint.setColor(textColor);
paint.setTypeface(NORMAL_TYPEFACE);
paint.setAntiAlias(true);
return paint;
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
registerReceiver();
// Update time zone in case it changed while we weren't visible.
mTime.clear(TimeZone.getDefault().getID());
mTime.setToNow();
} else {
unregisterReceiver();
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
private void registerReceiver() {
if (mRegisteredTimeZoneReceiver) {
return;
}
mRegisteredTimeZoneReceiver = true;
IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
MyWatchFace.this.registerReceiver(mTimeZoneReceiver, filter);
}
private void unregisterReceiver() {
if (!mRegisteredTimeZoneReceiver) {
return;
}
mRegisteredTimeZoneReceiver = false;
MyWatchFace.this.unregisterReceiver(mTimeZoneReceiver);
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
// Load resources that have alternate values for round watches.
Resources resources = MyWatchFace.this.getResources();
boolean isRound = insets.isRound();
mXOffset = resources.getDimension(isRound
? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset);
mDateXOffset = resources.getDimension(isRound
? R.dimen.date_x_offset_round : R.dimen.date_x_offset);
mLowTempXOffset = resources.getDimension(isRound
? R.dimen.low_temp_x_offset_round : R.dimen.low_temp_x_offset);
mWeatherXOffset = resources.getDimension(isRound
? R.dimen.weather_x_offset_round : R.dimen.weather_x_offset);
float textSize = resources.getDimension(isRound
? R.dimen.digital_text_size_round : R.dimen.digital_text_size);
float secondaryTextSize = resources.getDimension(isRound
? R.dimen.secondary_text_size_round : R.dimen.secondary_text_size);
float tempTextSize = resources.getDimension(isRound
? R.dimen.weather_text_size_round : R.dimen.weather_text_size);
mTextPaint.setTextSize(textSize);
mTextSecondaryPaint.setTextSize(secondaryTextSize);
mLowTempPaint.setTextSize(tempTextSize);
mHighTempPaint.setTextSize(tempTextSize);
}
@Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
}
@Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
@Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (mAmbient != inAmbientMode) {
mAmbient = inAmbientMode;
if (mLowBitAmbient) {
mTextPaint.setAntiAlias(!inAmbientMode);
mTextSecondaryPaint.setAntiAlias(!inAmbientMode);
mLinePaint.setAntiAlias(!inAmbientMode);
mLowTempPaint.setAntiAlias(!inAmbientMode);
mHighTempPaint.setAntiAlias(!inAmbientMode);
}
invalidate();
}
if (inAmbientMode) {
mTextSecondaryPaint.setColor(getResources().getColor(R.color.white));
} else {
mTextSecondaryPaint.setColor(getResources().getColor(R.color.text_secondary));
}
// Whether the timer should be running depends on whether we're visible (as well as
// whether we're in ambient mode), so we may need to start or stop the timer.
updateTimer();
}
@Override
public void onDraw(Canvas canvas, Rect bounds) {
// Draw the background.
if (isInAmbientMode()) {
canvas.drawColor(Color.BLACK);
} else {
canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint);
}
float halfCanvasWidth = canvas.getWidth() / 2;
// Draw H:MM in ambient mode or H:MM:SS in interactive mode.
mTime.setToNow();
String text = String.format("%d:%02d", mTime.hour, mTime.minute);
float timeX = (canvas.getWidth() / 2) - (mTextPaint.measureText(text) / 2);
canvas.drawText(text, timeX, mYOffset, mTextPaint);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd yyyy");
String date = dateFormat.format(new Date());
float dateX = halfCanvasWidth - (mTextSecondaryPaint.measureText(date) / 2);
canvas.drawText(date, dateX, mDateYOffset, mTextSecondaryPaint);
if (!mAmbient) {
canvas.drawLine((halfCanvasWidth - (mLineLength / 2)), mLineY, (halfCanvasWidth + mLineLength / 2), mLineY, mLinePaint);
String highTemp = String.valueOf(mHighTemp) + '\u00B0';
float highTempX = halfCanvasWidth - (mHighTempPaint.measureText(highTemp) / 2);
String lowTemp = String.valueOf(mLowTemp) + '\u00B0';
if (mHasWeatherData) {
canvas.drawText(highTemp, highTempX, mTempYOffset, mHighTempPaint);
canvas.drawText(lowTemp, mLowTempXOffset, mTempYOffset, mLowTempPaint);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), getIconResourceForWeatherCondition(mWeatherId));
canvas.drawBitmap(bitmap, mWeatherXOffset, mTempYOffset - (bitmap.getHeight() / 2), null);
}
}
}
/**
* Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently
* or stops it if it shouldn't be running but currently is.
*/
private void updateTimer() {
mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME);
if (shouldTimerBeRunning()) {
mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME);
}
}
/**
* Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should
* only run when we're visible and in interactive mode.
*/
private boolean shouldTimerBeRunning() {
return isVisible() && !isInAmbientMode();
}
/**
* Handle updating the time periodically in interactive mode.
*/
private void handleUpdateTimeMessage() {
invalidate();
if (shouldTimerBeRunning()) {
long timeMs = System.currentTimeMillis();
long delayMs = INTERACTIVE_UPDATE_RATE_MS
- (timeMs % INTERACTIVE_UPDATE_RATE_MS);
mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs);
}
}
}
private static class EngineHandler extends Handler {
private final WeakReference<MyWatchFace.Engine> mWeakReference;
public EngineHandler(MyWatchFace.Engine reference) {
mWeakReference = new WeakReference<>(reference);
}
@Override
public void handleMessage(Message msg) {
MyWatchFace.Engine engine = mWeakReference.get();
if (engine != null) {
switch (msg.what) {
case MSG_UPDATE_TIME:
engine.handleUpdateTimeMessage();
break;
}
}
}
}
}
| 37.376368 | 136 | 0.619285 |
e1f0cee9b75fc3a4ca806da37cd7c7b1e29f6d29 | 1,369 | package com.nxy006.project.algorithm.leetcode.p0001.two_sum;
import com.nxy006.project.alogtithm.utils.CaseAssertUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Map 解法
* 时间复杂度:O(n),空间复杂度:O(n)
*
* Runtime 3 ms , beats 58.77 % of java submissions.
* Memory 40.1 MB , beats 22.34 % of java submissions.
* 07/06/2021 11:29
*/
public class MapSolution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i]) && map.get(target - nums[i]) != i) {
return new int[]{map.get(target - nums[i]), i};
}
}
return new int[]{};
}
// ---------------------------------------------------------- TEST CASE ----------------------------------------------------------- //
public static void main(String[] args) {
CaseAssertUtils.assertEqualsIgnoreOrder(new int[]{0, 1}, new MapSolution().twoSum(new int[]{2, 7, 11, 15}, 9));
CaseAssertUtils.assertEqualsIgnoreOrder(new int[]{1, 2}, new MapSolution().twoSum(new int[]{3, 2, 4}, 6));
CaseAssertUtils.assertEqualsIgnoreOrder(new int[]{0, 1}, new MapSolution().twoSum(new int[]{3, 3}, 6));
}
}
| 35.102564 | 138 | 0.536888 |
e7804f6fb9df3486fd6ae3ea9ff95bb30f151349 | 218 | /**
* Simple Serialize (SSZ) annotations are used for automatic encoding/decoding routines handling
* standard Java class with annotations as SSZ model representation.
*/
package org.ethereum.beacon.ssz.annotation;
| 36.333333 | 96 | 0.793578 |
4a2adf93eee001bcafecdc4d555e758d3f56211b | 2,476 | package com.sengami.gui_diary.di.module;
import com.sengami.data_base.dbo.DiaryEntryDBO;
import com.sengami.data_base.mapper.Mapper;
import com.sengami.data_base.util.DatabaseConnectionProvider;
import com.sengami.data_diary.operation.local.CreateOrUpdateDiaryEntryOperationLocal;
import com.sengami.data_diary.operation.local.DeleteDiaryEntryOperationLocal;
import com.sengami.data_diary.operation.local.GetDiaryEntriesOperationLocal;
import com.sengami.domain_base.model.DiaryEntry;
import com.sengami.domain_base.operation.configuration.OperationConfiguration;
import com.sengami.domain_diary.operation.CreateOrUpdateDiaryEntryOperation;
import com.sengami.domain_diary.operation.DeleteDiaryEntryOperation;
import com.sengami.domain_diary.operation.GetDiaryEntriesOperation;
import org.jetbrains.annotations.NotNull;
import dagger.Module;
import dagger.Provides;
@Module
public final class OperationModule {
@Provides
@NotNull
GetDiaryEntriesOperation getHelloWorldOperation(@NotNull final OperationConfiguration operationConfiguration,
@NotNull final DatabaseConnectionProvider databaseConnectionProvider,
@NotNull final Mapper<DiaryEntryDBO, DiaryEntry> mapper) {
return new GetDiaryEntriesOperationLocal(
operationConfiguration,
databaseConnectionProvider,
mapper
);
}
@Provides
@NotNull
CreateOrUpdateDiaryEntryOperation createOrUpdateDiaryEntryOperation(@NotNull final OperationConfiguration operationConfiguration,
@NotNull final DatabaseConnectionProvider databaseConnectionProvider,
@NotNull final Mapper<DiaryEntryDBO, DiaryEntry> mapper) {
return new CreateOrUpdateDiaryEntryOperationLocal(
operationConfiguration,
databaseConnectionProvider,
mapper
);
}
@Provides
@NotNull
DeleteDiaryEntryOperation deleteDiaryEntryOperation(@NotNull final OperationConfiguration operationConfiguration,
@NotNull final DatabaseConnectionProvider databaseConnectionProvider) {
return new DeleteDiaryEntryOperationLocal(
operationConfiguration,
databaseConnectionProvider
);
}
} | 44.214286 | 141 | 0.703554 |
4e9b1cc1c18ba194aac12710eb930e3855c6a70a | 5,271 | /*
* (C) Copyright IBM Corp. 2021
*
* 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.ibm.healthpatterns.rest.controllers;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ibm.healthpatterns.app.CQLFile;
import com.ibm.healthpatterns.app.CohortService;
/**
* The controller that handles the library services (CRUD operations for libraries).
*
* @author Luis A. García
*/
@RestController
@RequestMapping("/libraries")
public class LibrariesController {
private CohortService cohortService;
/**
*
*/
public LibrariesController() {
cohortService = CohortService.getInstance();
}
/**
*
* @return all available libraries
*/
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<String> getLibraries() {
ObjectMapper mapper = new ObjectMapper();
String json;
Collection<CQLFile> libraries = cohortService.getLibraries();
for (CQLFile cqlFile : libraries) {
URI uri = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(cqlFile.getId())
.toUri();
cqlFile.setUri(uri.toString());
}
try {
json = mapper.writeValueAsString(libraries);
} catch (JsonProcessingException e) {
return new ResponseEntity<String>("Could not map connection info: " + e, HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<String>(json, HttpStatus.OK);
}
/**
*
* @param cql
* @return the response of adding a new library
* @throws IOException
*/
@PostMapping
public ResponseEntity<String> addLibrary(@RequestBody String cql) throws IOException {
CQLFile cqlFile;
try {
cqlFile = cohortService.addLibrary(cql);
} catch (IllegalArgumentException e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(cqlFile.getId())
.toUri();
return ResponseEntity.created(location).body("CQL created! - URI: " + location);
}
/**
*
* @param id
* @return the library by the given ID
*/
@GetMapping("/{id}")
public @ResponseBody ResponseEntity<String> getLibrary(@PathVariable String id) {
CQLFile cql = cohortService.getLibrary(id);
if (cql == null) {
return new ResponseEntity<String>("Library with ID '" + id + "' was not found.", HttpStatus.NOT_FOUND);
}
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(cql.getContent());
}
/**
*
* @param id
* @param cql
* @return the response of updating the given library
* @throws IOException
*/
@PutMapping("/{id}")
public @ResponseBody ResponseEntity<String> updateLibrary(@PathVariable String id, @RequestBody String cql) throws IOException {
CQLFile updatedCQL = cohortService.updateLibrary(id, cql);
if (updatedCQL == null) {
return new ResponseEntity<String>("Library with ID '" + id + "' was not found.", HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>("CQL Updated!", HttpStatus.OK);
}
/**
*
* @param id
* @return the response of updating the given library
* @throws IOException
*/
@DeleteMapping("/{id}")
public @ResponseBody ResponseEntity<String> deleteLibrary(@PathVariable String id) throws IOException {
CQLFile cql = cohortService.deleteLibrary(id);
if (cql == null) {
return new ResponseEntity<String>("Library with ID '" + id + "' was not found.", HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>("CQL Deleted!", HttpStatus.OK);
}
}
| 34.227273 | 129 | 0.728325 |
b6513c2dfed8ce4a8195cde70e66821c72f6f923 | 4,053 | /*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2013 - 2022 Andres Almiray.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Copyright 2008-2020 TOPdesk, the Netherlands
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.kordamp.jipsy.processor.service;
import org.kordamp.jipsy.processor.LogLocation;
import org.kordamp.jipsy.processor.Logger;
import java.util.*;
public final class Service {
private final Logger logger;
private final String serviceName;
private final Set<String> providers = new HashSet<String>();
public Service(Logger logger, String name) {
if (logger == null) {
throw new NullPointerException("logger");
}
if (name == null) {
throw new NullPointerException("name");
}
this.logger = logger;
logger.note(LogLocation.LOG_FILE, "Creating " + name);
this.serviceName = name;
}
public void addProvider(String provider) {
if (provider == null) {
throw new NullPointerException("provider");
}
logger.note(LogLocation.LOG_FILE, "Adding " + provider + " to " + serviceName);
providers.add(provider);
}
public boolean contains(String provider) {
return providers.contains(provider);
}
public boolean removeProvider(String provider) {
if (providers.remove(provider)) {
logger.note(LogLocation.LOG_FILE, "Removing " + provider + " from " + serviceName);
return true;
}
return false;
}
public String getName() {
return serviceName;
}
public String toProviderNamesList() {
StringBuilder sb = new StringBuilder();
List<String> names = new ArrayList<String>(providers);
Collections.sort(names);
for (String provider : names) {
sb.append(provider).append("\n");
}
return sb.toString();
}
public void fromProviderNamesList(String input) {
if (input == null) {
throw new NullPointerException("input");
}
String[] lines = input.split("\\n");
for (String line : lines) {
String[] content = line.split("#");
if (content.length > 0) {
String trimmed = content[0].trim();
if (trimmed.length() > 0) {
addProvider(trimmed);
}
}
}
}
@Override
public String toString() {
return serviceName + "=" + providers;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Service service = (Service) o;
return serviceName.equals(service.serviceName) &&
providers.containsAll(service.providers) && service.providers.containsAll(providers);
}
@Override
public int hashCode() {
int result = serviceName.hashCode();
result = 31 * result + providers.hashCode();
return result;
}
} | 30.704545 | 97 | 0.633851 |
515f21377e8052a7c391de6f0db897f4816edb87 | 299 | package br.com.studies.bean;
import java.math.BigDecimal;
import br.com.studies.service.Payment;
@br.com.studies.annotations.CreditCardPayment
public class CreditCardPayment implements Payment {
public String pay(BigDecimal amount) {
return "payed in credit card " + amount.toString();
}
} | 23 | 54 | 0.77592 |
e9f8b5828183053dc3d2c7ff0b286ddfd998bd10 | 241 | package arrays;
public class TestArguments {
public static void main(String[] args) {
System.out.println(args.length);
for(int iterator=0; iterator< args.length; iterator++){
System.out.println("Hello " + args [iterator]);
}
}
}
| 21.909091 | 57 | 0.692946 |
6bdb308500d5b7c3487e61ae6cb5c0d76b27ad79 | 9,748 | package org.hkijena.jipipe.extensions.ijweka.nodes;
import ij.ImagePlus;
import ij.ImageStack;
import org.hkijena.jipipe.JIPipe;
import org.hkijena.jipipe.api.JIPipeDocumentation;
import org.hkijena.jipipe.api.JIPipeNode;
import org.hkijena.jipipe.api.JIPipeProgressInfo;
import org.hkijena.jipipe.api.data.JIPipeDataTable;
import org.hkijena.jipipe.api.nodes.*;
import org.hkijena.jipipe.api.nodes.categories.ImagesNodeTypeCategory;
import org.hkijena.jipipe.api.parameters.JIPipeParameter;
import org.hkijena.jipipe.extensions.ijweka.datatypes.WekaModelData;
import org.hkijena.jipipe.extensions.ijweka.parameters.collections.WekaTiling2DSettings;
import org.hkijena.jipipe.extensions.imagejalgorithms.ij1.transform.TileImage2DAlgorithm;
import org.hkijena.jipipe.extensions.imagejalgorithms.ij1.transform.UnTileImage2DAlgorithm;
import org.hkijena.jipipe.extensions.imagejdatatypes.datatypes.ImagePlusData;
import org.hkijena.jipipe.extensions.imagejdatatypes.util.ImageJUtils;
import org.hkijena.jipipe.extensions.parameters.library.primitives.optional.OptionalAnnotationNameParameter;
import org.hkijena.jipipe.extensions.parameters.library.primitives.optional.OptionalIntegerParameter;
import org.hkijena.jipipe.utils.IJLogToJIPipeProgressInfoPump;
import trainableSegmentation.WekaSegmentation;
@JIPipeDocumentation(name = "Weka classifier 2D", description = "Classifies an image with a Weka model. If higher-dimensional data is provided, the classification is applied per slice. To obtain ROI from the generated labels, utilize the 'Labels to ROI' node.")
@JIPipeNode(nodeTypeCategory = ImagesNodeTypeCategory.class, menuPath = "Weka")
@JIPipeInputSlot(value = ImagePlusData.class, slotName = "Image", description = "Image on which the classification should be applied", autoCreate = true)
@JIPipeInputSlot(value = WekaModelData.class, slotName = "Model", description = "The model", autoCreate = true)
@JIPipeOutputSlot(value = ImagePlusData.class, slotName = "Classified image", description = "The classified image", autoCreate = true)
public class WekaClassification2DAlgorithm extends JIPipeIteratingAlgorithm {
private final WekaTiling2DSettings tilingSettings;
private OptionalIntegerParameter numThreads = new OptionalIntegerParameter(false, 0);
private boolean outputProbabilityMaps = false;
public WekaClassification2DAlgorithm(JIPipeNodeInfo info) {
super(info);
this.tilingSettings = new WekaTiling2DSettings();
registerSubParameter(tilingSettings);
}
public WekaClassification2DAlgorithm(WekaClassification2DAlgorithm other) {
super(other);
this.tilingSettings = new WekaTiling2DSettings(other.tilingSettings);
registerSubParameter(tilingSettings);
this.numThreads = new OptionalIntegerParameter(other.numThreads);
this.outputProbabilityMaps = other.outputProbabilityMaps;
}
@Override
protected void runIteration(JIPipeDataBatch dataBatch, JIPipeProgressInfo progressInfo) {
ImagePlus image = dataBatch.getInputData("Image", ImagePlusData.class, progressInfo).getDuplicateImage();
WekaModelData modelData = dataBatch.getInputData("Model", WekaModelData.class, progressInfo);
WekaSegmentation segmentation = modelData.getSegmentation();
TileImage2DAlgorithm tileImage2DAlgorithm = JIPipe.createNode(TileImage2DAlgorithm.class);
tileImage2DAlgorithm.setOverlapX(tilingSettings.getOverlapX());
tileImage2DAlgorithm.setOverlapY(tilingSettings.getOverlapY());
tileImage2DAlgorithm.setTileSizeX(tilingSettings.getTileSizeX());
tileImage2DAlgorithm.setTileSizeY(tilingSettings.getTileSizeY());
tileImage2DAlgorithm.setBorderMode(tilingSettings.getBorderMode());
tileImage2DAlgorithm.setTileInsetXAnnotation(new OptionalAnnotationNameParameter("inset_x", true));
tileImage2DAlgorithm.setTileInsetYAnnotation(new OptionalAnnotationNameParameter("inset_y", true));
tileImage2DAlgorithm.setTileRealXAnnotation(new OptionalAnnotationNameParameter("real_x", true));
tileImage2DAlgorithm.setTileRealYAnnotation(new OptionalAnnotationNameParameter("real_y", true));
tileImage2DAlgorithm.setImageWidthAnnotation(new OptionalAnnotationNameParameter("img_width", true));
tileImage2DAlgorithm.setImageHeightAnnotation(new OptionalAnnotationNameParameter("img_height", true));
UnTileImage2DAlgorithm unTileImage2DAlgorithm = JIPipe.createNode(UnTileImage2DAlgorithm.class);
unTileImage2DAlgorithm.setTileInsetXAnnotation(new OptionalAnnotationNameParameter("inset_x", true));
unTileImage2DAlgorithm.setTileInsetYAnnotation(new OptionalAnnotationNameParameter("inset_y", true));
unTileImage2DAlgorithm.setTileRealXAnnotation(new OptionalAnnotationNameParameter("real_x", true));
unTileImage2DAlgorithm.setTileRealYAnnotation(new OptionalAnnotationNameParameter("real_y", true));
unTileImage2DAlgorithm.setImageWidthAnnotation(new OptionalAnnotationNameParameter("img_width", true));
unTileImage2DAlgorithm.setImageHeightAnnotation(new OptionalAnnotationNameParameter("img_height", true));
ImageStack stack = new ImageStack(image.getWidth(), image.getHeight(), image.getNSlices() * image.getNChannels() * image.getNChannels());
try(IJLogToJIPipeProgressInfoPump pump = new IJLogToJIPipeProgressInfoPump(progressInfo.resolve("Weka"))) {
ImageJUtils.forEachIndexedZCTSlice(image, (ip, index) -> {
ImagePlus wholeSlice = new ImagePlus(image.getTitle() + " " + index, ip);
ImagePlus classified;
if (tilingSettings.isApplyTiling()) {
if (tilingSettings.isUseWekaNativeTiling()) {
int tilesX = (int) Math.ceil(1.0 * image.getWidth() / tilingSettings.getTileSizeX());
int tilesY = (int) Math.ceil(1.0 * image.getHeight() / tilingSettings.getTileSizeY());
progressInfo.log("Classifying with tiling (via Weka's native tiling)");
classified = segmentation.applyClassifier(wholeSlice, new int[]{tilesX, tilesY}, numThreads.getContentOrDefault(0), outputProbabilityMaps);
} else {
progressInfo.log("Generating tiles for " + wholeSlice);
// Generate tiles
tileImage2DAlgorithm.clearSlotData();
tileImage2DAlgorithm.getFirstInputSlot().addData(new ImagePlusData(wholeSlice), progressInfo);
tileImage2DAlgorithm.run(progressInfo.resolve("Generate tiles"));
// Classify tiles
JIPipeDataTable tileTable = tileImage2DAlgorithm.getFirstOutputSlot();
for (int i = 0; i < tileTable.getRowCount(); i++) {
JIPipeProgressInfo tileProgress = progressInfo.resolveAndLog("Classify tiles", i, tileTable.getRowCount());
ImagePlus tileSlice = tileTable.getData(i, ImagePlusData.class, tileProgress).getImage();
ImagePlus classifiedTileSlice = segmentation.applyClassifier(tileSlice, numThreads.getContentOrDefault(0), outputProbabilityMaps);
tileTable.setData(i, new ImagePlusData(classifiedTileSlice));
}
// Merge tiles
unTileImage2DAlgorithm.clearSlotData();
unTileImage2DAlgorithm.getFirstInputSlot().addFromTable(tileTable, progressInfo);
unTileImage2DAlgorithm.run(progressInfo.resolve("Merge tiles"));
classified = unTileImage2DAlgorithm.getFirstOutputSlot().getData(0, ImagePlusData.class, progressInfo).getImage();
// Cleanup
tileImage2DAlgorithm.clearSlotData();
unTileImage2DAlgorithm.clearSlotData();
}
} else {
progressInfo.log("Classifying whole image " + wholeSlice);
classified = segmentation.applyClassifier(wholeSlice, numThreads.getContentOrDefault(0), outputProbabilityMaps);
}
stack.setProcessor(classified.getProcessor(), index.zeroSliceIndexToOneStackIndex(image));
}, progressInfo);
}
dataBatch.addOutputData("Classified image", new ImagePlusData(new ImagePlus("Classified", stack)), progressInfo);
}
@JIPipeDocumentation(name = "Generate tiles", description = "The following settings allow the generation of tiles to save memory.")
@JIPipeParameter("tiling-parameters")
public WekaTiling2DSettings getTilingSettings() {
return tilingSettings;
}
@JIPipeDocumentation(name = "Override number of threads", description = "If enabled, set the number of threads to be utilized. Set to zero for automated assignment of threads.")
@JIPipeParameter("num-threads")
public OptionalIntegerParameter getNumThreads() {
return numThreads;
}
@JIPipeParameter("num-threads")
public void setNumThreads(OptionalIntegerParameter numThreads) {
this.numThreads = numThreads;
}
@JIPipeDocumentation(name = "Output probability maps", description = "If enabled, output probability maps instead of class labels.")
@JIPipeParameter("output-probability-maps")
public boolean isOutputProbabilityMaps() {
return outputProbabilityMaps;
}
@JIPipeParameter("output-probability-maps")
public void setOutputProbabilityMaps(boolean outputProbabilityMaps) {
this.outputProbabilityMaps = outputProbabilityMaps;
}
}
| 63.298701 | 261 | 0.725995 |
ef191147fcaa2caca87e163eadf9ffc87a34ad98 | 4,292 | package com.codepath.apps.simpletwitter.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.codepath.apps.simpletwitter.R;
import com.codepath.apps.simpletwitter.adapter.TweetsAdapter;
import com.codepath.apps.simpletwitter.models.User;
import java.util.ArrayList;
import butterknife.Bind;
import butterknife.ButterKnife;
public abstract class TweetsListFragment extends Fragment {
protected TweetsAdapter tweetsAdapter;
protected ArrayList<Long> tweetsIdArray;
protected TweetsListOnClickListener listener;
protected Handler handler;
@Bind(R.id.rvList) RecyclerView rvTimeline;
public interface TweetsListOnClickListener {
void onClickReply(Long tweetId);
void onClickText(Long tweetId);
void onClickUser(User user);
void endPullToRefresh();
}
public abstract void onScrollingDown();
public abstract void onPullToRefresh();
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof TweetsListOnClickListener) {
listener = (TweetsListOnClickListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implement TweetsListFragment.TweetsListOnClickListener");
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
// Bind views
ButterKnife.bind(this, view);
// Setup adapter
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
// Bind Recycle view with tweets
rvTimeline.setLayoutManager(linearLayoutManager);
tweetsAdapter = new TweetsAdapter(tweetsIdArray, rvTimeline) {
@Override
public void onClickReply(Long tweetId) {
listener.onClickReply(tweetId);
}
@Override
public void onClickText(Long tweetId) {
listener.onClickText(tweetId);
}
@Override
public void onClickUser(User user) {
listener.onClickUser(user);
}
};
rvTimeline.setAdapter(tweetsAdapter);
tweetsAdapter.setOnLoadMoreListener(new TweetsAdapter.OnLoadMoreListener() {
@Override
public void onLoadMore() {
//add progress item
int progress_position = tweetsIdArray.size();
tweetsIdArray.add(null);
tweetsAdapter.notifyItemInserted(progress_position);
handler.postDelayed(new Runnable() {
@Override
public void run() {
//remove progress item
tweetsIdArray.remove(tweetsIdArray.size() - 1);
tweetsAdapter.notifyItemRemoved(tweetsIdArray.size());
//add items one by one
onScrollingDown();
tweetsAdapter.setLoaded();
//or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();
}
}, 2000);
}
});
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initial data and adapter
tweetsIdArray = new ArrayList<>();
handler = new Handler();
}
@Override
public void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
}
public void add(int position, Long tweetId) {
tweetsIdArray.add(position, tweetId);
tweetsAdapter.notifyItemInserted(position);
}
public void scrollToPosition(int position) {
rvTimeline.scrollToPosition(position);
}
}
| 33.271318 | 111 | 0.639096 |
19833620660541cc2f0130c7c969a4148c3e41a2 | 289 | import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
System.out.println(new StringBuilder(sc.nextLine()).reverse().toString());
}
sc.close();
}
}
| 20.642857 | 81 | 0.615917 |
8c9a81ddb6b0974afacc1501e273cedd96e870bf | 3,154 | package com.hedera.services.context.properties;
/*-
*
* Hedera Services Node
*
* Copyright (C) 2018 - 2021 Hedera Hashgraph, 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.
*
*/
import com.hederahashgraph.api.proto.java.ServicesConfigurationList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static com.hedera.services.context.properties.BootstrapProperties.BOOTSTRAP_PROP_NAMES;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.verify;
@ExtendWith(MockitoExtension.class)
class StandardizedPropertySourcesTest {
@Mock
private PropertySource bootstrapProps;
@Mock
private ScreenedSysFileProps dynamicGlobalProps;
@Mock
private ScreenedNodeFileProps nodeProps;
private StandardizedPropertySources subject;
@BeforeEach
private void setup() {
subject = new StandardizedPropertySources(bootstrapProps, dynamicGlobalProps, nodeProps);
}
@Test
void usesDynamicGlobalAsPriority() {
given(dynamicGlobalProps.containsProperty("testProp")).willReturn(true);
given(dynamicGlobalProps.getProperty("testProp")).willReturn("perfectAnswer");
subject.reloadFrom(ServicesConfigurationList.getDefaultInstance());
assertEquals("perfectAnswer", subject.asResolvingSource().getStringProperty("testProp"));
}
@Test
void usesNodeAsSecondPriority() {
given(nodeProps.containsProperty("testProp2")).willReturn(true);
given(nodeProps.getProperty("testProp2")).willReturn("goodEnoughForMe");
given(dynamicGlobalProps.containsProperty("testProp")).willReturn(true);
given(dynamicGlobalProps.getProperty("testProp")).willReturn("perfectAnswer");
subject.reloadFrom(ServicesConfigurationList.getDefaultInstance());
assertEquals("perfectAnswer", subject.asResolvingSource().getStringProperty("testProp"));
assertEquals("goodEnoughForMe", subject.asResolvingSource().getStringProperty("testProp2"));
}
@Test
void propagatesReloadToDynamicGlobalProps() {
subject.reloadFrom(ServicesConfigurationList.getDefaultInstance());
verify(dynamicGlobalProps).screenNew(ServicesConfigurationList.getDefaultInstance());
}
@Test
void usesBootstrapSourceAsApropos() {
subject.getNodeProps().getFromFile().clear();
final var properties = subject.asResolvingSource();
BOOTSTRAP_PROP_NAMES.forEach(properties::getProperty);
for (final var bootstrapProp : BOOTSTRAP_PROP_NAMES) {
verify(bootstrapProps).getProperty(bootstrapProp);
}
}
}
| 33.913978 | 94 | 0.792327 |
aa846f3aa9b6bec5998f780c4f672bdcb9da9aef | 695 | package app.com.tvrecyclerview;
/**
* A {@link PresenterSelector} that always returns the same {@link Presenter}.
* Useful for rows of items of the same type that are all rendered the same way.
*/
public final class SinglePresenterSelector extends PresenterSelector {
private final Presenter mPresenter;
/**
* @param presenter The Presenter to return for every item.
*/
public SinglePresenterSelector(Presenter presenter) {
mPresenter = presenter;
}
@Override
public Presenter getPresenter(Object item) {
return mPresenter;
}
@Override
public Presenter[] getPresenters() {
return new Presenter[]{mPresenter};
}
}
| 24.821429 | 80 | 0.68777 |
36a6c1686ac2e09b73ae3d2138273a68f9b1fbd3 | 2,179 | /*
* Copyright (c) 2015 Andrej Halaj
*
* 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.perfcake.pc4nb.ui.actions;
import java.util.List;
import org.openide.WizardDescriptor;
import org.perfcake.model.Property;
import org.perfcake.pc4nb.model.GeneratorModel;
import org.perfcake.pc4nb.model.PropertyModel;
import org.perfcake.pc4nb.ui.wizards.GeneratorWizardPanel;
public class EditGeneratorAction extends AbstractPC4NBAction {
private GeneratorWizardPanel wizardPanel;
private GeneratorModel generatorModel;
public EditGeneratorAction(GeneratorModel generatorModel) {
this.generatorModel = generatorModel;
}
@Override
public WizardDescriptor.Panel<WizardDescriptor> getPanel() {
wizardPanel = new GeneratorWizardPanel();
wizardPanel.getComponent().setModel(generatorModel);
return wizardPanel;
}
@Override
public void doAction(WizardDescriptor wiz) {
generatorModel.setClazz((String) wiz.getProperty("generator-type"));
generatorModel.setThreads(wiz.getProperty("generator-threads").toString());
List<PropertyModel> properties = (List<PropertyModel>) wiz.getProperty("generator-properties");
List<Property> generatorProperties = generatorModel.getProperty();
for (int i = generatorProperties.size() - 1; i >= 0; i--) {
generatorModel.removeProperty(generatorProperties.get(i));
}
for (PropertyModel propertyModel : properties) {
if (!propertyModel.isDefault()) {
generatorModel.addProperty(propertyModel.getProperty());
}
}
}
}
| 35.721311 | 103 | 0.7095 |
3d8e4874bcc876d8d478d25abb821cec07f49dc9 | 41,683 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.job.entries.evalfilesmetrics;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.evalfilesmetrics.JobEntryEvalFilesMetrics;
import org.pentaho.di.job.entries.simpleeval.JobEntrySimpleEval;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
/**
* This dialog allows you to edit the eval files metrics job entry settings.
*
* @author Samatar Hassan
* @since 26-02-2010
*/
public class JobEntryEvalFilesMetricsDialog extends JobEntryDialog implements JobEntryDialogInterface
{
private static Class<?> PKG = JobEntryEvalFilesMetrics.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private static final String[] FILETYPES = new String[] {BaseMessages.getString(PKG, "JobEvalFilesMetrics.Filetype.All")};
private Label wlName;
private Text wName;
private FormData fdlName, fdName;
private Label wlSourceFileFolder;
private Button wbSourceFileFolder,
wbSourceDirectory;
private TextVar wSourceFileFolder;
private FormData fdlSourceFileFolder, fdbSourceFileFolder,
fdSourceFileFolder,fdbSourceDirectory;
private Button wOK, wCancel;
private Listener lsOK, lsCancel;
private JobEntryEvalFilesMetrics jobEntry;
private Shell shell;
private SelectionAdapter lsDef;
private boolean changed;
private Label wlFields;
private TableView wFields;
private FormData fdlFields, fdFields;
private Group wSettings;
private FormData fdSettings;
private Label wlWildcard;
private TextVar wWildcard;
private FormData fdlWildcard, fdWildcard;
private Label wlResultFilenamesWildcard;
private TextVar wResultFilenamesWildcard;
private FormData fdlResultFilenamesWildcard, fdResultFilenamesWildcard;
private Label wlResultFieldFile;
private TextVar wResultFieldFile;
private FormData fdlResultFieldFile, fdResultFieldFile;
private Label wlResultFieldWildcard;
private TextVar wResultFieldWildcard;
private FormData fdlResultFieldWildcard, fdResultFieldWildcard;
private Label wlResultFieldIncludeSubFolders;
private TextVar wResultFieldIncludeSubFolders;
private FormData fdlResultFieldIncludeSubFolders, fdResultFieldIncludeSubFolders;
private Button wbdSourceFileFolder; // Delete
private Button wbeSourceFileFolder; // Edit
private Button wbaSourceFileFolder; // Add or change
private CTabFolder wTabFolder;
private Composite wGeneralComp,wAdvancedComp;
private CTabItem wGeneralTab,wAdvancedTab;
private FormData fdGeneralComp,fdAdvancedComp;
private FormData fdTabFolder;
private Group wSuccessOn;
private FormData fdSuccessOn;
private Label wlSuccessNumberCondition;
private CCombo wSuccessNumberCondition;
private FormData fdlSuccessNumberCondition, fdSuccessNumberCondition;
private Label wlScale;
private CCombo wScale;
private FormData fdlScale, fdScale;
private Label wlSourceFiles;
private CCombo wSourceFiles;
private FormData fdlSourceFiles, fdSourceFiles;
private Label wlEvaluationType;
private CCombo wEvaluationType;
private FormData fdlEvaluationType, fdEvaluationType;
private Label wlCompareValue;
private TextVar wCompareValue;
private FormData fdlCompareValue, fdCompareValue;
private Label wlMinValue;
private TextVar wMinValue;
private FormData fdlMinValue, fdMinValue;
private Label wlMaxValue;
private TextVar wMaxValue;
private FormData fdlMaxValue, fdMaxValue;
private FormData fdbeSourceFileFolder, fdbaSourceFileFolder, fdbdSourceFileFolder;
public JobEntryEvalFilesMetricsDialog(Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta)
{
super(parent, jobEntryInt, rep, jobMeta);
jobEntry = (JobEntryEvalFilesMetrics) jobEntryInt;
if (this.jobEntry.getName() == null)
this.jobEntry.setName(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Name.Default"));
}
public JobEntryInterface open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, props.getJobsDialogStyle());
props.setLook(shell);
JobDialog.setShellImage(shell, jobEntry);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
jobEntry.setChanged();
}
};
changed = jobEntry.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Title"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Filename line
wlName=new Label(shell, SWT.RIGHT);
wlName.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Name.Label"));
props.setLook(wlName);
fdlName=new FormData();
fdlName.left = new FormAttachment(0, 0);
fdlName.right= new FormAttachment(middle, -margin);
fdlName.top = new FormAttachment(0, margin);
wlName.setLayoutData(fdlName);
wName=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wName);
wName.addModifyListener(lsMod);
fdName=new FormData();
fdName.left = new FormAttachment(middle, 0);
fdName.top = new FormAttachment(0, margin);
fdName.right= new FormAttachment(100, 0);
wName.setLayoutData(fdName);
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
//////////////////////////
// START OF GENERAL TAB ///
//////////////////////////
wGeneralTab=new CTabItem(wTabFolder, SWT.NONE);
wGeneralTab.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Tab.General.Label"));
wGeneralComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wGeneralComp);
FormLayout generalLayout = new FormLayout();
generalLayout.marginWidth = 3;
generalLayout.marginHeight = 3;
wGeneralComp.setLayout(generalLayout);
// SETTINGS grouping?
// ////////////////////////
// START OF SETTINGS GROUP
//
wSettings = new Group(wGeneralComp, SWT.SHADOW_NONE);
props.setLook(wSettings);
wSettings.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Settings.Label"));
FormLayout groupLayout = new FormLayout();
groupLayout.marginWidth = 10;
groupLayout.marginHeight = 10;
wSettings.setLayout(groupLayout);
//SourceFiles
wlSourceFiles = new Label(wSettings, SWT.RIGHT);
wlSourceFiles.setText(BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.SourceFiles.Label"));
props.setLook(wlSourceFiles);
fdlSourceFiles = new FormData();
fdlSourceFiles.left = new FormAttachment(0, 0);
fdlSourceFiles.right = new FormAttachment(middle, -margin);
fdlSourceFiles.top = new FormAttachment(wName, margin);
wlSourceFiles.setLayoutData(fdlSourceFiles);
wSourceFiles = new CCombo(wSettings, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
wSourceFiles.setItems(JobEntryEvalFilesMetrics.SourceFilesDesc);
wSourceFiles.select(0); // +1: starts at -1
props.setLook(wSourceFiles);
fdSourceFiles= new FormData();
fdSourceFiles.left = new FormAttachment(middle, 0);
fdSourceFiles.top = new FormAttachment(wName, margin);
fdSourceFiles.right = new FormAttachment(100, 0);
wSourceFiles.setLayoutData(fdSourceFiles);
wSourceFiles.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
jobEntry.setChanged();
RefreshSourceFiles();
}
});
// ResultFilenamesWildcard
wlResultFilenamesWildcard = new Label(wSettings, SWT.RIGHT);
wlResultFilenamesWildcard .setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.ResultFilenamesWildcard.Label"));
props.setLook(wlResultFilenamesWildcard );
fdlResultFilenamesWildcard = new FormData();
fdlResultFilenamesWildcard .left = new FormAttachment(0, 0);
fdlResultFilenamesWildcard .top = new FormAttachment(wSourceFiles, margin);
fdlResultFilenamesWildcard .right = new FormAttachment(middle, -margin);
wlResultFilenamesWildcard .setLayoutData(fdlResultFilenamesWildcard );
wResultFilenamesWildcard = new TextVar(jobMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wResultFilenamesWildcard .setToolTipText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.ResultFilenamesWildcard.Tooltip"));
props.setLook(wResultFilenamesWildcard );
wResultFilenamesWildcard .addModifyListener(lsMod);
fdResultFilenamesWildcard = new FormData();
fdResultFilenamesWildcard .left = new FormAttachment(middle, 0);
fdResultFilenamesWildcard .top = new FormAttachment(wSourceFiles, margin);
fdResultFilenamesWildcard .right= new FormAttachment(100, -margin);
wResultFilenamesWildcard .setLayoutData(fdResultFilenamesWildcard );
// ResultFieldFile
wlResultFieldFile = new Label(wSettings, SWT.RIGHT);
wlResultFieldFile .setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.ResultFieldFile.Label"));
props.setLook(wlResultFieldFile );
fdlResultFieldFile = new FormData();
fdlResultFieldFile .left = new FormAttachment(0, 0);
fdlResultFieldFile .top = new FormAttachment(wResultFilenamesWildcard, margin);
fdlResultFieldFile .right = new FormAttachment(middle, -margin);
wlResultFieldFile .setLayoutData(fdlResultFieldFile );
wResultFieldFile = new TextVar(jobMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wResultFieldFile .setToolTipText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.ResultFieldFile.Tooltip"));
props.setLook(wResultFieldFile );
wResultFieldFile .addModifyListener(lsMod);
fdResultFieldFile = new FormData();
fdResultFieldFile .left = new FormAttachment(middle, 0);
fdResultFieldFile .top = new FormAttachment(wResultFilenamesWildcard, margin);
fdResultFieldFile .right= new FormAttachment(100, -margin);
wResultFieldFile .setLayoutData(fdResultFieldFile );
// ResultFieldWildcard
wlResultFieldWildcard = new Label(wSettings, SWT.RIGHT);
wlResultFieldWildcard .setText(BaseMessages.getString(PKG, "JobEvalWildcardsMetrics.ResultFieldWildcard.Label"));
props.setLook(wlResultFieldWildcard );
fdlResultFieldWildcard = new FormData();
fdlResultFieldWildcard .left = new FormAttachment(0, 0);
fdlResultFieldWildcard .top = new FormAttachment(wResultFieldFile, margin);
fdlResultFieldWildcard .right = new FormAttachment(middle, -margin);
wlResultFieldWildcard .setLayoutData(fdlResultFieldWildcard );
wResultFieldWildcard = new TextVar(jobMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wResultFieldWildcard .setToolTipText(BaseMessages.getString(PKG, "JobEvalWildcardsMetrics.ResultFieldWildcard.Tooltip"));
props.setLook(wResultFieldWildcard );
wResultFieldWildcard .addModifyListener(lsMod);
fdResultFieldWildcard = new FormData();
fdResultFieldWildcard .left = new FormAttachment(middle, 0);
fdResultFieldWildcard .top = new FormAttachment(wResultFieldFile, margin);
fdResultFieldWildcard .right= new FormAttachment(100, -margin);
wResultFieldWildcard .setLayoutData(fdResultFieldWildcard );
// ResultFieldIncludeSubFolders
wlResultFieldIncludeSubFolders = new Label(wSettings, SWT.RIGHT);
wlResultFieldIncludeSubFolders .setText(BaseMessages.getString(PKG, "JobEvalIncludeSubFolderssMetrics.ResultFieldIncludeSubFolders.Label"));
props.setLook(wlResultFieldIncludeSubFolders );
fdlResultFieldIncludeSubFolders = new FormData();
fdlResultFieldIncludeSubFolders .left = new FormAttachment(0, 0);
fdlResultFieldIncludeSubFolders .top = new FormAttachment(wResultFieldWildcard, margin);
fdlResultFieldIncludeSubFolders .right = new FormAttachment(middle, -margin);
wlResultFieldIncludeSubFolders .setLayoutData(fdlResultFieldIncludeSubFolders );
wResultFieldIncludeSubFolders = new TextVar(jobMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wResultFieldIncludeSubFolders .setToolTipText(BaseMessages.getString(PKG, "JobEvalIncludeSubFolderssMetrics.ResultFieldIncludeSubFolders.Tooltip"));
props.setLook(wResultFieldIncludeSubFolders );
wResultFieldIncludeSubFolders .addModifyListener(lsMod);
fdResultFieldIncludeSubFolders = new FormData();
fdResultFieldIncludeSubFolders .left = new FormAttachment(middle, 0);
fdResultFieldIncludeSubFolders .top = new FormAttachment(wResultFieldWildcard, margin);
fdResultFieldIncludeSubFolders .right= new FormAttachment(100, -margin);
wResultFieldIncludeSubFolders .setLayoutData(fdResultFieldIncludeSubFolders );
//EvaluationType
wlEvaluationType = new Label(wSettings, SWT.RIGHT);
wlEvaluationType.setText(BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.EvaluationType.Label"));
props.setLook(wlEvaluationType);
fdlEvaluationType = new FormData();
fdlEvaluationType.left = new FormAttachment(0, 0);
fdlEvaluationType.right = new FormAttachment(middle, -margin);
fdlEvaluationType.top = new FormAttachment(wResultFieldIncludeSubFolders , margin);
wlEvaluationType.setLayoutData(fdlEvaluationType);
wEvaluationType = new CCombo(wSettings, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
wEvaluationType.setItems(JobEntryEvalFilesMetrics.EvaluationTypeDesc);
wEvaluationType.select(0); // +1: starts at -1
props.setLook(wEvaluationType);
fdEvaluationType= new FormData();
fdEvaluationType.left = new FormAttachment(middle, 0);
fdEvaluationType.top = new FormAttachment(wResultFieldIncludeSubFolders , margin);
fdEvaluationType.right = new FormAttachment(100, 0);
wEvaluationType.setLayoutData(fdEvaluationType);
wEvaluationType.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
RefreshSize();
jobEntry.setChanged();
}
});
fdSettings = new FormData();
fdSettings.left = new FormAttachment(0, margin);
fdSettings.top = new FormAttachment(wName, margin);
fdSettings.right = new FormAttachment(100, -margin);
wSettings.setLayoutData(fdSettings);
// ///////////////////////////////////////////////////////////
// / END OF SETTINGS GROUP
// ///////////////////////////////////////////////////////////
// SourceFileFolder line
wlSourceFileFolder=new Label(wGeneralComp, SWT.RIGHT);
wlSourceFileFolder.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.SourceFileFolder.Label"));
props.setLook(wlSourceFileFolder);
fdlSourceFileFolder=new FormData();
fdlSourceFileFolder.left = new FormAttachment(0, 0);
fdlSourceFileFolder.top = new FormAttachment(wSettings, 2*margin);
fdlSourceFileFolder.right= new FormAttachment(middle, -margin);
wlSourceFileFolder.setLayoutData(fdlSourceFileFolder);
// Browse Source folders button ...
wbSourceDirectory=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbSourceDirectory);
wbSourceDirectory.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.BrowseFolders.Label"));
fdbSourceDirectory=new FormData();
fdbSourceDirectory.right= new FormAttachment(100, 0);
fdbSourceDirectory.top = new FormAttachment(wSettings, margin);
wbSourceDirectory.setLayoutData(fdbSourceDirectory);
wbSourceDirectory.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
DirectoryDialog ddialog = new DirectoryDialog(shell, SWT.OPEN);
if (wSourceFileFolder.getText()!=null)
{
ddialog.setFilterPath(jobMeta.environmentSubstitute(wSourceFileFolder.getText()) );
}
// Calling open() will open and run the dialog.
// It will return the selected directory, or
// null if user cancels
String dir = ddialog.open();
if (dir != null) {
// Set the text box to the new selection
wSourceFileFolder.setText(dir);
}
}
}
);
// Browse Source files button ...
wbSourceFileFolder=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbSourceFileFolder);
wbSourceFileFolder.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.BrowseFiles.Label"));
fdbSourceFileFolder=new FormData();
fdbSourceFileFolder.right= new FormAttachment(wbSourceDirectory, -margin);
fdbSourceFileFolder.top = new FormAttachment(wSettings, margin);
wbSourceFileFolder.setLayoutData(fdbSourceFileFolder);
// Browse Destination file add button ...
wbaSourceFileFolder=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbaSourceFileFolder);
wbaSourceFileFolder.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.FilenameAdd.Button"));
fdbaSourceFileFolder=new FormData();
fdbaSourceFileFolder.right= new FormAttachment(wbSourceFileFolder, -margin);
fdbaSourceFileFolder.top = new FormAttachment(wSettings, margin);
wbaSourceFileFolder.setLayoutData(fdbaSourceFileFolder);
wSourceFileFolder=new TextVar(jobMeta, wGeneralComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wSourceFileFolder.setToolTipText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.SourceFileFolder.Tooltip"));
props.setLook(wSourceFileFolder);
wSourceFileFolder.addModifyListener(lsMod);
fdSourceFileFolder=new FormData();
fdSourceFileFolder.left = new FormAttachment(middle, 0);
fdSourceFileFolder.top = new FormAttachment(wSettings, 2*margin);
fdSourceFileFolder.right= new FormAttachment(wbSourceFileFolder, -55);
wSourceFileFolder.setLayoutData(fdSourceFileFolder);
// Whenever something changes, set the tooltip to the expanded version:
wSourceFileFolder.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
wSourceFileFolder.setToolTipText(jobMeta.environmentSubstitute(wSourceFileFolder.getText() ) );
}
}
);
wbSourceFileFolder.addSelectionListener
(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] {"*"});
if (wSourceFileFolder.getText()!=null)
{
dialog.setFileName(jobMeta.environmentSubstitute(wSourceFileFolder.getText()) );
}
dialog.setFilterNames(FILETYPES);
if (dialog.open()!=null)
{
wSourceFileFolder.setText(dialog.getFilterPath()+Const.FILE_SEPARATOR+dialog.getFileName());
}
}
}
);
// Buttons to the right of the screen...
wbdSourceFileFolder=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbdSourceFileFolder);
wbdSourceFileFolder.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.FilenameDelete.Button"));
wbdSourceFileFolder.setToolTipText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.FilenameDelete.Tooltip"));
fdbdSourceFileFolder=new FormData();
fdbdSourceFileFolder.right = new FormAttachment(100, 0);
fdbdSourceFileFolder.top = new FormAttachment (wSourceFileFolder, 40);
wbdSourceFileFolder.setLayoutData(fdbdSourceFileFolder);
wbeSourceFileFolder=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER);
props.setLook(wbeSourceFileFolder);
wbeSourceFileFolder.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.FilenameEdit.Button"));
fdbeSourceFileFolder=new FormData();
fdbeSourceFileFolder.right = new FormAttachment(100, 0);
fdbeSourceFileFolder.left = new FormAttachment(wbdSourceFileFolder, 0, SWT.LEFT);
fdbeSourceFileFolder.top = new FormAttachment (wbdSourceFileFolder, margin);
wbeSourceFileFolder.setLayoutData(fdbeSourceFileFolder);
// Wildcard
wlWildcard = new Label(wGeneralComp, SWT.RIGHT);
wlWildcard.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Wildcard.Label"));
props.setLook(wlWildcard);
fdlWildcard = new FormData();
fdlWildcard.left = new FormAttachment(0, 0);
fdlWildcard.top = new FormAttachment(wSourceFileFolder, margin);
fdlWildcard.right = new FormAttachment(middle, -margin);
wlWildcard.setLayoutData(fdlWildcard);
wWildcard = new TextVar(jobMeta, wGeneralComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wWildcard.setToolTipText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Wildcard.Tooltip"));
props.setLook(wWildcard);
wWildcard.addModifyListener(lsMod);
fdWildcard = new FormData();
fdWildcard.left = new FormAttachment(middle, 0);
fdWildcard.top = new FormAttachment(wSourceFileFolder, margin);
fdWildcard.right= new FormAttachment(wbSourceFileFolder, -55);
wWildcard.setLayoutData(fdWildcard);
wlFields = new Label(wGeneralComp, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Fields.Label"));
props.setLook(wlFields);
fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.right= new FormAttachment(middle, -margin);
fdlFields.top = new FormAttachment(wWildcard,margin);
wlFields.setLayoutData(fdlFields);
int rows = jobEntry.source_filefolder == null
? 1
: (jobEntry.source_filefolder.length == 0
? 0
: jobEntry.source_filefolder.length);
final int FieldsRows = rows;
ColumnInfo[] colinf=new ColumnInfo[]
{
new ColumnInfo(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Fields.SourceFileFolder.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false),
new ColumnInfo(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Fields.Wildcard.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Fields.IncludeSubDirs.Label"), ColumnInfo.COLUMN_TYPE_CCOMBO, JobEntryEvalFilesMetrics.IncludeSubFoldersDesc )
};
colinf[0].setUsingVariables(true);
colinf[0].setToolTip(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Fields.SourceFileFolder.Tooltip"));
colinf[1].setUsingVariables(true);
colinf[1].setToolTip(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Fields.Wildcard.Tooltip"));
wFields = new TableView(jobMeta, wGeneralComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props);
fdFields = new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(wbeSourceFileFolder, -margin);
fdFields.bottom = new FormAttachment(100, -margin);
wFields.setLayoutData(fdFields);
//RefreshArgFromPrevious();
// Add the file to the list of files...
SelectionAdapter selA = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
wFields.add(new String[] { wSourceFileFolder.getText(), wWildcard.getText() } );
wSourceFileFolder.setText("");
wWildcard.setText("");
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth(true);
}
};
wbaSourceFileFolder.addSelectionListener(selA);
wSourceFileFolder.addSelectionListener(selA);
// Delete files from the list of files...
wbdSourceFileFolder.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
int idx[] = wFields.getSelectionIndices();
wFields.remove(idx);
wFields.removeEmptyRows();
wFields.setRowNums();
}
});
// Edit the selected file & remove from the list...
wbeSourceFileFolder.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
int idx = wFields.getSelectionIndex();
if (idx>=0)
{
String string[] = wFields.getItem(idx);
wSourceFileFolder.setText(string[0]);
wWildcard.setText(string[1]);
wFields.remove(idx);
}
wFields.removeEmptyRows();
wFields.setRowNums();
}
});
fdGeneralComp=new FormData();
fdGeneralComp.left = new FormAttachment(0, 0);
fdGeneralComp.top = new FormAttachment(0, 0);
fdGeneralComp.right = new FormAttachment(100, 0);
fdGeneralComp.bottom= new FormAttachment(100, 0);
wGeneralComp.setLayoutData(fdGeneralComp);
wGeneralComp.layout();
wGeneralTab.setControl(wGeneralComp);
props.setLook(wGeneralComp);
/////////////////////////////////////////////////////////////
/// END OF GENERAL TAB
/////////////////////////////////////////////////////////////
//////////////////////////////////////
// START OF ADVANCED TAB ///
/////////////////////////////////////
wAdvancedTab=new CTabItem(wTabFolder, SWT.NONE);
wAdvancedTab.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.Tab.Advanced.Label"));
FormLayout contentLayout = new FormLayout ();
contentLayout.marginWidth = 3;
contentLayout.marginHeight = 3;
wAdvancedComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wAdvancedComp);
wAdvancedComp.setLayout(contentLayout);
// SuccessOngrouping?
// ////////////////////////
// START OF SUCCESS ON GROUP///
// /
wSuccessOn= new Group(wAdvancedComp, SWT.SHADOW_NONE);
props.setLook(wSuccessOn);
wSuccessOn.setText(BaseMessages.getString(PKG, "JobEvalFilesMetrics.SuccessOn.Group.Label"));
FormLayout successongroupLayout = new FormLayout();
successongroupLayout.marginWidth = 10;
successongroupLayout.marginHeight = 10;
wSuccessOn.setLayout(successongroupLayout);
//Scale
wlScale = new Label(wSuccessOn, SWT.RIGHT);
wlScale.setText(BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.Scale.Label"));
props.setLook(wlScale);
fdlScale = new FormData();
fdlScale.left = new FormAttachment(0, 0);
fdlScale.right = new FormAttachment(middle, -margin);
fdlScale.top = new FormAttachment(0, margin);
wlScale.setLayoutData(fdlScale);
wScale = new CCombo(wSuccessOn, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
wScale.setItems(JobEntryEvalFilesMetrics.scaleDesc);
wScale.select(0); // +1: starts at -1
props.setLook(wScale);
fdScale= new FormData();
fdScale.left = new FormAttachment(middle, 0);
fdScale.top = new FormAttachment(0, margin);
fdScale.right = new FormAttachment(100, 0);
wScale.setLayoutData(fdScale);
wScale.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
jobEntry.setChanged();
}
});
//Success number Condition
wlSuccessNumberCondition = new Label(wSuccessOn, SWT.RIGHT);
wlSuccessNumberCondition.setText(BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.SuccessCondition.Label"));
props.setLook(wlSuccessNumberCondition);
fdlSuccessNumberCondition = new FormData();
fdlSuccessNumberCondition.left = new FormAttachment(0, 0);
fdlSuccessNumberCondition.right = new FormAttachment(middle, -margin);
fdlSuccessNumberCondition.top = new FormAttachment(wScale, margin);
wlSuccessNumberCondition.setLayoutData(fdlSuccessNumberCondition);
wSuccessNumberCondition = new CCombo(wSuccessOn, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
wSuccessNumberCondition.setItems(JobEntrySimpleEval.successNumberConditionDesc);
wSuccessNumberCondition.select(0); // +1: starts at -1
props.setLook(wSuccessNumberCondition);
fdSuccessNumberCondition= new FormData();
fdSuccessNumberCondition.left = new FormAttachment(middle, 0);
fdSuccessNumberCondition.top = new FormAttachment(wScale, margin);
fdSuccessNumberCondition.right = new FormAttachment(100, 0);
wSuccessNumberCondition.setLayoutData(fdSuccessNumberCondition);
wSuccessNumberCondition.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
refresh();
jobEntry.setChanged();
}
});
// Compare with value
wlCompareValue= new Label(wSuccessOn, SWT.RIGHT);
wlCompareValue.setText(BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.CompareValue.Label"));
props.setLook(wlCompareValue);
fdlCompareValue= new FormData();
fdlCompareValue.left = new FormAttachment(0, 0);
fdlCompareValue.top = new FormAttachment(wSuccessNumberCondition, margin);
fdlCompareValue.right = new FormAttachment(middle, -margin);
wlCompareValue.setLayoutData(fdlCompareValue);
wCompareValue= new TextVar(jobMeta,wSuccessOn, SWT.SINGLE | SWT.LEFT | SWT.BORDER,
BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.CompareValue.Tooltip"));
props.setLook(wCompareValue);
wCompareValue.addModifyListener(lsMod);
fdCompareValue= new FormData();
fdCompareValue.left = new FormAttachment(middle, 0);
fdCompareValue.top = new FormAttachment(wSuccessNumberCondition, margin);
fdCompareValue.right = new FormAttachment(100, -margin);
wCompareValue.setLayoutData(fdCompareValue);
// Min value
wlMinValue= new Label(wSuccessOn, SWT.RIGHT);
wlMinValue.setText(BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.MinValue.Label"));
props.setLook(wlMinValue);
fdlMinValue= new FormData();
fdlMinValue.left = new FormAttachment(0, 0);
fdlMinValue.top = new FormAttachment(wSuccessNumberCondition, margin);
fdlMinValue.right = new FormAttachment(middle, -margin);
wlMinValue.setLayoutData(fdlMinValue);
wMinValue= new TextVar(jobMeta,wSuccessOn, SWT.SINGLE | SWT.LEFT | SWT.BORDER,
BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.MinValue.Tooltip"));
props.setLook(wMinValue);
wMinValue.addModifyListener(lsMod);
fdMinValue= new FormData();
fdMinValue.left = new FormAttachment(middle, 0);
fdMinValue.top = new FormAttachment(wSuccessNumberCondition, margin);
fdMinValue.right = new FormAttachment(100, -margin);
wMinValue.setLayoutData(fdMinValue);
// Maximum value
wlMaxValue= new Label(wSuccessOn, SWT.RIGHT);
wlMaxValue.setText(BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.MaxValue.Label"));
props.setLook(wlMaxValue);
fdlMaxValue= new FormData();
fdlMaxValue.left = new FormAttachment(0, 0);
fdlMaxValue.top = new FormAttachment(wMinValue, margin);
fdlMaxValue.right = new FormAttachment(middle, -margin);
wlMaxValue.setLayoutData(fdlMaxValue);
wMaxValue= new TextVar(jobMeta, wSuccessOn, SWT.SINGLE | SWT.LEFT | SWT.BORDER, BaseMessages.getString(PKG, "JobEvalFilesMetricsDialog.MaxValue.Tooltip"));
props.setLook(wMaxValue);
wMaxValue.addModifyListener(lsMod);
fdMaxValue= new FormData();
fdMaxValue.left = new FormAttachment(middle, 0);
fdMaxValue.top = new FormAttachment(wMinValue, margin);
fdMaxValue.right = new FormAttachment(100, -margin);
wMaxValue.setLayoutData(fdMaxValue);
fdSuccessOn= new FormData();
fdSuccessOn.left = new FormAttachment(0, margin);
fdSuccessOn.top = new FormAttachment(0, margin);
fdSuccessOn.right = new FormAttachment(100, -margin);
wSuccessOn.setLayoutData(fdSuccessOn);
// ///////////////////////////////////////////////////////////
// / END OF Success ON GROUP
// ///////////////////////////////////////////////////////////
fdAdvancedComp = new FormData();
fdAdvancedComp.left = new FormAttachment(0, 0);
fdAdvancedComp.top = new FormAttachment(0, 0);
fdAdvancedComp.right = new FormAttachment(100, 0);
fdAdvancedComp.bottom= new FormAttachment(100, 0);
wAdvancedComp.setLayoutData(wAdvancedComp);
wAdvancedComp.layout();
wAdvancedTab.setControl(wAdvancedComp);
/////////////////////////////////////////////////////////////
/// END OF ADVANCED TAB
/////////////////////////////////////////////////////////////
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wName, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
wOK = new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, wTabFolder);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener (SWT.Selection, lsOK );
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wName.addSelectionListener( lsDef );
wSourceFileFolder.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
getData();
refresh();
RefreshSize();
RefreshSourceFiles();
wTabFolder.setSelection(0);
BaseStepDialog.setSize(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return jobEntry;
}
private void RefreshSourceFiles()
{
boolean useStaticFiles=(JobEntryEvalFilesMetrics.getSourceFilesByDesc(wSourceFiles.getText())==JobEntryEvalFilesMetrics.SOURCE_FILES_FILES);
wlFields.setEnabled(useStaticFiles);
wFields.setEnabled(useStaticFiles);
wbdSourceFileFolder.setEnabled(useStaticFiles);
wbeSourceFileFolder.setEnabled(useStaticFiles);
wbSourceFileFolder.setEnabled(useStaticFiles);
wbaSourceFileFolder.setEnabled(useStaticFiles);
wlSourceFileFolder.setEnabled(useStaticFiles);
wSourceFileFolder.setEnabled(useStaticFiles);
wlWildcard.setEnabled(useStaticFiles);
wWildcard.setEnabled(useStaticFiles);
wbSourceDirectory.setEnabled(useStaticFiles);
boolean setResultWildcard=(JobEntryEvalFilesMetrics.getSourceFilesByDesc(wSourceFiles.getText())==JobEntryEvalFilesMetrics.SOURCE_FILES_FILENAMES_RESULT);
wlResultFilenamesWildcard .setEnabled(setResultWildcard);
wResultFilenamesWildcard .setEnabled(setResultWildcard);
boolean setResultFields=(JobEntryEvalFilesMetrics.getSourceFilesByDesc(wSourceFiles.getText())==JobEntryEvalFilesMetrics.SOURCE_FILES_PREVIOUS_RESULT);
wlResultFieldIncludeSubFolders.setEnabled(setResultFields);
wResultFieldIncludeSubFolders.setEnabled(setResultFields);
wlResultFieldFile.setEnabled(setResultFields);
wResultFieldFile.setEnabled(setResultFields);
wlResultFieldWildcard.setEnabled(setResultFields);
wResultFieldWildcard.setEnabled(setResultFields);
}
private void RefreshSize()
{
boolean useSize=(JobEntryEvalFilesMetrics.getEvaluationTypeByDesc(wEvaluationType.getText())==JobEntryEvalFilesMetrics.EVALUATE_TYPE_SIZE);
wlScale.setVisible(useSize);
wScale.setVisible(useSize);
}
public void dispose()
{
WindowProperty winprop = new WindowProperty(shell);
props.setScreen(winprop);
shell.dispose();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
if (jobEntry.getName() != null)
wName.setText(jobEntry.getName());
if (jobEntry.source_filefolder != null) {
for (int i = 0; i < jobEntry.source_filefolder.length; i++) {
TableItem ti = wFields.table.getItem(i);
if (jobEntry.source_filefolder[i] != null)
ti.setText(1, jobEntry.source_filefolder[i]);
if (jobEntry.wildcard[i] != null)
ti.setText(2, jobEntry.wildcard[i]);
if (jobEntry.includeSubFolders[i] != null)
ti.setText(3, JobEntryEvalFilesMetrics.getIncludeSubFoldersDesc(jobEntry.includeSubFolders[i]));
}
wFields.setRowNums();
wFields.optWidth(true);
}
if (jobEntry.getResultFilenamesWildcard() != null)
wResultFilenamesWildcard.setText(jobEntry.getResultFilenamesWildcard());
if (jobEntry.getResultFieldFile() != null)
wResultFieldFile.setText(jobEntry.getResultFieldFile());
if (jobEntry.getResultFieldWildcard() != null)
wResultFieldWildcard.setText(jobEntry.getResultFieldWildcard());
if (jobEntry.getResultFieldIncludeSubfolders() != null)
wResultFieldIncludeSubFolders.setText(jobEntry.getResultFieldIncludeSubfolders());
wSourceFiles.setText(JobEntryEvalFilesMetrics.getSourceFilesDesc(jobEntry.sourceFiles));
wEvaluationType.setText(JobEntryEvalFilesMetrics.getEvaluationTypeDesc(jobEntry.evaluationType));
wScale.setText(JobEntryEvalFilesMetrics.getScaleDesc(jobEntry.scale));
wSuccessNumberCondition.setText(JobEntrySimpleEval.getSuccessNumberConditionDesc(jobEntry.successnumbercondition));
if (jobEntry.getCompareValue() != null)
wCompareValue.setText(jobEntry.getCompareValue());
if (jobEntry.getMinValue() != null)
wMinValue.setText(jobEntry.getMinValue());
if (jobEntry.getMaxValue() != null)
wMaxValue.setText(jobEntry.getMaxValue());
wName.selectAll();
wName.setFocus();
}
private void cancel()
{
jobEntry.setChanged(changed);
jobEntry=null;
dispose();
}
private void ok()
{
if(Const.isEmpty(wName.getText()))
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR );
mb.setText(BaseMessages.getString(PKG, "System.StepJobEntryNameMissing.Title"));
mb.setMessage(BaseMessages.getString(PKG, "System.JobEntryNameMissing.Msg"));
mb.open();
return;
}
jobEntry.setName(wName.getText());
jobEntry.setResultFilenamesWildcard(wResultFilenamesWildcard .getText());
jobEntry.setResultFieldFile(wResultFieldFile.getText());
jobEntry.setResultFieldWildcard(wResultFieldWildcard.getText());
jobEntry.setResultFieldIncludeSubfolders(wResultFieldIncludeSubFolders.getText());
jobEntry.sourceFiles= JobEntryEvalFilesMetrics.getSourceFilesByDesc(wSourceFiles.getText());
jobEntry.evaluationType= JobEntryEvalFilesMetrics.getEvaluationTypeByDesc(wEvaluationType.getText());
jobEntry.scale= JobEntryEvalFilesMetrics.getScaleByDesc(wScale.getText());
jobEntry.successnumbercondition= JobEntrySimpleEval.getSuccessNumberConditionByDesc(wSuccessNumberCondition.getText());
jobEntry.setCompareValue(wCompareValue.getText());
jobEntry.setMinValue(wMinValue.getText());
jobEntry.setMaxValue(wMaxValue.getText());
int nritems = wFields.nrNonEmpty();
int nr = 0;
for (int i = 0; i < nritems; i++)
{
String arg = wFields.getNonEmpty(i).getText(1);
if (arg != null && arg.length() != 0)
nr++;
}
jobEntry.source_filefolder = new String[nr];
jobEntry.wildcard = new String[nr];
jobEntry.includeSubFolders = new String[nr];
nr = 0;
for (int i = 0; i < nritems; i++)
{
String source = wFields.getNonEmpty(i).getText(1);
String wild = wFields.getNonEmpty(i).getText(2);
String includeSubFolders = wFields.getNonEmpty(i).getText(3);
if (source != null && source.length() != 0)
{
jobEntry.source_filefolder[nr] = source;
jobEntry.wildcard[nr] = wild;
jobEntry.includeSubFolders[nr]=JobEntryEvalFilesMetrics.getIncludeSubFolders(includeSubFolders);
nr++;
}
}
dispose();
}
private void refresh()
{
boolean compareValue= (JobEntrySimpleEval.getSuccessNumberConditionByDesc(wSuccessNumberCondition.getText())
!=JobEntrySimpleEval.SUCCESS_NUMBER_CONDITION_BETWEEN);
wlCompareValue.setVisible(compareValue);
wCompareValue.setVisible(compareValue);
wlMinValue.setVisible(!compareValue);
wMinValue.setVisible(!compareValue);
wlMaxValue.setVisible(!compareValue);
wMaxValue.setVisible(!compareValue);
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return false;
}
}
| 38.666976 | 179 | 0.744356 |
790243013ef1fb5bcedc7bdb64b3a2948c1cc0f0 | 11,305 | package br.com.moip.unit_tests;
import br.com.moip.Moip;
import br.com.moip.models.Setup;
import br.com.moip.unit_tests.setup.SetupFactory;
import br.com.moip.utilities.Parser;
import com.rodrigosaito.mockwebserver.player.Play;
import com.rodrigosaito.mockwebserver.player.Player;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class NotificationTest {
@Rule
public Player player = new Player();
private Setup setup;
private Map<String, Object> body;
private Parser parser;
@Before
public void initialize() {
this.body = new HashMap<>();
this.setup = new SetupFactory().setupBasicAuth(player.getURL("").toString());
this.parser = new Parser();
}
@Play("notification/create_notification_preferences")
@Test
public void createNotificationPreferenceTest() {
Map<String, Object> notification = Moip.API.notificationPreferences().create(body, setup);
List events = parser.objectToList(notification.get("events"));
assertEquals("ORDER.*", events.get(0));
assertEquals("PAYMENT.AUTHORIZED", events.get(1));
assertEquals("PAYMENT.CANCELLED", events.get(2));
assertEquals("http://requestb.in/1dhjesw1", notification.get("target"));
assertEquals("WEBHOOK", notification.get("media"));
assertEquals("1457cbc9e2ab4bc7a62ab24951a9a878", notification.get("token"));
assertEquals("NPR-LQCZEI6Q7I1G", notification.get("id"));
}
@Play("notification/get_notification_preferences")
@Test
public void getNotificationPreferenceTest() {
Map<String, Object> notification = Moip.API.notificationPreferences().get("NPR-LQCZEI6Q7I1G", setup);
List events = parser.objectToList(notification.get("events"));
assertEquals("ORDER.*", events.get(0));
assertEquals("PAYMENT.AUTHORIZED", events.get(1));
assertEquals("PAYMENT.CANCELLED", events.get(2));
assertEquals("http://requestb.in/1dhjesw1", notification.get("target"));
assertEquals("WEBHOOK", notification.get("media"));
assertEquals("1457cbc9e2ab4bc7a62ab24951a9a878", notification.get("token"));
assertEquals("NPR-LQCZEI6Q7I1G", notification.get("id"));
}
@Play("notification/list_notification_preferences")
@Test
public void listNotificationPreferencesTest() {
List<Map<String, Object>> listPreferences = Moip.API.notificationPreferences().list(setup);
// listPreferences[0]
List events0 = parser.objectToList(listPreferences.get(0).get("events"));
assertEquals("ORDER.*", events0.get(0));
assertEquals("PAYMENT.AUTHORIZED", events0.get(1));
assertEquals("PAYMENT.CANCELLED", events0.get(2));
assertEquals("http://my.uri/0", listPreferences.get(0).get("target"));
assertEquals("WEBHOOK", listPreferences.get(0).get("media"));
assertEquals("63c351458ccc4967aaa84f66a79c2be6", listPreferences.get(0).get("token"));
assertEquals("NPR-O019G1CWTFV5", listPreferences.get(0).get("id"));
// listPreferences[1]
List events1 = parser.objectToList(listPreferences.get(1).get("events"));
assertEquals("ORDER.*", events1.get(0));
assertEquals("PAYMENT.AUTHORIZED", events1.get(1));
assertEquals("PAYMENT.CANCELLED", events1.get(2));
assertEquals("http://my.uri/1", listPreferences.get(1).get("target"));
assertEquals("WEBHOOK", listPreferences.get(1).get("media"));
assertEquals("688e2f2b75df4b968cad7d2b5c9c02d6", listPreferences.get(1).get("token"));
assertEquals("NPR-AV7URX6E5OUF", listPreferences.get(1).get("id"));
// listPreferences[2]
List events2 = parser.objectToList(listPreferences.get(2).get("events"));
assertEquals("ORDER.*", events2.get(0));
assertEquals("PAYMENT.AUTHORIZED", events2.get(1));
assertEquals("PAYMENT.CANCELLED", events2.get(2));
assertEquals("http://my.uri/2", listPreferences.get(2).get("target"));
assertEquals("WEBHOOK", listPreferences.get(2).get("media"));
assertEquals("19160e43b6df4f58b31bfe57d291cb8a", listPreferences.get(2).get("token"));
assertEquals("NPR-KCC2M2IYRQXJ", listPreferences.get(2).get("id"));
// listPreferences[3]
List events3 = parser.objectToList(listPreferences.get(3).get("events"));
assertEquals("ORDER.*", events3.get(0));
assertEquals("PAYMENT.AUTHORIZED", events3.get(1));
assertEquals("PAYMENT.CANCELLED", events3.get(2));
assertEquals("http://my.uri/3", listPreferences.get(3).get("target"));
assertEquals("WEBHOOK", listPreferences.get(3).get("media"));
assertEquals("a07451ff754449d18fedf60c6582e130", listPreferences.get(3).get("token"));
assertEquals("NPR-GFD5Q9JP0JHO", listPreferences.get(3).get("id"));
// listPreferences[4]
List events4 = parser.objectToList(listPreferences.get(4).get("events"));
assertEquals("ORDER.*", events4.get(0));
assertEquals("PAYMENT.AUTHORIZED", events4.get(1));
assertEquals("PAYMENT.CANCELLED", events4.get(2));
assertEquals("http://my.uri/4", listPreferences.get(4).get("target"));
assertEquals("WEBHOOK", listPreferences.get(4).get("media"));
assertEquals("dc5c0470a44145baad470693b1ac7416", listPreferences.get(4).get("token"));
assertEquals("NPR-F0TNENDS2PW0", listPreferences.get(4).get("id"));
}
@Play("notification/remove_notification_preferences")
@Test
public void deleteNotificationPreferenceTest() {
Map<String, Object> removePreference = Moip.API.notificationPreferences().remove("NPR-KCC2M2IYRQXJ", setup);
assertTrue(removePreference.isEmpty());
}
@Play("notification/get_webhooks")
@Test
public void getWebhooksTest() {
Map<String, Object> getWebhooks = Moip.API.webhooks().get("ORD-W496X7T9FVGZ", setup);
List<Map<String, Object>> webhooks = parser.objectToList(getWebhooks.get("webhooks"));
// webhooks[0]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(0).get("resourceId"));
assertEquals("ORDER.PAID", webhooks.get(0).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(0).get("url"));
assertEquals("FAILED", webhooks.get(0).get("status"));
assertEquals("EVE-VP3PTS0QP294", webhooks.get(0).get("id"));
assertEquals("2018-07-17T18:11:07.473Z", webhooks.get(0).get("sentAt"));
// webhooks[1]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(1).get("resourceId"));
assertEquals("ORDER.WAITING", webhooks.get(1).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(1).get("url"));
assertEquals("FAILED", webhooks.get(1).get("status"));
assertEquals("EVE-YA8Z6XXDZJCY", webhooks.get(1).get("id"));
assertEquals("2018-07-17T18:11:06.047Z", webhooks.get(1).get("sentAt"));
// webhooks[2]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(2).get("resourceId"));
assertEquals("ORDER.CREATED", webhooks.get(2).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(2).get("url"));
assertEquals("FAILED", webhooks.get(2).get("status"));
assertEquals("EVE-FXFWBXTD4CBM", webhooks.get(2).get("id"));
assertEquals("2018-07-17T18:11:02.628Z", webhooks.get(2).get("sentAt"));
// webhooks[3]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(3).get("resourceId"));
assertEquals("ORDER.PAID", webhooks.get(3).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(3).get("url"));
assertEquals("FAILED", webhooks.get(3).get("status"));
assertEquals("EVE-Z0H3OSCO6CG4", webhooks.get(3).get("id"));
assertEquals("2018-07-17T18:10:57.162Z", webhooks.get(3).get("sentAt"));
// webhooks[4]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(4).get("resourceId"));
assertEquals("ORDER.WAITING", webhooks.get(4).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(4).get("url"));
assertEquals("FAILED", webhooks.get(4).get("status"));
assertEquals("EVE-BM1MIMKDV6VR", webhooks.get(4).get("id"));
assertEquals("2018-07-17T18:10:55.716Z", webhooks.get(4).get("sentAt"));
// webhooks[5]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(5).get("resourceId"));
assertEquals("ORDER.CREATED", webhooks.get(5).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(5).get("url"));
assertEquals("FAILED", webhooks.get(5).get("status"));
assertEquals("EVE-HR1TKRMBBV6P", webhooks.get(5).get("id"));
assertEquals("2018-07-17T18:10:52.241Z", webhooks.get(5).get("sentAt"));
}
@Play("notification/list_webhooks")
@Test
public void listWebhooksTest() {
Map<String, Object> listWebhooks = Moip.API.webhooks().list(setup);
List<Map<String, Object>> webhooks = parser.objectToList(listWebhooks.get("webhooks"));
// webhooks[0]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(0).get("resourceId"));
assertEquals("ORDER.PAID", webhooks.get(0).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(0).get("url"));
assertEquals("FAILED", webhooks.get(0).get("status"));
assertEquals("EVE-VP3PTS0QP294", webhooks.get(0).get("id"));
assertEquals("2018-07-17T18:11:07.473Z", webhooks.get(0).get("sentAt"));
// webhooks[1]
assertEquals("PAY-NFSY35SXVCCN", webhooks.get(1).get("resourceId"));
assertEquals("PAYMENT.AUTHORIZED", webhooks.get(1).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(1).get("url"));
assertEquals("FAILED", webhooks.get(1).get("status"));
assertEquals("EVE-O8EC0FBUBBAP", webhooks.get(1).get("id"));
assertEquals("2018-07-17T18:11:07.303Z", webhooks.get(1).get("sentAt"));
// webhooks[2]
assertEquals("PAY-NFSY35SXVCCN", webhooks.get(2).get("resourceId"));
assertEquals("PAYMENT.IN_ANALYSIS", webhooks.get(2).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(2).get("url"));
assertEquals("FAILED", webhooks.get(2).get("status"));
assertEquals("EVE-6QJN2PWF6SOD", webhooks.get(2).get("id"));
assertEquals("2018-07-17T18:11:06.228Z", webhooks.get(2).get("sentAt"));
// webhooks[3]
assertEquals("ORD-W496X7T9FVGZ", webhooks.get(3).get("resourceId"));
assertEquals("ORDER.WAITING", webhooks.get(3).get("event"));
assertEquals("https://requestb.in/16pw5ncfjleofweojfewbl1", webhooks.get(3).get("url"));
assertEquals("FAILED", webhooks.get(3).get("status"));
assertEquals("EVE-YA8Z6XXDZJCY", webhooks.get(3).get("id"));
assertEquals("2018-07-17T18:11:06.047Z", webhooks.get(3).get("sentAt"));
}
}
| 47.5 | 116 | 0.664839 |
437792f140605da89345ddc1a86979c664b5a8b6 | 1,308 | /*
* Copyright (c) 2018 Uber Technologies, Inc. ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uber.hoodie.common.table.view;
/**
* Storage Type used to store/retrieve File system view of a table
*/
public enum FileSystemViewStorageType {
// In-memory storage of file-system view
MEMORY,
// Constrained Memory storage for file-system view with overflow data spilled to disk
SPILLABLE_DISK,
// EMBEDDED Key Value Storage for file-system view
EMBEDDED_KV_STORE,
// Delegate file-system view to remote server
REMOTE_ONLY,
// A composite storage where file-system view calls are first delegated to Remote server ( REMOTE_ONLY )
// In case of failures, switches subsequent calls to secondary local storage type
REMOTE_FIRST
}
| 37.371429 | 106 | 0.747706 |
99aeee4e85a1389b7818581237084155823e4e8e | 432 | public class evennumbers {
public static void main(String[] args) {
System.out.println("Folgende Zahlen sind durch zwei teilbar:");
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
// if ((i / 2) * 2 == i) {
System.out.println(i);
}
}
System.out.println("Davon durch 4 teilbar:");
for (int i = 1; i <= 100; i++) {
if (i % 4 == 0) {
// if ((i / 4) * 4== i) {
System.out.println(i);
}
}
}
}
| 19.636364 | 65 | 0.50463 |
c9b2ab7ad170ae6b14be3fa1d62c0b5ee5fe2716 | 4,989 | package io.entraos.monitor;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.bridge.SLF4JBridgeHandler;
import org.springframework.web.context.ContextLoaderListener;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.LogManager;
import static no.cantara.config.ServiceConfig.getProperty;
import static org.slf4j.LoggerFactory.getLogger;
@SuppressWarnings("restriction")
public class Main {
private static final Logger log = getLogger(Main.class);
public static final String CONTEXT_PATH = "/monitor";
private static final String LOGS_NAME = "logs";
public static final int DEFAULT_PORT = 8080;
private Integer webappPort;
private Server server;
public Main() {
this.server = new Server();
}
public Main withPort(Integer webappPort) {
this.webappPort = webappPort;
return this;
}
public static void main(String[] args) {
LogManager.getLogManager().reset();
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
LogManager.getLogManager().getLogger("").setLevel(Level.INFO);
Integer webappPort = DEFAULT_PORT;
String port = getProperty("server_port");
if (port != null) {
try {
webappPort = Integer.valueOf(port);
} catch (NumberFormatException nfe) {
log.warn("Failed to create port as integer from {}. Using default port: {}", port, webappPort);
}
}
try {
final Main main = new Main().withPort(webappPort);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
log.debug("ShutdownHook triggered. Exiting basicauthapplication");
main.stop();
}
});
main.start();
log.debug("Finished waiting for Thread.currentThread().join()");
main.stop();
} catch (RuntimeException e) {
log.error("Error during startup. Shutting down ConfigService.", e);
System.exit(1);
}
}
// https://github.com/psamsotha/jersey-spring-jetty/blob/master/src/main/java/com/underdog/jersey/spring/jetty/JettyServerMain.java
public void start() {
ServletContextHandler context = new ServletContextHandler();
context.setContextPath(CONTEXT_PATH);
ResourceConfig jerseyResourceConfig = new ResourceConfig();
jerseyResourceConfig.packages("io.entraos.monitor");
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(jerseyResourceConfig));
context.addServlet(jerseyServlet, "/*");
context.addEventListener(new ContextLoaderListener());
context.setInitParameter("contextConfigLocation", "classpath:context.xml");
ServerConnector connector = new ServerConnector(server);
if (webappPort != null) {
connector.setPort(webappPort);
}
NCSARequestLog requestLog = buildRequestLog();
server.setRequestLog(requestLog);
server.addConnector(connector);
server.setHandler(context);
try {
ensureLogsDirExist();
server.start();
} catch (Exception e) {
log.error("Error during Jetty startup. Exiting", e);
// "System. exit(2);"
}
webappPort = connector.getLocalPort();
String baseUri = "http://localhost:" + webappPort + "/" + CONTEXT_PATH + "/";
log.info("integration monitor started on {}", baseUri);
log.info(" Status on {}status", baseUri);
log.info(" Health on {}health", baseUri);
try {
server.join();
} catch (InterruptedException e) {
log.error("Jetty server thread when join. Pretend everything is OK.", e);
}
}
void ensureLogsDirExist() {
File directory = new File(LOGS_NAME);
if (! directory.exists()){
directory.mkdir();
}
}
private NCSARequestLog buildRequestLog() {
NCSARequestLog requestLog = new NCSARequestLog("logs/jetty-yyyy_mm_dd.request.log");
requestLog.setAppend(true);
requestLog.setExtended(true);
requestLog.setLogTimeZone("GMT");
return requestLog;
}
public void stop() {
try {
server.stop();
} catch (Exception e) {
log.warn("Error when stopping Jetty server", e);
}
}
public int getPort() {
return webappPort;
}
public boolean isStarted() {
return server.isStarted();
}
}
| 31.77707 | 135 | 0.633193 |
345c6b3c0e04b48155c42e1699c1d1b5bd8ba4aa | 425 | /*
* Anthony Tornetta & Troy Cope | P5 | 3/31/18
* This is our own work: ACT & TC
* Something that can be held
*/
package com.corntrip.turnbased.gameobject.modifier;
import org.newdawn.slick.Image;
import com.corntrip.turnbased.gameobject.Entity;
/**
* Anything that can be held by an {@link Entity}.
*/
public interface IEquipable
{
// Getters & Setters //
public Image getImage();
public Entity getOwner();
}
| 19.318182 | 51 | 0.703529 |
954585195d7fb739e21cc0c72bdf8923cae06c8a | 293 | package com.github.bordertech.webfriends.api.element.form.input;
import com.github.bordertech.webfriends.api.common.form.capability.Suggestable;
/**
* Input text element with suggestions.
*/
public interface InputTextSuggestionsElement extends InputTextElement, Suggestable {
}
| 26.636364 | 85 | 0.788396 |
43e69d82d58089b02f47adeaaec2892f86d43632 | 438 | package com.aggrepoint.winlet;
/**
* @see ReqConst
*
* @author Jiangming Yang ([email protected])
*/
public interface RespHeaderConst {
String HEADER_UPDATE = "X-Winlet-Update";
String HEADER_TARGET = "X-Winlet-Target";
String HEADER_TITLE = "X-Winlet-Title";
String HEADER_DIALOG = "X-Winlet-Dialog";
String HEADER_REDIRECT = "X-Winlet-Redirect";
String HEADER_CACHE = "X-Winlet-Cache";
String HEADER_MSG = "X-Winlet-Msg";
}
| 25.764706 | 46 | 0.726027 |
acbfb03f139629424749b1703d3e6d5db7c55cd6 | 413 | package cn.misection.cvac.ast.expr.terminator;
import cn.misection.cvac.ast.expr.AbstractExpression;
/**
* @author Military Intelligence 6 root
* @version 1.0.0
* @ClassName AbstractTerminator
* @Description TODO
* @CreateTime 2021年02月23日 18:22:00
*/
public abstract class AbstractTerminator extends AbstractExpression
{
protected AbstractTerminator(int lineNum)
{
super(lineNum);
}
}
| 21.736842 | 67 | 0.74092 |
1552cb34bca375f1137f377a1afd2b78dd002de9 | 1,841 | package dev.gradleplugins.documentationkit;
import dev.nokee.model.internal.core.NodeRegistration;
import dev.nokee.model.internal.core.NodeRegistrationFactory;
import dev.nokee.model.internal.type.TypeOf;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.SetProperty;
import javax.annotation.Generated;
import javax.inject.Inject;
import java.net.URI;
import static dev.nokee.model.internal.core.ModelActions.discover;
import static dev.nokee.model.internal.core.NodePredicate.self;
import static dev.nokee.model.internal.core.NodeRegistration.unmanaged;
import static dev.nokee.model.internal.type.ModelType.of;
@Generated("Manually generated")
public final class ApiReferenceManifestModelElementRegistrationFactory implements NodeRegistrationFactory<ApiReferenceManifest> {
private final ObjectFactory objects;
@Inject
public ApiReferenceManifestModelElementRegistrationFactory(ObjectFactory objects) {
this.objects = objects;
}
@Override
public NodeRegistration<ApiReferenceManifest> create(String name) {
return unmanaged(name, of(ApiReferenceManifest.class), ApiReferenceManifestModelElement::new)
.action(self(discover(context -> {
context.register(unmanaged("sources", of(ConfigurableFileCollection.class), () -> objects.fileCollection()));
context.register(unmanaged("dependencies", of(new TypeOf<SetProperty<Dependency>>() {}), () -> objects.setProperty(Dependency.class)));
context.register(unmanaged("repositories", of(new TypeOf<SetProperty<URI>>() {}), () -> objects.setProperty(URI.class)));
context.register(unmanaged("destinationLocation", of(DirectoryProperty.class), () -> objects.directoryProperty()));
})));
}
}
| 44.902439 | 139 | 0.803368 |
7e0a3299faef4dffd4341c58ceefaa4bbffd502a | 1,205 | package com.study.jpkc.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.study.jpkc.entity.LiveCourse;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author [email protected]
* @since 2021-02-05
*/
public interface ILiveCourseService extends IService<LiveCourse> {
/**
* 分页获取直播课程
* @param current 当前页
* @param size 每页大小
* @return list
*/
Page<LiveCourse> getLiveCourse(Integer current, Integer size);
/**
* 通过userId查询直播课程
* @param userId 用户id
* @return 直播课程
*/
List<LiveCourse> getByUserId(String userId);
/**
* 创建直播课程
* @param teacherId 教师id
* @param lCourse 课程信息
* @param logoFile logo
* @return 是否成功
*/
boolean save(String teacherId, LiveCourse lCourse, MultipartFile logoFile);
/**
* 通过id增加观看人数
* @param lCourseId 直播id
* @return 是否成功
*/
boolean addViews(String lCourseId);
/**
* 通过id增加收藏人数
* @param lCourseId 直播id
* @return 是否成功
*/
boolean addStar(String lCourseId);
}
| 20.775862 | 79 | 0.644813 |
1ad0705b67f10c6899f1da57eebb8871f75c795d | 1,739 | /*
* Copyright 2017 Banco Bilbao Vizcaya Argentaria, S.A.
*
* 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.bbva.arq.devops.ae.mirrorgate.mapper;
import static com.bbva.arq.devops.ae.mirrorgate.mapper.DashboardMapper.map;
import com.bbva.arq.devops.ae.mirrorgate.model.Dashboard;
import com.bbva.arq.devops.ae.mirrorgate.support.DashboardStatus;
import com.bbva.arq.devops.ae.mirrorgate.support.DashboardType;
import com.bbva.arq.devops.ae.mirrorgate.support.Filters;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class DashboardMapperTests {
@Test
public void itShouldMapAllFields() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
final Dashboard dashboard = new Dashboard()
.setStatus(DashboardStatus.ACTIVE)
.setType(DashboardType.Detail.name())
.setFilters(new Filters())
.setInfraCost(false)
.setLastTimeUsed(1L);
MapperTestingSupport.initializeTypicalSetters(dashboard);
MapperTestingSupport.assertBeanValues(dashboard, map(map(dashboard)));
}
}
| 37 | 120 | 0.751581 |
1287850c5118e76844285babdb468aecc179f1ab | 897 | package com.squad.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import com.squad.model.User;
import com.squad.service.UserService;
@Controller
public class MainController {
@Autowired
protected UserService userService;
public static final String ERROR_MESSAGE = "errorMessage";
public static final String MESSAGE = "message";
public static final String USER = "user";
/* PAGES */
public static final String INDEX_JSP = "index";
public void createMenu(HttpServletRequest request, ModelAndView modelAndView) {
if (request.getSession().getAttribute(USER) == null) {
request.getSession().setAttribute(USER, new User());
}
modelAndView.addObject(USER, request.getSession().getAttribute(USER));
}
}
| 28.03125 | 80 | 0.784838 |
6a877445b553eb3e7bdf5d30d1031152d6a35d36 | 2,153 | package com.github.howaric.alg.heap;
import java.util.Arrays;
public class Heap {
public static void main(String[] args) {
MinHeap minHeap = new MinHeap(5);
minHeap.add(1);
minHeap.add(3);
minHeap.add(4);
minHeap.add(2);
minHeap.add(5);
minHeap.traverse();
System.out.println(minHeap.poll());
minHeap.traverse();
System.out.println(minHeap.size());
}
}
class MinHeap {
private int size;
private int[] data;
public MinHeap(int initialCapacity) {
this.data = new int[initialCapacity];
}
public void add(int value) {
if (size == data.length) {
throw new RuntimeException("Heap is full!!");
}
data[size] = value;
heapInsert(size++);
}
public int poll() {
if (size == 0) {
throw new RuntimeException("Heap is empty!!");
}
int result = data[0];
swap(data, 0, --size);
heapify(0);
return result;
}
//O(logN)
//向上看父节点,如果小,则与父节点交换
private void heapInsert(int index) {
while (data[(index - 1) / 2] > data[index]) {
swap(data, (index - 1) / 2, index);
index = (index - 1) / 2;
}
}
//O(logN)
//与子节点比较,如果某个子节点小,则交换
private void heapify(int index) {
//左子节点
int left = index << 1 + 1;
//要判断是否越界
while (left < size) {
int smaller = left + 1 < size && data[left] < data[left + 1] ? left : left + 1;
int min = data[index] < data[smaller] ? index : smaller;
if (min == index) {
break;
}
swap(data, min, index);
index = min;
left = index << 1 + 1;
}
}
private static void swap(int[] array, int i, int j) {
if (i == j || array[i] == array[j]) {
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public void traverse() {
System.out.println(Arrays.toString(data));
}
public int size() {
return size;
}
} | 22.904255 | 91 | 0.489549 |
1d053234e53372dfbd6abbe376b04d43cc695b2d | 19,541 | package org.kuali.ole.deliver.service;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.ole.OLEConstants;
import org.kuali.ole.OLEParameterConstants;
import org.kuali.ole.deliver.bo.OleCirculationDesk;
import org.kuali.ole.deliver.bo.OleLoanDocument;
import org.kuali.ole.deliver.bo.OlePatronDocument;
import org.kuali.ole.deliver.processor.LoanProcessor;
import org.kuali.ole.service.OlePatronHelperService;
import org.kuali.ole.service.OlePatronHelperServiceImpl;
import org.kuali.ole.sys.context.SpringContext;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.util.RiceConstants;
import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
/**
* Created by premkb on 4/8/15.
*/
public class NoticePDFContentFormatter {
private static final Logger LOG = Logger.getLogger(NoticePDFContentFormatter.class);
private CircDeskLocationResolver circDeskLocationResolver;
private SimpleDateFormat simpleDateFormat;
private String urlProperty;
private ParameterValueResolver parameterResolverInstance;
private OlePatronHelperServiceImpl olePatronHelperService;
public OlePatronHelperService getOlePatronHelperService(){
if(olePatronHelperService==null)
olePatronHelperService=new OlePatronHelperServiceImpl();
return olePatronHelperService;
}
public void setOlePatronHelperService(OlePatronHelperServiceImpl olePatronHelperService) {
this.olePatronHelperService = olePatronHelperService;
}
public void setUrlProperty(String urlProperty) {
this.urlProperty = urlProperty;
}
public String generateOverDueNoticeContent(OleLoanDocument oleLoanDocument)
throws Exception {
Document document = new Document(PageSize.A4);
String fileName = createPDFFile(getParameterResolverInstance().getParameter(OLEConstants
.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEParameterConstants.OVERDUE_TITLE), oleLoanDocument.getItemId());
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
PdfWriter.getInstance(document, fileOutputStream);
document.open();
String title = getParameterResolverInstance().getParameter(OLEConstants
.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEParameterConstants.OVERDUE_TITLE);
String body = getParameterResolverInstance().getParameter(OLEConstants
.APPL_ID_OLE, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEConstants.OleDeliverRequest.OVERDUE_NOTICE_CONTENT);
addPdfHeader(document, title);
addPatronInfoToDocument(document, oleLoanDocument.getOlePatron(), title, body);
addOverdueNoticeInfoToDocument(oleLoanDocument, document);
addPdfFooter(document);
document.close();
return fileName;
}
private void addPatronInfoToDocument(Document document, OlePatronDocument olePatronDocument, String title, String body)
throws
Exception {
EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
Paragraph paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
paraGraph = new Paragraph();
paraGraph.add(new Chunk("Patron information", getBoldFont()));
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
PdfPTable pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20, 2, 30});
pdfTable.addCell(getPdfPCellInJustified("Patron Name"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((olePatronDocument.getEntity().getNames().get(0).getFirstName() + " " + olePatronDocument.getEntity().getNames().get(0).getLastName())));
pdfTable.addCell(getPdfPCellInJustified("Address"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronPreferredAddress(entityTypeContactInfoBo) : "")));
pdfTable.addCell(getPdfPCellInJustified("Email"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomeEmailId(entityTypeContactInfoBo) : "")));
pdfTable.addCell(getPdfPCellInJustified("Phone #"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getOlePatronHelperService().getPatronHomePhoneNumber(entityTypeContactInfoBo) : "")));
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
getPdfTemplateBody(document, title, body);
paraGraph = new Paragraph();
paraGraph.add(new Chunk("Title/item information", getBoldFont()));
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
}
private void getPdfTemplateBody(Document document, String title, String body) throws Exception {
//Notice Type
Paragraph paraGraph = new Paragraph();
paraGraph.add(new Chunk(title, getBoldFont()));
paraGraph.setAlignment(Element.ALIGN_CENTER);
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
//Notice-specific text
paraGraph = new Paragraph();
paraGraph.add(new Chunk(body, getBoldFont()));
paraGraph.setAlignment(Element.ALIGN_CENTER);
paraGraph.add(Chunk.NEWLINE);
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
}
public void addPdfFooter(Document document) throws DocumentException {
String url = getURLProperty();
// String myAccountURL = loanProcessor.getParameter(OLEConstants.MY_ACCOUNT_URL);
String myAccountURL = url + OLEConstants.OLE_MY_ACCOUNT_URL_CHANNEL + url + OLEConstants.OLE_MY_ACCOUNT_URL;
if (myAccountURL != null && !myAccountURL.trim().isEmpty()) {
Font ver_15_normal = FontFactory.getFont("Times-Roman", 15, Font.BOLD, BaseColor.BLUE);
ver_15_normal.setColor(BaseColor.BLUE);
ver_15_normal.setStyle(Font.UNDERLINE);
Anchor anchor = new Anchor("MyAccount", ver_15_normal);
anchor.setReference(myAccountURL);
Paragraph paraGraph = new Paragraph();
paraGraph.add(anchor);
paraGraph.setFont(ver_15_normal);
paraGraph.setAlignment(Element.ALIGN_CENTER);
document.add(paraGraph);
}
}
private String getURLProperty() {
if (null == urlProperty) {
urlProperty = ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base");
}
return urlProperty;
}
public void addOverdueNoticeInfoToDocument(OleLoanDocument oleLoanDocument, Document document) throws DocumentException {
Paragraph paraGraph;
SimpleDateFormat sdf = getSimpleDateFormat();
PdfPTable pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20, 2, 30});
String circulationLocation = null;
String circulationReplyToEmail = null;
OleCirculationDesk oleCirculationDesk = getCircDeskLocationResolver().getCirculationDesk(oleLoanDocument.getItemLocation());
if (oleCirculationDesk != null) {
circulationLocation = oleCirculationDesk.getCirculationDeskPublicName();
if (StringUtils.isNotBlank(oleCirculationDesk.getReplyToEmail())) {
circulationReplyToEmail = oleCirculationDesk.getReplyToEmail();
} else {
circulationReplyToEmail = getParameterResolverInstance().getParameter(OLEConstants
.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEParameterConstants.NOTICE_FROM_MAIL);
}
} else {
circulationLocation = getParameterResolverInstance().getParameter(OLEConstants
.APPL_ID_OLE, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEParameterConstants.DEFAULT_CIRCULATION_DESK);
circulationReplyToEmail = getParameterResolverInstance().getParameter(OLEConstants
.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,OLEParameterConstants.NOTICE_FROM_MAIL);
}
pdfTable.addCell(getPdfPCellInJustified("Circulation Location / Library Name"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified(circulationLocation));
pdfTable.addCell(getPdfPCellInJustified("Circulation Reply-To Email"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified(circulationReplyToEmail));
pdfTable.addCell(getPdfPCellInJustified("Title"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((oleLoanDocument.getTitle() == null ? "" : oleLoanDocument.getTitle())));
pdfTable.addCell(getPdfPCellInJustified("Author"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((oleLoanDocument.getAuthor() == null ? "" : oleLoanDocument.getAuthor())));
String volume = (String) oleLoanDocument.getEnumeration() != null && !oleLoanDocument.getEnumeration().equals("") ? oleLoanDocument.getEnumeration() : "";
String issue = new String(" ");
String copyNumber = (String) oleLoanDocument.getItemCopyNumber() != null && !oleLoanDocument.getItemCopyNumber().equals("") ? oleLoanDocument.getItemCopyNumber() : "";
String volumeNumber = volume + "/" + issue + "/" + copyNumber;
pdfTable.addCell(getPdfPCellInJustified("Volume/Issue/Copy #"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((volumeNumber == null ? "" : volumeNumber)));
pdfTable.addCell(getPdfPCellInJustified("Library shelving location "));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((oleLoanDocument.getItemLocation() == null ? "" : oleLoanDocument.getItemLocation())));
String callNumber = "";
if (oleLoanDocument.getItemCallNumber() != null && !oleLoanDocument.getItemCallNumber().equals("")) {
callNumber = (String) (oleLoanDocument.getItemCallNumber() != null && !oleLoanDocument.getItemCallNumber().equals("") ? oleLoanDocument.getItemCallNumber() : "");
}
pdfTable.addCell(getPdfPCellInJustified("Call # "));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((callNumber == null ? "" : callNumber)));
pdfTable.addCell(getPdfPCellInJustified("Item barcode"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((oleLoanDocument.getItemId() == null ? "" : oleLoanDocument.getItemId())));
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
pdfTable = new PdfPTable(3);
pdfTable.setWidths(new int[]{20, 2, 30});
pdfTable.addCell(getPdfPCellInJustified("Item was due"));
pdfTable.addCell(getPdfPCellInLeft(":"));
pdfTable.addCell(getPdfPCellInJustified((oleLoanDocument.getLoanDueDate() == null ? "" : (sdf.format(oleLoanDocument.getLoanDueDate()).toString()))));
document.add(pdfTable);
paraGraph = new Paragraph();
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
}
private void addPdfHeader(Document document, String title) throws
Exception {
Paragraph paraGraph = new Paragraph();
paraGraph.setAlignment(Element.ALIGN_CENTER);
paraGraph.add(new Chunk(title, getBoldFont()));
paraGraph.add(Chunk.NEWLINE);
document.add(paraGraph);
}
public Font getBoldFont() {
return FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, Font.BOLD);
}
private PdfPCell getPdfPCellInJustified(String chunk) {
if (null == chunk) {
chunk = "";
}
PdfPCell pdfPCell = new PdfPCell(new Paragraph(new Chunk(chunk, getFont(chunk))));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_JUSTIFIED);
return pdfPCell;
}
private PdfPCell getPdfPCellInLeft(String chunk) {
PdfPCell pdfPCell = new PdfPCell(new Paragraph(new Chunk(chunk, getDefaultFont())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
return pdfPCell;
}
private PdfPCell getPdfPCellInCenter(String chunk) {
PdfPCell pdfPCell = new PdfPCell(new Paragraph(new Chunk(chunk, getDefaultFont())));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
return pdfPCell;
}
private PdfPCell getPdfPCellInCenter(String chunk, Font font) {
PdfPCell pdfPCell = new PdfPCell(new Paragraph(new Chunk(chunk, font)));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
pdfPCell.setHorizontalAlignment(pdfPCell.ALIGN_LEFT);
return pdfPCell;
}
private PdfPCell getPdfPCellNewLine() {
PdfPCell pdfPCell = new PdfPCell(new Paragraph(Chunk.NEWLINE));
pdfPCell.setBorder(pdfPCell.NO_BORDER);
return pdfPCell;
}
public Font getDefaultFont() {
com.itextpdf.text.Font font = FontFactory.getFont(getFontFilePath("org/kuali/ole/deliver/batch/fonts/ARIALUNI.TTF"), BaseFont.IDENTITY_H, 10);
return font;
}
public String getFontFilePath(String classpathRelativePath) {
try {
Resource rsrc = new ClassPathResource(classpathRelativePath);
return rsrc.getFile().getAbsolutePath();
} catch (Exception e) {
LOG.error("Error : while accessing font file " + e);
}
return null;
}
public Font getFont(String data) {
if (null != data) {
String myData = new String(data);
java.util.List<Character.UnicodeBlock> unicodeBlocks = new ArrayList<>();
if (StringUtils.isNotBlank(myData)) {
unicodeBlocks = getListOfLanguage(myData);
}
if (unicodeBlocks.contains(Character.UnicodeBlock.ARABIC)) {
Font font = FontFactory.getFont(getFontFilePath("org/kuali/ole/deliver/batch/fonts/arial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
return font;
}
}
return getDefaultFont();
}
private List<Character.UnicodeBlock> getListOfLanguage(String data) {
Set<Character.UnicodeBlock> languageSet = new HashSet<Character.UnicodeBlock>();
char[] valueArray = data.toCharArray();
for (int counter = 0; counter < valueArray.length; counter++) {
languageSet.add(Character.UnicodeBlock.of(valueArray[counter]));
}
return (new ArrayList<Character.UnicodeBlock>(languageSet));
}
public String createPDFFile(String title, String itemId) throws Exception {
String pdfLocationSystemParam = getParameterResolverInstance().getParameter(OLEConstants
.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT, OLEParameterConstants.PDF_LOCATION);
if (LOG.isDebugEnabled()) {
LOG.debug("System Parameter for PDF_Location --> " + pdfLocationSystemParam);
}
if (pdfLocationSystemParam == null || pdfLocationSystemParam.trim().isEmpty()) {
pdfLocationSystemParam = ConfigContext.getCurrentContextConfig().getProperty("staging.directory") + "/";
if (LOG.isDebugEnabled()) {
LOG.debug("System Parameter for PDF_Location staging dir--> " + pdfLocationSystemParam);
}
} else {
pdfLocationSystemParam = ConfigContext.getCurrentContextConfig().getProperty("homeDirectory") + "/" + pdfLocationSystemParam + "/";
}
boolean locationExist = new File(pdfLocationSystemParam).exists();
boolean fileCreated = false;
if (LOG.isDebugEnabled()) {
LOG.debug("Is directory Exist ::" + locationExist);
}
try {
if (!locationExist) {
fileCreated = new File(pdfLocationSystemParam).mkdirs();
if (!fileCreated) {
throw new RuntimeException("Unable to create directory :" + pdfLocationSystemParam);
}
}
} catch (Exception e) {
LOG.error("Exception occurred while creating the directory : " + e.getMessage(), e);
throw e;
}
if (title == null || title.trim().isEmpty()) {
title = OLEConstants.ITEM_TITLE;
}
title = title.replaceAll(" ", "_");
if (itemId == null || itemId.trim().isEmpty()) {
itemId = OLEConstants.ITEM_ID;
}
String fileName = pdfLocationSystemParam + title + "_" + itemId + "_" + (new Date(System.currentTimeMillis())).toString().replaceAll(":", "_") + ".pdf";
String unModifiedFileName = fileName;
fileName = fileName.replace(" ", "_");
if (LOG.isDebugEnabled()) {
LOG.debug("File Created :" + title + "file name ::" + fileName + "::");
}
return unModifiedFileName;
}
private SimpleDateFormat getSimpleDateFormat() {
if (null == simpleDateFormat) {
simpleDateFormat = new SimpleDateFormat(RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE + " " + RiceConstants.SIMPLE_DATE_FORMAT_FOR_TIME);
}
return simpleDateFormat;
}
public void setSimpleDateFormat(SimpleDateFormat simpleDateFormat) {
this.simpleDateFormat = simpleDateFormat;
}
private CircDeskLocationResolver getCircDeskLocationResolver() {
if (circDeskLocationResolver == null) {
circDeskLocationResolver = new CircDeskLocationResolver();
}
return circDeskLocationResolver;
}
public void setCircDeskLocationResolver(CircDeskLocationResolver circDeskLocationResolver) {
this.circDeskLocationResolver = circDeskLocationResolver;
}
private ParameterValueResolver getParameterResolverInstance() {
if (null == parameterResolverInstance) {
parameterResolverInstance = ParameterValueResolver.getInstance();
}
return parameterResolverInstance;
}
public void setParameterResolverInstance(ParameterValueResolver parameterResolverInstance) {
this.parameterResolverInstance = parameterResolverInstance;
}
}
| 45.870892 | 225 | 0.689371 |
448759d3679256a1a170338e2cbf53b554dacbd3 | 615 | import java.io.*;
import java.util.*;
public class epigdanceoff {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] arr = new int[m];
for (int x = 0; x < n; x++) {
char[] line = sc.next().toCharArray();
for (int a = 0; a < m; a++)
if (line[a] == '_')
arr[a]++;
}
int count = 0;
for (int x : arr)
if (x == n)
count++;
System.out.println(count + 1);
}
} | 27.954545 | 61 | 0.437398 |
e626adef459d2e7ee35a2ad2bdefa1896e989f0c | 857 | /*
* 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 br.com.dsc.cbi.apirest.rest.converters;
import br.com.dsc.cbi.apirest.util.Datas;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDateTime;
/**
*
* @author Tiago
*/
public class LocalDateTimeSerialiazer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
serializers.defaultSerializeValue(Datas.localDateTimeTomillis(value), gen);
}
}
| 31.740741 | 119 | 0.760793 |
22b21e00fbb622c96ed1b282feb60361d510d8ef | 2,847 | package com.mossle.form.operation;
import java.util.Map;
import com.mossle.bpm.cmd.CompleteTaskWithCommentCmd;
import com.mossle.core.spring.ApplicationContextHelper;
import com.mossle.form.keyvalue.KeyValue;
import com.mossle.form.keyvalue.Prop;
import com.mossle.form.keyvalue.Record;
import com.mossle.form.keyvalue.RecordBuilder;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.task.Task;
import org.springframework.util.Assert;
/**
* 保存草稿.
*/
public class SaveDraftOperation extends AbstractOperation<String> {
public static final String OPERATION_BUSINESS_KEY = "businessKey";
public static final String OPERATION_TASK_ID = "taskId";
public static final String OPERATION_BPM_PROCESS_ID = "bpmProcessId";
public static final int STATUS_DRAFT_PROCESS = 0;
public static final int STATUS_DRAFT_TASK = 1;
public static final int STATUS_RUNNING = 2;
public String execute(CommandContext commandContext) {
String taskId = getParameter(OPERATION_TASK_ID);
String businessKey = getParameter(OPERATION_BUSINESS_KEY);
String bpmProcessId = getParameter(OPERATION_BPM_PROCESS_ID);
KeyValue keyValue = getKeyValue();
if (this.notEmpty(taskId)) {
// 如果是任务草稿,直接通过processInstanceId获得record,更新数据
// TODO: 分支肯定有问题
Task task = getProcessEngine().getTaskService().createTaskQuery()
.taskId(taskId).singleResult();
if (task == null) {
throw new IllegalStateException("任务不存在");
}
String processInstanceId = task.getProcessInstanceId();
Record record = keyValue.findByRef(processInstanceId);
record = new RecordBuilder().build(record, STATUS_DRAFT_TASK,
getParameters());
keyValue.save(record);
businessKey = record.getCode();
} else if (this.notEmpty(businessKey)) {
// 如果是流程草稿,直接通过businessKey获得record,更新数据
Record record = keyValue.findByCode(businessKey);
record = new RecordBuilder().build(record, STATUS_DRAFT_PROCESS,
getParameters());
keyValue.save(record);
} else {
// 如果是第一次保存草稿,肯定是流程草稿,先初始化record,再保存数据
Record record = new RecordBuilder().build(bpmProcessId,
STATUS_DRAFT_PROCESS, getParameters());
keyValue.save(record);
businessKey = record.getCode();
}
return businessKey;
}
public boolean notEmpty(String str) {
return (str != null) && (!"".equals(str));
}
public KeyValue getKeyValue() {
return ApplicationContextHelper.getBean(KeyValue.class);
}
}
| 35.148148 | 77 | 0.672638 |
14b8236268f921f4489b45886fe923f4e565de1f | 5,668 | package uk.gov.hmcts.reform.adoption.common.service.task;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.gov.hmcts.ccd.sdk.api.CaseDetails;
import uk.gov.hmcts.reform.adoption.adoptioncase.model.CaseData;
import uk.gov.hmcts.reform.adoption.adoptioncase.model.LanguagePreference;
import uk.gov.hmcts.reform.adoption.adoptioncase.model.Nationality;
import uk.gov.hmcts.reform.adoption.adoptioncase.model.State;
import uk.gov.hmcts.reform.adoption.adoptioncase.task.CaseTask;
import uk.gov.hmcts.reform.adoption.document.CaseDataDocumentService;
import java.time.LocalDateTime;
import java.util.EnumSet;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static uk.gov.hmcts.reform.adoption.adoptioncase.model.State.Submitted;
import static uk.gov.hmcts.reform.adoption.document.DocumentConstants.ADOPTION_APPLICATION_FILE_NAME;
import static uk.gov.hmcts.reform.adoption.document.DocumentConstants.ADOPTION_APPLICATION_SUMMARY;
import static uk.gov.hmcts.reform.adoption.document.DocumentType.APPLICATION_SUMMARY_CY;
import static uk.gov.hmcts.reform.adoption.document.DocumentType.APPLICATION_SUMMARY_EN;
import static uk.gov.hmcts.reform.adoption.document.DocumentUtil.formatDocumentName;
@Component
@Slf4j
public class GenerateApplicationSummaryDocument implements CaseTask {
@Autowired
private CaseDataDocumentService caseDataDocumentService;
@Autowired
private ObjectMapper objectMapper;
@Override
public CaseDetails<CaseData, State> apply(CaseDetails<CaseData, State> caseDetails) {
final CaseData caseData = caseDetails.getData();
final Long caseId = caseDetails.getId();
final State state = caseDetails.getState();
@SuppressWarnings("unchecked")
Map<String, Object> templateContent = objectMapper.convertValue(caseData, Map.class);
if (caseData.getBirthMother() != null && caseData.getBirthMother().getNationality() != null) {
templateContent.put("birthMotherNationality", caseData.getBirthMother().getNationality().stream()
.filter(item -> item != Nationality.OTHER).collect(
Collectors.toCollection(TreeSet<Nationality>::new)));
}
if (caseData.getBirthFather() != null && caseData.getBirthFather().getNationality() != null) {
templateContent.put("birthFatherNationality", caseData.getBirthFather().getNationality().stream()
.filter(item -> item != Nationality.OTHER).collect(
Collectors.toCollection(TreeSet<Nationality>::new)));
}
if (caseData.getChildren() != null && caseData.getChildren().getNationality() != null) {
templateContent.put("childrenNationality", caseData.getChildren().getNationality().stream()
.filter(item -> item != Nationality.OTHER).collect(
Collectors.toCollection(TreeSet<Nationality>::new)));
}
if (EnumSet.of(Submitted).contains(state)) {
log.info("Generating summary document for caseId: {}", caseId);
final CompletableFuture<Void> appSummaryEn = CompletableFuture
.runAsync(() -> caseDataDocumentService.renderDocumentAndUpdateCaseData(caseData,
APPLICATION_SUMMARY_EN,
templateContent,
caseDetails.getId(),
ADOPTION_APPLICATION_SUMMARY,
LanguagePreference.ENGLISH,
formatDocumentName(caseDetails.getId(),
ADOPTION_APPLICATION_FILE_NAME,
LocalDateTime.now())));
final CompletableFuture<Void> appSummaryCy = CompletableFuture
.runAsync(() -> caseDataDocumentService.renderDocumentAndUpdateCaseData(caseData,
APPLICATION_SUMMARY_CY,
templateContent,
caseDetails.getId(),
ADOPTION_APPLICATION_SUMMARY,
LanguagePreference.WELSH,
formatDocumentName(caseDetails.getId(),
ADOPTION_APPLICATION_FILE_NAME,
LocalDateTime.now())));
CompletableFuture.allOf(appSummaryEn, appSummaryCy).join();
} else {
log.error("Could not generate summary document for caseId: {}", caseId);
}
return caseDetails;
}
}
| 59.663158 | 127 | 0.563338 |
6c2d04789662e5e17103142067904fa5e78560dd | 5,428 | package net.minecraft.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.realms.RealmsSimpleScrolledSelectionList;
import net.minecraft.util.MathHelper;
public class GuiSimpleScrolledSelectionListProxy extends GuiSlot {
private final RealmsSimpleScrolledSelectionList field_178050_u;
public GuiSimpleScrolledSelectionListProxy(RealmsSimpleScrolledSelectionList p_i45525_1_, int widthIn, int heightIn,
int topIn, int bottomIn, int slotHeightIn) {
super(Minecraft.getMinecraft(), widthIn, heightIn, topIn, bottomIn, slotHeightIn);
this.field_178050_u = p_i45525_1_;
}
protected int getSize() {
return this.field_178050_u.getItemCount();
}
/**
* The element in the slot that was clicked, boolean for whether it was double
* clicked or not
*/
protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY) {
this.field_178050_u.selectItem(slotIndex, isDoubleClick, mouseX, mouseY);
}
/**
* Returns true if the element passed in is currently selected
*/
protected boolean isSelected(int slotIndex) {
return this.field_178050_u.isSelectedItem(slotIndex);
}
protected void drawBackground() {
this.field_178050_u.renderBackground();
}
protected void drawSlot(int entryID, int p_180791_2_, int p_180791_3_, int p_180791_4_, int mouseXIn,
int mouseYIn) {
this.field_178050_u.renderItem(entryID, p_180791_2_, p_180791_3_, p_180791_4_, mouseXIn, mouseYIn);
}
public int getWidth() {
return super.width;
}
public int getMouseY() {
return super.mouseY;
}
public int getMouseX() {
return super.mouseX;
}
/**
* Return the height of the content being scrolled
*/
protected int getContentHeight() {
return this.field_178050_u.getMaxPosition();
}
protected int getScrollBarX() {
return this.field_178050_u.getScrollbarPosition();
}
public void handleMouseInput() {
super.handleMouseInput();
}
public void drawScreen(int mouseXIn, int mouseYIn, float p_148128_3_) {
if (this.field_178041_q) {
this.mouseX = mouseXIn;
this.mouseY = mouseYIn;
this.drawBackground();
int i = this.getScrollBarX();
int j = i + 6;
this.bindAmountScrolled();
GlStateManager.disableLighting();
GlStateManager.disableFog();
Tessellator tessellator = Tessellator.getInstance();
WorldRenderer worldrenderer = tessellator.getWorldRenderer();
int k = this.left + this.width / 2 - this.getListWidth() / 2 + 2;
int l = this.top + 4 - (int) this.amountScrolled;
if (this.hasListHeader) {
this.drawListHeader(k, l, tessellator);
}
this.drawSelectionBox(k, l, mouseXIn, mouseYIn);
GlStateManager.disableDepth();
int i1 = 4;
this.overlayBackground(0, this.top, 255, 255);
this.overlayBackground(this.bottom, this.height, 255, 255);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1);
GlStateManager.disableAlpha();
GlStateManager.shadeModel(7425);
GlStateManager.disableTexture2D();
int j1 = this.func_148135_f();
if (j1 > 0) {
int k1 = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight();
k1 = MathHelper.clamp_int(k1, 32, this.bottom - this.top - 8);
int l1 = (int) this.amountScrolled * (this.bottom - this.top - k1) / j1 + this.top;
if (l1 < this.top) {
l1 = this.top;
}
worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
worldrenderer.pos((double) i, (double) this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255)
.endVertex();
worldrenderer.pos((double) j, (double) this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255)
.endVertex();
worldrenderer.pos((double) j, (double) this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex();
worldrenderer.pos((double) i, (double) this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex();
tessellator.draw();
worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
worldrenderer.pos((double) i, (double) (l1 + k1), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255)
.endVertex();
worldrenderer.pos((double) j, (double) (l1 + k1), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255)
.endVertex();
worldrenderer.pos((double) j, (double) l1, 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex();
worldrenderer.pos((double) i, (double) l1, 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex();
tessellator.draw();
worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR);
worldrenderer.pos((double) i, (double) (l1 + k1 - 1), 0.0D).tex(0.0D, 1.0D).color(192, 192, 192, 255)
.endVertex();
worldrenderer.pos((double) (j - 1), (double) (l1 + k1 - 1), 0.0D).tex(1.0D, 1.0D)
.color(192, 192, 192, 255).endVertex();
worldrenderer.pos((double) (j - 1), (double) l1, 0.0D).tex(1.0D, 0.0D).color(192, 192, 192, 255)
.endVertex();
worldrenderer.pos((double) i, (double) l1, 0.0D).tex(0.0D, 0.0D).color(192, 192, 192, 255).endVertex();
tessellator.draw();
}
this.func_148142_b(mouseXIn, mouseYIn);
GlStateManager.enableTexture2D();
GlStateManager.shadeModel(7424);
GlStateManager.enableAlpha();
GlStateManager.disableBlend();
}
}
}
| 36.186667 | 117 | 0.704127 |
df5d4efe9ffd8134b4ee6c67196484b0a2ba6079 | 471 | package org.cx.game.user.config;
import org.cx.game.user.dao.IDao;
import org.cx.game.user.domain.IEntity;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackageClasses = {IDao.class})
@EntityScan(basePackageClasses = {IEntity.class})
public class PersistenceConfig {
}
| 31.4 | 76 | 0.832272 |
7520f9a6e68c33c7257da7e6a47e9e088670a308 | 7,667 | package org.broadinstitute.ddp.service;
import static com.google.openlocationcode.OpenLocationCode.PADDING_CHARACTER;
import static java.util.stream.Collectors.toList;
import java.util.List;
import com.google.maps.model.GeocodingResult;
import com.google.openlocationcode.OpenLocationCode;
import org.apache.commons.lang3.StringUtils;
import org.broadinstitute.ddp.client.GoogleMapsClient;
import org.broadinstitute.ddp.db.dao.JdbiUmbrellaStudy;
import org.broadinstitute.ddp.db.dao.JdbiUserStudyEnrollment;
import org.broadinstitute.ddp.db.dto.StudyDto;
import org.broadinstitute.ddp.exception.DDPException;
import org.broadinstitute.ddp.model.address.MailAddress;
import org.broadinstitute.ddp.model.address.OLCPrecision;
import org.broadinstitute.ddp.model.study.ParticipantInfo;
import org.broadinstitute.ddp.model.study.StudyParticipantsInfo;
import org.jdbi.v3.core.Handle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OLCService {
public static final OLCPrecision DEFAULT_OLC_PRECISION = OLCPrecision.MOST;
private static final Logger LOG = LoggerFactory.getLogger(OLCService.class);
private static final int PRECISION_DELIMITER = 8;
private static final int FULL_PLUS_CODE_LENGTH = 11;
private final GoogleMapsClient maps;
/**
* For a given pluscode, make it as precise/generic as specified to hide exact address. This is done by
* incrementally removing specific values from end of pluscode and converting into 0's. For more information see:
* https://plus.codes/howitworks, also see: https://en.wikipedia.org/wiki/Open_Location_Code#Specification.
*
* @param plusCode the exact 11 character pluscode
* @param precision the degree of precision of the pluscode requested
* @return the (potentially) more vague pluscode address
*/
public static String convertPlusCodeToPrecision(String plusCode, OLCPrecision precision) {
if (OpenLocationCode.isValidCode(plusCode)) {
if (canConvertOLCToTargetPrecision(plusCode, precision)) {
String lessPreciseOlc = plusCode.substring(0, precision.getCodeLength())
+ StringUtils.repeat("0", PRECISION_DELIMITER - precision.getCodeLength());
if (!lessPreciseOlc.endsWith("+") && lessPreciseOlc.length() < FULL_PLUS_CODE_LENGTH) {
lessPreciseOlc = lessPreciseOlc.concat("+");
}
return lessPreciseOlc;
} else {
throw new DDPException("Plus code " + plusCode + " is not precise enough to convert"
+ " to desired precision.");
}
} else if (StringUtils.isEmpty(plusCode)) {
return plusCode;
} else {
throw new DDPException("Pluscode " + plusCode + " is not valid.");
}
}
private static boolean canConvertOLCToTargetPrecision(String plusCode, OLCPrecision targetPrecision) {
// we can always convert to a lower precision from the most precise
if (plusCode.length() == FULL_PLUS_CODE_LENGTH) {
return true;
}
int indexOfPaddingChar = plusCode.indexOf(PADDING_CHARACTER);
int indexOfTargetPaddingChar = targetPrecision.getCodeLength();
// can convert a MORE precise OLC to anything other than MOST precise
if (indexOfPaddingChar == -1) {
return targetPrecision != OLCPrecision.MOST;
} else if (indexOfPaddingChar >= indexOfTargetPaddingChar) {
// otherwise, all other precisions have padding so we need to make sure the padding is at
// least as long as (if not longer than) the target valid char length we want
return true;
} else {
return false;
}
}
/**
* For a study, get all OLCs (repeat identical ones) for enrolled participants.
*
* @param studyGuid the study guid
* @return the enrolled participant information object
*/
public static StudyParticipantsInfo getAllOLCsForEnrolledParticipantsInStudy(Handle handle, String studyGuid) {
StudyDto studyDto = handle.attach(JdbiUmbrellaStudy.class).findByStudyGuid(studyGuid);
if (!studyDto.isPublicDataSharingEnabled()) {
LOG.error("Study " + studyGuid + " does not allow location sharing.");
return null;
}
OLCPrecision precision = studyDto.getOlcPrecision();
if (precision == null) {
LOG.error("Study " + studyGuid + " has location sharing enabled but no plus code precision set in database.");
return null;
}
List<String> olcsForStudy = handle.attach(JdbiUserStudyEnrollment.class).findAllOLCsForEnrolledParticipantsInStudy(studyGuid);
return new StudyParticipantsInfo(
olcsForStudy
.stream()
.map(olc -> new ParticipantInfo(convertPlusCodeToPrecision(olc, precision)))
.collect(toList())
);
}
public OLCService(String geocodingKey) {
this(new GoogleMapsClient(geocodingKey));
}
public OLCService(GoogleMapsClient mapsClient) {
this.maps = mapsClient;
}
/**
* Make call to Google geocoding API with a written out address, get plus code
*
* @param fullAddress the mail address to calculate the plus code of
* @param precision the pluscode precision desired. see {@link OLCPrecision}
* @return the corresponding plus code at the specified precision
*/
public String calculatePlusCodeWithPrecision(String fullAddress, OLCPrecision precision) {
var res = maps.lookupGeocode(fullAddress);
if (res.getStatusCode() != 200) {
var e = res.hasThrown() ? res.getThrown() : res.getError();
LOG.warn("Location: " + fullAddress + " could not be found on google maps services", e);
return null;
}
GeocodingResult[] results = res.getBody();
String plusCode;
if (results.length != 1) {
LOG.warn("Address: " + fullAddress + " had " + results.length + " results so we could not support assigning a pluscode");
return null;
} else if (results[0].plusCode == null) {
double lat = results[0].geometry.location.lat;
double lng = results[0].geometry.location.lng;
plusCode = OpenLocationCode.encode(lat, lng);
} else {
plusCode = results[0].plusCode.globalCode;
}
return convertPlusCodeToPrecision(plusCode, precision);
}
/**
* Override function for calculatePlusCodeWithPrecision to be used when given a {@link MailAddress} object
*
* @param mailAddress the mail address to calculate the plus code of
* @param precision the pluscode precision desired. see {@link OLCPrecision}
* @return the corresponding plus code at the specified precision
*/
public String calculatePlusCodeWithPrecision(MailAddress mailAddress, OLCPrecision precision) {
String fullAddress = mailAddress.toAddressString();
return calculatePlusCodeWithPrecision(fullAddress, precision);
}
/**
* Override function for calculatePlusCodeWithPrecision to be used when calculating the plus code for a new/ updated address.
*
* @param mailAddress the mail address to calculate the plus code of
* @return the corresponding exact plus code to the highest precision
*/
public String calculateFullPlusCode(MailAddress mailAddress) {
return calculatePlusCodeWithPrecision(mailAddress, OLCPrecision.MOST);
}
}
| 43.5625 | 134 | 0.678753 |
a101ebe31948c4d057041b99c6945c80328b6193 | 967 | package core;
import java.io.IOException;
public class Core {
public enum Status
{
Ready,
Listening,
Busy,
}
// public static state variable to determine in other scripts of what our voice assistant is doing
public static Status currentState = Status.Ready;
// our main initialisation method that will load our modules and other classes
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Audio testing
//AudioHandler.Play(AudioHandler.AudioType.Listening, true);
//AudioHandler.Play(AudioHandler.AudioType.Working, true);
//AudioHandler.Play(AudioHandler.AudioType.Working, true);
//AudioHandler.Play(AudioHandler.AudioType.Working, true);
AudioHandler.Play(AudioHandler.AudioType.Error, true);
// Initialize the Speech Synthesis Handler
SpeechSynthesisHandler.Initialize();
// Initialise the Speech Recognition Engine
SpeechRecognitionHandler.Initialize();
}
}
| 26.135135 | 99 | 0.755946 |
22f761906b0be6760b5a28cc4b3a992c86f2e759 | 4,031 | /*
* 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.beam.runners.core.metrics;
import static org.apache.beam.vendor.guava.v20_0.com.google.common.base.Preconditions.checkArgument;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import org.apache.beam.model.pipeline.v1.MetricsApi;
import org.apache.beam.sdk.metrics.MetricName;
import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Strings;
/**
* An implementation of {@code MetricKey} based on a MonitoringInfo's URN and label to represent the
* key instead of only a name+namespace. This is useful when defining system defined metrics with a
* specific urn via a {@code CounterContainer}.
*/
public class MonitoringInfoMetricName extends MetricName {
private String urn;
private Map<String, String> labels = new HashMap<String, String>();
private MonitoringInfoMetricName(String urn, Map<String, String> labels) {
checkArgument(!Strings.isNullOrEmpty(urn), "MonitoringInfoMetricName urn must be non-empty");
checkArgument(labels != null, "MonitoringInfoMetricName labels must be non-null");
// TODO(ajamato): Move SimpleMonitoringInfoBuilder to :runners:core-construction-java
// and ensure all necessary labels are set for the specific URN.
this.urn = urn;
for (Entry<String, String> entry : labels.entrySet()) {
this.labels.put(entry.getKey(), entry.getValue());
}
}
@Override
public String getNamespace() {
if (labels.containsKey(MonitoringInfoConstants.Labels.NAMESPACE)) {
return labels.getOrDefault(MonitoringInfoConstants.Labels.NAMESPACE, null);
} else {
return urn.split(":", 2)[0];
}
}
@Override
public String getName() {
if (labels.containsKey(MonitoringInfoConstants.Labels.NAME)) {
return labels.getOrDefault(MonitoringInfoConstants.Labels.NAME, null);
} else {
return urn.split(":", 2)[1];
}
}
/** @return the urn of this MonitoringInfo metric. */
public String getUrn() {
return this.urn;
}
/** @return The labels associated with this MonitoringInfo. */
public Map<String, String> getLabels() {
return this.labels;
}
public static MonitoringInfoMetricName of(MetricsApi.MonitoringInfo mi) {
return new MonitoringInfoMetricName(mi.getUrn(), mi.getLabelsMap());
}
public static MonitoringInfoMetricName named(String urn, HashMap<String, String> labels) {
return new MonitoringInfoMetricName(urn, labels);
}
@Override
public int hashCode() {
// Don't include name and namespace, since they are lazily set.
return Objects.hash(urn, labels);
}
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
if (!(o instanceof MonitoringInfoMetricName)) {
return false;
}
MonitoringInfoMetricName other = (MonitoringInfoMetricName) o;
return this.urn.equals(other.urn) && this.labels.equals(other.labels);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.urn.toString());
builder.append(" ");
builder.append(this.labels.toString());
return builder.toString();
}
}
| 35.052174 | 100 | 0.724138 |
72d41edb4e2d402b5a7e44ad0084c1e53434a877 | 1,686 | /*
* Copyright 2006-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.dsl.endpoint;
import com.consol.citrus.endpoint.Endpoint;
import com.consol.citrus.endpoint.EndpointBuilder;
/**
* @author Christoph Deppisch
* @since 2.5
*/
public class AsyncSyncEndpointBuilder<A extends EndpointBuilder<? extends Endpoint>, S extends EndpointBuilder<? extends Endpoint>> {
private final A asyncEndpointBuilder;
private final S syncEndpointBuilder;
/**
* Default constructor setting the sync and async builder implementation.
* @param asyncEndpointBuilder
* @param syncEndpointBuilder
*/
public AsyncSyncEndpointBuilder(A asyncEndpointBuilder, S syncEndpointBuilder) {
this.asyncEndpointBuilder = asyncEndpointBuilder;
this.syncEndpointBuilder = syncEndpointBuilder;
}
/**
* Gets the async endpoint builder.
* @return
*/
public A asynchronous() {
return asyncEndpointBuilder;
}
/**
* Gets the sync endpoint builder.
* @return
*/
public S synchronous() {
return syncEndpointBuilder;
}
}
| 29.578947 | 133 | 0.711151 |
82a198cf358e255a6b8b514d74be380d25c14205 | 1,465 | package jp.chang.myclinic.scanner;
import jp.chang.wia.Wia;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.function.Consumer;
class ScannerLib {
//private static Logger logger = LoggerFactory.getLogger(ScannerLib.class);
private ScannerLib() {
}
static String getScannerDevice(Consumer<String> alertFunc){
String deviceId = getScannerDeviceSetting();
if( deviceId == null ){
deviceId = chooseScannerDevice(alertFunc);
}
return deviceId;
}
static String getScannerDeviceSetting(){
String deviceId = Globals.defaultDevice;
if( !"".equals(deviceId) ){
return deviceId;
} else {
return null;
}
}
static String chooseScannerDevice(Consumer<String> alertFunc){
List<Wia.Device> devices = Wia.listDevices();
if (devices.size() == 0) {
alertFunc.accept("接続された。スキャナーがみつかりません。");
return null;
} else if (devices.size() == 1) {
return devices.get(0).deviceId;
} else {
return Wia.pickScannerDevice();
}
}
static boolean convertImage(Path source, String format, Path output) throws IOException {
BufferedImage src = ImageIO.read(source.toFile());
return ImageIO.write(src, format, output.toFile());
}
}
| 26.636364 | 93 | 0.631399 |
e48758180f920010d5d86ea0a794a726522cae19 | 797 | package me.olmaneuh.blog.post;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(SpringExtension.class)
@DataJpaTest
class PostRepositoryTest {
@Autowired
private PostRepository repository;
@BeforeAll
static void initAll() {
}
@Test
void ShouldReturnAllPublicPosts() {
List<Post> results = repository.findByIsPrivateFalse();
assertEquals(0, results.size());
}
}
| 24.151515 | 71 | 0.766625 |
526bbea40d715dcfcd2ebad414e585985498f343 | 2,182 | package javacommon.base;
import static junit.framework.Assert.assertNotNull;
import javax.sql.DataSource;
import org.junit.Before;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.util.ResourceUtils;
import cn.org.rapid_framework.test.context.TestMethodContextExecutionListener;
import cn.org.rapid_framework.test.dbunit.DBUnitFlatXmlHelper;
/**
* 本基类主要为子类指定好要装载的spring配置文件
* 及在运行测试前通过dbunit插入测试数据在数据库中,运行完测试删除测试数据
*
* @author badqiu
* 请设置好要装载的spring配置文件,一般开发数据库与测试数据库分开
* 所以你要装载的资源文件应改为"classpath:/spring/*-test-resource.xml"
*/
@ContextConfiguration(locations={"classpath:/spring/*-resource.xml",
"classpath:/spring/*-validator.xml",
"classpath:/spring/*-datasource.xml",
"classpath:/spring/*-dao.xml",
})
@TestExecutionListeners(listeners = TestMethodContextExecutionListener.class) // TestMethodContextExecutionListener用于在@Before时可以得到测试方法名称
public class BaseDaoTestCase extends AbstractTransactionalJUnit4SpringContextTests {
protected DBUnitFlatXmlHelper dbUnitHelper = new DBUnitFlatXmlHelper();
protected DataSource getDataSource() {
DataSource ds = (DataSource)applicationContext.getBean("dataSource");
assertNotNull("not found 'dataSource'",ds);
return ds;
}
@Before
public void onSetUpInsertTestDatas() throws Exception {
String jdbcSchema = null; // set schema for oracle,出现AmbiguousTableNameException时,使用命令:purge recyclebin清空一下oracle回收站
dbUnitHelper.setDataSource(getDataSource(),jdbcSchema);
dbUnitHelper.insertTestDatas(getDbUnitDataFiles());
}
/** 得到要加载的dbunit文件 */
protected String[] getDbUnitDataFiles() {
return null;
}
protected void insertTestData(String classpathFileName) {
try {
dbUnitHelper.insertTestData(ResourceUtils.getFile("classpath:"+classpathFileName));
}catch(Exception e) {
throw new RuntimeException("insertTestData error,classpathFileName:"+classpathFileName,e);
}
}
}
| 35.770492 | 136 | 0.766269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.