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
|
|---|---|---|---|---|---|
bc39f5385fc7f2aacc94a417daf2aeae987a5d94
| 863
|
package br.com.lucasfuck.vacancy.entity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity(name = "person_correlation")
@Getter @Setter
@NoArgsConstructor
public class PersonCorrelation {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "person")
private Person person;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "correlation")
private Correlation correlation;
@Column(name = "level")
private int level;
}
| 24.657143
| 59
| 0.771727
|
ff6040286b72588a8e418aa2d9c27ec14a00bea1
| 802
|
package be.ugent.progress;
public interface TaskProgressListener {
/**
* Informs the listener of the progress of a task.
*
* @param task
* the name of the task
* @param message
* a message about the progress
* @param level
* a number between 0 and 1, 0 indicating no progress, 1
* indicating done
*/
void notifyProgress(String task, String message, float level);
/**
* Informs the listener that the specified task is finished.
*
* @param task
* the name of the task
*/
void notifyFinished(String task);
/**
* Informs the listener that the specified task was aborted or failed.
* @param task
*/
void notifyFailed(String task);
}
| 25.870968
| 74
| 0.578554
|
cb9e9fb4523aaae768c1776a3eb1451b52ff49e8
| 685
|
package io.renren.modules.app.dao.friend;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import io.renren.modules.app.dto.CommentDto;
import io.renren.modules.app.entity.friend.FriendShareCommentEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.HashMap;
import java.util.List;
/**
* @author xukaijun
* @email 383635738@qq.com
* @date 2019-03-02 09:38:43
*/
@Mapper
public interface FriendShareCommentDao extends BaseMapper<FriendShareCommentEntity> {
List<CommentDto> getPage(HashMap params);
List<CommentDto> querySubThroughParentId(@Param("fsmId") Long fsmId,@Param("parentId") Long parentId);
}
| 27.4
| 106
| 0.785401
|
626538bf194f3ef4f469db6084f3a9ca3e1959cf
| 129
|
package designpatterns.observer.java;
public interface ValueObserver {
void notifyChange(String oldText, String newText);
}
| 21.5
| 54
| 0.79845
|
d36fc0810d094c512421f24e367b34b8ad7d23fb
| 4,405
|
package setadokalo.customfog.gui;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.jetbrains.annotations.Nullable;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.text.TranslatableText;
import setadokalo.customfog.CustomFog;
import setadokalo.customfog.CustomFogConfig;
import setadokalo.customfog.DimensionConfig;
public class CustomFogConfigScreen extends Screen {
private final Screen parent;
protected DimensionConfigListWidget lWidget;
protected double value = 0.0;
private static final int HEADER_HEIGHT = 25;
private static final int FOOTER_HEIGHT = 40;
public CustomFogConfigScreen(@Nullable Screen parent) {
super(new TranslatableText("screen.customfog.config"));
this.parent = parent;
}
@Override
protected void init() {
super.init();
// the first entry in the list should always be the default config, that applies to any dimension without a more specific config
if (lWidget == null) {
createList(HEADER_HEIGHT, FOOTER_HEIGHT);
} else {
lWidget.updateSize(width, height, HEADER_HEIGHT, height - FOOTER_HEIGHT);
this.children.add(lWidget);
}
// Add load button.
this.addButton(new ButtonWidget(9, this.height - 29, 80, 20, new TranslatableText("button.customfog.load"),
btn -> {
CustomFog.config = CustomFogConfig.getConfig();
this.createList(HEADER_HEIGHT, FOOTER_HEIGHT);
}));
// Add done button.
int doneButtonX = Math.max(this.width / 2 - 100, 94);
this.addButton(new ButtonWidget(doneButtonX, this.height - 29, Math.min(200, this.width - (doneButtonX + 5)), 20, new TranslatableText("button.customfog.saveandquit"),
btn -> saveDimensionNames()));
}
private void saveDimensionNames() {
for (DimensionConfigEntry entry : this.lWidget.children()) {
saveDimensionName(entry);
}
CustomFog.config.saveConfig();
this.client.openScreen(this.parent);
}
private void saveDimensionName(DimensionConfigEntry entry) {
if (entry.dimensionId != null && !entry.dimensionId.isEmpty()) {
if (entry.originalDimId != null) {
if (entry.dimensionId.equals("Default")) {
CustomFog.config.defaultConfig = entry.config;
} else {
try {
CustomFogConfig.changeKey(CustomFog.config, entry.originalDimId, entry.dimensionId);
} catch (NullPointerException e) {
CustomFog.log(Level.ERROR, "Failed to update key - invalid original key " + entry.originalDimId);
}
}
} else {
CustomFogConfig.add(CustomFog.config, entry.dimensionId, entry.config);
}
}
}
private void createList(int headerHeight, int footerHeight) {
this.children.remove(lWidget);
DimensionConfigListWidget list = new DimensionConfigListWidget(
client, // the client
0, // x pos
headerHeight, // y pos
width, //width
height - (headerHeight + footerHeight), //height
25, // line height (height of each entry in the list)
this, // parent screen (of the widget)
this.textRenderer // text renderer to use
);
list.add(new DimensionConfigEntry(list, false, "Default", CustomFog.config.defaultConfig));
// for (int _i = 0; _i < 2; _i++)
// list.add(new DimensionConfigEntry(list, true, "Default", CustomFog.config.defaultConfig));
for (Map.Entry<String, DimensionConfig> config : CustomFog.config.dimensions.entrySet()) {
list.add(new DimensionConfigEntry(list, true, config.getKey(), config.getValue()));
}
// The Add Button - constructed by a magic constructor. I know it's bad, shut up.
list.add(new DimensionConfigEntry(list));
lWidget = list;
// while rendering is done manually, it is important that the list widget is in the list of children
// without adding it to the list, click and scroll events do not propogate
this.addChild(lWidget);
}
@Override
public void tick() {
super.tick();
this.lWidget.tick();
}
@Override
public void render(MatrixStack matrices, int mouseX, int mouseY, float delta)
{
this.renderBackground(matrices);
lWidget.render(matrices, mouseX, mouseY, delta);
super.render(matrices, mouseX, mouseY, delta);
// Draw the title text.
drawCenteredText(matrices, this.textRenderer, this.title, this.width / 2, 8, 0xFFFFFF);
}
public void openScreen(DimensionConfigScreen dimensionConfigScreen) {
client.openScreen(dimensionConfigScreen);
}
}
| 35.24
| 169
| 0.730079
|
92968e6ec0d672faeb06db4ccddf0acc4f3a909b
| 11,683
|
package com.guider.healthring.w30s.activity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.guider.healthring.MyApp;
import com.guider.healthring.R;
import com.guider.healthring.siswatch.WatchBaseActivity;
import com.suchengkeji.android.w30sblelibrary.utils.SharedPreferenceUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RequestExecutor;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* @aboutContent:
* @author: An
* @crateTime: 2018/3/16 11:55
* @mailBox: an.****.life@gmail.com
* @company: 东莞速成科技有限公司
*/
public class W30SReminderActivity extends WatchBaseActivity implements CompoundButton.OnCheckedChangeListener {
private static final int REQD_MSG_CONTENT_CODE = 1001; //读取短信内容权限code
private static final int REQUEST_REQDPHONE_STATE_CODE = 1002;
private static final String BOZLUN_PACKNAME_EN = "com.bozlun.bozhilun.android";
@BindView(R.id.switch_Skype)
Switch switchSkype;
@BindView(R.id.switch_WhatsApp)
Switch switchWhatsApp;
@BindView(R.id.switch_Facebook)
Switch switchFacebook;
@BindView(R.id.switch_LinkendIn)
Switch switchLinkendIn;
@BindView(R.id.switch_Twitter)
Switch switchTwitter;
@BindView(R.id.switch_Viber)
Switch switchViber;
@BindView(R.id.switch_LINE)
Switch switchLINE;
@BindView(R.id.switch_WeChat)
Switch switchWeChat;
@BindView(R.id.switch_QQ)
Switch switchQQ;
@BindView(R.id.switch_Msg)
Switch switchMsg;
@BindView(R.id.switch_Phone)
Switch switchPhone;
@BindView(R.id.watch_msgOpenAccessBtn)
RelativeLayout watch_msgOpenAccessBtn;
@BindView(R.id.newSearchTitleTv)
TextView newSearchTitleTv;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_w30s_reminder);
ButterKnife.bind(this);
newSearchTitleTv.setText(getResources().getString(R.string.string_application_reminding));
watch_msgOpenAccessBtn.setVisibility(View.GONE);
getSwitchState();
initSwitch();
}
private void getSwitchState() {
boolean w30sswitch_skype = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_Skype", false);
boolean w30sswitch_whatsApp = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_WhatsApp", false);
boolean w30sswitch_facebook = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_Facebook", false);
boolean w30sswitch_linkendIn = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_LinkendIn", false);
boolean w30sswitch_twitter = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_Twitter", false);
boolean w30sswitch_viber = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_Viber", false);
boolean w30sswitch_line = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_LINE", false);
boolean w30sswitch_weChat = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_WeChat", false);
boolean w30sswitch_qq = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_QQ", false);
boolean w30sswitch_msg = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_Msg", false);
boolean w30sswitch_Phone = (boolean) SharedPreferenceUtil.get(W30SReminderActivity.this, "w30sswitch_Phone", false);
switchSkype.setChecked(w30sswitch_skype);
switchWhatsApp.setChecked(w30sswitch_whatsApp);
switchFacebook.setChecked(w30sswitch_facebook);
switchLinkendIn.setChecked(w30sswitch_linkendIn);
switchTwitter.setChecked(w30sswitch_twitter);
switchViber.setChecked(w30sswitch_viber);
switchLINE.setChecked(w30sswitch_line);
switchWeChat.setChecked(w30sswitch_weChat);
switchQQ.setChecked(w30sswitch_qq);
switchMsg.setChecked(w30sswitch_msg);
switchPhone.setChecked(w30sswitch_Phone);
}
private void initSwitch() {
switchSkype.setOnCheckedChangeListener(this);
switchWhatsApp.setOnCheckedChangeListener(this);
switchFacebook.setOnCheckedChangeListener(this);
switchLinkendIn.setOnCheckedChangeListener(this);
switchTwitter.setOnCheckedChangeListener(this);
switchViber.setOnCheckedChangeListener(this);
switchLINE.setOnCheckedChangeListener(this);
switchWeChat.setOnCheckedChangeListener(this);
switchQQ.setOnCheckedChangeListener(this);
switchMsg.setOnCheckedChangeListener(this);
switchPhone.setOnCheckedChangeListener(this);
}
@OnClick({R.id.watch_msgOpenNitBtn,R.id.newSearchTitleLeft,
R.id.watch_msgOpenAccessBtn,R.id.newSearchRightImg1})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.newSearchTitleLeft:
finish();
break;
case R.id.watch_msgOpenNitBtn:
Intent intentr = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
startActivityForResult(intentr, 101);
break;
case R.id.watch_msgOpenAccessBtn:
Intent ints = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivityForResult(ints, 102);
break;
case R.id.newSearchRightImg1: //进入权限界面
String appPackName = getPackageName();
String contentTx = "Please open the required permissions";
Log.e("包名","------appName="+appPackName);
if(appPackName != null && appPackName.equals(BOZLUN_PACKNAME_EN)){
contentTx = "Please open the required permissions";
}else{
contentTx = "请打开所需权限";
}
new MaterialDialog.Builder(this)
.title(getResources().getString(R.string.prompt))
.content(contentTx)
.positiveText(getResources().getString(R.string.confirm))
.negativeText(getResources().getString(R.string.cancle))
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}).show();
break;
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.switch_Skype:
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_Skype", isChecked);
break;
case R.id.switch_WhatsApp:
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_WhatsApp", isChecked);
break;
case R.id.switch_Facebook:
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_Facebook", isChecked);
break;
case R.id.switch_LinkendIn:
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_LinkendIn", isChecked);
break;
case R.id.switch_Twitter:
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_Twitter", isChecked);
break;
case R.id.switch_Viber:
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_Viber", isChecked);
break;
case R.id.switch_LINE:
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_LINE", isChecked);
break;
case R.id.switch_WeChat: //微信
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_WeChat", isChecked);
break;
case R.id.switch_QQ: //QQ
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_QQ", isChecked);
break;
case R.id.switch_Msg: //短信
if(!AndPermission.hasPermissions(W30SReminderActivity.this,new String[] {
// Manifest.permission.READ_SMS,
Manifest.permission.READ_CONTACTS})){
AndPermission.with(W30SReminderActivity.this)
.runtime()
.permission(
// Manifest.permission.READ_SMS,
Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_CONTACTS)
.start();
}
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_Msg", isChecked);
break;
case R.id.switch_Phone: //来电
if(!AndPermission.hasPermissions(W30SReminderActivity.this,new String[]{Manifest.permission.CALL_PHONE,Manifest.permission.READ_PHONE_STATE})){
AndPermission.with(W30SReminderActivity.this)
.runtime()
.permission(Manifest.permission.CALL_PHONE,Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_CONTACTS)
.rationale(new Rationale<List<String>>() {
@Override
public void showRationale(Context context, List<String> data, RequestExecutor executor) {
executor.execute();
}
})
.start();
}
MyApp.getmW30SBLEManage().SendAnddroidLanguage(0x01);
SharedPreferenceUtil.put(W30SReminderActivity.this, "w30sswitch_Phone", isChecked);
break;
}
}
/**
* 动态申请权限回调
*/
// private PermissionListener permissionListener = new PermissionListener() {
// @Override
// public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
// switch (requestCode) {
//
// }
// }
//
// @Override
// public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
// switch (requestCode) {
// case REQD_MSG_CONTENT_CODE:
//
// break;
// }
// AndPermission.hasAlwaysDeniedPermission(W30SReminderActivity.this, deniedPermissions);
// }
// };
}
| 45.815686
| 159
| 0.646153
|
0266c63dec842f3c46d2e94d89998e8a21162640
| 2,800
|
/**
* Exom-Legacy (https://github.com/UnexomWid/Exom-Legacy)
*
* This project is licensed under the MIT license.
* Copyright (c) 2017-2019 UnexomWid (https://uw.exom.dev)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package Exom.Utils;
import java.math.BigInteger;
/**
* Contains methods used for mathematical calculations.
*
* @author UnexomWid
*
* @since 1.0
*/
public class MathUtils {
/**
* Interpolates two values with a given alpha.
* @param x0 The first value.
* @param x1 The second value.
* @param alpha The alpha.
*
* @return The interpolation result.
*
* @since 1.0
*/
public static float Interpolate(float x0, float x1, float alpha)
{
return x0 * (1 - alpha) + alpha * x1;
}
/**
* Checks whether or not a number is prime.
*
* @param x The number to check.
*
* @return Whether or not the number is prime.
*
* @since 1.0
*/
public static boolean IsPrime(long x) {
if(x < 2)
return false;
if(x < 4 || x == 5)
return true;
if(x % 2 == 0 || x % 3 == 0 || x % 5 == 0)
return false;
long sqrt = (long)Math.sqrt(x);
for(long u = 6; u <= sqrt; u += 6)
if(x % (u - 1) == 0 || x % (u + 1) == 0)
return false;
return true;
}
/**
* Computes n-factorial.
*
* @param n The number.
*
* @return n-factorial.
*
* @since 1.0
*/
public static BigInteger Factorial(int n) {
if(n < 0)
throw new IllegalArgumentException("The number cannot be negative.");
if(n < 2)
return BigInteger.ONE;
long sum = n;
BigInteger result = BigInteger.valueOf(n);
for (int i = n - 2; i > 1; i -= 2) {
sum += i;
result = result.multiply(BigInteger.valueOf(sum));
}
if (n % 2 != 0)
result = result.multiply(BigInteger.valueOf(n / 2 + 1));
return result;
}
}
| 27.45098
| 107
| 0.663571
|
396334afce5d3bd12fc41e2e2bc2d6b3901b82c8
| 5,296
|
package com.softicar.platform.core.module.file.stored.hash;
import com.softicar.platform.common.core.annotations.Generated;
import com.softicar.platform.core.module.file.stored.AGStoredFile;
import com.softicar.platform.db.core.DbResultSet;
import com.softicar.platform.db.runtime.query.AbstractDbQuery;
import com.softicar.platform.db.runtime.query.AbstractDbQueryRow;
import com.softicar.platform.db.runtime.query.DbQueryTableStubColumn;
import com.softicar.platform.db.runtime.query.IDbQuery;
import com.softicar.platform.db.runtime.query.IDbQueryColumn;
import com.softicar.platform.db.runtime.query.IDbQueryFactory;
import com.softicar.platform.db.runtime.query.IDbQueryRow;
import com.softicar.platform.db.runtime.query.IDbQueryTableColumn;
import com.softicar.platform.db.runtime.query.builder.AbstractDbQuerySqlBuilder;
import com.softicar.platform.db.runtime.select.IDbSqlSelect;
import com.softicar.platform.db.sql.token.SqlKeyword;
import com.softicar.platform.db.sql.token.SqlSymbol;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
@Generated
@SuppressWarnings("all")
public interface IStoredFileSha1Query extends IDbQuery<IStoredFileSha1Query.IRow> {
// -------------------------------- CONSTANTS -------------------------------- //
IDbQueryTableColumn<IRow, AGStoredFileSha1> SHA_1_COLUMN = new DbQueryTableStubColumn<>(IRow::getSha1, "sha1", AGStoredFileSha1.TABLE);
IDbQueryTableColumn<IRow, AGStoredFile> FILE_COLUMN = new DbQueryTableStubColumn<>(IRow::getFile, "file", AGStoredFile.TABLE);
IFactory FACTORY = new Implementation.Factory();
// -------------------------------- INTERFACES -------------------------------- //
interface IRow extends IDbQueryRow<IRow> {
AGStoredFileSha1 getSha1();
AGStoredFile getFile();
}
interface IFactory extends IDbQueryFactory<IRow> {
IFilesSetter createQuery();
}
interface IFilesSetter {
IStoredFileSha1Query setFiles(AGStoredFile... files);
IStoredFileSha1Query setFiles(Collection<? extends AGStoredFile> files);
}
// -------------------------------- IMPLEMENTATION -------------------------------- //
class Implementation {
private static class Factory implements IFactory {
private List<IDbQueryColumn<IRow, ?>> columns = new ArrayList<>(2);
public Factory() {
this.columns.add(SHA_1_COLUMN);
this.columns.add(FILE_COLUMN);
}
@Override
public IFilesSetter createQuery() {
return new Query().new FilesSetter();
}
@Override
public List<IDbQueryColumn<IRow, ?>> getColumns() {
return columns;
}
}
private static class Parameters {
private List<AGStoredFile> files = new ArrayList<>();
}
private static class Query extends AbstractDbQuery<IRow> implements IStoredFileSha1Query {
private final Parameters parameters = new Parameters();
@Override
public IRow createRow(IDbSqlSelect select, DbResultSet resultSet) {
return new Row(this, select, resultSet);
}
@Override
public List<IDbQueryColumn<IRow, ?>> getColumns() {
return FACTORY.getColumns();
}
@Override
public QuerySqlBuilder createSqlBuilder() {
return new QuerySqlBuilder();
}
public class FilesSetter implements IFilesSetter {
@Override
@SafeVarargs
public final IStoredFileSha1Query setFiles(AGStoredFile... files) {
return this.setFiles(Arrays.asList(files));
}
@Override
public final IStoredFileSha1Query setFiles(Collection<? extends AGStoredFile> files) {
Query.this.parameters.files.addAll(files);
return Query.this;
}
}
private class QuerySqlBuilder extends AbstractDbQuerySqlBuilder {
public void buildOriginalSelect() {
SELECT(SHA_1_COLUMN);
addIdentifier("sha1", AGStoredFileSha1.ID);
addToken(SqlKeyword.AS);
addIdentifier("sha1");
SELECT(FILE_COLUMN);
addIdentifier("file", AGStoredFile.ID);
addToken(SqlKeyword.AS);
addIdentifier("file");
FROM();
addIdentifier(AGStoredFile.TABLE);
addToken(SqlKeyword.AS);
addIdentifier("file");
JOIN(null);
addIdentifier(AGStoredFileSha1.TABLE);
addToken(SqlKeyword.AS);
addIdentifier("sha1");
ON();
addIdentifier("file", AGStoredFile.SHA_1);
addToken(SqlSymbol.EQUAL);
addIdentifier("sha1", AGStoredFileSha1.ID);
WHERE();
if(parameters.files.isEmpty()) {
addToken(SqlKeyword.FALSE);
} else {
addIdentifier("file", AGStoredFile.ID);
addToken(SqlKeyword.IN);
addToken(SqlSymbol.LEFT_PARENTHESIS);
addParameters(parameters.files);
addToken(SqlSymbol.RIGHT_PARENTHESIS);
}
}
}
}
private static class Row extends AbstractDbQueryRow<IRow> implements IRow {
private final AGStoredFileSha1 sha1;
private final AGStoredFile file;
private Row(IStoredFileSha1Query query, IDbSqlSelect select, DbResultSet resultSet) {
super(query);
this.sha1 = SHA_1_COLUMN.loadValue(select, resultSet);
this.file = FILE_COLUMN.loadValue(select, resultSet);
}
@Override
public Row getThis() {
return this;
}
@Override
public AGStoredFileSha1 getSha1() {
return this.sha1;
}
@Override
public AGStoredFile getFile() {
return this.file;
}
}
}
}
| 27.158974
| 136
| 0.706005
|
a4eb7305cd06fee95a2f334e84b63aa0b419e0d0
| 2,183
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) fieldsfirst lnc
// Source File Name: Pattern.java
package com.icl.saxon.pattern;
import com.icl.saxon.Context;
import com.icl.saxon.expr.*;
import com.icl.saxon.om.NodeInfo;
public abstract class Pattern
{
protected StaticContext staticContext;
protected String originalText;
public Pattern()
{
}
public static Pattern make(String s, StaticContext staticcontext)
throws XPathException
{
/* 29*/ Pattern pattern = (new ExpressionParser()).parsePattern(s, staticcontext).simplify();
/* 31*/ pattern.staticContext = staticcontext;
/* 34*/ pattern.setOriginalText(s);
/* 35*/ return pattern;
}
public void setOriginalText(String s)
{
/* 43*/ originalText = s;
}
public Pattern simplify()
throws XPathException
{
/* 53*/ return this;
}
public final void setStaticContext(StaticContext staticcontext)
{
/* 61*/ staticContext = staticcontext;
}
public StaticContext getStaticContext()
{
/* 69*/ return staticContext;
}
public abstract boolean matches(NodeInfo nodeinfo, Context context)
throws XPathException;
public short getNodeType()
{
/* 89*/ return 0;
}
public int getFingerprint()
{
/* 100*/ return -1;
}
public double getDefaultPriority()
{
/* 109*/ return 0.5D;
}
public String getSystemId()
{
/* 117*/ return staticContext.getSystemId();
}
public int getLineNumber()
{
/* 125*/ return staticContext.getLineNumber();
}
public String toString()
{
/* 133*/ return originalText;
}
}
| 25.682353
| 101
| 0.529088
|
0b5f25af26c74ebbb3c9a4b9e535f3d32884a221
| 270
|
package utils.datastructures.doublylinkedlist.core;
/**
* Interface to provide constructor for special nodes to DoublyLinkedList
*
* @author Riley McCuen
*
*/
public interface NodeSupplier<V, D extends DoublyLinkedListNode<V, D>> {
public D getNode(V value);
}
| 20.769231
| 73
| 0.751852
|
4bc4378b4152cacd7dd34171928afabb88fe9492
| 14,680
|
package org.innovateuk.ifs.crm.transactional;
import org.innovateuk.ifs.BaseServiceUnitTest;
import org.innovateuk.ifs.LambdaMatcher;
import org.innovateuk.ifs.address.builder.AddressTypeBuilder;
import org.innovateuk.ifs.address.domain.AddressType;
import org.innovateuk.ifs.address.resource.OrganisationAddressType;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.organisation.resource.OrganisationAddressResource;
import org.innovateuk.ifs.organisation.resource.OrganisationExecutiveOfficerResource;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.organisation.resource.OrganisationSicCodeResource;
import org.innovateuk.ifs.organisation.transactional.OrganisationAddressService;
import org.innovateuk.ifs.organisation.transactional.OrganisationService;
import org.innovateuk.ifs.sil.crm.resource.SilContact;
import org.innovateuk.ifs.sil.crm.service.SilCrmEndpoint;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.transactional.BaseUserService;
import org.junit.Test;
import org.mockito.Mock;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.address.builder.AddressTypeBuilder.newAddressType;
import static org.innovateuk.ifs.address.builder.AddressTypeResourceBuilder.newAddressTypeResource;
import static org.innovateuk.ifs.address.builder.AddressResourceBuilder.newAddressResource;
import static org.innovateuk.ifs.organisation.builder.OrganisationAddressResourceBuilder.newOrganisationAddressResource;
import static org.innovateuk.ifs.organisation.builder.OrganisationResourceBuilder.newOrganisationResource;
import static org.innovateuk.ifs.organisation.builder.OrganisationSicCodeResourceBuilder.newOrganisationSicCodeResource;
import static org.innovateuk.ifs.organisation.builder.OrganisationExecutiveOfficerResourceBuilder.newOrganisationExecutiveOfficerResource;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.innovateuk.ifs.user.resource.Role.APPLICANT;
import static org.innovateuk.ifs.user.resource.Role.MONITORING_OFFICER;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests around the {@link CrmServiceImpl}.
*/
public class CrmServiceImplTest extends BaseServiceUnitTest<CrmServiceImpl> {
@Mock
private BaseUserService baseUserService;
@Mock
private OrganisationService organisationService;
@Mock
private OrganisationAddressService organisationAddressService;
@Mock
private SilCrmEndpoint silCrmEndpoint;
@Override
protected CrmServiceImpl supplyServiceUnderTest() {
CrmServiceImpl service = new CrmServiceImpl();
ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", false);
return service;
}
@Test
public void syncExternalCrmContact() {
long userId = 1L;
UserResource user = newUserResource().withRoleGlobal(APPLICANT).build();
List<OrganisationResource> organisations = newOrganisationResource().withCompaniesHouseNumber("Something", "Else").build(2);
when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user));
when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(organisations));
when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess());
ServiceResult<Void> result = service.syncCrmContact(userId);
assertThat(result.isSuccess(), equalTo(true));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(0))));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(1))));
}
@Test
public void syncExternalCrmContactWithOrganisationUpdates() {
long userId = 1L;
UserResource user = newUserResource()
.withRoleGlobal(APPLICANT)
.build();
OrganisationResource organisation = newOrganisationResource()
.withDateOfIncorporation(LocalDate.now())
.withSicCodes(newOrganisationSicCodeResource().withSicCode("code-1", "code-2").build(2))
.withExecutiveOfficers(newOrganisationExecutiveOfficerResource().withName("director-1", "director-2").build(2))
.build();
AddressType addressType = newAddressType()
.withId(OrganisationAddressType.REGISTERED.getId())
.withName(OrganisationAddressType.REGISTERED.name())
.build();
OrganisationAddressResource organisationAddressResource = newOrganisationAddressResource()
.withAddress(newAddressResource()
.withAddressLine1("Line1")
.withAddressLine2("Line2")
.withAddressLine3("Line3")
.withCounty("County")
.withTown("Town")
.withCountry("Country")
.withPostcode("Postcode").build())
.withAddressType(newAddressTypeResource()
.withId(OrganisationAddressType.REGISTERED.getId())
.withName(OrganisationAddressType.REGISTERED.name()).build())
.build();
when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user));
when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(Collections.singletonList(organisation)));
when(organisationAddressService.findByOrganisationIdAndAddressType(organisation.getId(), addressType))
.thenReturn(serviceSuccess(Collections.singletonList(organisationAddressResource)));
when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess());
ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", true);
ServiceResult<Void> result = service.syncCrmContact(userId);
assertThat(result.isSuccess(), equalTo(true));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContactWithOrganisationUpdates(user, organisation)));
}
@Test
public void syncExternalCrmContactForProject() {
long userId = 1L;
long projectId = 2L;
UserResource user = newUserResource().withRoleGlobal(APPLICANT).build();
OrganisationResource organisation = newOrganisationResource()
.withCompaniesHouseNumber("Something", "Else")
.build();
when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user));
when(organisationService.getByUserAndProjectId(userId, projectId)).thenReturn(serviceSuccess(organisation));
when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess());
ServiceResult<Void> result = service.syncCrmContact(userId, projectId);
assertThat(result.isSuccess(), equalTo(true));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisation)));
}
@Test
public void syncExternalCrmContactForProjectWithOrganisationUpdates() {
long userId = 1L;
long projectId = 2L;
UserResource user = newUserResource()
.withRoleGlobal(APPLICANT)
.build();
OrganisationResource organisation = newOrganisationResource()
.withDateOfIncorporation(LocalDate.now())
.withSicCodes(newOrganisationSicCodeResource().withSicCode("code-1", "code-2").build(2))
.withExecutiveOfficers(newOrganisationExecutiveOfficerResource().withName("director-1", "director-2").build(2))
.build();
AddressType addressType = newAddressType()
.withId(OrganisationAddressType.REGISTERED.getId())
.withName(OrganisationAddressType.REGISTERED.name())
.build();
OrganisationAddressResource organisationAddressResource = newOrganisationAddressResource()
.withAddress(newAddressResource()
.withAddressLine1("Line1")
.withAddressLine2("Line2")
.withAddressLine3("Line3")
.withCounty("County")
.withTown("Town")
.withCountry("Country")
.withPostcode("Postcode").build())
.withAddressType(newAddressTypeResource()
.withId(OrganisationAddressType.REGISTERED.getId())
.withName(OrganisationAddressType.REGISTERED.name()).build())
.build();
when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user));
when(organisationService.getByUserAndProjectId(userId, projectId)).thenReturn(serviceSuccess(organisation));
when(organisationAddressService.findByOrganisationIdAndAddressType(organisation.getId(), addressType))
.thenReturn(serviceSuccess(Collections.singletonList(organisationAddressResource)));
when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess());
ReflectionTestUtils.setField(service, "newOrganisationSearchEnabled", true);
ServiceResult<Void> result = service.syncCrmContact(userId, projectId);
assertThat(result.isSuccess(), equalTo(true));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContactWithOrganisationUpdates(user, organisation)));
}
@Test
public void syncMonitoringOfficerOnlyCrmContact() {
long userId = 1L;
UserResource user = newUserResource().withRoleGlobal(MONITORING_OFFICER).build();
when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user));
when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(Collections.emptyList()));
when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess());
ServiceResult<Void> result = service.syncCrmContact(userId);
assertThat(result.isSuccess(), equalTo(true));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchMonitoringOfficerSilContact(user)));
}
@Test
public void syncMonitoringOfficerAndExternalCrmContact() {
long userId = 1L;
UserResource user = newUserResource().withRolesGlobal(asList(APPLICANT,MONITORING_OFFICER)).build();
List<OrganisationResource> organisations = newOrganisationResource().withCompaniesHouseNumber("Something", "Else").build(2);
when(baseUserService.getUserById(userId)).thenReturn(serviceSuccess(user));
when(organisationService.getAllByUserId(userId)).thenReturn(serviceSuccess(organisations));
when(silCrmEndpoint.updateContact(any(SilContact.class))).thenReturn(serviceSuccess());
ServiceResult<Void> result = service.syncCrmContact(userId);
assertThat(result.isSuccess(), equalTo(true));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(0))));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchExternalSilContact(user, organisations.get(1))));
verify(silCrmEndpoint).updateContact(LambdaMatcher.createLambdaMatcher(matchMonitoringOfficerSilContact(user)));
}
private Predicate<SilContact> matchExternalSilContact(UserResource user, OrganisationResource organisation) {
return silContact -> {
assertThat(silContact.getSrcSysContactId(), equalTo(String.valueOf(user.getId())));
assertThat(silContact.getOrganisation().getRegistrationNumber(), equalTo(organisation.getCompaniesHouseNumber()));
assertNull(silContact.getOrganisation().getDateOfIncorporation());
assertNull(silContact.getOrganisation().getSicCodes());
assertNull(silContact.getOrganisation().getExecutiveOfficers());
assertNull(silContact.getOrganisation().getRegisteredAddress());
return true;
};
}
private Predicate<SilContact> matchExternalSilContactWithOrganisationUpdates(UserResource user, OrganisationResource organisation) {
return silContact -> {
assertThat(silContact.getSrcSysContactId(), equalTo(String.valueOf(user.getId())));
assertThat(silContact.getOrganisation().getDateOfIncorporation(), equalTo(organisation.getDateOfIncorporation()));
assertThat(silContact.getOrganisation().getSicCodes(), equalTo(organisation.getSicCodes().stream()
.map(OrganisationSicCodeResource::getSicCode)
.collect(Collectors.toList())));
assertThat(silContact.getOrganisation().getExecutiveOfficers(), equalTo(organisation.getExecutiveOfficers().stream()
.map(OrganisationExecutiveOfficerResource::getName)
.collect(Collectors.toList())));
assertThat(silContact.getOrganisation().getRegisteredAddress().getBuildingName(), equalTo("Line1"));
assertThat(silContact.getOrganisation().getRegisteredAddress().getStreet(), equalTo("Line2, Line3"));
assertThat(silContact.getOrganisation().getRegisteredAddress().getLocality(), equalTo("County"));
assertThat(silContact.getOrganisation().getRegisteredAddress().getTown(), equalTo("Town"));
assertThat(silContact.getOrganisation().getRegisteredAddress().getPostcode(), equalTo("Postcode"));
assertThat(silContact.getOrganisation().getRegisteredAddress().getCountry(), equalTo("Country"));
return true;
};
}
private Predicate<SilContact> matchMonitoringOfficerSilContact(UserResource user) {
return silContact -> {
assertThat(silContact.getSrcSysContactId(), equalTo(String.valueOf(user.getId())));
assertThat(silContact.getOrganisation().getRegistrationNumber(), equalTo(""));
return true;
};
}
}
| 52.241993
| 148
| 0.725409
|
b8bd9ca5ee7cd3f6f2aef964fec77025ab6e10f4
| 3,360
|
package cn.com.lingnan.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.print.attribute.standard.PrinterState;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import cn.com.lingnan.pojo.Region;
import cn.com.lingnan.service.RegionService;
import cn.com.lingnan.utils.POIUtil;
import cn.com.lingnan.utils.PageBean;
@Controller
@RequestMapping("/region")
public class RegionController {
@Resource(name = "regionService")
private RegionService regionService;
@RequestMapping("/findBypageUi")
public String toFindBypageUi() {
return "base/region";
}
/**
* 分页查询方法
*/
@RequestMapping("/findBypage")
@ResponseBody
public PageBean pageQuery(@RequestParam(required = true, defaultValue = "1") String page,
@RequestParam(value = "rows", required = true, defaultValue = "10") String pagesize, Region region,
HttpServletRequest request) {
PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(pagesize));
System.out.println(region.toString());
regionService.pageQuery(pageBean, region);
return pageBean;
}
@RequestMapping("/findById")
@ResponseBody
public Region findById(String id) {
System.out.println("aaa");
System.out.println(id);
Region region = regionService.findById(id);
return region;
}
/* @RequestMapping("/addRegion")
@ResponseBody
public boolean addRegion(Region region) throws Exception {
try {
regionService.save(region);
return true;
} catch (Exception e) {
return false;
}
}
*/
//批量删除
@RequestMapping("/deleteBatch")
@ResponseBody
public boolean deleteBatch(String ids) {
try {
regionService.deleteBatch(ids);
return true;
} catch (Exception e) {
System.out.println("aaa");
return false;
}
}
@RequestMapping("/updateById")
@ResponseBody
public boolean updateById(Region region) {
try {
// 判断有没有修改
if (0 != regionService.update(region)) {
return true;
}
} catch (Exception e) {
System.out.println("aaa");
}
return false;
}
@RequestMapping("/importXls")
@ResponseBody
public String importXls(MultipartFile importFile,HttpSession session) {
session.setAttribute("importedFlag", "false");
List<Region> regionList = new ArrayList<Region>();
//判断上传的文件是否符合格式和上传的文件是否存在
try {
POIUtil.checkFile(importFile);
} catch (IOException e1) {
//回传错误信息
return e1.getMessage();
}
try {
regionList = POIUtil.readRegionExcel(importFile);
int influence = regionService.saveBatch(regionList);
session.removeAttribute("importedFlag");
//判断受影响的条数
if (0==influence) {
return "已经存在这些记录";
}
} catch (Exception e) {
e.printStackTrace();
return "插入失败";
}
return "true";
}
//提供上传是否完成的依据,ajax
@RequestMapping("/isImport")
@ResponseBody
public String isImport(HttpSession session){
Object importFlag = session.getAttribute("importedFlag");
if (importFlag != null) {
return "false";
}else{
return "true";
}
}
}
| 23.661972
| 102
| 0.728571
|
08d62e51e78f2eaa9cfd8449ac2d4be97637c8e8
| 6,846
|
package net.clgd.ccemux.plugins.builtin;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.auto.service.AutoService;
import com.google.common.io.ByteStreams;
import dan200.computercraft.api.lua.*;
import dan200.computercraft.core.computer.ComputerSide;
import dan200.computercraft.core.computer.ComputerThread;
import net.clgd.ccemux.Utils;
import net.clgd.ccemux.api.config.Group;
import net.clgd.ccemux.api.emulation.EmulatedComputer;
import net.clgd.ccemux.api.emulation.Emulator;
import net.clgd.ccemux.api.emulation.filesystem.VirtualFile;
import net.clgd.ccemux.api.peripheral.Peripheral;
import net.clgd.ccemux.api.peripheral.PeripheralFactory;
import net.clgd.ccemux.api.plugins.Plugin;
import net.clgd.ccemux.api.plugins.PluginManager;
import net.clgd.ccemux.api.plugins.hooks.ComputerCreated;
import net.clgd.ccemux.api.plugins.hooks.CreatingROM;
import net.clgd.ccemux.config.LuaAdapter;
@AutoService(Plugin.class)
public class CCEmuXAPI extends Plugin {
private static final Logger log = LoggerFactory.getLogger(CCEmuXAPI.class);
@FunctionalInterface
private interface APIMethod {
Object[] accept(ILuaContext c, Object[] o) throws LuaException, InterruptedException;
}
public static class API implements ILuaAPI {
private final Emulator emu;
private final EmulatedComputer computer;
public API(Emulator emu, EmulatedComputer computer) {
this.emu = emu;
this.computer = computer;
}
@LuaFunction
public final String getVersion() {
return emu.getEmulatorVersion();
}
@LuaFunction
public final void closeEmu() {
computer.shutdown();
emu.removeComputer(computer);
}
@LuaFunction
public final int openEmu(Optional<Integer> id) {
return emu.createComputer(b -> b.id(id.orElse(-1))).getID();
}
@LuaFunction
public final Object[] openDataDir(Optional<Integer> id) {
try {
Path path = id.isPresent() ? emu.getConfig().getComputerDir(id.get()) : emu.getConfig().getDataDir();
if (!Files.isDirectory(path)) return new Object[] { false, "Directory does not exist." };
Desktop.getDesktop().browse(path.toUri());
return new Object[] { true };
} catch (Exception e) {
return new Object[] { false, e.toString() };
}
}
@LuaFunction
public final long milliTime() {
return System.currentTimeMillis();
}
@LuaFunction
public final long nanoTime() {
return System.nanoTime();
}
@LuaFunction
public final void echo(String message) {
log.info("[Computer {}] {}", computer.getID(), message);
}
@LuaFunction
public final void setClipboard(String contents) {
StringSelection sel = new StringSelection(contents);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(sel, sel);
}
@LuaFunction
public final Object[] openConfig() {
if (emu.getRendererFactory().createConfigEditor(emu.getConfig())) {
return new Object[] { true };
} else {
return new Object[] { false, "Not supported with this renderer" };
}
}
@LuaFunction
public final MethodResult attach(IArguments arguments) throws LuaException {
ComputerSide side = arguments.getEnum(0, ComputerSide.class);
String peripheral = arguments.getString(1);
Object configuration = arguments.get(2);
PeripheralFactory<?> factory = emu.getPeripheralFactory(peripheral);
if (factory == null) throw new LuaException("Invalid peripheral");
Peripheral built = factory.create(computer, emu.getConfig());
// Setup the config for this peripheral. In the future this could be
// persisted to disk.
Group group = new Group("peripheral");
built.configSetup(group);
if (configuration != null) LuaAdapter.fromLua(group, configuration);
computer.getEnvironment().setPeripheral(side, built);
return awaitPeripheralChange(computer);
}
@LuaFunction
public final MethodResult detach(ComputerSide side) {
computer.getEnvironment().setPeripheral(side, null);
return awaitPeripheralChange(computer);
}
public final MethodResult screenshot() {
return Utils.awaitFuture(computer, computer.screenshot(),
f -> MethodResult.of(f.getName()),
e -> {
log.error("Cannot create screenshot", e);
return MethodResult.of(null, "Cannot create screenshot.");
});
}
@Override
public String[] getNames() {
return new String[] { "ccemux" };
}
/**
* Waits for peripherals to finish attaching/detaching.
*
* Peripherals are attached/detached on the {@link ComputerThread}, which means they won't have been properly
* changed after {@code ccemux.attach}/{@code ccemux.detach} has been called. Instead, we queue an event on the
* computer thread, so we are resumed after peripherals have actually been attached.
*
* @param computer The computer to queue an event on
*/
static MethodResult awaitPeripheralChange(EmulatedComputer computer) {
computer.queueEvent("ccemux_peripheral_update", null);
return MethodResult.pullEvent("ccemux_peripheral_update", x -> MethodResult.of());
}
}
@Nonnull
@Override
public String getName() {
return "CCEmuX API";
}
@Nonnull
@Override
public String getDescription() {
return "Adds the 'ccemux' Lua API, which adds methods for interacting with the emulator and real computer.\n"
+ "Also adds the `emu` program and help ROM files, which use the API.";
}
@Nonnull
@Override
public Optional<String> getVersion() {
return Optional.empty();
}
@Nonnull
@Override
public Collection<String> getAuthors() {
return Collections.emptyList();
}
@Nonnull
@Override
public Optional<String> getWebsite() {
return Optional.empty();
}
@Override
public void setup(@Nonnull PluginManager manager) {
registerHook((ComputerCreated) (emu, computer) -> computer.addApi(new API(emu, computer)));
registerHook((CreatingROM) (emu, romBuilder) -> {
try {
romBuilder.addEntry("programs/emu.lua", new VirtualFile(
ByteStreams.toByteArray(CCEmuXAPI.class.getResourceAsStream("/rom/emu_program.lua"))));
romBuilder.addEntry("help/emu.txt", new VirtualFile(
ByteStreams.toByteArray(CCEmuXAPI.class.getResourceAsStream("/rom/emu_help.txt"))));
romBuilder.addEntry("help/credits-emu.txt", new VirtualFile(
ByteStreams.toByteArray(CCEmuXAPI.class.getResourceAsStream("/rom/credits_help.txt"))));
romBuilder.addEntry("autorun/emu.lua", new VirtualFile(
ByteStreams.toByteArray(CCEmuXAPI.class.getResourceAsStream("/rom/emu_completion.lua"))));
} catch (IOException e) {
log.error("Failed to register ROM entries", e);
}
});
}
}
| 30.837838
| 113
| 0.733713
|
d46d857c94085f28d2acfa15f857b74cc342bf70
| 1,523
|
package com.hsamgle.basic.controller;
import com.hsamgle.basic.entity.TokenInfo;
import com.hsamgle.basic.security.TokenManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
*
* @feture : TODO 控制器父类
* @file_name: BaseController.java
* @packge: com.hsamgle.basic.controller
* @author: 黄鹤老板
* @create_time: 2018/3/27 9:08
* @company: 江南皮革厂
*/
@RestController
public class BaseController {
@Autowired
private HttpServletRequest request;
/**
*
* @method: TODO 获取当前操作的用户token信息
* @time : 2018/6/7 9:40
* @author: 黄鹤老板
* @return: T
*/
public <T extends TokenInfo> T getTokenInfo(){
try {
String token = request.getHeader("token");
if(token!=null){
return TokenManager.getTokenInfo(token);
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 获取调用者的IP
* @return
*/
protected String getIpAddr() {
String ip = request.getHeader("X-Forwarded-For");
if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = ip.indexOf(",");
if(index != -1){
return ip.substring(0,index);
}else{
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
return ip;
}
return request.getRemoteAddr();
}
}
| 21.152778
| 68
| 0.67367
|
c33dfa0de6e3aa0153bcaf31c1991cc647ef7a52
| 418
|
package com.sjet.auracascade.common.items.gems;
import com.sjet.auracascade.AuraCascade;
import com.sjet.auracascade.common.api.IAuraColor;
public class AuraGemOrangeItem extends BaseAuraGemItem {
public AuraGemOrangeItem() {
super(new Properties().group(AuraCascade.MAIN_GROUP));
this.setRegistryName(AuraCascade.MODID, "aura_gem_orange");
this.auraColor = IAuraColor.ORANGE;
}
}
| 26.125
| 67
| 0.751196
|
42ef502329c4279d491371140eaadf2c65e7771e
| 2,285
|
/**
* Most of the code in the Qalingo project is copyrighted Hoteia and licensed
* under the Apache License Version 2.0 (release version 0.8.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Hoteia, 2012-2014
* http://www.hoteia.com - http://twitter.com/hoteia - contact@hoteia.com
*
*/
package org.hoteia.qalingo.core.web.mvc.controller.common;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hoteia.qalingo.core.ModelConstants;
import org.hoteia.qalingo.core.domain.enumtype.BoUrls;
import org.hoteia.qalingo.core.i18n.enumtype.ScopeWebMessage;
import org.hoteia.qalingo.core.web.mvc.controller.AbstractBackofficeQalingoController;
import org.hoteia.qalingo.core.web.mvc.viewbean.SeoDataViewBean;
import org.hoteia.qalingo.core.web.resolver.RequestData;
import org.hoteia.qalingo.core.web.servlet.ModelAndViewThemeDevice;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
*
*/
@Controller("legalTermsController")
public class LegalTermsController extends AbstractBackofficeQalingoController {
@RequestMapping(BoUrls.LEGAL_TERMS_URL)
public ModelAndView legalTerms(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
return new ModelAndViewThemeDevice(getCurrentVelocityPath(request), BoUrls.LEGAL_TERMS.getVelocityPage());
}
@ModelAttribute(ModelConstants.SEO_DATA_VIEW_BEAN)
protected SeoDataViewBean initSeo(final HttpServletRequest request, final Model model) throws Exception {
final RequestData requestData = requestUtil.getRequestData(request);
SeoDataViewBean seoDataViewBean = backofficeViewBeanFactory.buildViewSeoData(requestData);
final Locale locale = requestData.getLocale();
final String pageKey = BoUrls.LEGAL_TERMS_KEY;
final String pageTitle = getSpecificMessage(ScopeWebMessage.SEO, getMessageTitleKey(pageKey), locale);
seoDataViewBean.setPageTitle(pageTitle);
return seoDataViewBean;
}
}
| 44.803922
| 120
| 0.79256
|
f660c79c8867c38d0fd28bda15c90cc0b34d9775
| 5,497
|
package hr.fer.zemris.optjava.dz8.models.neural;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealVector;
import java.util.Arrays;
import java.util.Objects;
/**
* Created by Dominik on 5.12.2016..
*/
public class Layer {
private static final ArrayRealVector BIAS_NEURON = new ArrayRealVector(new double[] { 1 });
private RealVector values;
private ActivationFunction activationFunction;
private Layer previous;
private Layer next;
private ContextLayer context;
private RealMatrix weights;
public Layer(int size, ActivationFunction function) {
if (size < 1) {
throw new NeuralNetworkException("Layer should have at lease one neuron.");
}
Objects.requireNonNull(function, "Activation function cannot be null.");
values = new ArrayRealVector(size);
this.activationFunction = function;
}
public Layer(int size) {
this(size, ActivationFunction.SIGMOID);
}
public int numberOfNeurons() {
return values.getDimension();
}
public void giveInput(RealVector input) {
if (previous != null) {
throw new NeuralNetworkException("Cannot give input to non-input layer.");
}
Objects.requireNonNull(input, "Input cannot be null.");
if (input.getDimension() != values.getDimension()) {
throw new NeuralNetworkException("Given input has different size than input layer.");
}
values = input;
}
public RealVector calculateOutput() {
RealVector result;
if (context != null) {
values = values.add(context.getValues());
}
if (previous == null) {
result = values;
} else {
result = Utils.map(values, activationFunction);
}
if (context != null) {
context.copyValues(result);
}
if (next != null) {
fire(result);
}
return result;
}
private void fire(RealVector result) {
Objects.requireNonNull(result, "Result vector cannot be null.");
result = new ArrayRealVector(result, BIAS_NEURON);
for (int i = 0, n = next.numberOfNeurons(); i < n; i++) {
RealVector weightsForNeuron = weights.getColumnVector(i);
double total = result.dotProduct(weightsForNeuron);
next.setValue(i, total);
}
}
private void setValue(int position, double value) {
values.setEntry(position, value);
}
public void activateContextLayer() {
if (context == null) {
context = new ContextLayer(values.getDimension());
} else {
throw new NeuralNetworkException("Context layer is already activated.");
}
}
public void setNext(Layer layer, RealMatrix weights) {
Objects.requireNonNull(layer, "Layer cannot be null.");
Objects.requireNonNull(weights, "Weights matrix cannot be null.");
this.next = layer;
this.weights = weights;
layer.setPrevious(this);
}
public void setNext(Layer layer) {
Objects.requireNonNull(layer, "Layer cannot be null.");
//number of neurons + one weight for bias neuron
setNext(layer, Utils.createRandomMatrix(values.getDimension() + 1, layer.numberOfNeurons(), -1, 1));
}
public void setPrevious(Layer layer) {
Objects.requireNonNull(layer, "Layer cannot be null.");
this.previous = layer;
}
public void deactivateContextLayer() {
if (context == null) {
throw new NeuralNetworkException("Context layer is not activated");
} else {
context = null;
}
}
public boolean isInput() {
return previous == null;
}
public boolean isOutput() {
return next == null;
}
public void setWeightMatrix(RealMatrix weights) {
this.weights = weights;
}
public void setWeightMatrix(double[] weights) {
int m = this.weights.getRowDimension();
int n = this.weights.getColumnDimension();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
this.weights.setEntry(i, j, weights[i * n + j]);
}
}
if (context != null) {
context.setWeights(Arrays.copyOfRange(weights, m * n, weights.length));
}
}
public int numberOfWeights() {
if (weights == null) {
return 0;
}
int total = weights.getColumnDimension() * weights.getRowDimension();
if (context != null) {
total += context.numberOfWeights();
}
return total;
}
public void clearContext() {
if (context != null) {
context.clear();
}
}
public void setContextValues(double[] values) {
if (context == null) {
throw new NeuralNetworkException(
"Cannot set context values to a layer that doesn't have context layer " + "activated.");
}
if (values.length != this.values.getDimension()) {
throw new NeuralNetworkException(
"Different size for given values and the number of values in the context" + " layer.");
}
context.setValues(values);
}
public boolean isContextActivated() {
return context != null;
}
}
| 27.762626
| 108
| 0.593597
|
09dee5beee3edb7e07cc958fcac63b79a2332f46
| 1,851
|
package net.fortytwo.smsn.rdf.vocab;
import net.fortytwo.rdfagents.RDFAgents;
import org.openrdf.model.IRI;
/**
* The Event Ontology as a collection of terms
* This class was created on 2013-09-19 from Event Ontology version published 25th October 2007
*/
public interface Event {
String NAMESPACE = "http://purl.org/NET/c4dm/event.owl#";
// classes
IRI
Event = RDFAgents.createIRI(NAMESPACE + "Event"),
Factor = RDFAgents.createIRI(NAMESPACE + "Factor"),
Product = RDFAgents.createIRI(NAMESPACE + "Product");
// properties
IRI
agent = RDFAgents.createIRI(NAMESPACE + "agent"),
agent_in = RDFAgents.createIRI(NAMESPACE + "agent_in"),
factor = RDFAgents.createIRI(NAMESPACE + "factor"),
factor_of = RDFAgents.createIRI(NAMESPACE + "factor_of"),
hasAgent = RDFAgents.createIRI(NAMESPACE + "hasAgent"),
hasFactor = RDFAgents.createIRI(NAMESPACE + "hasFactor"),
hasLiteralFactor = RDFAgents.createIRI(NAMESPACE + "hasLiteralFactor"),
hasProduct = RDFAgents.createIRI(NAMESPACE + "hasProduct"),
hasSubEvent = RDFAgents.createIRI(NAMESPACE + "hasSubEvent"),
isAgentIn = RDFAgents.createIRI(NAMESPACE + "isAgentIn"),
isFactorOf = RDFAgents.createIRI(NAMESPACE + "isFactorOf"),
literal_factor = RDFAgents.createIRI(NAMESPACE + "literal_factor"),
place = RDFAgents.createIRI(NAMESPACE + "place"),
producedIn = RDFAgents.createIRI(NAMESPACE + "producedIn"),
produced_in = RDFAgents.createIRI(NAMESPACE + "produced_in"),
product = RDFAgents.createIRI(NAMESPACE + "product"),
sub_event = RDFAgents.createIRI(NAMESPACE + "sub_event"),
time = RDFAgents.createIRI(NAMESPACE + "time");
}
| 46.275
| 95
| 0.654241
|
28817384a603d14f45073a0ecec637528a6d765e
| 17,826
|
/*
* Copyright 2018 Malmoset 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.malmoset.campaigntracker.Monsters;
import com.malmoset.campaigndata.Action;
import com.malmoset.campaigndata.CreatureSize.CreatureSizes;
import com.malmoset.campaigndata.GenericValueString;
import com.malmoset.campaigndata.Monster;
import com.malmoset.campaigndata.StatWithModifier;
import com.malmoset.campaigntracker.MainApp;
import com.malmoset.controls.BaseForm;
import com.malmoset.controls.ContextMenus;
import com.malmoset.controls.IntegerStringConverter;
import com.malmoset.controls.NoHeaderTableView;
import com.malmoset.controls.NumberTextField;
import com.malmoset.controls.StatBlock;
import com.malmoset.controls.StatDice;
import com.malmoset.controls.TableViewCellFactories;
import com.malmoset.controls.TextEditCell;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.css.StyleConverter;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.util.StringConverter;
import javafx.util.converter.DefaultStringConverter;
import javafx.util.converter.NumberStringConverter;
/**
* FXML Controller class
*
* @author sean
*/
public class MonsterViewerController extends BaseForm implements Initializable {
private Monster monster;
@FXML
private TextField NameField;
@FXML
private TextField SourceField;
@FXML
private TextField TypeField;
@FXML
private ChoiceBox<String> SizeField;
@FXML
private TextField AlignField;
@FXML
private Button HPButton;
@FXML
private TextField HPField;
@FXML
private StatDice HPDice;
@FXML
private TextField HPNotesField;
@FXML
private NumberTextField ACField;
@FXML
private TextField ACNotesField;
@FXML
private NumberTextField InitField;
@FXML
private TextField CHField;
@FXML
private StatBlock StrField;
@FXML
private StatBlock DexField;
@FXML
private StatBlock ConField;
@FXML
private StatBlock IntField;
@FXML
private StatBlock WisField;
@FXML
private StatBlock ChaField;
@FXML
private NoHeaderTableView<GenericValueString> SpeedList;
@FXML
private NoHeaderTableView<StatWithModifier> SavesList;
@FXML
private NoHeaderTableView<GenericValueString> DmgVulList;
@FXML
private NoHeaderTableView<GenericValueString> DmgResList;
@FXML
private NoHeaderTableView<GenericValueString> ConImList;
@FXML
private NoHeaderTableView<GenericValueString> DmgImList;
@FXML
private NoHeaderTableView<StatWithModifier> SkillsList;
@FXML
private NoHeaderTableView<GenericValueString> LanguageList;
@FXML
private TableView<Action> TraitsList;
@FXML
private NoHeaderTableView<GenericValueString> SensesList;
@FXML
private TableView<Action> ActionsList;
@FXML
private TableView<Action> ReactionsList;
@FXML
private TableView<Action> LegActionsList;
@FXML
private Button SaveButton;
private ObservableList<Monster> saveList;
private boolean tablesRedrawn = false;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@Override
public void onActivated() {
System.out.println(this.getStage().getTitle() + "Activated");
//On MacOS, this can run right away.
//Windows has a little delay from initial display until the form actually works
//So, we use runLater to add a little delay to this
//Seems to work well on Mac and Windows
if (!tablesRedrawn) {
Platform.runLater(() -> {
//Voodoo to force re-drawing the tables
//This fixes the line wrapping and makes them look good
TraitsList.getColumns().get(0).setVisible(false);
TraitsList.getColumns().get(0).setVisible(true);
ActionsList.getColumns().get(0).setVisible(false);
ActionsList.getColumns().get(0).setVisible(true);
ReactionsList.getColumns().get(0).setVisible(false);
ReactionsList.getColumns().get(0).setVisible(true);
LegActionsList.getColumns().get(0).setVisible(false);
LegActionsList.getColumns().get(0).setVisible(true);
});
tablesRedrawn = true;
}
}
private void BindData() {
// Modifier.getValueFactory().valueProperty().bindBidirectional(statModifier.asObject());
if (this.monster != null) {
NameField.textProperty().bindBidirectional(monster.nameProperty());
SourceField.textProperty().bindBidirectional(monster.sourceProperty());
TypeField.textProperty().bindBidirectional(monster.typeProperty());
SizeField.setItems(CreatureSizes.getSizes());
SizeField.valueProperty().bindBidirectional(monster.getSize().valueProperty());
AlignField.textProperty().bindBidirectional(monster.alignmentProperty());
HPField.textProperty().bindBidirectional(monster.getHP().hpValueProperty(), new NumberStringConverter());
HPNotesField.textProperty().bindBidirectional(monster.getHP().notesProperty());
ACField.textProperty().bindBidirectional(monster.getAC().acValueProperty(), new NumberStringConverter());
ACNotesField.textProperty().bindBidirectional(monster.getAC().notesProperty());
InitField.textProperty().bindBidirectional(monster.initiativeModifierProperty(), new NumberStringConverter());
CHField.textProperty().bindBidirectional(monster.getChallenge().strValueProperty());
StrField.statValueProperty().bindBidirectional(monster.getAbilities().strProperty());
DexField.statValueProperty().bindBidirectional(monster.getAbilities().dexProperty());
ConField.statValueProperty().bindBidirectional(monster.getAbilities().conProperty());
IntField.statValueProperty().bindBidirectional(monster.getAbilities().intelligenceProperty());
WisField.statValueProperty().bindBidirectional(monster.getAbilities().wisProperty());
ChaField.statValueProperty().bindBidirectional(monster.getAbilities().chaProperty());
HPDice.statDiceCountProperty().bindBidirectional(monster.getHP().hitDiceCountProperty());
HPDice.statDiceSizeProperty().bindBidirectional(monster.getHP().hitDiceProperty());
HPDice.statModifierProperty().bindBidirectional(monster.getHP().hitModifierProperty());
configGenericTable(SpeedList, FXCollections.observableArrayList(monster.getSpeed()));
configGenericTable(DmgVulList, FXCollections.observableArrayList(monster.getDamageVulnerabilities()));
configGenericTable(DmgResList, FXCollections.observableArrayList(monster.getDamageResistances()));
configGenericTable(ConImList, FXCollections.observableArrayList(monster.getConditionImmunities()));
configGenericTable(DmgImList, FXCollections.observableArrayList(monster.getDamageImmunities()));
configGenericTable(LanguageList, FXCollections.observableArrayList(monster.getLanguages()));
configGenericTable(SensesList, FXCollections.observableArrayList(monster.getSenses()));
configModifierTable(SavesList, FXCollections.observableArrayList(monster.getSaves()));
configModifierTable(SkillsList, FXCollections.observableArrayList(monster.getSkills()));
configActionsTable(TraitsList, FXCollections.observableArrayList(monster.getTraits()));
configActionsTable(ActionsList, FXCollections.observableArrayList(monster.getActions()));
configActionsTable(ReactionsList, FXCollections.observableArrayList(monster.getReactions()));
configActionsTable(LegActionsList, FXCollections.observableArrayList(monster.getLegendaryActions()));
}
}
private void configActionsTable(TableView table, ObservableList<Action> list) {
table.setItems(list);
TableColumn<Action, String> nameCol = new TableColumn<>("Name");
TableColumn<Action, String> attackCol = new TableColumn<>("Attack");
TableColumn<Action, String> contentCol = new TableColumn<>("Content");
nameCol.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
attackCol.setCellValueFactory(cellData -> cellData.getValue().attackProperty());
contentCol.setCellValueFactory(cellData -> cellData.getValue().contentProperty());
nameCol.setCellFactory(TextEditCell.editCellFactory(new DefaultStringConverter(), true));
attackCol.setCellFactory(TextEditCell.editCellFactory(new DefaultStringConverter(), true));
contentCol.setCellFactory(TextEditCell.editCellFactory(new DefaultStringConverter(), true));
table.getColumns().addAll(nameCol, attackCol, contentCol);
boolean hasAttack = false;
boolean hasContent = false;
String longestAttack = "";
String longestName = "";
for (Action ac : list) {
if (ac.getName() != null && ac.getName().length() > longestName.length()) {
longestName = ac.getName();
}
if (ac.getAttack() != null && ac.getAttack().length() > 0) {
//Find the longest one to use for sizing
if (ac.getAttack().length() > longestAttack.length()) {
longestAttack = ac.getAttack();
}
hasAttack = true;
}
if (ac.getContent() != null && ac.getContent().length() > 0) {
hasContent = true;
}
}
{
//Measure the size needed to hold the longest name string
final Text text = new Text(longestName);
text.applyCss();
double size = text.getLayoutBounds().getWidth() + 5;
double maxwidth = 200;
nameCol.setMinWidth(100);
nameCol.setPrefWidth(size < maxwidth ? size : maxwidth);
nameCol.maxWidthProperty().bind(table.widthProperty().divide(4));
}
if (hasAttack) {
//Measure the size needed to hold the longest attack string
final Text text = new Text(longestAttack);
text.applyCss();
attackCol.setMinWidth(65);
attackCol.setPrefWidth(text.getLayoutBounds().getWidth() + 10);
attackCol.maxWidthProperty().bind(table.widthProperty().divide(3));
} else {
attackCol.setPrefWidth(20);
attackCol.maxWidthProperty().bind(table.widthProperty().divide(3));
}
if (hasContent) {
contentCol.prefWidthProperty().bind(table.widthProperty().subtract(20).subtract(nameCol.widthProperty()).subtract(attackCol.widthProperty()));
// contentCol.setPrefWidth(500);
// contentCol.setMaxWidth(500);
} else {
contentCol.setPrefWidth(20);
contentCol.maxWidthProperty().bind(table.widthProperty().multiply(0.7));
}
if (!monster.isReadOnly()) {
table.setEditable(true);
table.setContextMenu(ContextMenus.AddDelContextMenu(
(ActionEvent event) -> {
Object selected = table.getSelectionModel().getSelectedItem();
if (selected != null) {
list.remove(selected);
}
},
(ActionEvent event) -> {
Action object = new Action();
list.add(object);
}));
}
}
private void configModifierTable(TableView table, ObservableList list) {
table.setItems(list);
TableColumn<StatWithModifier, String> statCol = new TableColumn<>("Name");
TableColumn<StatWithModifier, Integer> valueCol = new TableColumn<>("Modifier");
statCol.prefWidthProperty().bind(table.widthProperty().multiply(0.7).subtract(7));
//statCol.setMaxWidth(100.0);
valueCol.prefWidthProperty().bind(table.widthProperty().multiply(0.3).subtract(7));
//valueCol.setMaxWidth(50.0);
statCol.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
valueCol.setCellValueFactory(cellData -> cellData.getValue().modifierProperty().asObject());
statCol.setCellFactory(TextEditCell.editCellFactory());
valueCol.setCellFactory(TextEditCell.editCellFactory(new IntegerStringConverter()));
table.getColumns().addAll(statCol, valueCol);
if (!monster.isReadOnly()) {
table.setEditable(true);
table.setContextMenu(ContextMenus.AddDelContextMenu(
(ActionEvent event) -> {
Object selected = table.getSelectionModel().getSelectedItem();
if (selected != null) {
list.remove(selected);
}
},
(ActionEvent event) -> {
try {
StatWithModifier object = new StatWithModifier();
list.add(object);
} catch (Exception ex) {
Logger.getLogger(MonsterViewerController.class.getName()).log(Level.INFO, null, ex);
}
}));
}
}
private void configGenericTable(TableView table, ObservableList list) {
table.setItems(list);
TableColumn<GenericValueString, String> valueCol = new TableColumn<>("Value");
valueCol.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
valueCol.setCellFactory(TextEditCell.editCellFactory());
table.getColumns().add(valueCol);
if (!monster.isReadOnly()) {
table.setEditable(true);
table.setContextMenu(ContextMenus.AddDelContextMenu(
(ActionEvent event) -> {
Object selected = table.getSelectionModel().getSelectedItem();
if (selected != null) {
list.remove(selected);
}
},
(ActionEvent event) -> {
try {
GenericValueString object = new GenericValueString();
list.add(object);
} catch (Exception ex) {
Logger.getLogger(MonsterViewerController.class.getName()).log(Level.INFO, null, ex);
}
}));
}
}
public void SetRO(boolean readonly) {
NameField.setEditable(!readonly);
SourceField.setEditable(!readonly);
TypeField.setEditable(!readonly);
SizeField.setDisable(readonly);
AlignField.setEditable(!readonly);
HPField.setEditable(!readonly);
HPDice.setDisable(readonly);
HPNotesField.setEditable(!readonly);
ACField.setEditable(!readonly);
ACNotesField.setEditable(!readonly);
InitField.setEditable(!readonly);
CHField.setEditable(!readonly);
StrField.setDisable(readonly);
DexField.setDisable(readonly);
ConField.setDisable(readonly);
IntField.setDisable(readonly);
WisField.setDisable(readonly);
ChaField.setDisable(readonly);
SpeedList.setEditable(!readonly);
SavesList.setEditable(!readonly);
DmgVulList.setEditable(!readonly);
DmgResList.setEditable(!readonly);
ConImList.setEditable(!readonly);
DmgImList.setEditable(!readonly);
SkillsList.setEditable(!readonly);
LanguageList.setEditable(!readonly);
TraitsList.setEditable(!readonly);
SensesList.setEditable(!readonly);
ActionsList.setEditable(!readonly);
ReactionsList.setEditable(!readonly);
LegActionsList.setEditable(!readonly);
SaveButton.setDisable(readonly);
SaveButton.setText(readonly ? "Read Only" : "Save");
}
public Monster getMonster() {
return monster;
}
public void setMonster(ObservableList<Monster> list, Monster monster) {
saveList = list;
this.monster = monster;
BindData();
SetRO(monster.isReadOnly());
}
@FXML
private void HPButtonClick(ActionEvent event) {
monster.getHP().RollHP();
}
@FXML
private void SaveButtonClick(ActionEvent event) {
ArrayList<Monster> newmonsters = new ArrayList<>();
newmonsters.add(monster);
MainApp.getAppData().getMon_db().ImportMonsters(saveList, newmonsters);
}
}
| 41.943529
| 154
| 0.655952
|
5602f9604380e6e48181af9253874a2c2a747ff9
| 693
|
package com.my.test;
import com.my.app.APPConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: huzp
* @Description:
* @Date: Created in 11:06 2020/11/9
* @param:
*/
public class GPIOCTest {
public static void main(String[] args) {
/**
* 定位 ---> 加载 --->注册
*/
ApplicationContext app = new ClassPathXmlApplicationContext(
"application.xml"
);
//todo 自己完成对Annation的解析的源码阅读
AnnotationConfigApplicationContext ac =
new AnnotationConfigApplicationContext(APPConfig.class);
}
}
| 21
| 81
| 0.746032
|
80995d59468be374d909392881b68b54209534ca
| 845
|
package nz.pumbas.halpbot.commands.actioninvokable.context.constructor;
import org.dockbox.hartshorn.core.annotations.Factory;
import org.dockbox.hartshorn.core.annotations.stereotype.Service;
import org.dockbox.hartshorn.core.context.element.TypeContext;
import java.util.List;
import java.util.Set;
import nz.pumbas.halpbot.actions.invokable.ActionInvokable;
import nz.pumbas.halpbot.commands.actioninvokable.context.CommandInvocationContext;
import nz.pumbas.halpbot.converters.tokens.Token;
@Service
public interface CustomConstructorContextFactory
{
@Factory
CustomConstructorContext create(String usage,
ActionInvokable<CommandInvocationContext> actionInvokable,
Set<TypeContext<?>> reflections,
List<Token> tokens);
}
| 36.73913
| 94
| 0.733728
|
d3472e8dc1270f8813fb39bcf4cc00c0181c7dd6
| 661
|
package org.zalando.riptide.opentelemetry.span;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.Span;
import org.zalando.riptide.RequestArguments;
import java.util.HashMap;
import java.util.Map;
public class StaticSpanDecorator implements SpanDecorator {
private final Map<AttributeKey<String>, String> attributes = new HashMap<>();
public StaticSpanDecorator(Map<String, String> source) {
source.forEach((k, v) -> attributes.put(AttributeKey.stringKey(k), v));
}
@Override
public void onRequest(Span span, RequestArguments arguments) {
attributes.forEach(span::setAttribute);
}
}
| 30.045455
| 81
| 0.748865
|
8a53b78fe8856b62412296a3e3fd9bf312949067
| 712
|
package exercise_02;
public class InsertionSort {
public int[] sort(int array[]) {
//System.out.println("before Sort :- ");
print(array);
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
//System.out.println("atfer Sort");
//print(array);
return array;
}
public void print(int array[]) {
//System.out.println("After Insertion Sort");
for(int i:array){
System.out.print(i+"|");
}
}
}
| 22.967742
| 57
| 0.439607
|
67af7fb5f64e6492e59312ca7b09bfd678b9d378
| 1,191
|
package net.sourceforge.mayfly.datastore;
import net.sourceforge.mayfly.UnimplementedException;
import net.sourceforge.mayfly.datastore.constraint.Constraints;
import net.sourceforge.mayfly.evaluation.Checker;
import net.sourceforge.mayfly.evaluation.condition.Condition;
public class NullChecker extends Checker {
@Override
public void checkDelete(Row rowToDelete, Row replacementRow) {
}
@Override
public void checkInsert(Constraints constraints, Row proposedRow) {
}
@Override
public boolean evaluate(Condition condition, Row row, String tableName) {
// Don't need subselects
return condition.evaluate(row, tableName);
}
@Override
public void checkDropTable() {
throw new UnimplementedException();
}
@Override
public Cell newIdentityValue() {
throw new UnimplementedException();
}
@Override
public String schema() {
throw new UnimplementedException();
}
@Override
public void setIdentityValue(Cell cell) {
throw new UnimplementedException();
}
@Override
public DataStore store() {
throw new UnimplementedException();
}
}
| 23.82
| 77
| 0.697733
|
0696e685b8f62711e774900f3bc5688e13c122a8
| 3,124
|
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* 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 net.fabricmc.fabric.api.lookup.v1.block;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import net.minecraft.block.BlockBase;
import net.minecraft.level.Level;
import net.minecraft.util.maths.Vec3i;
import net.fabricmc.fabric.impl.lookup.block.BlockApiCacheImpl;
import net.fabricmc.fabric.impl.lookup.block.BlockApiLookupImpl;
/**
* A {@link BlockApiLookup} bound to a {@link Level} and a position, providing much faster API access.
* Refer to {@link BlockApiLookup} for example code.
*
* <p>This object caches the block entity at the target position, and the last used API provider, removing those queries.
* If a block entity is available or if the block state is passed as a parameter, the block state doesn't have to be looked up either.
*
* @param <A> The type of the API.
* @param <C> The type of the additional context object.
* @see BlockApiLookup
*/
public interface BlockApiCache<A, C> {
/**
* Attempt to retrieve an API from a block in the world, using the world and the position passed at creation time.
*
* <p>Note: If the block state is known, it is more efficient to use {@link BlockApiCache#find(BlockBase, int, Object)}.
*
* @param context Additional context for the query, defined by type parameter C.
* @return The retrieved API, or {@code null} if no API was found.
*/
@Nullable
default A find(C context) {
return find(null, 0, context);
}
/**
* Attempt to retrieve an API from a block in the world, using the world and the position passed at creation time.
*
* @param block The block at the target position, or null if unknown.
* @param context Additional context for the query, defined by type parameter C.
* @return The retrieved API, or {@code null} if no API was found.
*/
@Nullable
A find(@Nullable BlockBase block, int meta, C context);
/**
* Create a new instance bound to the passed {@link Level} and position, and querying the same API as the passed lookup.
*/
static <A, C> BlockApiCache<A, C> create(BlockApiLookup<A, C> lookup, Level level, Vec3i pos) {
Objects.requireNonNull(pos, "BlockPos may not be null.");
Objects.requireNonNull(level, "Level may not be null.");
if (!(lookup instanceof BlockApiLookupImpl)) {
throw new IllegalArgumentException("Cannot cache foreign implementation of BlockApiLookup. Use `BlockApiLookup#get(Identifier, Class<A>, Class<C>);` to get instances.");
}
return new BlockApiCacheImpl<>((BlockApiLookupImpl<A, C>) lookup, level, pos);
}
}
| 39.544304
| 172
| 0.732714
|
e0eccf9198ecc8f81106ec1dd23c7d52811f10e3
| 3,104
|
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.api.consumer.recordingstream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import jdk.jfr.Event;
import jdk.jfr.consumer.RecordingStream;
/**
* @test
* @summary Tests RecordingStream::disable(...)
* @key jfr
* @requires vm.hasJFR
* @library /test/lib
* @run main/othervm jdk.jfr.api.consumer.recordingstream.TestDisable
*/
public class TestDisable {
private static class DisabledEvent extends Event {
}
private static class EnabledEvent extends Event {
}
public static void main(String... args) throws Exception {
testDisableWithClass();
testDisableWithEventName();
}
private static void testDisableWithEventName() {
test(r -> r.disable(DisabledEvent.class.getName()));
}
private static void testDisableWithClass() {
test(r -> r.disable(DisabledEvent.class));
}
private static void test(Consumer<RecordingStream> disablement) {
CountDownLatch twoEvent = new CountDownLatch(2);
AtomicBoolean fail = new AtomicBoolean(false);
try(RecordingStream r = new RecordingStream()) {
r.onEvent(e -> {
if (e.getEventType().getName().equals(DisabledEvent.class.getName())) {
fail.set(true);
}
twoEvent.countDown();
});
disablement.accept(r);
r.startAsync();
EnabledEvent e1 = new EnabledEvent();
e1.commit();
DisabledEvent d1 = new DisabledEvent();
d1.commit();
EnabledEvent e2 = new EnabledEvent();
e2.commit();
try {
twoEvent.await();
} catch (InterruptedException ie) {
throw new RuntimeException("Unexpexpected interruption of thread", ie);
}
if (fail.get()) {
throw new RuntimeException("Should not receive a disabled event");
}
}
}
}
| 34.10989
| 87
| 0.653995
|
131b2cabde06a35d066df8d1e99068251589c120
| 4,333
|
/*
* Copyright (c) 2015, Alachisoft. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alachisoft.tayzgrid.socketserver;
import com.alachisoft.tayzgrid.common.threading.Monitor;
import com.alachisoft.tayzgrid.runtime.util.TimeSpan;
import java.lang.Thread;
/**
Follows Singleton patren. This class is responsible to do preodic collections of GEN#2.
By default the due time and period is set to 5 mins. The minimum interval of 1 mins can be specified.
*/
public final class GarbageCollectionTimer
{
private static GarbageCollectionTimer _instance = null;
private Thread timer;
private static boolean stopped = true;
/**
To prevent Object creation by user.
*/
private GarbageCollectionTimer() {
}
/**
Returns the GarbageCollectionThread instance. It ensures that only one instance
of this class exist.
@return GarbageCollectionThread instance
*/
public static GarbageCollectionTimer GetInstance() {
if (_instance == null) {
_instance = new GarbageCollectionTimer();
}
return _instance;
}
/**
priate reentrant mehtod used for the timercallback.
*/
private void StartColletion(Object[] objs) {
TimeSpan dueTime=(TimeSpan)((objs[0] instanceof TimeSpan) ? objs[0] : null);
TimeSpan period=(TimeSpan)((objs[0] instanceof TimeSpan) ? objs[0] : null);
if(dueTime.getTotalMiliSeconds()>0)
{
try
{
Monitor.wait(this, dueTime.getTotalMiliSeconds());
while (!stopped)
{
System.gc();
if (SocketServer.getLogger().getIsErrorLogsEnabled()) {
SocketServer.getLogger().getCacheLog().Error("GarbageCollectionTimer.StartCollection");
}
Monitor.wait(this,period.getTotalMiliSeconds());
}
}
catch (java.lang.InterruptedException e)
{
}
}
else if (dueTime.getTotalMiliSeconds() == 0)
{
try
{
while (!stopped)
{
System.gc();
if (SocketServer.getLogger().getIsErrorLogsEnabled()) {
SocketServer.getLogger().getCacheLog().Error("GarbageCollectionTimer.StartCollection");
}
Monitor.wait(this,period.getTotalMiliSeconds());
}
}catch (java.lang.InterruptedException e)
{
}
}
else
return;
}
/**
Starts the timer.
@param dueTime The amount of time to delay before first collection, in minutes. minimum value is 0 mins which does the collection immediately.
@param period The time interval between tw oconsective collections, in minutes. minimus value is 1 mins.
*/
public void Start(int dueTime, int period) {
if (dueTime < 0) {
throw new IllegalArgumentException("The Value must be greater than equal to zero");
}
if (period < 1) {
throw new IllegalArgumentException("The value must be greater than 0.");
}
if (timer == null) {
final Object[] args = new Object[]
{
dueTime, period
};
timer = new Thread(new Runnable()
{
@Override
public void run()
{
StartColletion(args);
}
});
}
stopped = false;
}
public void Stop() {
stopped = true;
timer = null;
}
public void dispose() {
Stop();
_instance = null;
}
}
| 28.886667
| 144
| 0.577891
|
6e64bb1b276b33ae6b82fb7ca7518f00f2a5c6d1
| 1,354
|
package server;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for addSample complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="addSample">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="sample" type="{http://server/}temperatureSample" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "addSample", propOrder = {
"sample"
})
public class AddSample {
protected TemperatureSample sample;
/**
* Gets the value of the sample property.
*
* @return
* possible object is
* {@link TemperatureSample }
*
*/
public TemperatureSample getSample() {
return sample;
}
/**
* Sets the value of the sample property.
*
* @param value
* allowed object is
* {@link TemperatureSample }
*
*/
public void setSample(TemperatureSample value) {
this.sample = value;
}
}
| 22.196721
| 95
| 0.615214
|
5e279c2814104c4cc363d3a1313cbe516bc01d99
| 423
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v9/enums/listing_group_filter_product_channel.proto
package com.google.ads.googleads.v9.enums;
public interface ListingGroupFilterProductChannelEnumOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v9.enums.ListingGroupFilterProductChannelEnum)
com.google.protobuf.MessageOrBuilder {
}
| 42.3
| 117
| 0.832151
|
42f17d3b0e69bc23c36aa54f74ae76d3a675a660
| 12,462
|
package ocaml.build;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ocaml.OcamlPlugin;
import ocaml.util.FileUtil;
import ocaml.util.Misc;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.texteditor.MarkerUtilities;
/**
* Parse error messages returned by the OCaml compiler, and create error markers for the
* corresponding resources in the project.
*/
public class ProblemMarkers {
private final IProject project;
private boolean bErrorsFound;
private boolean bWarningsFound;
private boolean bProjectErrorsFound;
private boolean bProjectWarningsFound;
private final TreeSet<ErrorFile> errorFiles = new TreeSet<ErrorFile>();
private final TreeSet<WarningFile> warningFiles = new TreeSet<WarningFile>();
public ProblemMarkers(IProject project) {
this.project = project;
bErrorsFound = false;
bWarningsFound = false;
bProjectErrorsFound = false;
bProjectWarningsFound = false;
}
private final Pattern patternErrorMessages = Pattern.compile("^(?:" + "Values do not match|"
+ "Type declarations do not match|" + "Exception declarations do not match|"
+ "Modules do not match|" + "Module type declarations do not match|"
+ "Illegal permutation of structure fields|" + "The implementation |"
+ "Class type declarations do not match|" + "Class declarations do not match|"
+ "Unbound module type )");
/** regex: File "[f]" line [l], characters [a]-[b]: (Ocaml compilers)
* or File [f] line [l]: characters [a]-[b] (Omake)
*/
private final Pattern patternFile = Pattern
.compile("^\\s*File (\"?)(.+?)\\1[:,] line (\\d+), characters (\\d+)-(\\d+):?\\s*$");
/** Create the markers for error messages coming from the OCaml compiler. */
public void makeMarkers(String compilerOutput) {
String[] lines = compilerOutput.split("\\r?\\n");
String currentMessage = "";
int charStart = 0;
int charEnd = 0;
int lineNumber = 0;
String filename = "";
for (String line : lines) {
Matcher matcher = patternFile.matcher(line);
if (matcher.find()) {
if (!currentMessage.equals("")) {
writeProblemMarker(filename, lineNumber, charStart, charEnd, currentMessage
.trim());
currentMessage = "";
}
filename = matcher.group(2);
lineNumber = Integer.parseInt(matcher.group(3));
charStart = Integer.parseInt(matcher.group(4));
charEnd = Integer.parseInt(matcher.group(5));
/* if the start and end positions are equal, the marker doesn't appear */
if (charStart == charEnd && charStart > 0)
charStart--;
} else if (line.startsWith("Error while linking") && (!currentMessage.equals(""))) {
writeProblemMarker("", 0, 0, 0, currentMessage.trim());
currentMessage = line;
} else {
currentMessage = currentMessage + "\n" + line;
}
}
currentMessage = currentMessage.trim();
if (!currentMessage.equals(""))
writeProblemMarker(filename, lineNumber, charStart, charEnd, currentMessage);
}
/** Create error markers for the error messages returned by the make command */
public void makeMarkers2(String makeOutput) {
String[] lines = makeOutput.split("\\r?\\n");
String currentMessage = "";
int charStart = 0;
int charEnd = 0;
int lineNumber = 0;
String filename = "";
boolean skip = true;
for (String line : lines) {
if (line
.matches("^-?(?:make|o?caml|rm |mkdir |cp |mv |cd |for |if |gcc |/|\\.|Command exited ).*")) {
if (!currentMessage.trim().equals("")) {
writeProblemMarker(filename, lineNumber, charStart, charEnd, currentMessage
.trim());
currentMessage = "";
}
skip = true;
}
Matcher matcherError = patternErrorMessages.matcher(line);
if (matcherError.find()) {
skip = false;
if (!currentMessage.trim().equals("")) {
writeProblemMarker(filename, lineNumber, charStart, charEnd, currentMessage
.trim());
currentMessage = "";
}
filename = "";
lineNumber = 0;
charStart = 0;
charEnd = 0;
currentMessage = line;
continue;
}
Matcher matcher = patternFile.matcher(line);
if (matcher.find()) {
skip = false;
if (!currentMessage.trim().equals("")) {
writeProblemMarker(filename, lineNumber, charStart, charEnd, currentMessage
.trim());
currentMessage = "";
}
filename = matcher.group(2);
lineNumber = Integer.parseInt(matcher.group(3));
charStart = Integer.parseInt(matcher.group(4));
charEnd = Integer.parseInt(matcher.group(5));
} else if (line.startsWith("Error while linking")) {
if (!currentMessage.equals(""))
writeProblemMarker("", 0, 0, 0, currentMessage.trim());
currentMessage = line;
} else if (!skip) {
currentMessage = currentMessage + "\n" + line;
}
}
currentMessage = currentMessage.trim();
if (!currentMessage.equals(""))
writeProblemMarker(filename, lineNumber, charStart, charEnd, currentMessage);
}
/**
* Write a problem marker for the file <code>fullProjectRelativeFilePath</code> that generated
* the error message <code>msg</code> on the line <code>lineNumber</code> that starts at
* character <code>charStart</code> and ends at character <code>charEnd</code>.
*
*/
private void writeProblemMarker(String fullWorkspaceRelativePath, int lineNumber,
int charStart, int charEnd, String msg) {
String projectRelativePath;
String projectPath = project.getName() + File.separatorChar;
if (fullWorkspaceRelativePath.startsWith(projectPath))
projectRelativePath = fullWorkspaceRelativePath.substring(projectPath.length());
else
projectRelativePath = fullWorkspaceRelativePath;
// if the project relative path is empty, then this is the project itself
if (projectRelativePath.equals("")) {
try {
// create a marker for the project
IMarker m = project.createMarker(IMarker.PROBLEM);
m.setAttribute(IMarker.MESSAGE, msg);
m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
if (msg.startsWith("Warning")) {
m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
bProjectWarningsFound = true;
} else /* if (msg.startsWith("Error")) */{
m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
bProjectErrorsFound = true;
}
} catch (CoreException e) {
OcamlPlugin.logError("ProblemMarkers:writeProblemMarkers", e);
}
return;
}
IResource fileAsResource = project.findMember(projectRelativePath);
if ((fileAsResource == null) || (fileAsResource.getType() != IResource.FILE)) {
/*
* If the resource wasn't found. This is certainly because the makefile changed the
* directory. So, we have to search for the file among all the project files.
*/
// only keep the filename
int idx = fullWorkspaceRelativePath.lastIndexOf(File.separatorChar);
if (idx != -1)
fullWorkspaceRelativePath = fullWorkspaceRelativePath.substring(idx + 1);
for (IFile file : Misc.getProjectFiles(project)) {
if (file.getName().equals(fullWorkspaceRelativePath)) {
fileAsResource = file;
break;
}
}
if (fileAsResource == null) {
OcamlPlugin.logError("ProblemMarkers:writeProblemMarkers: can't find "
+ projectRelativePath);
return;
}
}
final IFile file = (IFile) fileAsResource;
int lineOffset = getLineOffset(lineNumber, file);
Hashtable<String, Integer> attributes = new Hashtable<String, Integer>();
MarkerUtilities.setMessage(attributes, msg.toString());
if (msg.startsWith("Warning")) {
attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING));
bWarningsFound = true;
warningFiles.add(new WarningFile(file));
} else /* if (msg.startsWith("Error")) */{
attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR));
bErrorsFound = true;
errorFiles.add(new ErrorFile(file));
}
if (lineNumber > 0 && charStart >= 0 && charEnd >= charStart) {
MarkerUtilities.setCharStart(attributes, lineOffset + charStart);
MarkerUtilities.setCharEnd(attributes, lineOffset + charEnd);
MarkerUtilities.setLineNumber(attributes, lineNumber);
}
try {
MarkerUtilities.createMarker(file, attributes, IMarker.PROBLEM);
} catch (CoreException e) {
OcamlPlugin.logError("error in ProblemMarkers:writeProblemMarkers", e);
}
}
/**
* Get the absolute position in <code>file</code>, in number of characters from the beginning
* of line <code>lineNumber</code>.
*/
private static int getLineOffset(int lineNumber, IFile file) {
BufferedReader in = null;
if (!file.exists()) {
OcamlPlugin
.logError("ProblemMarkesr:getLineOffset:" + file.getProjectRelativePath() + " does not exist"); //$NON-NLS-1$ //$NON-NLS-2$
return 0;
}
InputStream contentsStream = null;
int charCount = 0;
try {
try {
contentsStream = file.getContents();
in = new BufferedReader(new InputStreamReader(contentsStream, file.getCharset()));
} catch (CoreException e) {
OcamlPlugin.logError("Error 1 in OcamlBuilder:getLineOffset()", e);
} catch (UnsupportedEncodingException e) {
OcamlPlugin.logError("Unsupported encoding in OcamlBuilder:getLineOffset()", e);
}
int ch = 0;
int lineCount = 0;
while ((lineCount < lineNumber - 1) && (ch != -1)) {
try {
ch = in.read();
} catch (IOException e1) {
OcamlPlugin.logError("Error in 2 OcamlBuilder:getLineOffset()", e1);
}
if (ch != -1) {
charCount++;
if (ch == '\n') {
lineCount++;
}
}
}
} finally {
FileUtil.closeResource(in);
FileUtil.closeResource(contentsStream);
}
return charCount;
}
public boolean errorsFound() {
return bErrorsFound;
}
public boolean warningsFound() {
return bWarningsFound;
}
public boolean projectErrorsFound() {
return bProjectErrorsFound;
}
public boolean projectWarningsFound() {
return bProjectWarningsFound;
}
public IFile[] getFilesWithErrors() {
ArrayList<IFile> filesWithErrors = new ArrayList<IFile>();
for (ErrorFile f : errorFiles)
filesWithErrors.add(f.getFile());
return filesWithErrors.toArray(new IFile[filesWithErrors.size()]);
}
/** Return the files that have at least a warning, but no error */
public IFile[] getFilesWithWarnings() {
ArrayList<IFile> filesWithWarnings = new ArrayList<IFile>();
for (WarningFile f : warningFiles)
if (!errorFiles.contains(f)) {
filesWithWarnings.add(f.getFile());
}
return filesWithWarnings.toArray(new IFile[filesWithWarnings.size()]);
}
private class WarningFile implements Comparable<Object> {
final IFile file;
public WarningFile(IFile file) {
this.file = file;
}
public IFile getFile() {
return file;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof WarningFile) {
return ((WarningFile) obj).file.getLocation().toOSString().equals(
file.getLocation().toOSString());
} else
return super.equals(obj);
}
public int compareTo(Object o) {
if (o instanceof WarningFile) {
WarningFile file2 = (WarningFile) o;
return file.getLocation().toOSString().compareTo(
file2.file.getLocation().toOSString());
} else if (o instanceof ErrorFile) {
ErrorFile file2 = (ErrorFile) o;
return file.getLocation().toOSString().compareTo(
file2.file.getLocation().toOSString());
} else
throw new ClassCastException();
}
}
private class ErrorFile implements Comparable<Object> {
final IFile file;
public ErrorFile(IFile file) {
this.file = file;
}
public IFile getFile() {
return file;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ErrorFile) {
return ((ErrorFile) obj).file.getLocation().toOSString().equals(
file.getLocation().toOSString());
} else
return super.equals(obj);
}
public int compareTo(Object o) {
if (o instanceof ErrorFile) {
ErrorFile file2 = (ErrorFile) o;
return file.getLocation().toOSString().compareTo(
file2.file.getLocation().toOSString());
} else
throw new ClassCastException();
}
}
}
| 29.956731
| 128
| 0.690258
|
ea443a7326a4c09a72226a750593d1f365a3a982
| 621
|
package org.whrhs.dlamson.ocp.ch14;
import java.util.function.Predicate;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
public class LamdaLamdaLamda {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89));
//Predicate<Integer> p = (x) -> x % 2 == 0;
nums.removeIf((num) -> num % 2 == 0);
System.out.println(nums);
List<String> names = new ArrayList<>(List.of("Dan", "Mo", "Cora"));
names.sort((a, b) -> a.compareTo(b));
names.forEach((name) -> System.out.println(name));
}
}
| 28.227273
| 87
| 0.623188
|
41ae1b10d737a0c73b51bba504bc375834278b5d
| 169
|
package com.cqrs.commands;
import java.util.List;
public interface CommandValidator {
List<Throwable> validateCommand(CommandWithMetadata commandWithMetadata);
}
| 18.777778
| 77
| 0.810651
|
fc812deb9a52f035f5720e3fa3091716f04ae66c
| 3,577
|
package org.sgiusa.model.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.ForeignKey;
import org.sgiusa.model.ActivityGroup;
import org.sgiusa.model.Division;
import org.sgiusa.model.SubDivision;
import org.sgiusa.model.entity.OrganizationEntity;
import org.sgiusa.model.entity.UserEntity;
/**
* Generated by Nam.
*
*/
@Entity(name = "EmailList")
@Table(name = "email_list")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class EmailListEntity {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "enabled")
private Boolean enabled;
@Column(name = "divisions")
@Enumerated(EnumType.STRING)
@ElementCollection(targetClass = Division.class)
@CollectionTable(name = "email_list_division")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private List<Division> divisions;
@Column(name = "sub_divisions")
@Enumerated(EnumType.STRING)
@ElementCollection(targetClass = SubDivision.class)
@CollectionTable(name = "email_list_sub_division")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private List<SubDivision> subDivisions;
@Column(name = "activity_groups")
@Enumerated(EnumType.STRING)
@ElementCollection(targetClass = ActivityGroup.class)
@CollectionTable(name = "email_list_activity_group")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private List<ActivityGroup> activityGroups;
@JoinColumn(name = "organization", referencedColumnName = "id")
@OneToOne(cascade = CascadeType.ALL)
@ForeignKey(name = "email_list_entity_organization_fk")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private OrganizationEntity organization;
@JoinColumn(name = "id")
@OneToMany(cascade = CascadeType.ALL, targetEntity = UserEntity.class)
@ForeignKey(name = "email_list_entity_email_address_list_fk")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
private List<UserEntity> emailAddressList;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<Division> getDivisions() {
return divisions;
}
public void setDivisions(List<Division> divisions) {
this.divisions = divisions;
}
public List<SubDivision> getSubDivisions() {
return subDivisions;
}
public void setSubDivisions(List<SubDivision> subDivisions) {
this.subDivisions = subDivisions;
}
public List<ActivityGroup> getActivityGroups() {
return activityGroups;
}
public void setActivityGroups(List<ActivityGroup> activityGroups) {
this.activityGroups = activityGroups;
}
public OrganizationEntity getOrganization() {
return organization;
}
public void setOrganization(OrganizationEntity organization) {
this.organization = organization;
}
public List<UserEntity> getEmailAddressList() {
return emailAddressList;
}
public void setEmailAddressList(List<UserEntity> emailAddressList) {
this.emailAddressList = emailAddressList;
}
}
| 27.098485
| 71
| 0.788091
|
19d8ba42fa4395251c49842d57748f332276268d
| 664
|
package util;
import data_structures.BorderType;
import data_structures.CellShape;
import neighbors.*;
import patch_level.Patch;
/**
* Chooses the correct neighbors object based on the CellShape
* and the border type
*
* @author maddiebriere
*
*/
public class NeighborsChooser {
public static Neighbors chooseNeighbors(BorderType b, CellShape s, Patch[][] grid){
Neighbors neighbors;
switch (s){
case TRIANGLE:
neighbors = new TriangleNeighbors(grid, b);
break;
case HEXAGON:
neighbors = new HexagonNeighbors(grid, b);
break;
default:
neighbors = new SquareNeighbors(grid, b);
break;
}
return neighbors;
}
}
| 19.529412
| 84
| 0.709337
|
b3c381f2f59eb8edb3541aea4c856ad2d9b3d889
| 924
|
package imallett.FlashBang.Views;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import imallett.FlashBang.Measurement.MeasurerLight;
public class ViewGraphLight extends ViewGraphBase {
public MeasurerLight light;
public ViewGraphLight(Context context) { super(context); }
public ViewGraphLight(Context context, AttributeSet attrs) { super(context,attrs); }
public ViewGraphLight(Context context, AttributeSet attrs, int defStyleAttr) { super(context,attrs,defStyleAttr); }
@Override public void onDraw(Canvas canvas) {
try {
synchronized(this) {
super._drawBackground(canvas,light.valid);
super._drawAxes(canvas);
synchronized(light.stream) {
super._drawGraph(canvas,light.stream,1);
//super._drawGraph(canvas,light.stream,5);
}
}
} catch (NullPointerException ignored) {} //Workaround for moronic bugs in Android Studio
}
}
| 31.862069
| 116
| 0.766234
|
417aea5a784b0a0bd0dd174aaa1894ab89b08f74
| 2,411
|
/*
* 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.servicecomb.core.filter.config;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.servicecomb.config.ConfigUtil;
import org.springframework.util.CollectionUtils;
public class InvocationFilterChainsConfig extends AbstractFilterChainsConfig {
private final String policiesRoot;
private final List<String> frameworkChain;
private final List<String> defaultChain;
private final Map<String, List<String>> microserviceChains = new HashMap<>();
public InvocationFilterChainsConfig(String root) {
frameworkChain = ConfigUtil.getStringList(config, root + ".framework");
defaultChain = loadDefaultChain(root);
policiesRoot = root + ".policies";
loadKeys(policiesRoot, this::loadPolicies);
}
private List<String> loadDefaultChain(String root) {
String defaultChainKey = root + ".default";
List<String> defaultChain = ConfigUtil.getStringList(config, defaultChainKey);
if (CollectionUtils.isEmpty(defaultChain) && config.getProperty(defaultChainKey) == null) {
defaultChain = frameworkChain;
}
return defaultChain;
}
private void loadPolicies(String qualifiedKey) {
String microserviceName = qualifiedKey.substring(policiesRoot.length() + 1);
microserviceChains.put(microserviceName, ConfigUtil.getStringList(config, qualifiedKey));
}
public List<String> getFrameworkChain() {
return frameworkChain;
}
public List<String> getDefaultChain() {
return defaultChain;
}
public Map<String, List<String>> getMicroserviceChains() {
return microserviceChains;
}
}
| 34.442857
| 95
| 0.756533
|
79d2f573b0c88573f4e256649f0c9b7a5165340f
| 124
|
package com.appsmith.server.dtos;
import lombok.Data;
@Data
public class GitCheckoutBranchDTO {
Boolean isRemote;
}
| 11.272727
| 35
| 0.758065
|
9ebc671ef4fe9e3e053ef4dcb3fed37a61d0577e
| 5,581
|
package org.onetwo.boot.core.web.view;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.onetwo.boot.core.json.ObjectMapperProvider;
import org.onetwo.boot.core.web.mvc.interceptor.BootFirstInterceptor;
import org.onetwo.boot.core.web.utils.BootWebHelper;
import org.onetwo.boot.core.web.utils.BootWebUtils;
import org.onetwo.common.data.DataResult;
import org.onetwo.common.data.DataResultWrapper;
import org.onetwo.common.jackson.JsonMapper;
import org.onetwo.common.spring.mvc.utils.DataWrapper;
import org.onetwo.common.web.utils.Browsers.BrowserMeta;
import org.onetwo.common.web.utils.RequestUtils;
import org.onetwo.common.web.utils.ResponseUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.BindingResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import com.google.common.collect.Lists;
/****
* 统一处理json对象
* DataWrapper类型的对象获取value直接返回,其它包装成Result类型对象
* @author way
*
*/
public class BootJsonView extends MappingJackson2JsonView implements InitializingBean {
public static final DataResultWrapper DATA_RESULT_WRAPPER = new DefaultDataResultWrapper();
public static final String CONTENT_TYPE = "application/json;charset=utf-8";
private List<String> excludeClasses = Lists.newArrayList("org.springframework.security.core.userdetails.UserDetails");
// protected final Logger log = JFishLoggerFactory.getLogger(getClass());
// @Autowired
// private BootJFishConfig bootJFishConfig;
@Autowired(required=false)
private XResponseViewManager xresponseViewManager;
@Autowired(required=false)
private ObjectMapperProvider objectMapperProvider;
public BootJsonView(){
JsonMapper jsonMapper = JsonMapper.ignoreNull();
this.setObjectMapper(jsonMapper.getObjectMapper());
}
public void afterPropertiesSet() throws Exception {
this.setContentType(CONTENT_TYPE);
if(objectMapperProvider!=null){
setObjectMapper(objectMapperProvider.createObjectMapper());
}
}
@Override
protected void setResponseContentType(HttpServletRequest request, HttpServletResponse response) {
BrowserMeta meta = RequestUtils.getBrowerMetaByAgent(request);
if(meta.isFuckingBrowser()){
String contextType = ResponseUtils.HTML_TYPE;
response.setContentType(contextType);
}else{
super.setResponseContentType(request, response);
}
}
/*****
* DataWrapper类型的对象获取value直接返回,其它包装成Result类型对象
* spring新版本加了MappingJacksonValue对象,是否统一处理掉它?
*/
protected Object filterModel(Map<String, Object> model) {
model.remove(BootFirstInterceptor.NOW_KEY);
//先根据header获取特定的DataWrapper返回的数据
Optional<Object> data = getResponseViewFromModel(model);
if(data.isPresent()){//因为这里是已经经过header查找到的DataWrapper类型的view,所以直接返回
return data.get();
}
Object result = null;
List<Entry<String, Object>> entryList = Lists.newArrayList(model.entrySet());
for(Map.Entry<String, Object> entry : entryList){
if(DataResult.class.isInstance(entry.getValue())){
result = entry.getValue();
// result = processData(result); //Result 特殊类型无需另外处理
return result;
}else if(DataWrapper.class.isInstance(entry.getValue())){
// result = entry.getValue();
//如果不是默认的DataWrapper,则忽略
if(!DataWrapper.DEFAULT_NAME.equals(entry.getKey())){
continue;
}
result = ((DataWrapper)entry.getValue()).getValue();
// result = processData(result, model);
//默认的DataWrapper也需要查找是否有response view指定的包装器处理
result = getResponseViewFromAnnotation(result, false);
return result;
}
if(BindingResult.class.isInstance(entry.getValue()) ||
// UserDetails.class.isInstance(entry.getValue()) ||
MultipartFile.class.isInstance(entry.getValue())){
model.remove(entry.getKey());
}else if(entry.getValue()!=null && excludeClasses.contains(entry.getValue().getClass().getName())){
model.remove(entry.getKey());
}
}
// setExtractValueFromSingleKeyModel(false);
// filterModelByCallback(model);
if(result==null){
result = super.filterModel(model);
}
result = processData(result, model);
return result;
}
protected Object processData(Object data, Map<String, Object> model){
return getResponseViewFromAnnotation(data, true);
}
/****
* 根据header获取view,view必须是DataWrapper类型
* @author wayshall
* @param model
* @return
*/
protected Optional<Object> getResponseViewFromModel(Map<String, Object> model){
return xresponseViewManager.getResponseViewFromModel(model);
}
/***
* @author wayshall
* @param data
* @return
*/
protected Object getResponseViewFromAnnotation(final Object data, boolean defaultWrapIfNotFoud){
BootWebHelper helper = BootWebUtils.webHelper();
if(helper==null || helper.getControllerHandler()==null){
return data;
}
HandlerMethod hm = helper.getControllerHandler();
if(xresponseViewManager!=null){
return xresponseViewManager.getHandlerMethodResponseView(hm, data, defaultWrapIfNotFoud);
}
return data;
}
protected Object delegateSpringFilterModel(Map<String, Object> model) {
return super.filterModel(model);
}
public void setObjectMapperProvider(ObjectMapperProvider objectMapperProvider) {
this.objectMapperProvider = objectMapperProvider;
}
}
| 31.891429
| 119
| 0.772801
|
a3c5ff4f4de891c79a8fca1950245c17abbfab3d
| 370
|
package com.atguigu.gulimall.member.feign;
import com.atguigu.common.utils.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "gulimall-coupon", url = "127.0.0.1:7001")
public interface CouponFeignService {
@RequestMapping("/coupon/coupon/member/list")
R membercoupons();
}
| 28.461538
| 62
| 0.791892
|
a22c3a2137b6dc11f4e77137602b44fcb72427bb
| 13,860
|
package com.bdoemu.gameserver.model.creature.player.itemPack.events;
import com.bdoemu.commons.model.enums.EStringTable;
import com.bdoemu.commons.utils.Rnd;
import com.bdoemu.core.configs.EtcOptionConfig;
import com.bdoemu.core.configs.RateConfig;
import com.bdoemu.core.network.sendable.SMBroadcastGetItem;
import com.bdoemu.core.network.sendable.SMEnchantItem;
import com.bdoemu.core.network.sendable.SMUpdateEnchantFailCount;
import com.bdoemu.gameserver.model.creature.observers.enums.EObserveType;
import com.bdoemu.gameserver.model.creature.player.Player;
import com.bdoemu.gameserver.model.creature.player.itemPack.ItemPack;
import com.bdoemu.gameserver.model.creature.player.itemPack.PlayerBag;
import com.bdoemu.gameserver.model.items.Item;
import com.bdoemu.gameserver.model.items.MasterItemMarket;
import com.bdoemu.gameserver.model.items.enums.EEnchantType;
import com.bdoemu.gameserver.model.items.enums.EItemGetType;
import com.bdoemu.gameserver.model.items.enums.EItemStorageLocation;
import com.bdoemu.gameserver.model.items.services.ItemMarketService;
import com.bdoemu.gameserver.model.items.templates.ItemEnchantT;
import com.bdoemu.gameserver.model.journal.JournalEntry;
import com.bdoemu.gameserver.model.journal.enums.EJournalEntryType;
import com.bdoemu.gameserver.service.GameTimeService;
import com.bdoemu.gameserver.utils.PARand;
import com.bdoemu.gameserver.worldInstance.World;
public class EnchantItemEvent implements IBagEvent {
private final PlayerBag playerBag;
private Player player;
private EItemStorageLocation itemStorageType;
private EItemStorageLocation stoneStorageType;
private EItemStorageLocation croneStorageType;
private int itemSlot;
private int stoneSlot;
private int croneSlotIndex;
private boolean isPerfect;
private Item stone;
private Item item;
private Item crone;
private ItemPack stonePack;
private ItemPack itemPack;
private ItemPack croneItemPack;
private ItemEnchantT enchantTemplate;
private int enchantRate;
private int enchantResultType;
private int itemId;
private int maxEndurance;
private int enchantLevel;
private EStringTable msg;
private Long stoneCount;
private boolean type;
private EEnchantType enchantType;
private long croneStoneCount;
public EnchantItemEvent(final Player player, final EItemStorageLocation itemStorageType, final int itemSlot, final EItemStorageLocation stoneStorageType, final int stoneSlot, final EItemStorageLocation croneStorageType, final int croneSlotIndex, final boolean isPerfect) {
this.msg = EStringTable.NONE;
this.stoneCount = 1L;
this.type = false;
this.croneStoneCount = 0L;
this.player = player;
this.itemStorageType = itemStorageType;
this.stoneStorageType = stoneStorageType;
this.croneStorageType = croneStorageType;
this.itemSlot = itemSlot;
this.stoneSlot = stoneSlot;
this.croneSlotIndex = croneSlotIndex;
this.isPerfect = isPerfect;
this.playerBag = player.getPlayerBag();
}
@Override
public void onEvent() {
final boolean isSuccess = PARand.PARollChance(this.enchantRate + RateConfig.ENCHANT_FAIL_RATE * player.getEnchantFailCount());
this.type = true;
this.enchantLevel = this.item.getEnchantLevel();
this.itemId = this.item.getItemId();
final JournalEntry journalEntry = new JournalEntry();
journalEntry.setDate(GameTimeService.getServerTimeInMillis());
journalEntry.setParam0((short) this.itemId);
journalEntry.setParam1((short) this.enchantLevel);
if (this.crone != null) {
this.crone.addCount(-this.croneStoneCount);
if (this.crone.getCount() <= 0L) {
this.croneItemPack.removeItem(this.croneSlotIndex);
}
this.player.getGameStats().getWeight().addWeight(-this.crone.getTemplate().getWeight());
}
if (isSuccess) {
++this.enchantLevel;
if (this.enchantRate < 1000000) {
this.player.setEnchantFailCount(0);
this.player.setEnchantSuccessCount(this.player.getEnchantSuccessCount() + 1);
}
if (this.enchantTemplate.isNotifyWorld()) {
World.getInstance().broadcastWorldPacket(new SMBroadcastGetItem(EItemGetType.ENCHANT, this.player.getName(), this.itemId, this.item.getEnchantLevel(), this.enchantLevel));
}
if (this.isPerfect) {
this.item.addMaxEndurance(-this.enchantTemplate.getReduceMaxEnduranceAtPerfectEnchant());
}
journalEntry.setParam4((short) this.enchantLevel);
journalEntry.setType(EJournalEntryType.ItemEnchantSuccess);
} else {
if (this.enchantTemplate.isNotifyWorld()) {
World.getInstance().broadcastWorldPacket(
new SMBroadcastGetItem(
EItemGetType.ENCHANT_FAIL,
this.player.getName(),
this.itemId,
this.enchantLevel,
this.item.getEnchantLevel()
)
);
}
if (this.enchantType.isAccessoryEnchant()) {
if (this.crone == null) {
this.itemId = 0;
this.enchantLevel = 0;
this.item.addCount(-1L);
this.enchantResultType = 1;
} else {
if (this.enchantLevel > 0) {
--this.enchantLevel;
}
this.enchantResultType = 2;
}
} else {
this.enchantResultType = 3;
this.item.addMaxEndurance(-this.enchantTemplate.getReduceMaxEnduranceAtFail());
}
int enchantFailCount = 1;
switch (this.item.getEnchantLevel()) {
case 15: {
enchantFailCount = 2;
break;
}
case 16: {
enchantFailCount = 3;
break;
}
case 17: {
enchantFailCount = 4;
break;
}
case 18: {
enchantFailCount = 5;
break;
}
case 19: {
enchantFailCount = 6;
break;
}
}
if (this.crone == null) {
if (this.enchantType.isUnsafeRiskEnchant()) {
--this.enchantLevel;
}
this.player.setEnchantFailCount(this.player.getEnchantFailCount() + enchantFailCount);
}
this.player.setEnchantSuccessCount(0);
journalEntry.setParam4((short) this.enchantLevel);
journalEntry.setType(EJournalEntryType.ItemEnchantFail);
}
this.item.setEnchantLevel(this.enchantLevel);
this.maxEndurance = this.item.getMaxEndurance();
this.stone.addCount(-this.stoneCount);
this.player.getGameStats().getWeight().addWeight(-this.stone.getTemplate().getWeight() * this.stoneCount);
if (this.stone.getCount() <= 0L) {
this.stonePack.removeItem(this.stoneSlot);
}
if (this.item.getCount() <= 0L) {
this.itemPack.removeItem(this.itemSlot);
this.player.getGameStats().getWeight().addWeight(-this.item.getTemplate().getWeight());
}
this.player.addJournalEntryAndNotify(journalEntry);
this.player.getObserveController().notifyObserver(EObserveType.enchantItem, (int) (isSuccess ? 1 : 0), isSuccess ? this.player.getEnchantSuccessCount() : this.player.getEnchantFailCount());
this.player.sendPacket(new SMUpdateEnchantFailCount(this.player));
this.player.sendPacket(new SMEnchantItem(this));
}
@Override
public boolean canAct() {
if (!this.stoneStorageType.isPlayerInventories() || !this.itemStorageType.isPlayerInventories()) {
return false;
}
this.stonePack = this.playerBag.getItemPack(this.stoneStorageType);
this.itemPack = this.playerBag.getItemPack(this.itemStorageType);
this.item = this.itemPack.getItem(this.itemSlot);
this.stone = this.stonePack.getItem(this.stoneSlot);
if (this.item == null || this.stone == null) {
return false;
}
this.enchantTemplate = this.item.getTemplate().getEnchantTemplates().get(this.item.getEnchantLevel() + 1);
if (this.enchantTemplate == null) {
return false;
}
if (this.croneStorageType.isPlayerInventories()) {
this.croneItemPack = this.playerBag.getItemPack(this.croneStorageType);
this.crone = this.croneItemPack.getItem(this.croneSlotIndex);
if (this.crone != null) {
if (this.crone.getItemId() != EtcOptionConfig.PREVENT_DOWNGRADE_ITEM_KEY) {
return false;
}
if (!EtcOptionConfig.ENABLE_ENCHANT_CRONE_STONE) {
this.enchantResultType = 5;
this.msg = EStringTable.eErrNoItemDontEnchantItem;
this.player.sendPacket(new SMEnchantItem(this));
return false;
}
final MasterItemMarket currentMasterItemMarket = ItemMarketService.getInstance().getMasterItemMarket(this.item.getItemId(), this.item.getEnchantLevel());
final MasterItemMarket nextMasterItemMarket = ItemMarketService.getInstance().getMasterItemMarket(this.item.getItemId(), this.item.getEnchantLevel() + 1);
final long diffMarketPrice = nextMasterItemMarket.getItemMaxPrice() - currentMasterItemMarket.getItemMaxPrice();
this.croneStoneCount = 1L;
if (diffMarketPrice >= 4000000L) {
this.croneStoneCount = (long) Math.floor(diffMarketPrice / 2000000.0f);
}
if (this.crone.getCount() < this.croneStoneCount) {
return false;
}
}
}
if (this.stone.getTemplate().getGradeType().isWhite()) {
return false;
}
if (this.item.getEnchantLevel() >= EtcOptionConfig.MAX_ENCHANT_LEVEL) {
this.enchantResultType = 5;
this.msg = EStringTable.eErrNoItemEnchantLevelIsMax;
this.player.sendPacket(new SMEnchantItem(this));
return false;
}
if (this.item.getTemplate().getEndurance() * this.item.getMaxEndurance() / 100 <= 20) {
this.enchantResultType = 5;
this.msg = EStringTable.eErrNoItemMaxEnduranceIsLack;
this.player.sendPacket(new SMEnchantItem(this));
return false;
}
this.enchantType = this.enchantTemplate.getEnchantType();
this.stoneCount = (this.isPerfect ? this.enchantTemplate.getPerfectEnchantItemCount() : this.enchantTemplate.getReqEnchantItemCount());
if (this.stoneCount == null || this.enchantTemplate.getReqEnchantItemId() != this.stone.getItemId() || this.stone.getCount() < this.stoneCount) {
return false;
}
if (this.isPerfect) {
this.enchantRate = 1000000;
} else {
switch (this.enchantType) {
case SafeEnchant:
case UnsafeEnchant:
case UnsafeRiskEnchant: {
if (this.item.getItemClassify().isArmor()) {
this.enchantRate = RateConfig.ENCHANT_ARMOR_RATES[this.item.getEnchantLevel() + 1];
break;
}
if (this.item.getItemClassify().isWeapon()) {
this.enchantRate = RateConfig.ENCHANT_WEAPON_RATES[this.item.getEnchantLevel() + 1];
break;
}
break;
}
case AccessoryEnchant: {
if (this.item.getItemClassify().isAccessory()) {
this.enchantRate = RateConfig.ENCHANT_ACCESSORY_RATES[this.item.getEnchantLevel() + 1];
break;
}
if (this.item.getItemClassify().isArmor()) {
this.enchantRate = RateConfig.ENCHANT_CLOTHES_RATES[this.item.getEnchantLevel() + 1];
break;
}
break;
}
}
}
return true;
}
public long getCroneStoneCount() {
return croneStoneCount;
}
public Item getCrone() {
return crone;
}
public EItemStorageLocation getCroneStorageType() {
return croneStorageType;
}
public int getCroneSlotIndex() {
return croneSlotIndex;
}
public boolean isType() {
return type;
}
public int getMaxEndurance() {
return maxEndurance;
}
public int getItemId() {
return itemId;
}
public int getEnchantLevel() {
return enchantLevel;
}
public EStringTable getMsg() {
return msg;
}
public Long getStoneCount() {
return stoneCount;
}
public int getStoneSlot() {
return stoneSlot;
}
public EItemStorageLocation getStoneStorageType() {
return stoneStorageType;
}
public int getItemSlot() {
return itemSlot;
}
public EItemStorageLocation getItemStorageType() {
return itemStorageType;
}
public int getEnchantType() {
return enchantResultType;
}
}
| 41.497006
| 276
| 0.607648
|
d804bee1d83564f46cda9c08c1b65a374926b2ad
| 1,648
|
package com.github.ma1co.pmcademo.app;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.github.ma1co.openmemories.framework.DisplayManager;
public class ScalingBitmapView extends ImageView implements AppNotificationManager.NotificationListener {
protected class ScaledBitmapDrawable extends BitmapDrawable {
private float xScale;
public ScaledBitmapDrawable(Bitmap bitmap, float xScale) {
super(bitmap);
this.xScale = xScale;
}
@Override
public int getIntrinsicWidth() {
return Math.round(super.getIntrinsicWidth() * xScale);
}
}
private Bitmap bitmap;
public ScalingBitmapView(Context context, AttributeSet attrs) {
super(context, attrs);
AppNotificationManager.getInstance().addListener(this);
}
@Override
public void setImageBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
update();
}
@Override
public void onNotify(String message) {
if (message.equals(BaseActivity.NOTIFICATION_DISPLAY_CHANGED))
update();
}
private void update() {
DisplayManager displayManager = DisplayManager.create(getContext());
float displayAspect = displayManager.getActiveDisplayInfo().aspectRatio;
float frameBufferAspect = displayManager.getFrameBufferInfo().aspectRatio;
displayManager.release();
setImageDrawable(new ScaledBitmapDrawable(bitmap, frameBufferAspect / displayAspect));
}
}
| 31.09434
| 105
| 0.707524
|
e6750c46e9e2bb5551d1f612f9c15a5bda602371
| 2,707
|
package io.odpf.dagger.core.protohandler;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import io.odpf.dagger.core.protohandler.typehandler.PrimitiveTypeHandler;
import io.odpf.dagger.core.protohandler.typehandler.PrimitiveTypeHandlerFactory;
import com.google.gson.Gson;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.DynamicMessage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.google.protobuf.Descriptors.FieldDescriptor.JavaType.ENUM;
import static com.google.protobuf.Descriptors.FieldDescriptor.JavaType.MESSAGE;
/**
* The type Repeated primitive proto handler.
*/
public class RepeatedPrimitiveProtoHandler implements ProtoHandler {
private final FieldDescriptor fieldDescriptor;
private static final Gson GSON = new Gson();
/**
* Instantiates a new Repeated primitive proto handler.
*
* @param fieldDescriptor the field descriptor
*/
public RepeatedPrimitiveProtoHandler(FieldDescriptor fieldDescriptor) {
this.fieldDescriptor = fieldDescriptor;
}
@Override
public boolean canHandle() {
return fieldDescriptor.isRepeated() && fieldDescriptor.getJavaType() != MESSAGE && fieldDescriptor.getJavaType() != ENUM;
}
@Override
public DynamicMessage.Builder transformForKafka(DynamicMessage.Builder builder, Object field) {
if (!canHandle() || field == null) {
return builder;
}
if (field.getClass().isArray()) {
field = Arrays.asList((Object[]) field);
}
return builder.setField(fieldDescriptor, field);
}
@Override
public Object transformFromPostProcessor(Object field) {
ArrayList<Object> outputValues = new ArrayList<>();
if (field != null) {
List<Object> inputValues = (List<Object>) field;
PrimitiveProtoHandler primitiveProtoHandler = new PrimitiveProtoHandler(fieldDescriptor);
for (Object inputField : inputValues) {
outputValues.add(primitiveProtoHandler.transformFromPostProcessor(inputField));
}
}
return outputValues;
}
@Override
public Object transformFromKafka(Object field) {
PrimitiveTypeHandler primitiveTypeHandler = PrimitiveTypeHandlerFactory.getTypeHandler(fieldDescriptor);
return primitiveTypeHandler.getArray(field);
}
@Override
public Object transformToJson(Object field) {
return GSON.toJson(field);
}
@Override
public TypeInformation getTypeInformation() {
return PrimitiveTypeHandlerFactory.getTypeHandler(fieldDescriptor).getArrayType();
}
}
| 34.265823
| 129
| 0.71703
|
f206df746b730d2937adfdd63f6468ae09b63d91
| 2,420
|
package jtoolset.memory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jtoolset.commons.UnsafeHelper;
import sun.misc.Unsafe;
@SuppressWarnings("restriction")
public class Address {
private static final Logger logger = LoggerFactory.getLogger(Address.class);
private static final Unsafe unsafe = UnsafeHelper.get();
//SEE typeArrayOpp.hpp static int object_size(int lh, int length)
public static final long OBJECT_HEADER_SIZE = 12;
/*
* See arrayOop.hpp from hotspot source code
*/
public static final long ARRAY_LENGTH_HEADER= 4;
public static final long ARRAY_HEADER_SIZE = OBJECT_HEADER_SIZE + ARRAY_LENGTH_HEADER;
public static final int ADDRESS32BIT = 4;
public static final int ADDRESS64BIT = 8;
public static final int JVM_ADDRESS_SIZE = calculateAddressSize();
public static final int ADDRESS_SIZE = unsafe.addressSize();
public static long get(Object o) {
Object[] array = new Object[] { o };
Unsafe unsafe = UnsafeHelper.get();
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
long objectAddress;
switch (ADDRESS_SIZE) {
case ADDRESS32BIT:
objectAddress = unsafe.getInt(array, baseOffset);
break;
case ADDRESS64BIT:
objectAddress = unsafe.getLong(array, baseOffset);
break;
default:
throw new Error("unsupported address size: " + ADDRESS_SIZE);
}
return objectAddress;
}
public static long alignment(long size) {
long sizeWithoutRemainder = (size / Address.ADDRESS_SIZE) * Address.ADDRESS_SIZE;
if (size - sizeWithoutRemainder > 0) {
return sizeWithoutRemainder + Address.ADDRESS_SIZE;
}
return size;
}
/**
* JVM address size depends on platform (32 or 64),
* JVM option UseCompressedOops and maybe something else.
* The best way to calculate real address size is measure field offset.
* @return
*/
private static int calculateAddressSize() {
int addressSize = 0;
try {
addressSize =
(int) (unsafe.objectFieldOffset(Sample.class.getDeclaredField("o2"))
- unsafe.objectFieldOffset(Sample.class.getDeclaredField("o1")));
} catch (NoSuchFieldException | SecurityException e) {
logger.error("Something bad just happened ", e);
}
assert(addressSize > 0);
return addressSize;
}
private static class Sample {
private Object o1;
private Object o2;
}
}
| 29.876543
| 88
| 0.705372
|
9cf266c44f39fe27e5096fca4ba41a789d6554f1
| 2,922
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.json;
import org.openqa.selenium.internal.Require;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.CharBuffer;
/**
* Similar to a {@link Readable} but with the ability to peek a single character ahead.
* <p>
* For the sake of providing a useful {@link #toString()} implementation, keeps a small circular
* buffer of the most recently read characters.
*/
class Input {
public static final char EOF = (char) -1;
private final Readable source;
private boolean read;
private char peekedChar;
private char[] lastRead = new char[128];
private int insertAt = 0;
private boolean filled = false;
public Input(Readable source) {
this.source = Require.nonNull("Source", source);
}
public char peek() {
init();
return peekedChar;
}
public char read() {
init();
read = false;
append();
return peekedChar;
}
@Override
public String toString() {
String preamble = "Last " + (filled ? lastRead.length : insertAt) + " characters read: ";
if (!filled) {
return preamble + new String(lastRead, 0, insertAt);
}
// We filled the array. The insertion point would overwrite the first thing we should read.
char[] buf = new char[lastRead.length];
int lengthToRead = lastRead.length - insertAt;
System.arraycopy(lastRead, insertAt, buf, 0, lengthToRead);
System.arraycopy(lastRead, 0, buf, lengthToRead, insertAt);
return preamble + new String(buf);
}
private void init() {
if (read) {
return;
}
CharBuffer buf = CharBuffer.allocate(1);
int charsRead;
try {
charsRead = source.read(buf);
} catch (IOException e) {
throw new UncheckedIOException(e.getMessage(), e);
}
if (charsRead != 1) {
peekedChar = EOF;
} else {
peekedChar = buf.array()[0];
}
read = true;
}
private void append() {
if (peekedChar == Input.EOF) {
return;
}
lastRead[insertAt] = peekedChar;
insertAt = ++insertAt % lastRead.length;
if (insertAt == 0) {
filled = true;
}
}
}
| 27.828571
| 96
| 0.675222
|
648c83c0882460c73f48aa7be18d814d5ab17cea
| 534
|
package com.example.armychess;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class custom_position extends AppCompatActivity {
/*
* 自定义布局的底类
*
* */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_position);
customview custom= findViewById(R.id.custom);
Button save= findViewById(R.id.savebuju);
custom.setButton(save);
}
}
| 25.428571
| 58
| 0.730337
|
62dd85ce15a3268ec13d29c67fb1269d00699f8a
| 3,708
|
/*******************************************************************************
* Copyright © Microsoft Open Technologies, Inc.
*
* All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS//
* OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
* ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
* PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache License, Version 2.0 for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.pliu.powerbiembed;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.microsoft.aad.adal4j.AuthenticationResult;
@Controller
@RequestMapping("/secure/reports")
public class ReportsController {
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String getReports(ModelMap model, HttpServletRequest httpRequest) {
HttpSession session = httpRequest.getSession();
AuthenticationResult result = (AuthenticationResult) session.getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
if (result == null) {
model.addAttribute("//error", new Exception("AuthenticationResult not found in session."));
return "/error";
}
try {
ServletContext cxt = session.getServletContext();
String proxyToken = AuthHelper.getAccessTokenFromProxyUserCredentials(cxt);
String workspaceId = cxt.getInitParameter("workspaceId");
String apiUrl = cxt.getInitParameter("apiUrl");
Report[] data;
data = getReportsFromPowerBI(workspaceId, apiUrl, proxyToken);
model.addAttribute("reports", data);
} catch (Exception e) {
model.addAttribute("error", e);
return "/error";
}
return "/secure/reports";
}
private Report[] getReportsFromPowerBI(String workspaceId, String apiUrl, String proxyToken)
throws Exception {
URL url = new URL(String.format("%s/v1.0/myorg/groups/%s/reports",
apiUrl, workspaceId));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", String.format("Bearer %s", proxyToken));
String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
int responseCode = conn.getResponseCode();
JSONObject response = HttpClientHelper.processGoodRespStr(responseCode, goodRespStr);
JSONArray jreports = JSONHelper.fetchDirectoryObjectJSONArray(response);
int numReports = jreports.length();
Report[] reports = new Report[numReports];
for (int i = 0; i < numReports; i++) {
JSONObject thisReportJSONObject = jreports.optJSONObject(i);
reports[i] = new Report();
JSONHelper.convertJSONObjectToDirectoryObject(thisReportJSONObject, reports[i]);
}
return reports;
}
}
| 40.747253
| 117
| 0.673948
|
2b0b339a0d9343dd19d585125af822cb2a72886d
| 14,800
|
package nl.geodan.steward;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
public class SensorService extends Service implements SensorEventListener {
public static int counter = 0;
public static double longitude = 0d;
public static double latitude = 0d;
public static double accuracy = 0d;
public static double bearing = 0d;
public static boolean hasConnection = false;
public static String ip = "";
private static Timer timer;
private static TimerTask timerTask;
private static final String TAG = "STEWARDSERVICE";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private static PahoMqttClient pahoMqttClient;
private static MqttAndroidClient mqttAndroidClient;
private boolean mqttConnecting;
private static final String TAG_FOREGROUND_SERVICE = "STEWARDCHANNEL";
private SensorManager SensorManager;
public synchronized void setCounter(int newValue) {
counter = newValue;
}
public synchronized void setAccuracy(double newValue) {
accuracy = newValue;
}
public synchronized void setBearing(double newValue) {
bearing = newValue;
}
public synchronized void setLongitude(double newValue) {
longitude = newValue;
}
public synchronized void setLatitude(double newValue) {
latitude = newValue;
}
public synchronized void setHasConnection(boolean newValue) {
hasConnection = newValue;
}
public synchronized void setIp(String newValue) {
ip = newValue;
}
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
public String getStewardName(){
return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("stewardName", "steward1");
}
public String getUniqueId(){
return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("uuid", "empty");
}
public String getBroker(){
return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("broker", "tcp://iot.eclipse.org:1883");
}
public int getUpdateFrequency(){
return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt("updateFrequency", 1000);
}
@Override
public int onStartCommand(Intent Intent, int flags, int startId) {
super.onStartCommand(Intent, flags, startId);
startMqtt();
startLocation();
startCompass();
startTimer();
//return START_STICKY;
Log.d(TAG_FOREGROUND_SERVICE, "Start foreground service.");
createNotificationChannel();
// Create notification default intent.
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, Intent, 0);
// Create notification builder.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, TAG_FOREGROUND_SERVICE);
// Make notification show big text.
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle("ArenA Steward Tracker");
bigTextStyle.bigText("Status: Tracking");
builder.setStyle(bigTextStyle);
builder.setWhen(System.currentTimeMillis());
builder.setSmallIcon(R.drawable.route);
// Make the notification max priority.
builder.setPriority(Notification.PRIORITY_MAX);
// Make head-up notification.
builder.setFullScreenIntent(pendingIntent, true);
// Build the notification.
Notification notification = builder.build();
// Start foreground service.
startForeground(1, notification);
return super.onStartCommand(Intent, flags, startId);
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "steward";
String description = "tracking steward";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(TAG_FOREGROUND_SERVICE, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
@Override
public void onDestroy() {
Log.i("EXIT", "ondestroy!");
// Intent broadcastIntent = new Intent("nl.geodan.steward.RestartSensor");
// sendBroadcast(broadcastIntent);
stoptimertask();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
super.stopSelf();
super.onDestroy();
}
public void startCompass(){
SensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
SensorManager.registerListener(this, SensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_GAME);
}
public void startMqtt(){
if(!hasConnection){
return;
}
mqttConnecting = true;
pahoMqttClient = new PahoMqttClient();
mqttAndroidClient = pahoMqttClient.getMqttClient(getApplicationContext(), getBroker(), getUniqueId());
mqttAndroidClient.setCallback(new MqttCallbackExtended() {
@Override
public void connectComplete(boolean b, String s) {
mqttConnecting = false;
}
@Override
public void connectionLost(Throwable throwable) {}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {}
});
try {
mqttAndroidClient.connect(pahoMqttClient.getMqttConnectionOption());
} catch (MqttException e) {
e.printStackTrace();
mqttConnecting = false;
}
}
public void startLocation(){
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, getUpdateFrequency(), getUpdateFrequency()); //
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
updateConnection();
if(!hasConnection){
return;
}
setAccuracy(Math.floor(mLocationListeners[0].mLastLocation.getAccuracy()));
setLongitude(longitude = mLocationListeners[0].mLastLocation.getLongitude());
setLatitude(mLocationListeners[0].mLastLocation.getLatitude());
if(!mqttAndroidClient.isConnected() && !mqttConnecting){
startMqtt();
return;
}
if(mqttConnecting || longitude == 0d || latitude == 0d){
return;
}
setCounter(counter + 1);
String msg = String.valueOf(longitude) + "," + String.valueOf(latitude) + "," + String.valueOf(accuracy) + "," + String.valueOf(bearing) + "," + ip + "," + getStewardName() + "," + getDateTimeString();
try {
pahoMqttClient.publishMessage(mqttAndroidClient, msg, 1, "arena/" + getUniqueId());
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
public String publishIncident(String id, String stewardName, String incident, String description){
if(!hasConnection || !mqttAndroidClient.isConnected()){
return "No connection, incident not created";
}
String msg = id + "," + stewardName + "," + incident + "," + description + "," + String.valueOf(longitude) + "," + String.valueOf(latitude) + "," + getDateTimeString();
try {
pahoMqttClient.publishMessage(mqttAndroidClient, msg, 1, "arena/incidents");
} catch (Exception e) {
return e.getMessage();
}
return null;
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
public void stoptimertask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
public void updateConnection(){
String localIp = getLocalIpAddress();
boolean hasConnection = localIp == null ? false : true;
if(this.hasConnection != hasConnection){
setHasConnection(hasConnection);
if(this.hasConnection){ // connection restored, reconnect mqtt
startMqtt();
}
}
localIp = localIp == null ? "0.0.0.0" : localIp;
setIp(localIp);
}
private String getDateTimeString(){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return df.format(Calendar.getInstance().getTime());
}
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
@Override
public void onSensorChanged(SensorEvent event) {
float[] mRotationMatrix = new float[9];
float[] mChangedRotationMatrix = new float[9];
float[] mOrientation = new float[9];
SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values);
SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z, mChangedRotationMatrix);
SensorManager.getOrientation(mChangedRotationMatrix, mOrientation);
float magneticHeading = (float) Math.toDegrees(mOrientation[0]);
//change range 0,180/-180,-1 -> 0-360
if(magneticHeading < 0){
magneticHeading = 360 - Math.abs(magneticHeading);
}
setBearing(Math.floor(magneticHeading));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location)
{
mLastLocation.set(location);
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| 35.491607
| 214
| 0.633649
|
07b0e4521a6cfda735b3257704ec7ecc38bf5cc0
| 601
|
package com.github.pozo.game.client.auth;
/**
* Created by pozo on 2016.06.19..
*/
public class User {
private String nickName;
private String password;
public User(String nickName, String password) {
this.nickName = nickName;
this.password = password;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 19.387097
| 51
| 0.625624
|
146e03d0ddbae0e2d17d04f4babf39bcdc9be82a
| 432
|
package top.bluesword.laboratory.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import top.bluesword.laboratory.domain.DataModel;
/**
* @author 李林峰
*/
@Repository
public interface DataJpaRepository extends JpaRepository<DataModel, Long>, JpaSpecificationExecutor<DataModel> {
}
| 30.857143
| 112
| 0.837963
|
01452413c89c24be8212038fb6ea5b2b13adb331
| 4,318
|
package net.ibizsys.paas.ctrlmodel;
import java.util.HashMap;
import net.ibizsys.paas.control.ControlTypes;
import net.ibizsys.paas.control.tree.ITreeNode;
import net.ibizsys.paas.ctrlhandler.ITreeNodeFetchContext;
import net.ibizsys.paas.sysmodel.CodeListGlobal;
import net.ibizsys.paas.sysmodel.ICodeListModel;
import net.ibizsys.paas.util.StringHelper;
import net.ibizsys.paas.web.MDAjaxActionResult;
import net.ibizsys.paas.web.WebContext;
/**
* 树部件模型对象
* @author Administrator
*
*/
public abstract class TreeModelBase extends CtrlModelBase implements ITreeModel
{
private HashMap<String, ITreeNodeModel> treeNodeModelMap = new HashMap<String, ITreeNodeModel>();
private boolean bEnableRootSelect = false;
private ITreeNodeModel rootTreeNodeModel = null;
private boolean bRootVisible = false;
private String strCatCodeListId = null;
@Override
public String getControlType()
{
return ControlTypes.TreeView;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.CtrlModelBase#onInit()
*/
@Override
protected void onInit() throws Exception
{
super.onInit();
onPrepareTreeMode();
}
/**
* 准备树模型
* @throws Exception
*/
protected void onPrepareTreeMode() throws Exception
{
}
/**
* 注树节点模型对象
* @param iTreeNodeTypeModel
* @throws Exception
*/
protected void registerTreeNodeModel(ITreeNodeModel iTreeNodeTypeModel)throws Exception
{
treeNodeModelMap.put(iTreeNodeTypeModel.getId(), iTreeNodeTypeModel);
if(iTreeNodeTypeModel.isRootNode())
{
this.rootTreeNodeModel = iTreeNodeTypeModel;
}
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.ITreeModel#getTreeNodeModel(java.lang.String)
*/
@Override
public ITreeNodeModel getTreeNodeModel(String strTreeNodeModelId)throws Exception
{
ITreeNodeModel iTreeNodeModel = treeNodeModelMap.get(strTreeNodeModelId);
if(iTreeNodeModel == null)
{
//无法获取指定树节点模型
throw new Exception(StringHelper.format("无法获取指定树节点模型[%1$s]", strTreeNodeModelId));
}
return iTreeNodeModel;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.ITreeModel#getRootTreeNodeModel()
*/
@Override
public ITreeNodeModel getRootTreeNodeModel()
{
return this.rootTreeNodeModel ;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.ITreeModel#isEnableRootSelect()
*/
@Override
public boolean isEnableRootSelect()
{
return this.bEnableRootSelect;
}
/**
* 设置是否允许根节点选中
* @param bEnableRootSelect
*/
protected void setEnableRootSelect(boolean bEnableRootSelect)
{
this.bEnableRootSelect = bEnableRootSelect;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.ITreeModel#isRootVisible()
*/
@Override
public boolean isRootVisible()
{
return this.bRootVisible;
}
/**
* 根节点是否可见
* @param bRootVisible
*/
protected void setRootVisible(boolean bRootVisible)
{
this.bRootVisible = bRootVisible;
}
/**
* 获取树分类代码表标识
* @return
*/
@Override
public String getCatCodeListId()
{
return this.strCatCodeListId ;
}
/**
* 设置分类代码表标识
* @param bRootVisible
*/
protected void setCatCodeListId(String strCatCodeListId)
{
this.strCatCodeListId =strCatCodeListId;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.ITreeModel#fillCatFetchResult(net.ibizsys.paas.web.MDAjaxActionResult)
*/
@Override
public void fillCatFetchResult(MDAjaxActionResult fetchResult) throws Exception
{
if(StringHelper.isNullOrEmpty(getCatCodeListId()))
return ;
ICodeListModel iCodeListModel = (ICodeListModel) CodeListGlobal.getCodeList(getCatCodeListId());
iCodeListModel.fillFetchResult(fetchResult, WebContext.getCurrent());
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.ITreeModel#isOutputTreeNodeRS(net.ibizsys.paas.ctrlhandler.ITreeNodeFetchContext, net.ibizsys.paas.ctrlmodel.ITreeNodeRSModel)
*/
@Override
public boolean isOutputTreeNodeRS(ITreeNodeFetchContext iTreeNodeFetchContext, ITreeNodeRSModel iTreeNodeRSModel) throws Exception
{
return true;
}
/* (non-Javadoc)
* @see net.ibizsys.paas.ctrlmodel.ITreeModel#isOutputTreeNode(net.ibizsys.paas.ctrlhandler.ITreeNodeFetchContext, net.ibizsys.paas.control.tree.ITreeNode)
*/
@Override
public boolean isOutputTreeNode(ITreeNodeFetchContext iTreeNodeFetchContext, ITreeNode iTreeNode) throws Exception
{
return true;
}
}
| 23.090909
| 162
| 0.7566
|
0245a97101bfd5b897a6d59f3ac97142226a3ba3
| 311
|
public static void openInBrowser(String string) {
if (java.awt.Desktop.isDesktopSupported()) {
try {
java.awt.Desktop.getDesktop().browse(new URI(string));
} catch (IOException ex) {
} catch (URISyntaxException ex) {
}
}
}
| 31.1
| 70
| 0.524116
|
cbdb9474ff4f84eda45eaeb7eb1cabf162fb6097
| 70
|
package org.globus.gsi.testutils;
public interface SecurityTest {
}
| 11.666667
| 33
| 0.785714
|
4eb631e5112ccbd8a790a879665c7a81ceb56d95
| 207
|
package com.lmt.data.unstructured.entity.search;
import com.lmt.data.unstructured.base.BaseSearch;
/**
* @author MT-Lin
* @date 2018/1/10 12:48
*/
public class ResourceTempSearch extends BaseSearch {
}
| 18.818182
| 52
| 0.748792
|
74d8001e28b0c92b76cacaa226627a1b29014b22
| 631
|
package br.com.aisdigital.app.service;
import br.com.aisdigital.app.model.AlocacaoHoras;
import br.com.aisdigital.app.payload.AlocacaoHorasRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional(rollbackFor=Exception.class)
@Service
public class AlocacaoHorasService {
public AlocacaoHoras mapper(AlocacaoHorasRequest req) {
AlocacaoHoras entidade = new AlocacaoHoras();
entidade.setData(req.getData());
entidade.setHoras(req.getHoras());
entidade.setProjeto(req.getProjeto());
return entidade;
}
}
| 30.047619
| 64
| 0.763867
|
86038de374da7f2fb66567ef1a8d7605ce00b047
| 1,519
|
/*
* Copyright (C) 2020 Intel Corporation. All rights reserved. SPDX-License-Identifier: Apache-2.0
*/
package com.openiot.cloud.base.mongo.dao.custom;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import com.openiot.cloud.base.help.ConstDef;
import com.openiot.cloud.base.mongo.model.ResProperty;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
public class ResProRepositoryImpl implements ResProRepositoryCustom {
@Autowired private MongoOperations monOp;
@Override
public List<ResProperty> filter(
String devId, String resUrl, String propName, Boolean implemented, Pageable pageable) {
Query q = new Query();
Optional.ofNullable(devId).ifPresent(di -> q.addCriteria(where(ConstDef.F_DEVID).is(di)));
Optional.ofNullable(resUrl).ifPresent(url -> q.addCriteria(where(ConstDef.F_RES).is(url)));
Optional.ofNullable(propName).ifPresent(name -> q.addCriteria(where(ConstDef.F_NAME).is(name)));
Optional.ofNullable(implemented)
.ifPresent(impl -> q.addCriteria(where(ConstDef.F_IMPLED).is(impl)));
pageable = pageable == null ? PageRequest.of(0, ConstDef.DFLT_SIZE) : pageable;
q.with(pageable);
return monOp.find(q, ResProperty.class);
}
}
| 36.166667
| 100
| 0.768927
|
8809d0b4489a1fe112e8cb921b4ec99e07ac0d16
| 1,823
|
// Targeted by JavaCPP version 1.5-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.opencv.opencv_core;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.opencv.global.opencv_core.*;
@Name("std::vector<std::pair<int,double> >") @Properties(inherit = org.bytedeco.opencv.presets.opencv_core.class)
public class IntDoublePairVector extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public IntDoublePairVector(Pointer p) { super(p); }
public IntDoublePairVector(int[] firstValue, double[] secondValue) { this(Math.min(firstValue.length, secondValue.length)); put(firstValue, secondValue); }
public IntDoublePairVector() { allocate(); }
public IntDoublePairVector(long n) { allocate(n); }
private native void allocate();
private native void allocate(@Cast("size_t") long n);
public native @Name("operator=") @ByRef IntDoublePairVector put(@ByRef IntDoublePairVector x);
public boolean empty() { return size() == 0; }
public native long size();
public void clear() { resize(0); }
public native void resize(@Cast("size_t") long n);
@Index(function = "at") public native int first(@Cast("size_t") long i); public native IntDoublePairVector first(@Cast("size_t") long i, int first);
@Index(function = "at") public native double second(@Cast("size_t") long i); public native IntDoublePairVector second(@Cast("size_t") long i, double second);
public IntDoublePairVector put(int[] firstValue, double[] secondValue) {
for (int i = 0; i < firstValue.length && i < secondValue.length; i++) {
first(i, firstValue[i]);
second(i, secondValue[i]);
}
return this;
}
}
| 45.575
| 162
| 0.691717
|
2dd4a574f53d677c43d4e645757c06be9b25be29
| 5,996
|
/*
* The MIT License
*
* Copyright 2016 Olavi Mustanoja.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.tilastokeskus.minotaurus.simulation;
import com.github.tilastokeskus.minotaurus.maze.Maze;
import com.github.tilastokeskus.minotaurus.maze.MazeGenerator;
import com.github.tilastokeskus.minotaurus.scenario.Scenario;
import com.github.tilastokeskus.minotaurus.util.Direction;
import java.util.List;
import java.util.Observable;
import com.github.tilastokeskus.minotaurus.runner.Runner;
import com.github.tilastokeskus.minotaurus.util.ArrayList;
import com.github.tilastokeskus.minotaurus.util.Rotation;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Simulation handler is the mediator between a MazeGenerator, Scenario and
* a set of Runners. Its job is to figure out each runner's preferred move each
* turn, and move them if it's allowed.
*/
public class SimulationHandler extends Observable {
private static final Logger LOGGER = Logger.getLogger(SimulationHandler.class.getName());
private final Maze maze;
private final Scenario scenario;
private final List<Runner> runners;
private ScheduledExecutorService executor;
/**
* Creates a new simulation handler with the given maze generator, scenario
* and runners.
*
* @param gen Maze generator to use.
* @param scenario Scenario to use.
* @param runners Runners to use.
*/
public SimulationHandler(MazeGenerator gen, Scenario scenario, List<Runner> runners) {
this.maze = gen.generateMaze(50, 50).clone();
this.scenario = scenario;
this.runners = runners;
executor = Executors.newSingleThreadScheduledExecutor();
}
/**
* Starts the simulation with the specified speed.
*
* @param rate Delay, in milliseconds, between each move.
*/
public void startSimulation(int rate, int cap) {
// Initialize the scenario and ask it to place the runners in the maze.
this.scenario.setMaze(maze);
this.scenario.placeRunners(runners);
// Place runners in the maze.
for (Runner runner : runners)
maze.addEntity(runner);
executor.scheduleWithFixedDelay(() -> {
// Wrap call to try-catch, since Future devours exceptions.
try {
simulateRound();
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "", ex);
}
if (runners.isEmpty())
stop();
if (cap > 0) {
for (Runner r : runners) {
if (scenario.getScore(r) >= cap) {
stop();
break;
}
}
}
}, rate, rate, TimeUnit.MILLISECONDS);
}
/**
* Simulates a single round, a round being when all runners have moved once.
* If a runner makes a move that is not allowed, that runner will be removed
* from the simulation.
*/
private void simulateRound() {
Iterator<Runner> it = runners.iterator();
while (it.hasNext()) {
Runner runner = it.next();
// Get the direction the runner wants to go next.
Direction dir = runner.getNextMove(maze,
scenario.getRunnerGoals(runner),
scenario.getPositionPredicate(runner));
boolean acceptedMove = scenario.handleRunnerMove(runner, dir);
if (acceptedMove) {
// Update the runner to point in the direction it moved.
switch (dir) {
case UP:
runner.setRotation(Rotation.UP.angle);
break;
case RIGHT:
runner.setRotation(Rotation.RIGHT.angle);
break;
case DOWN:
runner.setRotation(Rotation.DOWN.angle);
break;
case LEFT:
runner.setRotation(Rotation.LEFT.angle);
break;
}
} else {
System.out.println("illegal");
it.remove();
}
}
this.setChanged();
this.notifyObservers();
}
/**
* Stops the simulation.
*/
public void stop() {
executor.shutdown();
}
public Maze getMaze() {
return maze;
}
public List<Runner> getRunners() {
return new ArrayList<>(runners);
}
public Scenario getScenario() {
return scenario;
}
}
| 34.262857
| 93
| 0.604069
|
01b57cd7bca4b2cc77d0b764530eceb6769dac0f
| 1,309
|
package app.beelabs.com.coconut.model.api.response;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
import app.beelabs.com.coconut.model.pojo.Article;
import app.beelabs.com.codebase.base.response.BaseDataResponse;
import app.beelabs.com.codebase.base.response.BaseResponse;
/**
* Created by arysuryawan on 8/19/17.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ArticleResponse extends BaseResponse {
private DataResponse data;
private String source;
private String sortBy;
private List<Article> articles;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getSortBy() {
return sortBy;
}
public void setSortBy(String sortBy) {
this.sortBy = sortBy;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
@Override
public DataResponse getBaseData() {
return data;
}
public void setData(DataResponse data) {
this.data = data;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class DataResponse extends BaseDataResponse {
}
}
| 21.112903
| 63
| 0.685256
|
e610a2368672ac1cb5d68227f06a4335a166c387
| 3,173
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.test.multidevice;
import com.android.annotations.NonNull;
import com.google.common.base.Joiner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
/**
* Utility methods for communicating with the device pool, as defined in buildSrc.
*
* This is used by the the AdbPoolDeviceProvider to reserve a device during test execution,
* and by the Adb test rule to reserve one device over multiple builds for testing instant run
* and other tasks.
*/
public class DevicePoolClient {
/** This needs to be kept in sync with the port in integration-test/build.gradle */
private static final int PORT = 5554;
public static String reserveDevice(
@NonNull List<String> serials, @NonNull String displayName) throws IOException {
if (serials.isEmpty()) {
throw new IllegalArgumentException("Must supply list of device serials to reserve");
}
return request(
"request " + Joiner.on(',').join(serials) + " " + displayName.replace(' ', '_'));
}
public static void returnDevices(
@NonNull List<String> serials, @NonNull String displayName) throws IOException {
if (serials.isEmpty()) {
throw new IllegalArgumentException("Must supply list of device serials to return");
}
for (String serial : serials) {
if (serial.isEmpty()) {
throw new IllegalArgumentException("Device serial must exist");
}
request("return " + serial + " " + displayName.replace(' ', '_'));
}
}
public static void reserveAllDevices(@NonNull String displayName) throws IOException {
request("requestAll " + displayName.replace(' ', '_'));
}
public static void returnAllDevices(@NonNull String displayName) throws IOException {
request("returnAll " + displayName.replace(' ', '_'));
}
private static String request(@NonNull String command) throws IOException {
try (Socket socket = new Socket((String) null, PORT)) {
try (BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
try (PrintWriter out = new PrintWriter(socket.getOutputStream())) {
out.println(command);
out.flush();
return input.readLine();
}
}
}
}
}
| 38.228916
| 97
| 0.658367
|
96680e966188ba560d8ceba3cf58b34b373e2428
| 6,481
|
package seedu.address.storage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.person.Email;
import seedu.address.model.person.Gender;
import seedu.address.model.person.Involvement;
import seedu.address.model.person.Name;
import seedu.address.model.person.Phone;
import seedu.address.model.person.student.Address;
import seedu.address.model.person.student.FormClass;
import seedu.address.model.person.student.MedicalHistory;
import seedu.address.model.person.student.Student;
import seedu.address.model.tag.Tag;
/**
* Jackson-friendly version of {@link Student}.
*/
class JsonAdaptedStudent extends JsonAdaptedPerson {
public static final String MISSING_FIELD_MESSAGE_FORMAT = "Student's %s field is missing!";
private final String address;
private final String emergencyContact;
private final String formClass;
private final String medicalHistory;
/**
* Constructs a {@code JsonAdaptedStudent} with the given student details.
*/
@JsonCreator
public JsonAdaptedStudent(@JsonProperty("name") String name, @JsonProperty("phone") String phone,
@JsonProperty("email") String email, @JsonProperty("gender") String gender,
@JsonProperty("involvement") String involvement,
@JsonProperty("address") String address,
@JsonProperty("emergencyContact") String emergencyContact,
@JsonProperty("formClass") String formClass,
@JsonProperty("medicalHistory") String medicalHistory,
@JsonProperty("tagged") List<JsonAdaptedTag> tagged) {
super(name, phone, email, gender, involvement, tagged);
this.address = address;
this.emergencyContact = emergencyContact;
this.formClass = formClass;
this.medicalHistory = medicalHistory;
}
/**
* Converts a given {@code Student} into this class for Jackson use.
*/
public JsonAdaptedStudent(Student source) {
super(source);
this.address = source.getAddress().value;
this.emergencyContact = source.getEmergencyContact().value;
this.formClass = source.getFormClass().value;
this.medicalHistory = source.getMedicalHistory().value;
}
/**
* Converts this Jackson-friendly adapted student object into the model's {@code Student} object.
*
* @throws IllegalValueException if there were any data constraints violated in the adapted student.
*/
@Override
public Student toModelType() throws IllegalValueException {
final List<Tag> studentTags = new ArrayList<>();
for (JsonAdaptedTag tag : tagged) {
studentTags.add(tag.toModelType());
}
if (name == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Name.class.getSimpleName()));
}
if (!Name.isValidName(name)) {
throw new IllegalValueException(Name.MESSAGE_CONSTRAINTS);
}
final Name modelName = new Name(name);
if (phone == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Phone.class.getSimpleName()));
}
if (!Phone.isValidPhone(phone)) {
throw new IllegalValueException(Phone.MESSAGE_CONSTRAINTS);
}
final Phone modelPhone = new Phone(phone);
if (email == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Email.class.getSimpleName()));
}
if (!Email.isValidEmail(email)) {
throw new IllegalValueException(Email.MESSAGE_CONSTRAINTS);
}
final Email modelEmail = new Email(email);
if (gender == null) {
throw new IllegalValueException(String.format(
MISSING_FIELD_MESSAGE_FORMAT, Gender.class.getSimpleName()));
}
if (!Gender.isValidGender(gender)) {
throw new IllegalValueException(Gender.MESSAGE_CONSTRAINTS);
}
final Gender modelGender = new Gender(gender);
if (involvement == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT,
Involvement.class.getSimpleName()));
}
if (!Involvement.isValidInvolvement(involvement)) {
throw new IllegalValueException(Involvement.MESSAGE_CONSTRAINTS);
}
final Involvement modelInvolvement = new Involvement(involvement);
if (address == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Address.class.getSimpleName()));
}
if (!Address.isValidAddress(address)) {
throw new IllegalValueException(Address.MESSAGE_CONSTRAINTS);
}
final Address modelAddress = new Address(address);
if (emergencyContact == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Phone.class.getSimpleName()));
}
if (!Phone.isValidPhone(emergencyContact)) {
throw new IllegalValueException(Phone.MESSAGE_CONSTRAINTS);
}
final Phone modelEmergencyContact = new Phone(emergencyContact);
if (formClass == null) {
throw new IllegalValueException(String.format(
MISSING_FIELD_MESSAGE_FORMAT, FormClass.class.getSimpleName()));
}
if (!FormClass.isValidFormClass(formClass)) {
throw new IllegalValueException(FormClass.MESSAGE_CONSTRAINTS);
}
final FormClass modelFormClass = new FormClass(formClass);
if (medicalHistory == null) {
throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT,
MedicalHistory.class.getSimpleName()));
}
final MedicalHistory modelMedicalHistory = new MedicalHistory(medicalHistory);
final Set<Tag> modelTags = new HashSet<>(studentTags);
return new Student(modelName, modelPhone, modelEmail, modelGender, modelInvolvement,
modelAddress, modelEmergencyContact, modelFormClass, modelTags, modelMedicalHistory);
}
}
| 41.544872
| 120
| 0.66857
|
55f03f173c991f6835ff9c6855039196f39ed777
| 22,990
|
package com.mpraski.jmonitor.adapters;
import static com.mpraski.jmonitor.util.Constants.CLASS_DOUBLE;
import static com.mpraski.jmonitor.util.Constants.CLASS_FLOAT;
import static com.mpraski.jmonitor.util.Constants.CLASS_INTEGER;
import static com.mpraski.jmonitor.util.Constants.CLASS_LONG;
import static com.mpraski.jmonitor.util.Constants.INSNS_REF;
import static com.mpraski.jmonitor.util.Constants.insteadMonitorClass;
import static com.mpraski.jmonitor.util.Constants.insteadMonitorClassFunc;
import static com.mpraski.jmonitor.util.Constants.insteadMonitorClassFuncType;
import static com.mpraski.jmonitor.util.Constants.insteadMonitorClassType;
import static com.mpraski.jmonitor.util.Constants.monitorClass;
import static com.mpraski.jmonitor.util.Constants.monitorClassFunc;
import static com.mpraski.jmonitor.util.Constants.monitorClassFuncType;
import static com.mpraski.jmonitor.util.Constants.monitorClassType;
import static com.mpraski.jmonitor.util.Constants.typeOfArray;
import static com.mpraski.jmonitor.util.Constants.typeOfDouble;
import static com.mpraski.jmonitor.util.Constants.typeOfFloat;
import static com.mpraski.jmonitor.util.Constants.typeOfInteger;
import static com.mpraski.jmonitor.util.Constants.typeOfLong;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.AnalyzerAdapter;
import org.objectweb.asm.commons.LocalVariablesSorter;
import com.mpraski.jmonitor.EventOrder;
import com.mpraski.jmonitor.instead.FieldReadGenerator;
import com.mpraski.jmonitor.instead.FieldWriteGenerator;
import com.mpraski.jmonitor.instead.InsteadActionGenerator;
import com.mpraski.jmonitor.instead.MethodCallGenerator;
import com.mpraski.jmonitor.instead.NewInstanceGenerator;
import com.mpraski.jmonitor.util.Pair;
import com.mpraski.jmonitor.util.EventUtil;
import com.mpraski.jmonitor.util.TypeUtil;
public class InstrumentationAdapter extends AnalyzerAdapter implements Opcodes {
/*
* Instance of enclosing MonitorClassAdapter, used to get indices of next inner
* class / accessor method.
*/
private final ClassAdapter adapter;
/*
* Used to add local variables in cases where certain values (e.g. method
* arguments, event arguments array) need to be preserved.
*/
private final LocalVariablesSorter sorter;
/*
* Characteristics of instrumented method
*/
private final String name;
private final String desc;
private final String owner;
private final String source;
private final Type ownerType;
/*
* Temporaries signaling presence of certain scenarios (e.g. capture local
* variable for sending event after field write)
*/
private boolean shouldGenerateLocal;
private boolean shouldGenerateDup;
private boolean shouldGenerateArgsArray;
private boolean shouldPreserveOriginal = true;
private int line;
private int generatedLocal;
private int generatedArgsArray;
private int currentNumArgs;
public InstrumentationAdapter(
String owner,
int access,
String name,
String descriptor,
String source,
ClassAdapter adapter,
LocalVariablesSorter sorter) {
super(ASM5, owner, access, name, descriptor, sorter);
this.adapter = adapter;
this.sorter = sorter;
this.name = name;
this.desc = descriptor;
this.owner = owner;
this.source = source;
this.ownerType = Type.getObjectType(owner);
}
@Override
public void visitLineNumber(int line, Label start) {
this.line = line;
super.visitLineNumber(line, start);
}
public boolean shouldGenerateLocal() {
return shouldGenerateLocal;
}
public boolean shouldGenerateDup() {
return shouldGenerateDup;
}
public boolean shouldGenerateArgsArray() {
return shouldGenerateArgsArray;
}
public boolean shouldPreserveOriginal() {
return shouldPreserveOriginal;
}
public void generateLocal() {
generatedLocal = captureLocal();
}
public void generatedArgsArray() {
LocalVariable[] vars = captureMethodArguments(currentNumArgs);
restoreMethodArguments(currentNumArgs, vars);
generatedArgsArray = vars[vars.length - 1].getIndex();
}
public void setShouldGenerateLocal(boolean shouldGenerateLocal) {
this.shouldGenerateLocal = shouldGenerateLocal;
}
public void setShouldGenerateDup(boolean shouldGenerateDup) {
this.shouldGenerateDup = shouldGenerateDup;
}
public void setShouldGenerateArgsArray(boolean shouldGenerateArgsArray) {
this.shouldGenerateArgsArray = shouldGenerateArgsArray;
}
public void setShouldPreserveOriginal(boolean shouldPreserveOriginal) {
this.shouldPreserveOriginal = shouldPreserveOriginal;
}
public void setNumArgs(int args) {
this.currentNumArgs = args;
}
public void reset() {
shouldGenerateLocal = shouldGenerateDup = shouldGenerateArgsArray = false;
shouldPreserveOriginal = true;
}
public void visitFieldRead(EventData e) {
visitEventStart(e);
super.visitVarInsn(ALOAD, 0);
super.visitFieldInsn(GETFIELD, e.getOwner(), e.getName(), e.getDesc());
box(e.getDesc());
super.visitInsn(ACONST_NULL);
visitEventEnd(e);
}
public void visitFieldWrite(EventData e) {
visitEventStart(e);
super.visitVarInsn(ALOAD, 0);
super.visitFieldInsn(GETFIELD, e.getOwner(), e.getName(), e.getDesc());
box(e.getDesc());
visitEventEndWithArg(e, generatedLocal);
}
public void visitStaticFieldRead(EventData e) {
visitEventStart(e);
super.visitFieldInsn(GETSTATIC, e.getOwner(), e.getName(), e.getDesc());
box(e.getDesc());
super.visitInsn(ACONST_NULL);
visitEventEnd(e);
}
public void visitStaticFieldWrite(EventData e) {
visitEventStart(e);
super.visitFieldInsn(GETSTATIC, e.getOwner(), e.getName(), e.getDesc());
box(e.getDesc());
visitEventEndWithArg(e, generatedLocal);
}
public void visitTopWithAutobox(EventData e) {
box(getTopType());
visitEventStartWithSwap(e);
super.visitInsn(ACONST_NULL);
visitEventEnd(e);
}
public void visitTopWithSwap(EventData e) {
visitEventStartWithSwap(e);
super.visitInsn(ACONST_NULL);
visitEventEnd(e);
}
public void visitNewInstanceAfter(EventData e) {
super.visitInsn(DUP);
visitEventStartWithSwap(e);
super.visitInsn(ACONST_NULL);
visitEventEnd(e);
}
public void visitNewInstance(EventData e) {
visitEventStart(e);
super.visitInsn(ACONST_NULL);
super.visitInsn(ICONST_1);
super.visitTypeInsn(ANEWARRAY, "java/lang/Object");
super.visitInsn(DUP);
super.visitInsn(ICONST_0);
super.visitLdcInsn(e.getName());
super.visitInsn(AASTORE);
visitEventEnd(e);
}
public void visitMethodCallBefore(EventData e) {
LocalVariable[] vars = captureMethodArguments(e.getNumArgs());
visitEventStart(e);
super.visitLdcInsn(e.getName());
super.visitVarInsn(ALOAD, vars[e.getNumArgs()].getIndex());
visitEventEnd(e);
restoreMethodArguments(e.getNumArgs(), vars);
}
public void visitReturnInstead(EventData e) {
Type oldType = getTopType();
boxWithoutDup(oldType);
visitEventStartWithSwap(e);
super.visitInsn(ACONST_NULL);
visitEventEnd(e);
if (TypeUtil.isReference(oldType))
super.visitTypeInsn(CHECKCAST, oldType.getInternalName());
else
unbox(oldType);
}
public void visitThrowInstead(EventData e) {
Type oldType = getTopType();
visitEventStartWithSwap(e);
super.visitInsn(ACONST_NULL);
visitEventEnd(e);
super.visitTypeInsn(CHECKCAST, oldType.getInternalName());
}
public void visitMethodCallAfter(EventData e) {
visitEventStart(e);
super.visitLdcInsn(e.getName());
super.visitVarInsn(ALOAD, generatedArgsArray);
visitEventEnd(e);
}
public void visitReadInstead(EventData e) {
Type oldType = Type.getType(e.getDesc());
Type ownerType = Type.getObjectType(owner);
String nextInnerClass = adapter.getNextInnerClass();
String nextAccessor = adapter.getNextAccessor();
InsteadActionGenerator action = new FieldReadGenerator(
nextInnerClass,
owner,
name,
desc,
nextAccessor,
"(" + ownerType.getDescriptor() + ")" + e.getDesc(),
e.getName(),
e.getDesc());
adapter.addActionGenerator(action);
newInsteadAction(action, ownerType);
visitEventStartWithSwap(e);
super.visitInsn(ACONST_NULL);
visitEventEndWithAction(e);
if (TypeUtil.isReference(oldType))
super.visitTypeInsn(CHECKCAST, oldType.getInternalName());
else
unbox(oldType);
shouldPreserveOriginal = false;
}
public void visitWriteInstead(EventData e) {
Type oldType = Type.getType(e.getDesc());
String nextInnerClass = adapter.getNextInnerClass();
String nextAccessor = adapter.getNextAccessor();
InsteadActionGenerator action = new FieldWriteGenerator(
nextInnerClass,
owner,
name,
desc,
nextAccessor,
TypeUtil.methodOf(Type.VOID_TYPE, ownerType, Type.getType(e.getDesc())),
e.getName(),
e.getDesc());
adapter.addActionGenerator(action);
boxWithoutDup(oldType);
super.visitInsn(ICONST_1);
super.visitTypeInsn(ANEWARRAY, "java/lang/Object");
super.visitInsn(DUP_X1);
super.visitInsn(SWAP);
super.visitInsn(ICONST_0);
super.visitInsn(SWAP);
super.visitInsn(AASTORE);
int argsArray = captureLocal();
newInsteadAction(action, ownerType);
visitEventStartWithSwap(e);
super.visitVarInsn(ALOAD, argsArray);
visitEventEndWithAction(e);
super.visitInsn(POP);
shouldPreserveOriginal = false;
}
public void visitMethodCallInstead(EventData e) {
Type retType = e.getRetType();
String nextInnerClass = adapter.getNextInnerClass();
String[] parts = e.getName().split(Pattern.quote("."));
String methodName = parts[parts.length - 1];
Pair<Integer, List<Type>> arrayAndTypes = captureArgumentsArray(e.getNumArgs());
super.visitInsn(POP);
InsteadActionGenerator action = new MethodCallGenerator(
nextInnerClass,
owner,
name,
desc,
methodName,
e.getDesc(),
arrayAndTypes.getValue());
adapter.addActionGenerator(action);
newInsteadAction(action, ownerType);
visitEventStartWithSwap(e);
super.visitVarInsn(ALOAD, arrayAndTypes.getKey());
visitEventEndWithAction(e);
if (TypeUtil.isReference(retType))
super.visitTypeInsn(CHECKCAST, retType.getInternalName());
else
unbox(retType);
shouldPreserveOriginal = false;
}
public void visitInstanceInstead(EventData e) {
Type retType = e.getRetType();
String nextInnerClass = adapter.getNextInnerClass();
Pair<Integer, List<Type>> arrayAndTypes = captureArgumentsArray(e.getNumArgs());
super.visitInsn(POP2);
InsteadActionGenerator action = new NewInstanceGenerator(
nextInnerClass,
owner,
name,
desc,
retType.getInternalName(),
e.getDesc(),
arrayAndTypes.getValue());
adapter.addActionGenerator(action);
newInsteadAction(action, ownerType);
visitEventStartWithSwap(e);
super.visitVarInsn(ALOAD, arrayAndTypes.getKey());
visitEventEndWithAction(e);
super.visitTypeInsn(CHECKCAST, retType.getInternalName());
shouldPreserveOriginal = false;
}
public void visitEventStart(EventData e) {
super.visitFieldInsn(
GETSTATIC,
"com/mpraski/jmonitor/Resolver",
e.getMonitor(),
e.getOrder() == EventOrder.INSTEAD ? insteadMonitorClassType : monitorClassType);
super.visitTypeInsn(NEW, "com/mpraski/jmonitor/Event");
super.visitInsn(DUP);
if (e.getTag() == null)
super.visitInsn(ACONST_NULL);
else
super.visitLdcInsn(e.getTag());
super.visitFieldInsn(
GETSTATIC,
"com/mpraski/jmonitor/EventType",
EventUtil.eventType(e.getType()),
"Lcom/mpraski/jmonitor/EventType;");
super.visitFieldInsn(
GETSTATIC,
"com/mpraski/jmonitor/EventOrder",
EventUtil.eventOrder(e.getOrder()),
"Lcom/mpraski/jmonitor/EventOrder;");
if (source == null)
super.visitInsn(ACONST_NULL);
else
super.visitLdcInsn(source);
pushInt(line);
}
public void visitEventStartWithSwap(EventData e) {
super.visitFieldInsn(
GETSTATIC,
"com/mpraski/jmonitor/Resolver",
e.getMonitor(),
e.getOrder() == EventOrder.INSTEAD ? insteadMonitorClassType : monitorClassType);
super.visitInsn(SWAP);
super.visitTypeInsn(NEW, "com/mpraski/jmonitor/Event");
super.visitInsn(DUP_X1);
super.visitInsn(SWAP);
if (e.getTag() == null)
super.visitInsn(ACONST_NULL);
else
super.visitLdcInsn(e.getTag());
super.visitInsn(SWAP);
super.visitFieldInsn(
GETSTATIC,
"com/mpraski/jmonitor/EventType",
EventUtil.eventType(e.getType()),
"Lcom/mpraski/jmonitor/EventType;");
super.visitInsn(SWAP);
super.visitFieldInsn(
GETSTATIC,
"com/mpraski/jmonitor/EventOrder",
EventUtil.eventOrder(e.getOrder()),
"Lcom/mpraski/jmonitor/EventOrder;");
super.visitInsn(SWAP);
if (source == null)
super.visitInsn(ACONST_NULL);
else
super.visitLdcInsn(source);
super.visitInsn(SWAP);
pushInt(line);
super.visitInsn(SWAP);
}
public void visitEventEnd(EventData e) {
super.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "currentThread", "()Ljava/lang/Thread;", false);
super.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/Thread",
"getStackTrace",
"()[Ljava/lang/StackTraceElement;",
false);
super.visitMethodInsn(
INVOKESPECIAL,
"com/mpraski/jmonitor/Event",
"<init>",
"(Ljava/lang/String;Lcom/mpraski/jmonitor/EventType;Lcom/mpraski/jmonitor/EventOrder;Ljava/lang/String;ILjava/lang/Object;[Ljava/lang/Object;[Ljava/lang/StackTraceElement;)V",
false);
if (e.getOrder() == EventOrder.INSTEAD)
super.visitMethodInsn(
INVOKEINTERFACE,
insteadMonitorClass,
insteadMonitorClassFunc,
insteadMonitorClassFuncType,
true);
else
super.visitMethodInsn(INVOKEINTERFACE, monitorClass, monitorClassFunc, monitorClassFuncType, true);
}
public void visitEventEndWithArg(EventData e, int localArg) {
super.visitInsn(ICONST_1);
super.visitTypeInsn(ANEWARRAY, "java/lang/Object");
super.visitInsn(DUP);
super.visitInsn(ICONST_0);
super.visitVarInsn(ALOAD, localArg);
super.visitInsn(AASTORE);
super.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "currentThread", "()Ljava/lang/Thread;", false);
super.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/Thread",
"getStackTrace",
"()[Ljava/lang/StackTraceElement;",
false);
super.visitMethodInsn(
INVOKESPECIAL,
"com/mpraski/jmonitor/Event",
"<init>",
"(Ljava/lang/String;Lcom/mpraski/jmonitor/EventType;Lcom/mpraski/jmonitor/EventOrder;Ljava/lang/String;ILjava/lang/Object;[Ljava/lang/Object;[Ljava/lang/StackTraceElement;)V",
false);
if (e.getOrder() == EventOrder.INSTEAD)
super.visitMethodInsn(
INVOKEINTERFACE,
insteadMonitorClass,
insteadMonitorClassFunc,
insteadMonitorClassFuncType,
true);
else
super.visitMethodInsn(INVOKEINTERFACE, monitorClass, monitorClassFunc, monitorClassFuncType, true);
}
public void visitEventEndWithAction(EventData e) {
super.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "currentThread", "()Ljava/lang/Thread;", false);
super.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/Thread",
"getStackTrace",
"()[Ljava/lang/StackTraceElement;",
false);
super.visitMethodInsn(
INVOKESPECIAL,
"com/mpraski/jmonitor/Event",
"<init>",
"(Ljava/lang/String;Lcom/mpraski/jmonitor/EventType;Lcom/mpraski/jmonitor/EventOrder;Ljava/lang/String;ILcom/mpraski/jmonitor/InsteadAction;[Ljava/lang/Object;[Ljava/lang/StackTraceElement;)V",
false);
super.visitMethodInsn(
INVOKEINTERFACE,
insteadMonitorClass,
insteadMonitorClassFunc,
insteadMonitorClassFuncType,
true);
}
public void newInsteadAction(InsteadActionGenerator action, Type ownerType) {
super.visitTypeInsn(NEW, action.getName());
super.visitInsn(DUP);
super.visitIntInsn(ALOAD, 0);
super.visitMethodInsn(INVOKESPECIAL, action.getName(), "<init>", TypeUtil.constructorOf(ownerType), false);
}
public Object getTop() {
if (stack.isEmpty())
throw new IllegalStateException("Stack is empty");
return stack.get(stack.size() - 1);
}
/*
* Creates a local variable holding boxed value on the top of the stack.
*/
private int captureLocal() {
Type topType = getTopType();
if (TypeUtil.takesTwoWords(topType))
super.visitInsn(DUP2);
else
super.visitInsn(DUP);
int l = sorter.newLocal(box(topType));
super.visitVarInsn(ASTORE, l);
return l;
}
/*
* Builds an array of indices of local variables added to preserve the arguments
* of instrumented method in between the event generation. Also, the last entry
* contains the index of an array of boxed arguments ready to be passed to an
* event.
*/
private LocalVariable[] captureMethodArguments(int numArgs) {
LocalVariable[] localsVars = new LocalVariable[numArgs + 1];
pushInt(numArgs);
super.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int methodArgs = sorter.newLocal(typeOfArray);
super.visitVarInsn(ASTORE, methodArgs);
Type topType;
boolean twoWords;
for (int i = numArgs - 1; i >= 0; i--) {
topType = getTopType();
twoWords = TypeUtil.takesTwoWords(topType);
if (twoWords)
super.visitInsn(DUP2);
else
super.visitInsn(DUP);
Pair<Integer, Integer> insns = TypeUtil.getLoadStoreInsns(topType);
int l = sorter.newLocal(topType);
super.visitVarInsn(insns.getKey(), l);
localsVars[i] = new LocalVariable(l, insns.getValue());
super.visitVarInsn(ALOAD, methodArgs);
if (twoWords) {
super.visitInsn(DUP_X2);
super.visitInsn(POP);
} else {
super.visitInsn(SWAP);
}
if (!insns.equals(INSNS_REF))
boxWithoutDup(topType);
pushInt(i);
super.visitInsn(SWAP);
super.visitInsn(AASTORE);
}
localsVars[numArgs] = new LocalVariable(methodArgs, 0);
return localsVars;
}
private Pair<Integer, List<Type>> captureArgumentsArray(int numArgs) {
Type[] types = new Type[numArgs];
pushInt(numArgs);
super.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int methodArgs = sorter.newLocal(typeOfArray);
super.visitVarInsn(ASTORE, methodArgs);
Type topType;
for (int i = numArgs - 1; i >= 0; i--) {
topType = getTopType();
types[i] = topType;
super.visitVarInsn(ALOAD, methodArgs);
if (TypeUtil.takesTwoWords(topType)) {
super.visitInsn(DUP_X2);
super.visitInsn(POP);
} else {
super.visitInsn(SWAP);
}
if (!TypeUtil.isReference(topType))
boxWithoutDup(topType);
pushInt(i);
super.visitInsn(SWAP);
super.visitInsn(AASTORE);
}
return new Pair<>(methodArgs, Arrays.asList(types));
}
/*
* Pushes the values of captured method arguments back onto the stack.
*/
private void restoreMethodArguments(int numArgs, LocalVariable[] localVars) {
for (int i = 0; i < numArgs; i++)
super.visitVarInsn(localVars[i].getLoadInsn(), localVars[i].getIndex());
}
private void pushInt(int i) {
if (i < 6) {
switch (i) {
case 0:
super.visitInsn(ICONST_0);
break;
case 1:
super.visitInsn(ICONST_1);
break;
case 2:
super.visitInsn(ICONST_2);
break;
case 3:
super.visitInsn(ICONST_3);
break;
case 4:
super.visitInsn(ICONST_4);
break;
case 5:
super.visitInsn(ICONST_5);
break;
}
} else if (i > 5 && i < 128) {
super.visitIntInsn(BIPUSH, i);
} else if (i > 127 && i < 32768) {
super.visitIntInsn(SIPUSH, i);
} else {
super.visitLdcInsn(i);
}
}
/*
* Returns the type of value on the top of the stack. Aware of long/double types
* taking two words.
*/
private Type getTopType() {
Object v2 = getTop();
if (v2 instanceof String)
return Type.getObjectType((String) v2);
if (stack.size() > 1) {
Object v1 = stack.get(stack.size() - 2);
if (v1 instanceof Integer && v2.equals(TOP)) {
Integer desc = (Integer) v1;
if (desc.equals(LONG))
return Type.LONG_TYPE;
else if (desc.equals(DOUBLE))
return Type.DOUBLE_TYPE;
}
}
Integer i = (Integer) v2;
if (i.equals(INTEGER))
return Type.INT_TYPE;
else if (i.equals(FLOAT))
return Type.FLOAT_TYPE;
throw new IllegalStateException("Neither a reference nor a primitive");
}
/*
* Attempts to produce a boxed value from descriptor of type of the value on top
* of the stack.
*/
private void box(String desc) {
if (desc.length() > 1)
return;
Pair<String, String> type = TypeUtil.getPrimitiveClass(desc);
super.visitMethodInsn(INVOKESTATIC, type.getKey(), "valueOf", type.getValue(), false);
}
/*
* Pushes a boxed value of the top of the stack.
*/
private Type box(Type type) {
if (type.equals(Type.LONG_TYPE)) {
super.visitInsn(DUP2);
super.visitMethodInsn(INVOKESTATIC, CLASS_LONG.getKey(), "valueOf", CLASS_LONG.getValue(), false);
return typeOfLong;
} else if (type.equals(Type.DOUBLE_TYPE)) {
super.visitInsn(DUP2);
super.visitMethodInsn(INVOKESTATIC, CLASS_DOUBLE.getKey(), "valueOf", CLASS_DOUBLE.getValue(), false);
return typeOfDouble;
} else if (type.equals(Type.INT_TYPE)) {
super.visitInsn(DUP);
super.visitMethodInsn(INVOKESTATIC, CLASS_INTEGER.getKey(), "valueOf", CLASS_INTEGER.getValue(), false);
return typeOfInteger;
} else if (type.equals(Type.FLOAT_TYPE)) {
super.visitInsn(DUP);
super.visitMethodInsn(INVOKESTATIC, CLASS_FLOAT.getKey(), "valueOf", CLASS_FLOAT.getValue(), false);
return typeOfFloat;
}
return type;
}
/*
* Pushes a boxed value of the top of the stack. Does not duplicate the raw
* value.
*/
private Type boxWithoutDup(Type type) {
if (type.equals(Type.LONG_TYPE)) {
super.visitMethodInsn(INVOKESTATIC, CLASS_LONG.getKey(), "valueOf", CLASS_LONG.getValue(), false);
return typeOfLong;
} else if (type.equals(Type.DOUBLE_TYPE)) {
super.visitMethodInsn(INVOKESTATIC, CLASS_DOUBLE.getKey(), "valueOf", CLASS_DOUBLE.getValue(), false);
return typeOfDouble;
} else if (type.equals(Type.INT_TYPE)) {
super.visitMethodInsn(INVOKESTATIC, CLASS_INTEGER.getKey(), "valueOf", CLASS_INTEGER.getValue(), false);
return typeOfInteger;
} else if (type.equals(Type.FLOAT_TYPE)) {
super.visitMethodInsn(INVOKESTATIC, CLASS_FLOAT.getKey(), "valueOf", CLASS_FLOAT.getValue(), false);
return typeOfFloat;
}
return type;
}
private void unbox(Type type) {
if (type.equals(Type.LONG_TYPE)) {
super.visitTypeInsn(CHECKCAST, CLASS_LONG.getKey());
super.visitMethodInsn(INVOKEVIRTUAL, CLASS_LONG.getKey(), "longValue", "()J", false);
} else if (type.equals(Type.DOUBLE_TYPE)) {
super.visitTypeInsn(CHECKCAST, CLASS_DOUBLE.getKey());
super.visitMethodInsn(INVOKEVIRTUAL, CLASS_DOUBLE.getKey(), "doubleValue", "()D", false);
} else if (type.equals(Type.INT_TYPE)) {
super.visitTypeInsn(CHECKCAST, CLASS_INTEGER.getKey());
super.visitMethodInsn(INVOKEVIRTUAL, CLASS_INTEGER.getKey(), "intValue", "()I", false);
} else if (type.equals(Type.FLOAT_TYPE)) {
super.visitTypeInsn(CHECKCAST, CLASS_FLOAT.getKey());
super.visitMethodInsn(INVOKEVIRTUAL, CLASS_FLOAT.getKey(), "floatValue", "()F", false);
}
}
}
| 27.83293
| 197
| 0.730883
|
8bca059384337ad3ecdc25c31117f7e5f3508bed
| 2,094
|
package com.libre.excel.handler;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.libre.excel.annotation.ResponseExcel;
import com.libre.excel.config.ExcelConfigProperties;
import com.libre.excel.exception.ExcelException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.ObjectProvider;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* @author lengleng
* @author Libre
* @date 2020/3/29
*/
@SuppressWarnings("rawtypes")
@RequiredArgsConstructor
public class ManySheetWriteHandler extends AbstractSheetWriteHandler {
private final ExcelConfigProperties configProperties;
private final ObjectProvider<List<Converter<?>>> converterProvider;
/**
* 当且仅当List不为空且List中的元素也是List 才返回true
*
* @param obj 返回对象
* @return
*/
@Override
public boolean support(Object obj) {
if (obj instanceof List) {
List objList = (List) obj;
return !objList.isEmpty() && objList.get(0) instanceof List;
} else {
throw new ExcelException("@ResponseExcel 返回值必须为List类型");
}
}
@Override
@SneakyThrows
public void write(Object obj, HttpServletResponse response, ResponseExcel responseExcel) {
List objList = (List) obj;
ExcelWriter excelWriter = getExcelWriter(response, responseExcel, configProperties.getTemplatePath());
String[] sheets = responseExcel.sheet();
WriteSheet sheet;
for (int i = 0; i < sheets.length; i++) {
List eleList = (List) objList.get(i);
Class<?> dataClass = eleList.get(0).getClass();
//创建sheet
sheet = this.sheet(i, responseExcel.sheet()[i], dataClass, responseExcel.template(),
responseExcel.headGenerator());
// 写入sheet
excelWriter.write((List) objList.get(i), sheet);
}
excelWriter.finish();
}
@Override
public void registerCustomConverter(ExcelWriterBuilder builder) {
converterProvider.ifAvailable(converters -> converters.forEach(builder::registerConverter));
}
}
| 29.914286
| 104
| 0.762178
|
bcd84911779a2fa099c90933f45811388842b606
| 790
|
package com.alibaba.alink.operator.batch.feature;
import org.apache.flink.ml.api.misc.param.Params;
import com.alibaba.alink.operator.common.feature.QuantileDiscretizerModelMapper;
import com.alibaba.alink.operator.batch.utils.ModelMapBatchOp;
import com.alibaba.alink.params.feature.QuantileDiscretizerPredictParams;
/**
* The batch operator that predict the data using the quantile discretizer model.
*/
public final class QuantileDiscretizerPredictBatchOp extends ModelMapBatchOp <QuantileDiscretizerPredictBatchOp>
implements QuantileDiscretizerPredictParams <QuantileDiscretizerPredictBatchOp> {
public QuantileDiscretizerPredictBatchOp() {
this(null);
}
public QuantileDiscretizerPredictBatchOp(Params params) {
super(QuantileDiscretizerModelMapper::new, params);
}
}
| 34.347826
| 112
| 0.836709
|
d30399fda4d2ee1049c706dfa9720e72558b2f62
| 786
|
package amazed;
public class ReverseString {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* We will be given a sentence. We have to reverse the string.
* (e.g. Input: I am a coder. OutpuT: Coder a am I)
* @param sentence
* @return
*/
public String reverse(String sentence){
if (sentence != null) {
StringBuilder sb = new StringBuilder();
String[] words = sentence.split(" ");
words[words.length - 1] = words[words.length - 1].substring(0, 1).toUpperCase() + words[words.length -1].substring(1,words[words.length -1].length());
words[0] = words[0].toLowerCase();
for (int i = words.length -1; i > -1; i--){
sb.append(words[i]);
sb.append(" ");
}
return sb.toString().trim();
}
return null;
}
}
| 25.354839
| 153
| 0.629771
|
105c0802b745002de0fe03327ba179e43bf1e45d
| 1,440
|
/*
* Copyright 2018 Waldemar Kłaczyński.
*
* 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.ssoft.faces.impl.state.facelets;
import javax.faces.view.ViewDeclarationLanguage;
import javax.faces.view.ViewDeclarationLanguageFactory;
/**
*
* @author Waldemar Kłaczyński
*/
public class StateFlowViewDeclarationLanguageFactory extends ViewDeclarationLanguageFactory {
private final ViewDeclarationLanguageFactory wrapped;
/**
*
* @param wrapped
*/
public StateFlowViewDeclarationLanguageFactory(ViewDeclarationLanguageFactory wrapped) {
this.wrapped = wrapped;
}
@Override
public ViewDeclarationLanguageFactory getWrapped() {
return wrapped;
}
@Override
public ViewDeclarationLanguage getViewDeclarationLanguage(String viewId) {
return new StateFlowViewDeclarationLanguage(getWrapped().getViewDeclarationLanguage(viewId));
}
}
| 30
| 101
| 0.745833
|
70f074083b1c4f7d6bbb6f2db988fd16a73771eb
| 421
|
package org.example.data.profile;
import org.example.data.ModelRepository;
import org.example.domain.profile.Office;
/**
* Contract for data access operations on {@link Office}.
*/
public interface OfficeRepository extends ModelRepository<Office>
{
/**
* Finds an office by its name.
*
* @param name The name of the office to find.
* @return An {@link Office}.
*/
Office findByName(String name);
}
| 22.157895
| 65
| 0.710214
|
677b4afd86597f1a5d766a7e7378c5c57ee58e30
| 2,400
|
package com.xtoon.boot.sys.domain.model.user;
import com.xtoon.boot.common.domain.StatusEnum;
import com.xtoon.boot.sys.ApplicationTest;
import com.xtoon.boot.sys.domain.external.TokenGeneratorExternalService;
import com.xtoon.boot.sys.domain.model.role.RoleId;
import com.xtoon.boot.sys.domain.model.tenant.TenantId;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* UserTest
*
* @author haoxin
* @date 2021-04-04
**/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes= ApplicationTest.class)
@DisplayName("用户测试")
class UserTest {
@Autowired
private TokenGeneratorExternalService tokenGeneratorExternalService;
User user;
@BeforeEach
void setUp() {
Password password = Password.create("123456","11111");
Account account = new Account(new Mobile("18555555555"),new Email("2323@qq.com"),password);
List<RoleId> roles = new ArrayList<>();
roles.add(new RoleId("1"));
user = new User(new UserId("1"), new UserName("test"), StatusEnum.ENABLE, account, new TenantId("2"), roles);
}
@Test
@DisplayName("是否有效")
void isEnable() {
assertTrue(user.isEnable());
}
@Test
@DisplayName("是否相等")
void sameIdentityAs() {
User user2 = new User(new UserId("1"), null,null, null, null, null);
assertTrue(user.sameIdentityAs(user2));
}
@Test
@DisplayName("禁用")
void disable() {
StatusEnum statusEnum = user.getStatus();
user.disable();
assertFalse(statusEnum.sameValueAs(user.getStatus()));
}
@Test
@DisplayName("刷新token")
void refreshToken() {
user.refreshToken(tokenGeneratorExternalService.generateValue());
assertNotNull(user.getAccount().getToken());
}
@Test
@DisplayName("修改密码")
void changePassword() {
user.changePassword("123456","654321");
assertTrue(user.getAccount().getPassword().sameValueAs(Password.create("654321","11111")));
}
}
| 29.268293
| 117
| 0.698333
|
a466ff9d2afe2b8973263d2acfe849c97839238b
| 184
|
package com.rentalcars.models;
import java.util.List;
/**
* Matches the structure of the rentalcars vehicles json file
*/
public class Search {
public List<Car> VehicleList;
}
| 16.727273
| 61
| 0.733696
|
2491911dc753186289e4bc5219331766dead3ec0
| 2,780
|
/*
* Copyright 2013 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 leap.orm.domain;
import leap.lang.Strings;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
class FieldDomainMappings {
private String entityName;
private Pattern entityPattern;
private Map<String, Domain> fields = new HashMap<>();
private Map<String, Domain> aliases = new HashMap<>();
public boolean hasEntityPattern() {
return null != entityPattern;
}
public boolean hasEntityName() {
return !Strings.isEmpty(entityName);
}
public boolean hasEntity() {
return hasEntityPattern() || hasEntityName();
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public Pattern getEntityPattern() {
return entityPattern;
}
public void setEntityPattern(Pattern entityPattern) {
this.entityPattern = entityPattern;
}
public Domain getField(String name) {
return fields.get(name.toLowerCase());
}
public Map<String, Domain> getFields() {
return fields;
}
public Map<String, Domain> getAliases() {
return aliases;
}
public void addField(Domain domain) {
fields.put(domain.getName().toLowerCase(), domain);
}
public void addAlias(String field, String alias) {
Domain domain = getField(field);
if(null == domain) {
throw new DomainConfigException("The field '" + field + "' not found in {entityName=" + entityName + ", entityPattern=" + entityPattern + "}");
}
aliases.put(alias.toLowerCase(), domain);
}
public Domain mapping(String entityName, String fieldName) {
if(hasEntityName() && !this.entityName.equalsIgnoreCase(entityName)) {
return null;
}
if(hasEntityPattern() && !entityPattern.matcher(entityName).matches()) {
return null;
}
String key = fieldName.toLowerCase();
Domain domain = fields.get(key);
if(null == domain) {
domain = aliases.get(key);
}
return domain;
}
}
| 28.080808
| 155
| 0.648201
|
49055ade6287e4ad0974e8baaa5b8db5cd03c34f
| 3,664
|
/*
* Copyright (c) 2017-2020. Nitrite 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 org.dizitart.no2.support;
import org.dizitart.no2.Nitrite;
import org.dizitart.no2.collection.Document;
import org.dizitart.no2.collection.NitriteCollection;
import org.dizitart.no2.mvstore.MVStoreModule;
import org.dizitart.no2.repository.ObjectRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import static org.dizitart.no2.common.Constants.*;
import static org.junit.Assert.assertTrue;
/**
* @author Anindya Chatterjee.
*/
public abstract class BaseExternalTest {
protected ObjectRepository<Employee> sourceEmpRepo;
protected ObjectRepository<Employee> sourceKeyedEmpRepo;
protected ObjectRepository<Company> sourceCompRepo;
protected NitriteCollection sourceFirstColl;
protected NitriteCollection sourceSecondColl;
protected Nitrite sourceDb;
protected Nitrite destDb;
protected String schemaFile;
private String sourceDbFile;
private String destDbFile;
@Rule
public Retry retry = new Retry(3);
public static String getRandomTempDbFile() {
String dataDir = System.getProperty("java.io.tmpdir") + File.separator + "nitrite" + File.separator + "data";
File file = new File(dataDir);
if (!file.exists()) {
assertTrue(file.mkdirs());
}
return file.getPath() + File.separator + UUID.randomUUID().toString() + ".db";
}
@Before
public void setUp() {
sourceDbFile = getRandomTempDbFile();
destDbFile = getRandomTempDbFile();
sourceDb = createDb(sourceDbFile);
destDb = createDb(destDbFile);
sourceEmpRepo = sourceDb.getRepository(Employee.class);
sourceKeyedEmpRepo = sourceDb.getRepository(Employee.class, "key");
sourceCompRepo = sourceDb.getRepository(Company.class);
sourceFirstColl = sourceDb.getCollection("first");
sourceSecondColl = sourceDb.getCollection("second");
}
@After
public void cleanUp() throws IOException {
sourceFirstColl.close();
sourceSecondColl.close();
sourceEmpRepo.close();
sourceCompRepo.close();
sourceDb.close();
destDb.close();
Files.delete(Paths.get(sourceDbFile));
Files.delete(Paths.get(destDbFile));
Files.delete(Paths.get(schemaFile));
}
protected List<Document> filter(List<Document> documents) {
for (Document document : documents) {
document.remove(DOC_REVISION);
document.remove(DOC_MODIFIED);
document.remove(DOC_SOURCE);
}
return documents;
}
private Nitrite createDb(String filePath) {
MVStoreModule storeModule = MVStoreModule.withConfig()
.filePath(filePath)
.build();
return Nitrite.builder()
.loadModule(storeModule)
.fieldSeparator(".")
.openOrCreate();
}
}
| 31.316239
| 117
| 0.689138
|
3c6f2961a06c965ffad7aaeec464a8f54ba4f62b
| 1,162
|
/*
* Copyright (c) 2021 - for information on the respective copyright owner
* see the NOTICE file and/or the repository https://github.com/carbynestack/castor.
*
* SPDX-License-Identifier: Apache-2.0
*/
package io.carbynestack.castor.common.entities;
import java.io.Serializable;
import lombok.*;
/**
* {@link TupleMetric} provides metrics for a given {@link TupleType} like the number of {@link
* Tuple} that were available at the time of request, or how many {@link Tuple}s of this type have
* been consumed by clients or internal services within a defined timeframe.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(staticName = "of")
@Data
@Setter(value = AccessLevel.NONE)
public class TupleMetric implements Serializable {
private static final long serialVersionUID = -288015321240466836L;
/** The number of available {@link Tuple}s for the given {@link #type}. */
private long available;
/** The consumption rate for the given {@link #type TupleType} and the requested timeframe. */
private long consumptionRate;
/** The {@link TupleType} these {@link TupleMetric}s belong to */
private TupleType type;
}
| 36.3125
| 98
| 0.746127
|
763a53d6ed2c81c09344460ab25d0324d6451daa
| 10,039
|
/*
* Copyright 2019 The Hekate Project
*
* The Hekate Project 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 io.hekate.cluster.seed.zookeeper;
import io.hekate.cluster.ClusterServiceFactory;
import io.hekate.cluster.seed.SeedNodeProvider;
import io.hekate.core.HekateBootstrap;
import io.hekate.core.HekateException;
import io.hekate.core.internal.util.AddressUtils;
import io.hekate.core.internal.util.ArgAssert;
import io.hekate.core.internal.util.ConfigCheck;
import io.hekate.util.format.ToString;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ZooKeeper-based implementation of {@link SeedNodeProvider} interface.
*
* <p>
* This provides uses a ZooKeeper cluster to store and discover seed node addresses. When provider starts discovering other nodes it
* creates a new empty Z-node whose name contains local node's host address and under the
* {@link ZooKeeperSeedNodeProviderConfig#setBasePath(String) [base_path]}/{@link HekateBootstrap#setClusterName(String) [cluster_name]}/
* path. In order to find other seed nodes it reads the list of all Z-nodes in that folder and parses addresses from their names.
* </p>
*
* <p>
* Please see the documentation of {@link ZooKeeperSeedNodeProviderConfig} class for more details about the available configuration options.
* </p>
*
* @see ClusterServiceFactory#setSeedNodeProvider(SeedNodeProvider)
* @see SeedNodeProvider
*/
public class ZooKeeperSeedNodeProvider implements SeedNodeProvider {
private interface ZooKeeperTask {
void execute(CuratorFramework client) throws HekateException;
}
private static final Logger log = LoggerFactory.getLogger(ZooKeeperSeedNodeProvider.class);
private static final boolean DEBUG = log.isDebugEnabled();
private final String connectionString;
private final String basePath;
private final int connectTimeout;
private final int sessionTimeout;
private final int cleanupInterval;
/**
* Constructs new instance.
*
* @param cfg Configuration.
*/
public ZooKeeperSeedNodeProvider(ZooKeeperSeedNodeProviderConfig cfg) {
ArgAssert.notNull(cfg, "Configuration");
ConfigCheck check = ConfigCheck.get(ZooKeeperSeedNodeProviderConfig.class);
check.notEmpty(cfg.getConnectionString(), "connection string");
check.notEmpty(cfg.getBasePath(), "base path");
check.positive(cfg.getConnectTimeout(), "connect timeout");
check.positive(cfg.getSessionTimeout(), "session timeout");
connectionString = cfg.getConnectionString().trim();
connectTimeout = cfg.getConnectTimeout();
sessionTimeout = cfg.getSessionTimeout();
cleanupInterval = cfg.getCleanupInterval();
String path = cfg.getBasePath().trim();
if (path.endsWith("/")) {
basePath = path;
} else {
basePath = path + '/';
}
}
/**
* Returns the ZooKeeper connection string.
*
* @return ZooKeeper connection string.
*
* @see ZooKeeperSeedNodeProviderConfig#setConnectionString(String)
*/
public String connectionString() {
return connectionString;
}
/**
* Returns the base path for storing seed nodes information in ZooKeeper.
*
* @return Base path for storing seed nodes information in ZooKeeper.
*
* @see ZooKeeperSeedNodeProviderConfig#setBasePath(String)
*/
public String basePath() {
return basePath;
}
@Override
public List<InetSocketAddress> findSeedNodes(String cluster) throws HekateException {
String path = basePath + cluster;
if (DEBUG) {
log.debug("Searching for seed nodes [path={}]", path);
}
List<InetSocketAddress> seedNodes = new ArrayList<>();
withZooKeeper(client -> {
try {
client.getChildren()
.forPath(path).stream()
.map(it -> AddressUtils.fromFileName(it, log))
.filter(Objects::nonNull)
.peek(address -> {
if (DEBUG) {
log.debug("Seed node address discovered [address={}]", address);
}
})
.forEach(seedNodes::add);
if (DEBUG) {
log.debug("Done searching for seed nodes [found={}]", seedNodes.size());
}
} catch (NoNodeException e) {
// No-op.
} catch (Exception e) {
throw new HekateException("Failed to load seed nodes from ZooKeeper [path=" + path + ']', e);
}
});
return seedNodes;
}
@Override
public void startDiscovery(String cluster, InetSocketAddress node) throws HekateException {
if (log.isInfoEnabled()) {
log.info("Starting discovery [cluster={}, {}]", cluster, ToString.formatProperties(this));
}
withZooKeeper(client ->
doRegister(client, cluster, node, true)
);
}
@Override
public void stopDiscovery(String cluster, InetSocketAddress node) throws HekateException {
withZooKeeper(client ->
doUnregister(client, cluster, node, true)
);
}
@Override
public long cleanupInterval() {
return cleanupInterval;
}
@Override
public void registerRemote(String cluster, InetSocketAddress node) throws HekateException {
withZooKeeper(client ->
doRegister(client, cluster, node, false)
);
}
@Override
public void unregisterRemote(String cluster, InetSocketAddress node) throws HekateException {
withZooKeeper(client ->
doUnregister(client, cluster, node, false)
);
}
@Override
public void suspendDiscovery() throws HekateException {
// No-op.
}
private void doRegister(CuratorFramework client, String cluster, InetSocketAddress node, boolean local) throws HekateException {
try {
String clusterDir = basePath + cluster;
String seedPath = clusterDir + '/' + AddressUtils.toFileName(node);
if (log.isInfoEnabled()) {
log.info("Registering {} seed node [path={}]", local ? "local" : "remote", seedPath);
}
createDirs(client, clusterDir);
// Create a new z-node.
client.create().withMode(CreateMode.PERSISTENT).forPath(seedPath);
} catch (NodeExistsException e) {
// Ignore (node already registered).
} catch (Exception e) {
throw new HekateException("Failed to register seed node to ZooKeeper [cluster=" + cluster + ", node=" + node + ']', e);
}
}
private void doUnregister(CuratorFramework client, String cluster, InetSocketAddress node, boolean local) throws HekateException {
String seedPath = basePath + cluster + '/' + AddressUtils.toFileName(node);
try {
if (log.isInfoEnabled()) {
log.info("Unregistering {} seed node [path={}]", local ? "local" : "remote", seedPath);
}
client.delete().forPath(seedPath);
} catch (NoNodeException e) {
// Ignore.
} catch (Exception e) {
throw new HekateException("Failed to unregister seed node from ZooKeeper [cluster=" + cluster + ", node=" + node + ']', e);
}
}
private void createDirs(CuratorFramework client, String dir) throws Exception {
StringBuilder path = new StringBuilder();
for (String name : dir.split("/", -1)) {
if (!name.isEmpty()) {
path.append('/').append(name);
try {
client.create().withMode(CreateMode.PERSISTENT).forPath(path.toString());
if (DEBUG) {
log.debug("Created a base directory for seed nodes [path={}]", path);
}
} catch (NodeExistsException e) {
// Ignore (path already exists).
}
}
}
}
private void withZooKeeper(ZooKeeperTask task) throws HekateException {
try (CuratorFramework client = CuratorFrameworkFactory.newClient(
connectionString,
sessionTimeout,
connectTimeout,
new RetryOneTime(0)
)) {
client.start();
try {
if (!client.blockUntilConnected(connectTimeout, TimeUnit.MILLISECONDS)) {
throw new HekateException("Timeout connecting to ZooKeeper [connections-string=" + connectionString + ']');
}
} catch (InterruptedException e) {
throw new HekateException("Thread got interrupted while connecting to ZooKeeper.", e);
}
task.execute(client);
}
}
@Override
public String toString() {
return ToString.format(this);
}
}
| 34.737024
| 140
| 0.633828
|
e792f15f99cc3315bb4ad894024373172d942874
| 2,728
|
package com.ms.dxmedia;
import com.ms.dxmedia.rawcom.*;
import com.ms.com.*;
public class SoundBvr extends Behavior {
public SoundBvr (IDASound COMptr) {
super(COMptr);
_COMptr = (IDASound)COMptr ;
}
public SoundBvr () {
super(null);
_COMptr = null ;
}
public IDASound getCOMPtr() { return (IDASound) _COMptr; }
public void setCOMBvr(IDABehavior b) {
super.setCOMBvr(b);
_COMptr = (IDASound) b;
}
protected IDASound _getCOMPtr() { return _COMptr; }
public SoundBvr phase (NumberBvr arg0) {
try {
return new SoundBvr (_getCOMPtr().PhaseAnim (arg0._getCOMPtr())) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr phase (double arg0) {
try {
return new SoundBvr (_getCOMPtr().Phase ( (arg0))) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr rate (NumberBvr arg0) {
try {
return new SoundBvr (_getCOMPtr().RateAnim (arg0._getCOMPtr())) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr rate (double arg0) {
try {
return new SoundBvr (_getCOMPtr().Rate ( (arg0))) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr pan (NumberBvr arg0) {
try {
return new SoundBvr (_getCOMPtr().PanAnim (arg0._getCOMPtr())) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr pan (double arg0) {
try {
return new SoundBvr (_getCOMPtr().Pan ( (arg0))) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr gain (NumberBvr arg0) {
try {
return new SoundBvr (_getCOMPtr().GainAnim (arg0._getCOMPtr())) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr gain (double arg0) {
try {
return new SoundBvr (_getCOMPtr().Gain ( (arg0))) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public SoundBvr loop () {
try {
return new SoundBvr (_getCOMPtr().Loop ()) ;
} catch (ComFailException e) {
throw Statics.handleError(e);
}
}
public static SoundBvr newUninitBvr() {
return new SoundBvr(new DASound()) ;
}
protected Behavior newUninitBehavior() {
return newUninitBvr() ;
}
private IDASound _COMptr;
}
| 23.118644
| 76
| 0.559384
|
f895b1d341aea93e720334c82136d64d00c4a7a8
| 1,732
|
package com.kmcontrol.arquivos;
public class DadosRelatorio {
private long totalKm;
private double outrasDespesas;
private String nome;
private String nomeBanco;
private Integer conta;
private Integer agencia;
public DadosRelatorio() {
}
public DadosRelatorio(long totalKm, double outrasDespesas, String nome, String nomeBanco, Integer conta, Integer agencia) {
this.totalKm = totalKm;
this.outrasDespesas = outrasDespesas;
this.nome = nome;
this.nomeBanco = nomeBanco;
this.conta = conta;
this.agencia = agencia;
}
public long getTotalKm() {
return totalKm;
}
public void setTotalKm(long totalKm) {
this.totalKm = totalKm;
}
public double getOutrasDespesas() {
return outrasDespesas;
}
public void setOutrasDespesas(double outrasDespesas) {
this.outrasDespesas = outrasDespesas;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNomeBanco() {
return nomeBanco;
}
public void setNomeBanco(String nomeBanco) {
this.nomeBanco = nomeBanco;
}
public Integer getConta() {
return conta;
}
public void setConta(Integer conta) {
this.conta = conta;
}
public Integer getAgencia() {
return agencia;
}
public void setAgencia(Integer agencia) {
this.agencia = agencia;
}
@Override
public String toString() {
return nome + " | " + totalKm + " | " + outrasDespesas;
}
}
| 21.65
| 128
| 0.584873
|
2224e0afd95fd1f0aa619d344481011d78534c2a
| 4,818
|
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.0. You may not use this file
* except in compliance with the Zeebe Community License 1.0.
*/
package io.zeebe.engine.processor.workflow.deployment;
import io.zeebe.engine.processor.TypedRecord;
import io.zeebe.engine.processor.TypedRecordProcessor;
import io.zeebe.engine.processor.TypedResponseWriter;
import io.zeebe.engine.processor.TypedStreamWriter;
import io.zeebe.engine.processor.workflow.deployment.model.element.ExecutableCatchEventElement;
import io.zeebe.engine.processor.workflow.deployment.model.element.ExecutableStartEvent;
import io.zeebe.engine.processor.workflow.deployment.model.element.ExecutableWorkflow;
import io.zeebe.engine.state.deployment.DeployedWorkflow;
import io.zeebe.engine.state.deployment.WorkflowState;
import io.zeebe.protocol.impl.record.value.deployment.DeploymentRecord;
import io.zeebe.protocol.impl.record.value.deployment.Workflow;
import io.zeebe.protocol.impl.record.value.message.MessageStartEventSubscriptionRecord;
import io.zeebe.protocol.record.intent.DeploymentIntent;
import io.zeebe.protocol.record.intent.MessageStartEventSubscriptionIntent;
import java.util.List;
public class DeploymentCreatedProcessor implements TypedRecordProcessor<DeploymentRecord> {
private final WorkflowState workflowState;
private final boolean isDeploymentPartition;
private final MessageStartEventSubscriptionRecord subscriptionRecord =
new MessageStartEventSubscriptionRecord();
public DeploymentCreatedProcessor(WorkflowState workflowState, boolean isDeploymentPartition) {
this.workflowState = workflowState;
this.isDeploymentPartition = isDeploymentPartition;
}
@Override
public void processRecord(
final TypedRecord<DeploymentRecord> event,
final TypedResponseWriter responseWriter,
final TypedStreamWriter streamWriter) {
final DeploymentRecord deploymentEvent = event.getValue();
if (isDeploymentPartition) {
streamWriter.appendFollowUpCommand(
event.getKey(), DeploymentIntent.DISTRIBUTE, deploymentEvent);
}
for (final Workflow workflowRecord : deploymentEvent.workflows()) {
if (isLatestWorkflow(workflowRecord)) {
closeExistingMessageStartEventSubscriptions(workflowRecord, streamWriter);
openMessageStartEventSubscriptions(workflowRecord, streamWriter);
}
}
}
private boolean isLatestWorkflow(Workflow workflow) {
return workflowState
.getLatestWorkflowVersionByProcessId(workflow.getBpmnProcessIdBuffer())
.getVersion()
== workflow.getVersion();
}
private void closeExistingMessageStartEventSubscriptions(
Workflow workflowRecord, TypedStreamWriter streamWriter) {
final DeployedWorkflow lastMsgWorkflow = findLastMessageStartWorkflow(workflowRecord);
if (lastMsgWorkflow == null) {
return;
}
subscriptionRecord.reset();
subscriptionRecord.setWorkflowKey(lastMsgWorkflow.getKey());
streamWriter.appendNewCommand(MessageStartEventSubscriptionIntent.CLOSE, subscriptionRecord);
}
private DeployedWorkflow findLastMessageStartWorkflow(final Workflow workflowRecord) {
for (int version = workflowRecord.getVersion() - 1; version > 0; --version) {
final DeployedWorkflow lastMsgWorkflow =
workflowState.getWorkflowByProcessIdAndVersion(
workflowRecord.getBpmnProcessIdBuffer(), version);
if (lastMsgWorkflow != null
&& lastMsgWorkflow.getWorkflow().getStartEvents().stream().anyMatch(e -> e.isMessage())) {
return lastMsgWorkflow;
}
}
return null;
}
private void openMessageStartEventSubscriptions(
Workflow workflowRecord, TypedStreamWriter streamWriter) {
final long workflowKey = workflowRecord.getKey();
final DeployedWorkflow workflowDefinition = workflowState.getWorkflowByKey(workflowKey);
final ExecutableWorkflow workflow = workflowDefinition.getWorkflow();
final List<ExecutableStartEvent> startEvents = workflow.getStartEvents();
// if startEvents contain message events
for (ExecutableCatchEventElement startEvent : startEvents) {
if (startEvent.isMessage()) {
subscriptionRecord.reset();
subscriptionRecord
.setMessageName(startEvent.getMessage().getMessageName())
.setWorkflowKey(workflowKey)
.setBpmnProcessId(workflow.getId())
.setStartEventId(startEvent.getId());
streamWriter.appendNewCommand(MessageStartEventSubscriptionIntent.OPEN, subscriptionRecord);
}
}
}
}
| 43.017857
| 100
| 0.774595
|
dadf069e853741df231759c98f6dd0f99deed4cf
| 303
|
package tk.booky.jdahelper.api.exceptions.events;
// Created by booky10 in JDABotHelper (21:10 01.03.21)
import tk.booky.jdahelper.api.exceptions.JDAException;
public class NoAnnotationException extends JDAException {
public NoAnnotationException(String message) {
super(message);
}
}
| 27.545455
| 57
| 0.765677
|
baf4dd467520309275623a8e4d27abb8d85e8938
| 11,199
|
package com.kylenicholls.stash.parameterizedbuilds;
import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.commit.CommitService;
import com.atlassian.bitbucket.hook.repository.RepositoryHookRequest;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.repository.MinimalRef;
import com.atlassian.bitbucket.repository.RefChange;
import com.atlassian.bitbucket.repository.RefChangeType;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scope.RepositoryScope;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.atlassian.bitbucket.setting.Settings;
import com.atlassian.bitbucket.setting.SettingsValidationErrors;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.kylenicholls.stash.parameterizedbuilds.ciserver.Jenkins;
import com.kylenicholls.stash.parameterizedbuilds.eventHandlers.PushHandler;
import com.kylenicholls.stash.parameterizedbuilds.eventHandlers.RefCreatedHandler;
import com.kylenicholls.stash.parameterizedbuilds.eventHandlers.RefDeletedHandler;
import com.kylenicholls.stash.parameterizedbuilds.eventHandlers.RefHandler;
import com.kylenicholls.stash.parameterizedbuilds.helper.SettingsService;
import com.kylenicholls.stash.parameterizedbuilds.item.Job;
import com.kylenicholls.stash.parameterizedbuilds.item.Server;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ParameterizedBuildHookTest {
private final String BRANCH_REF = "refs/heads/branch";
private final String COMMIT = "commithash";
private final String PROJECT_KEY = "projectkey";
private final String REPO_SLUG = "reposlug";
private final String URI = "http://uri";
private final Server globalServer = new Server("globalurl", null, "globaluser", "globaltoken", false, false);
private final Server projectServer = new Server("projecturl", null, "projectuser", "projecttoken",
false, false);
private RepositoryHookRequest request;
private Settings settings;
private RefChange refChange;
private MinimalRef minimalRef;
private ParameterizedBuildHook buildHook;
private SettingsService settingsService;
private Jenkins jenkins;
private ApplicationPropertiesService propertiesService;
private Repository repository;
private RepositoryScope repositoryScope;
private ExecutorService executorService;
private SettingsValidationErrors validationErrors;
private Project project;
private ApplicationUser user;
List<Job> jobs;
@Before
public void setup() throws URISyntaxException {
settingsService = mock(SettingsService.class);
CommitService commitService = mock(CommitService.class);
jenkins = mock(Jenkins.class);
propertiesService = mock(ApplicationPropertiesService.class);
AuthenticationContext authContext = mock(AuthenticationContext.class);
executorService = mock(ExecutorService.class);
// executor simply invokes run on argument
doAnswer(invocationOnMock -> {
Object[] args = invocationOnMock.getArguments();
Runnable runnable = (Runnable) args[0];
runnable.run();
return null;
}).when(executorService).submit(any(Runnable.class));
request = mock(RepositoryHookRequest.class);
settings = mock(Settings.class);
refChange = mock(RefChange.class);
minimalRef = mock(MinimalRef.class);
repository = mock(Repository.class);
repositoryScope = mock(RepositoryScope.class);
validationErrors = mock(SettingsValidationErrors.class);
project = mock(Project.class);
user = mock(ApplicationUser.class);
when(authContext.getCurrentUser()).thenReturn(user);
when(request.getRepository()).thenReturn(repository);
when(refChange.getRef()).thenReturn(minimalRef);
when(refChange.getToHash()).thenReturn(COMMIT);
when(repository.getSlug()).thenReturn(REPO_SLUG);
when(repository.getProject()).thenReturn(project);
when(repositoryScope.accept(any())).thenReturn(project);
when(jenkins.getJenkinsServer(null)).thenReturn(globalServer);
when(jenkins.getJenkinsServer(project.getKey())).thenReturn(projectServer);
when(propertiesService.getBaseUrl()).thenReturn(new URI(URI));
when(project.getKey()).thenReturn(PROJECT_KEY);
when(minimalRef.getId()).thenReturn(BRANCH_REF);
jobs = new ArrayList<>();
when(settingsService.getJobs(any())).thenReturn(jobs);
buildHook = new ParameterizedBuildHook(settingsService, commitService, jenkins,
propertiesService, authContext, executorService);
}
@Test
public void testCreateHandlerADD() {
when(refChange.getType()).thenReturn(RefChangeType.ADD);
RefHandler handler = buildHook.createHandler(refChange, repository);
Assert.assertTrue(handler instanceof RefCreatedHandler);
}
@Test
public void testCreateHandlerDELETE() {
when(refChange.getType()).thenReturn(RefChangeType.DELETE);
RefHandler handler = buildHook.createHandler(refChange, repository);
Assert.assertTrue(handler instanceof RefDeletedHandler);
}
@Test
public void testCreateHandlerUPDATE() {
when(refChange.getType()).thenReturn(RefChangeType.UPDATE);
RefHandler handler = buildHook.createHandler(refChange, repository);
Assert.assertTrue(handler instanceof PushHandler);
}
@Test
public void testShowErrorIfJenkinsSettingsNull() {
when(jenkins.getJenkinsServer(null)).thenReturn(null);
when(jenkins.getJenkinsServer(project.getKey())).thenReturn(null);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError("jenkins-admin-error", "Jenkins is not setup in Bitbucket Server");
}
@Test
public void testShowErrorIfBaseUrlEmpty() {
Server server = new Server("", null, null, null, false, false);
when(jenkins.getJenkinsServer(null)).thenReturn(server);
when(jenkins.getJenkinsServer(project.getKey())).thenReturn(server);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError("jenkins-admin-error", "Jenkins is not setup in Bitbucket Server");
}
@Test
public void testShowErrorIfJenkinsSettingsUrlEmpty() {
Server server = new Server("", null, null, null, false, false);
when(jenkins.getJenkinsServer(null)).thenReturn(server);
when(jenkins.getJenkinsServer(project.getKey())).thenReturn(null);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError("jenkins-admin-error", "Jenkins is not setup in Bitbucket Server");
}
@Test
public void testShowErrorIfProjectSettingsUrlEmpty() {
when(jenkins.getJenkinsServer(null)).thenReturn(null);
Server server = new Server("", null, null, null, false, false);
when(jenkins.getJenkinsServer(project.getKey())).thenReturn(server);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError("jenkins-admin-error", "Jenkins is not setup in Bitbucket Server");
}
@Test
public void testNoErrorIfOnlyJenkinsSettingsNull() {
when(jenkins.getJenkinsServer(null)).thenReturn(null);
Server server = new Server("baseurl", null, null, null, false, false);
when(jenkins.getJenkinsServer(project.getKey())).thenReturn(server);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(0)).addFieldError(any(), any());
}
@Test
public void testNoErrorIfOnlyProjectSettingsNull() {
Server server = new Server("baseurl", null, null, null, false, false);
when(jenkins.getJenkinsServer(null)).thenReturn(server);
when(jenkins.getJenkinsServer(project.getKey())).thenReturn(null);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(0)).addFieldError(any(), any());
}
@Test
public void testShowErrorIfJobNameEmpty() {
Job job = new Job.JobBuilder(1).jobName("").jenkinsServer("test").triggers("add".split(";"))
.buildParameters("").branchRegex("").pathRegex("").build();
jobs.add(job);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError(SettingsService.JOB_PREFIX + "0", "Field is required");
}
@Test
public void testShowErrorIfJenkinsServerEmpty() {
Job job = new Job.JobBuilder(1).jobName("name").jenkinsServer("").triggers("add".split(";"))
.buildParameters("").branchRegex("").pathRegex("").build();
jobs.add(job);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError(SettingsService.SERVER_PREFIX + "0", "You must choose a jenkins server");
}
@Test
public void testShowErrorIfTriggersEmpty() {
Job job = new Job.JobBuilder(1).jobName("name").jenkinsServer("test").triggers("".split(";"))
.buildParameters("").branchRegex("").pathRegex("").build();
jobs.add(job);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1)).addFieldError(SettingsService.TRIGGER_PREFIX
+ "0", "You must choose at least one trigger");
}
@Test
public void testShowErrorIfBranchRegexInvalid() {
Job job = new Job.JobBuilder(1).jobName("name").jenkinsServer("test")
.triggers("add".split(";")).buildParameters("").branchRegex("(").pathRegex("").build();
jobs.add(job);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError(SettingsService.BRANCH_PREFIX + "0", "Unclosed group");
}
@Test
public void testShowErrorIfPathRegexInvalid() {
Job job = new Job.JobBuilder(1).jobName("name").jenkinsServer("test").triggers("add".split(";"))
.buildParameters("").branchRegex("").pathRegex("(").build();
jobs.add(job);
buildHook.validate(settings, validationErrors, repositoryScope);
verify(validationErrors, times(1))
.addFieldError(SettingsService.PATH_PREFIX + "0", "Unclosed group");
}
}
| 44.440476
| 113
| 0.710956
|
40d7e821726ff2db0633d1979c5a4d802e8f7780
| 2,131
|
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.maehem.flatlinejack;
import com.maehem.flatlinejack.engine.Vignette;
import com.maehem.flatlinejack.engine.gui.CrtTextPane;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* @author mark
*/
public class CrtTest extends Application {
public static final Logger log = Logger.getLogger("flatline");
private double SCALE = 2.0;
private Stage window;
private CrtTextPane narrationPane;
private final VBox gamePane = new VBox();
private final HBox bottomArea = new HBox(); // gui and naration
private final StackPane root = new StackPane(gamePane);
private final Scene scene = new Scene(root);
@Override
public void start(Stage window) {
ConsoleHandler handler = new ConsoleHandler();
// Add console handler as handler of logs
log.addHandler(handler);
log.setLevel(Level.FINER);
for (Handler h : log.getHandlers()) {
h.setLevel(Level.FINER);
}
this.window = window;
window.setScene(this.scene);
window.setResizable(false);
//quit when the window is close().
window.setOnCloseRequest(e -> Platform.exit());
//gamePane.setBottom(bottomArea);
gamePane.getChildren().add(bottomArea);
this.narrationPane = new CrtTextPane(Vignette.NATIVE_WIDTH*SCALE/2);
this.bottomArea.getChildren().addAll(narrationPane );
root.layout();
window.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| 29.191781
| 101
| 0.689348
|
2ad40d1b222b0c8878b0f9697a5d9811532e8234
| 7,971
|
package com.aaa.mygym.service.impl;
import com.aaa.mygym.dao.CardDao;
import com.aaa.mygym.dao.UserDao;
import com.aaa.mygym.dao.impl.CardDaoImpl;
import com.aaa.mygym.dao.impl.UserDaoImpl;
import com.aaa.mygym.entity.Card;
import com.aaa.mygym.entity.CardType;
import com.aaa.mygym.entity.RechargeRecord;
import com.aaa.mygym.entity.User;
import com.aaa.mygym.service.UserService;
import com.aaa.mygym.util.BusinessException;
import com.aaa.mygym.util.IntegerUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author
* @date
*
**/
public class UserServiceImpl implements UserService {
UserDao userDao = new UserDaoImpl();
CardDao cardDao = new CardDaoImpl();
/**
* 获取会员列表
* @param pageNumber
* @param pageSize
* @return
*/
@Override
public Map<String, Object> getAllUserList(Integer pageNumber, Integer pageSize,
Integer searchId,String searchName) throws BusinessException {
if(pageNumber == null){
throw new BusinessException("页数不能为空");
}
if(pageSize == null){
throw new BusinessException("列数不能为空");
}
pageNumber = (pageNumber - 1) * pageSize;
List<User> userDaoList = userDao.getAllUserList(pageNumber, pageSize,searchId,searchName);
int userDaoCount = userDao.getAllUserCount(searchName,searchId);
Map<String, Object> map = new HashMap<>();
map.put("list",userDaoList);
map.put("count",userDaoCount);
return map;
}
/**
* 查询所有卡类型
* @return
*/
@Override
public List<CardType> getCardTypeList() {
return userDao.getCardTypeList();
}
/**
* 根据手机号 判断是否唯一
* @param phone
* @return
*/
@Override
public String checkOnlyUser(String phone) throws Exception {
if (StringUtils.isBlank(phone)) {
throw new BusinessException("电话号码不能为空");
}
List<User> users = userDao.checkOnlyUser(phone);
if (users != null && users.size() > 0) {
return "该电话号码已经存在,请重新输入";
}
return null;
}
/**
* 新增会员
* @param userName
* @param userPhone
* @param userLevel
* @param userStatus
* @param staffName
* @param credit
* @param amount
* @param idno
* @param userSex
* @param province
* @param city
* @param address
* @param momo
* @param ruleId
* @param staffId
* @param cardId
* @return
* @throws Exception
*/
@Override
public int addUser(String userName, String userPhone, String userLevel, String userStatus, String staffName, String credit,
String amount, String idno, String userSex, String province, String city, String address, String momo,
String ruleId, String staffId,Integer cardId) throws Exception {
//参数校验
/**
* 会员登记
* 1.user //会员
* 2.card //卡
* 3.rechargeRecord 充值记录
*/
User user = new User();
//获取最后一个对象
User user1 = userDao.getLastUser();
if (user1 == null) {
throw new BusinessException("用户为空");
}
user.setUserId(user1.getUserId() + 1);
user.setUserName(userName);
user.setPhone(userPhone);
user.setStatus(IntegerUtils.ToInteger(userStatus));
user.setIdCard(idno);
user.setCardId(cardId);
user.setBirthday(idno.substring(6, 14));
user.setSex(IntegerUtils.ToInteger(userSex));
user.setAddress(address);
user.setArea(province + city);
user.setStaffId(IntegerUtils.ToInteger(staffId));
user.setCreatedTime(new Date());
user.setMomo(momo);
int len1 = userDao.addUser(user);
if (len1 <= 0) {
throw new BusinessException("会员登记失败,请重新操作");
}
Card card = new Card();
if (cardId == null) {
throw new BusinessException("卡为空");
}
card.setCardId(cardId + 1);
card.setUserId(user.getUserId());
card.setAmount(Double.parseDouble(amount));
card.setCredit(IntegerUtils.ToInteger(credit));
card.setStatus(1);
card.setStaffId(IntegerUtils.ToInteger(staffId));
card.setLevel(IntegerUtils.ToInteger(userLevel));
int len2 = cardDao.add(card);
if (len2 <= 0) {
throw new BusinessException("开卡失败,请重新操作");
}
card = cardDao.findById(card.getCardId());
RechargeRecord rechargeRecord = new RechargeRecord();
rechargeRecord.setcardId(card.getCardId());
rechargeRecord.setrechargeAmount(Double.parseDouble(amount));
rechargeRecord.setafterAmount(card.getAmount());
rechargeRecord.setbeforeAmount(0.0);
rechargeRecord.setruleId(IntegerUtils.ToInteger(ruleId));
rechargeRecord.setstaffId(IntegerUtils.ToInteger(staffId));
rechargeRecord.setcreatedTime(new Date());
rechargeRecord.setMomo(staffName + "开卡,开卡时间" + new Date());
int len3 = cardDao.addRechargeRecord(rechargeRecord);
if (len3 <= 0) {
throw new BusinessException("卡记录增加失败");
}
return 1;
}
/**
* 获取近一年注册会员
* @return
*/
@Override
public List<Map<String, Object>> getDataByNearYear() {
return userDao.getDataByNearYear();
}
/**
* 修改会员
* @param userName
* @param phone
* @param status
* @param address
* @param idCard
* @return
*/
@Override
public int updateUserById(String userName, String phone, Integer status, String address, String idCard, Integer cardId, Integer userId)
throws Exception {
if (userId == 0) {
throw new BusinessException("id不能为空");
}
User user = new User();
user.setUserName(userName);
user.setStatus(status);
user.setPhone(phone);
user.setIdCard(idCard);
user.setAddress(address);
user.setCardId(cardId);
user.setUserId(userId);
user.setCreatedTime(new Date());
return userDao.updateUser(user);
}
/**
* 删除会员
* 虽然 我们叫做删除 但是实际上只是修改状态不能删除
* @param userId
* @param status
* @return
* @throws Exception
*/
@Override
public int deluser(Integer userId, Integer status) throws Exception {
if (userId == null || userId == 0) {
throw new BusinessException("会员id不能为空");
}
return userDao.delUser(userId, status);
}
/**
* 根据id获得卡信息
* @param userId
* @return
* @throws Exception
*/
@Override
public Map<String, Object> getCardInfoById(Integer userId) throws Exception {
List<Map<String, Object>> list = userDao.getCardInfoById(userId);
if (list == null){
Map<String,Object> maps = new HashMap<>(0);
return maps;
}else {
Map<String,Object> map = list.get(0);
return map;
}
}
/**
* 获取最后一个会员的id
* 用来实现会员id自增
* @return
*/
@Override
public String getLastCardId() {
return Integer.parseInt(userDao.getLastCardId())+"";
}
/**
* 在创建会员的时候办一张卡
* @param cardId
* @param userId
* @param amount
* @param credit
* @param status
* @param staffId
* @param leavel
* @return
*/
@Override
public int createCard(Integer cardId, String userId, double amount, Integer credit, Integer status, Integer staffId, Integer leavel) throws Exception {
return userDao.createCard(cardId+1,userId,amount,credit,status,staffId,leavel);
}
/**
* 获取最后一个会员的id
* 用来实现会员id自增
* @return
*/
@Override
public String getLastUserId() {
return userDao.getLastUserId();
}
}
| 30.423664
| 155
| 0.598545
|
fa01e30fdf7fb944a205005077e56e4d0ff94239
| 302
|
package listeningrain.cn.blog.input.data;
import lombok.Getter;
import lombok.Setter;
/**
* author: listeningrain
* Date: 2018/10/4
* Time: 10:55
* Description:
*/
@Setter
@Getter
public class AdminInputData extends CommonInputData{
private String username;
private String password;
}
| 15.1
| 52
| 0.731788
|
3d8604548ce2633bf5f2c8e94acf4715043f277c
| 1,332
|
/**
* Copyright 2017 Pogeyan Technologies
*
* 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.pogeyan.cmis.server;
import java.io.File;
public class ServiceFactory {
private static ServiceFactory instance = new ServiceFactory();
public static ServiceFactory getInstance() {
return instance;
}
public File getTempDirectory() {
String tempDir = System.getProperty("java.io.tmpdir");
return new File(tempDir);
}
/**
* Returns {@code false}, do not encrypt temporary files.
*/
public boolean encryptTempFiles() {
return false;
}
/**
* Returns a threshold of 4 MiB.
*/
public int getMemoryThreshold() {
return 4 * 1024 * 1024;
}
/**
* Returns a max size of 4 GiB.
*/
public long getMaxContentSize() {
return (long) 4 * 1024 * 1024 * 1024;
}
}
| 24.666667
| 78
| 0.694444
|
a4344d2c9d14c75fbe180fd2fc1f9142690fa374
| 454
|
package com.kunal;
public class Basics {
public static void main(String[] args) {
// int a = 10;
// if (a == 10) {
// System.out.println("Hello World");
// }
// int count = 1;
// while(count != 5) {
// System.out.println(count);
// count++;
// }
// for loop
for(int count = 1; count != 5; count++) {
System.out.println(count);
}
}
}
| 21.619048
| 49
| 0.431718
|
6bb14be1510e3bb464448d5eed445c8aba88560c
| 4,246
|
package srs.appliance.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.Data;
import org.springframework.validation.annotation.Validated;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* Rent
*/
@Validated
@Entity
@Table(name = "rent")
@Data
public class Rent implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty("id")
@Id
@GeneratedValue
@JsonIgnore
private Integer id = null;
@JsonProperty("serial_number")
@Column(name = "serial_number", insertable = false, nullable = false)
private Integer serialNumber = null;
@JsonProperty("student")
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "student_id", insertable = true, updatable = false, nullable = false)
private Student student = null;
@JsonProperty("appliance")
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "appliance_id", insertable = true, updatable = false, nullable = false)
private Appliance appliance = null;
@JsonProperty("creation_date")
@Column(name = "creation_date")
private Date creationDate = null;
@JsonProperty("selected_end_date")
@Column(name = "selected_end_date")
private Date selectedEndDate = null;
@JsonProperty("actual_end_date")
@Column(name = "actual_end_date")
private Date actualEndDate = null;
@JsonProperty("rent_amount")
@Column(name = "rent_amount")
private Double rentAmount = null;
@JsonProperty("number_of_appliances")
@Column(name = "number_of_appliances")
private Integer numberOfAppliances = null;
@JsonProperty("status")
@Column(name = "status")
@Enumerated(EnumType.ORDINAL)
private StatusEnum status = null;
/**
* Gets or Sets status
*/
public enum StatusEnum {
RENTED("RENTED"),
TERMINATED("TERMINATED");
private String value;
StatusEnum(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static StatusEnum fromValue(String text) {
for (StatusEnum b : StatusEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
public Rent id(Integer id) {
this.id = id;
return this;
}
public Rent serialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
return this;
}
public Rent student(Student student) {
this.student = student;
return this;
}
public Rent appliance(Appliance appliance) {
this.appliance = appliance;
return this;
}
public Rent creationDate(Date creationDate) {
this.creationDate = creationDate;
return this;
}
public Rent selectedEndDate(Date selectedEndDate) {
this.selectedEndDate = selectedEndDate;
return this;
}
public Rent actualEndDate(Date actualEndDate) {
this.actualEndDate = actualEndDate;
return this;
}
public Rent rentAmount(Double rentAmount) {
this.rentAmount = rentAmount;
return this;
}
public Rent status(StatusEnum status) {
this.status = status;
return this;
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 25.27381
| 94
| 0.650966
|
4a740918883f08291d384fba0b5772dd08f4cb0d
| 355
|
package franco.gutierrez.ie.instagramfg.Util;
/**
* Created by Franco on 9/18/2016.
*/
public class ApplicationData {
public static final String Client_ID = "4577119038ca40e4b15bfacf1bbd68a2";
public static final String Client_Secret_ID = "2612ef332ebc4ee0828ef808fa285072";
public static final String CallBackURL = "http://showoff.ie/";
}
| 32.272727
| 85
| 0.76338
|
d8df79adac5c7eeed1395651f50fa946b98526f8
| 13,950
|
package com.github.mikesafonov.smpp.core.sender;
import com.cloudhopper.smpp.SmppConstants;
import com.cloudhopper.smpp.SmppSession;
import com.cloudhopper.smpp.pdu.EnquireLink;
import com.cloudhopper.smpp.pdu.EnquireLinkResp;
import com.cloudhopper.smpp.pdu.SubmitSm;
import com.cloudhopper.smpp.pdu.SubmitSmResp;
import com.cloudhopper.smpp.type.*;
import com.github.mikesafonov.smpp.core.dto.Message;
import com.github.mikesafonov.smpp.core.dto.MessageErrorInformation;
import com.github.mikesafonov.smpp.core.dto.MessageResponse;
import com.github.mikesafonov.smpp.core.dto.MessageType;
import com.github.mikesafonov.smpp.core.exceptions.IllegalAddressException;
import com.github.mikesafonov.smpp.core.exceptions.SmppMessageBuildingException;
import org.junit.jupiter.api.Test;
import static com.github.mikesafonov.smpp.util.Randomizer.randomString;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
* @author Mike Safonov
*/
class StandardSenderClientSendMessageTest extends BaseStandardSenderClientTest {
@Test
void shouldReturnErrorBecauseMessageIsEmpty() {
Message originalMessage = new Message(null, randomString(), randomString(), randomString(), MessageType.SIMPLE);
MessageErrorInformation messageErrorInformation = new MessageErrorInformation(0, "Empty message text");
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertNull(messageResponse.getSmscMessageID());
assertFalse(messageResponse.isSent());
assertEquals(messageErrorInformation, messageResponse.getMessageErrorInformation());
}
@Test
void successSendMessage() throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
String smscMessageId = randomString();
SubmitSm submitSm = new SubmitSm();
SubmitSmResp submitSmResp = new SubmitSmResp();
submitSmResp.setCommandStatus(SmppConstants.STATUS_OK);
submitSmResp.setMessageId(smscMessageId);
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(false);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenReturn(new EnquireLinkResp());
when(session.submit(eq(submitSm), anyLong())).thenReturn(submitSmResp);
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenReturn(submitSm);
assertDoesNotThrow(() -> senderClient.setup());
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertEquals(smscMessageId, messageResponse.getSmscMessageID());
assertNull(messageResponse.getMessageErrorInformation());
}
@Test
void successSendMessageWhenNoConnection() throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
String smscMessageId = randomString();
SubmitSm submitSm = new SubmitSm();
SubmitSmResp submitSmResp = new SubmitSmResp();
submitSmResp.setCommandStatus(SmppConstants.STATUS_OK);
submitSmResp.setMessageId(smscMessageId);
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(false);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenReturn(new EnquireLinkResp());
when(session.submit(eq(submitSm), anyLong())).thenReturn(submitSmResp);
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenReturn(submitSm);
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertEquals(smscMessageId, messageResponse.getSmscMessageID());
assertNull(messageResponse.getMessageErrorInformation());
}
@Test
void successSendMessageAfterReconnect() throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
String smscMessageId = randomString();
SubmitSm submitSm = new SubmitSm();
SubmitSmResp submitSmResp = new SubmitSmResp();
submitSmResp.setCommandStatus(SmppConstants.STATUS_OK);
submitSmResp.setMessageId(smscMessageId);
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(true);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenThrow(RuntimeException.class);
when(session.submit(eq(submitSm), anyLong())).thenReturn(submitSmResp);
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenReturn(submitSm);
assertDoesNotThrow(() -> senderClient.setup());
MessageResponse messageResponse = senderClient.send(originalMessage);
verify(session, times(1)).close();
verify(session, times(1)).destroy();
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertEquals(smscMessageId, messageResponse.getSmscMessageID());
assertNull(messageResponse.getMessageErrorInformation());
}
@Test
void failSendMessage() throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
String smscMessageId = randomString();
SubmitSm submitSm = new SubmitSm();
SubmitSmResp submitSmResp = new SubmitSmResp();
submitSmResp.setCommandStatus(SmppConstants.STATUS_INVEXPIRY);
submitSmResp.setMessageId(smscMessageId);
submitSmResp.setResultMessage(randomString());
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(false);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenReturn(new EnquireLinkResp());
when(session.submit(eq(submitSm), anyLong())).thenReturn(submitSmResp);
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenReturn(submitSm);
assertDoesNotThrow(() -> senderClient.setup());
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertNull( messageResponse.getSmscMessageID());
assertEquals(submitSmResp.getResultMessage(), messageResponse.getMessageErrorInformation().getErrorMessage());
assertEquals(101, messageResponse.getMessageErrorInformation().getErrorCode());
}
@Test
void failSendMessageBecauseThrowException() throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
String smscMessageId = randomString();
SubmitSm submitSm = new SubmitSm();
SubmitSmResp submitSmResp = new SubmitSmResp();
submitSmResp.setCommandStatus(SmppConstants.STATUS_INVEXPIRY);
submitSmResp.setMessageId(smscMessageId);
submitSmResp.setResultMessage(randomString());
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(false);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenReturn(new EnquireLinkResp());
when(session.submit(eq(submitSm), anyLong())).thenThrow(SmppInvalidArgumentException.class);
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenReturn(submitSm);
assertDoesNotThrow(() -> senderClient.setup());
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertNull( messageResponse.getSmscMessageID());
assertEquals("Invalid param", messageResponse.getMessageErrorInformation().getErrorMessage());
assertEquals(101, messageResponse.getMessageErrorInformation().getErrorCode());
}
@Test
void failSendMessageBecauseThrowUnexpectedException() throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
String smscMessageId = randomString();
SubmitSm submitSm = new SubmitSm();
SubmitSmResp submitSmResp = new SubmitSmResp();
submitSmResp.setCommandStatus(SmppConstants.STATUS_INVEXPIRY);
submitSmResp.setMessageId(smscMessageId);
submitSmResp.setResultMessage(randomString());
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(false);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenReturn(new EnquireLinkResp());
when(session.submit(eq(submitSm), anyLong())).thenThrow(RuntimeException.class);
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenReturn(submitSm);
assertDoesNotThrow(() -> senderClient.setup());
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertNull( messageResponse.getSmscMessageID());
assertEquals("Cant send message", messageResponse.getMessageErrorInformation().getErrorMessage());
assertEquals(102, messageResponse.getMessageErrorInformation().getErrorCode());
}
@Test
void failSendMessageBecauseThrowIllegalAddressException() throws UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException, RecoverablePduException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
IllegalAddressException illegalAddressException = new IllegalAddressException(randomString());
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(false);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenReturn(new EnquireLinkResp());
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenThrow(illegalAddressException);
assertDoesNotThrow(() -> senderClient.setup());
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertEquals(101, messageResponse.getMessageErrorInformation().getErrorCode());
assertEquals(illegalAddressException.getMessage(), messageResponse.getMessageErrorInformation().getErrorMessage());
assertNull(messageResponse.getSmscMessageID());
}
@Test
void failSendMessageBecauseThrowSmppMessageBuildingException() throws UnrecoverablePduException, SmppChannelException, InterruptedException, SmppTimeoutException, RecoverablePduException {
SmppSession session = mock(SmppSession.class);
Message originalMessage = new Message(randomString(), randomString(), randomString(), randomString(), MessageType.SIMPLE);
SmppMessageBuildingException exception = new SmppMessageBuildingException();
when(smppClient.bind(transmitterConfiguration)).thenReturn(session);
when(session.isBound()).thenReturn(false);
when(session.enquireLink(any(EnquireLink.class), anyLong())).thenReturn(new EnquireLinkResp());
when(messageBuilder.createSubmitSm(eq(originalMessage), anyBoolean())).thenThrow(exception);
assertDoesNotThrow(() -> senderClient.setup());
MessageResponse messageResponse = senderClient.send(originalMessage);
assertEquals(originalMessage, messageResponse.getOriginal());
assertEquals(senderClient.getId(), messageResponse.getSmscId());
assertEquals(101, messageResponse.getMessageErrorInformation().getErrorCode());
assertEquals("Invalid param", messageResponse.getMessageErrorInformation().getErrorMessage());
assertNull(messageResponse.getSmscMessageID());
}
}
| 54.705882
| 192
| 0.751398
|
4672d1c6379dee99f136d061e452e73dae8e0be6
| 1,972
|
package vn.techmaster.demoauth.repository;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import vn.techmaster.demoauth.entity.CustomUser;
@Service
public class UserRoleRepository {
static Map<String, CustomUser> DB_BASED_USER_MAPPING;
static {
DB_BASED_USER_MAPPING = new LinkedHashMap<>();
DB_BASED_USER_MAPPING.put("alice",
new CustomUser("alice", "123", getGrantedAuthorities("ROLE_USER", "ROLE_VIEWER"), "alice"));
DB_BASED_USER_MAPPING.put("bob",
new CustomUser("bob", "123", getGrantedAuthorities("ROLE_EDITOR", "ROLE_ADMIN"), "bob"));
DB_BASED_USER_MAPPING.put("tom",
new CustomUser("tom", "123", getGrantedAuthorities("ROLE_USER", "ROLE_REVIEWER"), "tom"));
}
private static List<GrantedAuthority> getGrantedAuthorities(String... roles) {
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
public CustomUser loadUserByUserName(String username) {
if (DB_BASED_USER_MAPPING.containsKey(username)) {
return DB_BASED_USER_MAPPING.get(username);
}
throw new UsernameNotFoundException("User " + username + " cannot be found");
}
public boolean isValidUsername(String username) {
return DB_BASED_USER_MAPPING.containsKey(username);
}
public boolean isValidRole(String roleName) {
return roleName.startsWith("ROLE_");
}
public List<String> getAllUsernames() {
List<String> usernames = new ArrayList<>();
usernames.add("alice");
usernames.add("bob");
usernames.add("tom");
return usernames;
}
}
| 32.327869
| 100
| 0.738337
|
2ff697e824bcf0b6a864e12946d2359a0c68ec94
| 515
|
package com.synthetic;
import java.util.LinkedList;
import java.util.List;
public class SyntheticMethodTest3 {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
List<?> a = new MyLink();
Object z = a.get(0);
List b = new MyLink();
b.add("");
b.add(13);
}
public static class MyLink extends LinkedList<String> {
@Override
public boolean add(String s) {
return true;
}
@Override
public String get(int i) {
return "";
}
}
}
| 17.166667
| 57
| 0.615534
|
94b3eefaf3781d397e748fe1bdea0891a27c034d
| 3,633
|
package com.qianyitian.hope2.analyzer.controller;
import com.alibaba.fastjson.JSON;
import com.qianyitian.hope2.analyzer.config.PropertyConfig;
import com.qianyitian.hope2.analyzer.job.fixedinvestiment.FixedInvestmentJob;
import com.qianyitian.hope2.analyzer.job.fixedinvestiment.IFixedInvestmentPolicy;
import com.qianyitian.hope2.analyzer.job.fixedinvestiment.MonthlyPolicy;
import com.qianyitian.hope2.analyzer.job.fixedinvestiment.WeeklyPolicy;
import com.qianyitian.hope2.analyzer.model.Stock;
import com.qianyitian.hope2.analyzer.model.ValueLog;
import com.qianyitian.hope2.analyzer.service.DefaultStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Created by bing.a.qian on 13/2/2018.
*/
@RestController
public class FixedInvestmentController {
@Autowired
private DefaultStockService stockService;
@Autowired
PropertyConfig propertyConfig;
@RequestMapping("/fixInvestment/{code}")
public String calcFixInvestment(@PathVariable String code, @RequestParam String startDate, @RequestParam String endDate, @RequestParam String type, @RequestParam String days) {
LocalDate fromDate = null;
try {
fromDate = LocalDate.parse(startDate);
} catch (Exception e) {
//300 index starts from 2002 01
//500 index starts from here
fromDate = LocalDate.parse("2005-02-04");
}
LocalDate toDate = null;
try {
toDate = LocalDate.parse(endDate);
} catch (Exception e) {
toDate = LocalDate.now();
}
Stock stock = stockService.getStockDaily(code);
IFixedInvestmentPolicy policy = buildPolicy(type, days);
FixedInvestmentJob job = new FixedInvestmentJob(stock, policy);
job.setFromDate(fromDate);
job.setToDate(toDate);
job.run();
List<ValueLog> jobR1ValueLogList = job.getAccountSummary().getValueLogList();
List<ValueLog> benchmarkValueLogList = job.getBenchmarkAccountSummary().getValueLogList();
List<String> categoryList = new LinkedList<>();
List<Double> r1DataList = new LinkedList<>();
List<Double> r2DataList = new LinkedList<>();
for (int i = 0; i < jobR1ValueLogList.size(); i++) {
ValueLog wanted = jobR1ValueLogList.get(i);
categoryList.add(getCategoryLabel(wanted));
r1DataList.add(wanted.getTotalValue());
r2DataList.add(benchmarkValueLogList.get(i).getTotalValue());
}
Map<String, List> map = new HashMap<String, List>();
map.put("category", categoryList);
map.put("r1", r1DataList);
map.put("r2", r2DataList);
return JSON.toJSONString(map);
}
private IFixedInvestmentPolicy buildPolicy(String type, String days) {
IFixedInvestmentPolicy policy;
if ("week".equals(type)) {
policy = new WeeklyPolicy();
} else {
policy = new MonthlyPolicy();
}
policy.setDays(days);
return policy;
}
private String getCategoryLabel(ValueLog wanted) {
return wanted.getDate().getYear() + "-" + wanted.getDate().getMonthValue() + "-" + wanted.getDate().getDayOfMonth();
}
}
| 35.970297
| 180
| 0.692265
|
3233452394ed0339784cec517cf2bb30742c9e67
| 931
|
package com.hsj.egameserver.server;
public class Crypt {
private static Crypt _instance = null;
private synchronized static void createInstance() {
if (_instance == null) {
_instance = new Crypt();
}
}
public static Crypt getInstance() {
if (_instance == null) {
createInstance();
}
return _instance;
}
public Crypt() {
}
public char[] C2Sdecrypt(byte encdata[]) {
char decdata[] = new char[encdata.length];
for (int i = 0; i < encdata.length; i++) {
decdata[i] = (char) ((char) (encdata[i] - 15) % 256);
}
return decdata;
}
public byte[] S2Cencrypt(char decdata[]) {
byte encdata[] = new byte[decdata.length];
for (int i = 0; i < decdata.length; i++) {
encdata[i] = (byte) ((decdata[i] ^ 0xc3) + 0x0f);
}
return encdata;
}
}
| 22.707317
| 65
| 0.524168
|
3db86885cdfdad4114cd05f93b2868f32e718146
| 1,095
|
package org.tourgune.pandora.bean;
public class Envios {
private Integer id;
private Integer fenceid;
private String userid;
private String fecha;
private Integer cantidad;
private String fencename;
private Integer diffusers;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getFenceid() {
return fenceid;
}
public void setFenceid(Integer fenceid) {
this.fenceid = fenceid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public Integer getCantidad() {
return cantidad;
}
public void setCantidad(Integer cantidad) {
this.cantidad = cantidad;
}
public String getFencename() {
return fencename;
}
public void setFencename(String fencename) {
this.fencename = fencename;
}
public Integer getDiffusers() {
return diffusers;
}
public void setDiffusers(Integer diffusers) {
this.diffusers = diffusers;
}
}
| 17.66129
| 46
| 0.711416
|
c1216b265bc951670cd9333790b0aa59f36233f3
| 4,444
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Builtin {
/**
* * A:获取功能
* public String getAbsolutePath():获取绝对路径
* public String getPath():获取路径
* public String getName():获取名称
* public long length():获取长度。字节数
* public long lastModified():获取最后一次的修改时间,毫秒值
* public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
* public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
*/
static File dir = new File("/Users/wentingzhu");
static File[] list = (new File("/Users/wentingzhu")).listFiles();
// public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
// ArrayList<String> history = new ArrayList<>();
//
// System.out.println("Welcom! What can I do for you?");
// boolean over = false;
// while(true) {
// System.out.print("slugshell>> ");
// String string = sc.nextLine();
// String[] commend = string.split("\\u007C");
// for (String subString : commend) {
// over = builtinCommend(history, over, subString.trim());
// }
// if(over) break;
// history.add(string);
// }
// }
// static File dir = new File("/Users/wentingzhu");
// static File[] list = (new File("/Users/wentingzhu")).listFiles();
public static boolean isBuiltinCommend(String string) {
if(string.equals("ls") || string.startsWith("ls *") || string.equals("history") || string.equals("status") || string.equals("cd ..")
|| string.equals("cd ~") || string.startsWith("cd") || string.equals("pwd") || string.equals("quit") || string.startsWith("mv ")
|| string.startsWith("cp ")) {
return true;
} else {
return false;
}
}
public static boolean builtinCommend(ArrayList<String> history, boolean over, String string) {
if(string.equals("ls")) {
list();
}else if(string.startsWith("ls *")){
list(string);
}else if(string.equals("history")) {
history(history);
}else if(string.equals("status")){
System.out.println(history.get(history.size()-1));
}else if(string.equals("cd ..")) {
goback();
}else if(string.equals("cd ~")){
home();
}else if(string.startsWith("cd ")) {
cd(string);
}else if(string.startsWith("mv ") || string.startsWith("cp ")){
change(string);
}else if(string.equals("pwd")) {
System.out.println(dir);
}else if(string.equals("quit")){
System.out.println("See you!");
over = true;
}
return over;
}
public static void change(String string) {
String[] fs = string.substring(3).split(" ");
if(fs.length != 2) {
System.out.println("You should input like: mv/cp aFile bFile");
}else {
File original = new File(dir, fs[0]);
File newFile = new File(dir,fs[1]);
System.out.println(original.renameTo(newFile));
if(string.startsWith("cp "))copyFile(newFile , original);
}
}
public static void history(ArrayList<String> history) {
for (int i = 0; i < history.size(); i++) {
System.out.println(i + 1 + "." + history.get(i));
}
}
public static void copyFile(File fromFile,File toFile){
try {
FileInputStream ins = new FileInputStream(fromFile);
FileOutputStream out = new FileOutputStream(toFile);
byte[] b = new byte[1024];
int n=0;
while((n=ins.read(b))!=-1){
out.write(b, 0, n);
}
ins.close();
out.close();
} catch (Exception e) {
// TODO: handle exception
}
}
public static void home() {
dir = new File("/Users/wentingzhu");
list = (new File("/Users/wentingzhu")).listFiles();
}
public static void list(String string) {
for (File file : list) { //获取文件对象
if(file.getName().endsWith(string.substring(4)))System.out.println(file);
}
}
public static void goback() {
try {
dir = dir.getParentFile();
list = dir.listFiles();
} catch (Exception e) {
System.out.println("It is root now");
dir = new File("/Users/wentingzhu");
}
}
public static void cd(String string) {
String cd = string.substring(3);
for(File subFile : list) {
if(subFile.isFile())continue;
if(subFile.getName().equals(cd)) {
dir = subFile;
list = dir.listFiles();
return;
}
}
System.out.println("Folder doesn't exist!");
}
public static void list() {
for (File file : list) { //获取文件对象
System.out.println(file);
}
}
}
| 28.487179
| 134
| 0.626688
|
010603f94c16ed7ce4599d42ab101eaa5837f02a
| 3,899
|
package com.carloan.integration.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.carloan.business.model.Agency;
import com.carloan.business.model.Operator;
import com.carloan.integration.database.ConnectorFactory;
import com.carloan.integration.util.Replacer;
import com.carloan.presentation.factory.FXAlert;
class OperatorDAO implements DAO<Operator> {
private static final String SELECT_ALL = "SELECT * FROM operator";
private static final String SELECT_FROM_ID = "SELECT * FROM operator WHERE id=?";
private static final String INSERT = "INSERT INTO operator(first_name,last_name,email,username,password,agency_id)"
+ "VALUES('?','?','?','?','?',?)";
private static final String UPDATE = "UPDATE operator SET first_name='?',last_name='?',email='?',"
+ "username='?',password='?',agency_id=?, admin=? WHERE id=?";
private static final String DELETE = "DELETE FROM operator WHERE username='?'";
private DAO<Agency> agencyDAO;
OperatorDAO(){
agencyDAO = new AgencyDAO();
}
private Operator setOperator(ResultSet rs) throws SQLException{
Operator operator = new Operator();
operator.setId(rs.getInt(1));
operator.setFirstName(rs.getString(2));
operator.setLastName(rs.getString(3));
operator.setEmail(rs.getString(4));
operator.setUsername(rs.getString(5));
operator.setPassword(rs.getString(6));
operator.setAgency(agencyDAO.get(rs.getInt(7)));
operator.setAdmin(rs.getBoolean(8));
return operator;
}
@Override
public Operator get(int id) {
String query = SELECT_FROM_ID;
query = Replacer.replaceFirst(query, id);
ResultSet rs = ConnectorFactory.getConnection().executeQuery(query);
try {
if(rs.next()) {
return setOperator(rs);
}
} catch (SQLException e) {
FXAlert.warning(e,"Database Error");
}
return null;
}
@Override
public List<Operator> getAll() {
List<Operator> operators = new ArrayList<>();
ResultSet rs = ConnectorFactory.getConnection().executeQuery(SELECT_ALL);
try {
while(rs.next()) {
operators.add(setOperator(rs));
}
} catch (SQLException e) {
FXAlert.warning(e,"Database Error");
}
return operators;
}
@Override
public void create(Operator operator) {
String query = INSERT;
query = Replacer.replaceFirst(query, operator.getFirstName());
query = Replacer.replaceFirst(query, operator.getLastName());
query = Replacer.replaceFirst(query, operator.getEmail());
query = Replacer.replaceFirst(query, operator.getUsername());
query = Replacer.replaceFirst(query, operator.getPassword());
query = Replacer.replaceFirst(query, operator.getAgency().getId());
operator.setId(ConnectorFactory.getConnection().executeUpdate(query));
}
@Override
public void update(Operator operator) {
String query = UPDATE;
query = Replacer.replaceFirst(query, operator.getFirstName());
query = Replacer.replaceFirst(query, operator.getLastName());
query = Replacer.replaceFirst(query, operator.getEmail());
query = Replacer.replaceFirst(query, operator.getUsername());
query = Replacer.replaceFirst(query, operator.getPassword());
query = Replacer.replaceFirst(query, operator.getAgency().getId());
query = Replacer.replaceFirst(query, operator.isAdmin());
query = Replacer.replaceFirst(query, operator.getId());
ConnectorFactory.getConnection().executeUpdate(query);
}
@Override
public void delete(Operator operator) {
String query = DELETE;
query = Replacer.replaceFirst(query, operator.getId());
ConnectorFactory.getConnection().executeUpdate(query);
}
}
| 39.383838
| 116
| 0.678379
|
ca4b12e4967bf458863b270c631e7df308bedf20
| 2,234
|
package com.android.gaojun.weather.GSON;
import java.util.List;
/**
* Created by Administrator on 2016/5/3.
*/
public class NewsDao {
private Body showapi_res_body;
public Body getShowapi_res_body() {
return showapi_res_body;
}
public void setShowapi_res_body(Body showapi_res_body) {
this.showapi_res_body = showapi_res_body;
}
public class Body{
private Pagebean pagebean;
public Pagebean getPagebean() {
return pagebean;
}
public void setPagebean(Pagebean pagebean) {
this.pagebean = pagebean;
}
}
public class Pagebean{
private List<ContentList> contentlist;
public List<ContentList> getContentlist() {
return contentlist;
}
public void setContentlist(List<ContentList> contentlist) {
this.contentlist = contentlist;
}
}
public class ContentList{
private String channelId;
private String channelName;
private String title;
private String link;
private List<ImageUrls> imageurls;
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public List<ImageUrls> getImageurls() {
return imageurls;
}
public void setImageurls(List<ImageUrls> imageurls) {
this.imageurls = imageurls;
}
}
public class ImageUrls{
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
| 21.901961
| 67
| 0.568039
|
2eef61074d9a63231e26174d80906dbfe47bfb37
| 1,305
|
package ru.otus.lantukh.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author sergey
* created on 14.12.18.
*/
public class HWCacheDemo {
private static final Logger logger = LoggerFactory.getLogger(HWCacheDemo.class);
public static void main(String[] args) {
new HWCacheDemo().demo();
}
private void demo() {
HwCache<Integer, Integer> cache = new MyCache<>();
HwListener<Integer, Integer> listener1 = new HwListener<Integer, Integer>() {
@Override
public void notify(Integer key, Integer value, OperationType action) {
logger.info("key:{}, value:{}, action: {}", key, value, action);
}
};
HwListener<Integer, Integer> listener2 = new HwListener<Integer, Integer>() {
@Override
public void notify(Integer key, Integer value, OperationType action) {
logger.info("key:{}, value:{}, action: {}", key, value, action);
}
};
cache.addListener(listener1);
cache.addListener(listener2);
cache.put(1, 155);
cache.put(2, 266);
logger.info("getValue:{}", cache.get(1));
cache.remove(1);
cache.removeListener(listener1);
cache.put(3, 355);
}
}
| 27.765957
| 85
| 0.587739
|
ed6779f429fac1f7ebd30096975b994240d98b2a
| 335
|
package Release_VIII.A_Chapter_5;
public class S28_Continue_Label {
public static void main(String[] args) {
outer: for(int i=0; i<10; i++) {
for(int j=1; j<10; j++) {
if(j>i) {
System.out.println();
continue outer;
}
System.out.print(" " +(i*j));
}
}
System.out.println();
}
}
| 16.75
| 41
| 0.546269
|
8bc1bf14bfb8f61719f1ae5a9588059aa6ae6116
| 1,536
|
package streams.exercises.moneymanager.solutions;
import streams.exercises.moneymanager.domain.TransactionFeedEntry;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
public class TransactionChecker {
private Stream<TransactionFeedEntry> transactionFeed;
private TransactionChecker(Stream<TransactionFeedEntry> transactionFeed) {
this.transactionFeed = transactionFeed;
}
public static TransactionChecker from(Stream<TransactionFeedEntry> transactionFeed) {
return new TransactionChecker(transactionFeed);
}
private final Predicate<TransactionFeedEntry> HAS_ZERO_VALUE = (entry -> entry.getDeposit() == 0 && entry.getWithdrawal() == 0);
private final Predicate<TransactionFeedEntry> HAS_NEGATIVE_VALUES= (entry -> entry.getDeposit() < 0 || entry.getWithdrawal() < 0);
private final Predicate<TransactionFeedEntry> HAS_MISSING_COUNTERPARTY= (entry -> entry.getCounterparty() == null || entry.getCounterparty().trim().isEmpty());
private final List<Predicate<TransactionFeedEntry>> RULES = asList(
HAS_ZERO_VALUE, HAS_NEGATIVE_VALUES, HAS_MISSING_COUNTERPARTY
);
public boolean hasInvalidTransactions() {
return transactionFeed.anyMatch(this::violatesConstraints);
}
private boolean violatesConstraints(TransactionFeedEntry entry) {
return RULES.stream().anyMatch(
rule -> rule.test(entry)
);
}
}
| 36.571429
| 163
| 0.745443
|
d335c24d090427491047db1b3f297215d3e58671
| 17,883
|
/*
* Copyright 2013-2015 Alex Lin.
*
* 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.opoo.press.impl;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.opoo.press.Category;
import org.opoo.press.Factory;
import org.opoo.press.Highlighter;
import org.opoo.press.Named;
import org.opoo.press.ObjectFactory;
import org.opoo.press.Page;
import org.opoo.press.PaginationUpdater;
import org.opoo.press.Plugin;
import org.opoo.press.PluginManager;
import org.opoo.press.RelatedPostsFinder;
import org.opoo.press.Renderer;
import org.opoo.press.ResourceBuilder;
import org.opoo.press.Site;
import org.opoo.press.SlugHelper;
import org.opoo.press.Source;
import org.opoo.press.SourceDirectoryWalker;
import org.opoo.press.SourceManager;
import org.opoo.press.SourceWalker;
import org.opoo.press.Tag;
import org.opoo.press.highlighter.SyntaxHighlighter;
import org.opoo.press.pagination.ConfigurablePaginationUpdater;
import org.opoo.press.plugin.PluginManagerImpl;
import org.opoo.press.renderer.FreeMarkerRenderer;
import org.opoo.press.slug.DefaultSlugHelper;
import org.opoo.press.source.SourceDirectoryWalkerImpl;
import org.opoo.press.source.SourceManagerImpl;
import org.opoo.press.util.ClassUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/**
* @author Alex Lin
*/
public class FactoryImpl extends PluginManagerImpl implements Factory, PluginManager, ObjectFactory {
private static final Logger log = LoggerFactory.getLogger(FactoryImpl.class);
private Site site;
private Map<String, Object> configuration = new LinkedHashMap<String, Object>();
private SourceDirectoryWalker sourceDirectoryWalker;
private List<SourceWalker> sourceWalkers;
private SourceManager sourceManager;
private Highlighter highlighter;
private SlugHelper slugHelper;
private RelatedPostsFinder relatedPostsFinder;
private PaginationUpdater paginationUpdater;
private List<Plugin> plugins;
private Map<String, Object> instances = new HashMap<String, Object>();
public FactoryImpl(Site site) {
super(site);
this.site = site;
//default factory config
InputStream is = Site.class.getResourceAsStream("/factory.yml");
addConfiguration(is);
//theme factory config
File themeDir = site.getTheme().getPath();
File factoryFile = new File(themeDir, "factory.yml");
addConfiguration(factoryFile);
//site factory config
File basedir = site.getBasedir();
factoryFile = new File(basedir, "factory.yml");
addConfiguration(factoryFile);
initializePlugins();
}
public static Factory createInstance(Site site) {
String factoryClassName = site.getConfig().get("factory");
if (StringUtils.isNotBlank(factoryClassName)) {
log.debug("Create factory: {}", factoryClassName);
return ClassUtils.newInstance(factoryClassName, site.getClassLoader(), site, site.getConfig());
}
//default factory
return new FactoryImpl(site);
}
void addConfiguration(InputStream is) {
if (is != null) {
Map map = new Yaml().loadAs(is, Map.class);
configuration.putAll(map);
IOUtils.closeQuietly(is);
}
}
void addConfiguration(File factoryFile) {
if (factoryFile != null && factoryFile.exists()) {
try {
addConfiguration(new FileInputStream(factoryFile));
} catch (FileNotFoundException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
@Override
public SourceDirectoryWalker getSourceDirectoryWalker() {
if (sourceDirectoryWalker == null) {
sourceDirectoryWalker = getInstance(SourceDirectoryWalker.class);
if (sourceDirectoryWalker == null) {
sourceDirectoryWalker = new SourceDirectoryWalkerImpl();
}
}
return sourceDirectoryWalker;
}
@Override
public List<SourceWalker> getSourceWalkers() {
if (sourceWalkers == null) {
sourceWalkers = instantiateList(SourceWalker.class);
}
return sourceWalkers;
}
@Override
public SourceManager getSourceManager() {
if (sourceManager == null) {
sourceManager = getInstance(SourceManager.class);
if (sourceManager == null) {
sourceManager = new SourceManagerImpl();
}
}
return sourceManager;
}
@Override
public Highlighter getHighlighter() {
if (highlighter == null) {
highlighter = getInstance(Highlighter.class);
if (highlighter == null) {
highlighter = new SyntaxHighlighter();
}
}
return highlighter;
}
@Override
public SlugHelper getSlugHelper() {
if (slugHelper == null) {
if (site.getLocale() != null) {
String hint = site.getLocale().toString();
String str = SlugHelper.class.getName() + "-" + hint;
String className = (String) configuration.get(str);
if (className != null) {
slugHelper = newInstance(className);
}
}
if (slugHelper == null) {
slugHelper = createInstance(SlugHelper.class);
}
if (slugHelper == null) {
slugHelper = new DefaultSlugHelper();
}
}
return slugHelper;
}
@Override
public RelatedPostsFinder getRelatedPostsFinder() {
if (relatedPostsFinder == null) {
relatedPostsFinder = getInstance(RelatedPostsFinder.class);
if (relatedPostsFinder == null) {
relatedPostsFinder = new NoOpRelatedPostsFinder();
}
}
return relatedPostsFinder;
}
@Override
public Page createPage(Site site, Source source) {
return createPage(site, source, (String) source.getMeta().get("layout"));
}
@Override
public Page createPage(Site site, Source source, String layout) {
Page page = constructInstance(Page.class, layout,
new Class[]{Site.class, Source.class},
new Object[]{site, source});
if (page != null) {
return page;
}
if ("post".equalsIgnoreCase(layout)) {
if (log.isDebugEnabled()) {
log.debug("Create post using SourcePost as default: {}", source.getOrigin());
}
return new SourcePost(site, source);
}
if (log.isDebugEnabled()) {
log.debug("Create page using SourcePage as default: {}", source.getOrigin());
}
return new SourcePage(site, source);
}
private void initializePlugins() {
if (plugins == null) {
log.debug("Initializing plugins");
plugins = instantiateList(Plugin.class);
for (Plugin plugin : plugins) {
log.debug("Initializing plugin: {}", plugin.getClass().getName());
plugin.initialize(this);
}
}
}
@Override
public List<Plugin> getPlugins() {
return plugins;
}
@Override
public PluginManager getPluginManager() {
return this;
}
@Override
public Renderer getRenderer() {
ServiceLoader<Renderer> loader = ServiceLoader.load(Renderer.class, site.getClassLoader());
Iterator<Renderer> iterator = loader.iterator();
if (iterator.hasNext()) {
return iterator.next();
}
String className = (String) site.getTheme().get("renderer");
if (className != null) {
Class<Renderer> clazz;
try {
clazz = ClassUtils.getClass(site.getClassLoader(), className);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage());
}
Constructor<?> theConstructor = null;
try {
theConstructor = clazz.getConstructor(Site.class);
} catch (NoSuchMethodException e) {
//ignore
}
try {
if (theConstructor != null) {
return (Renderer) theConstructor.newInstance(site);
} else {
Renderer renderer = clazz.newInstance();
return apply(renderer);
}
} catch (InstantiationException e) {
throw new RuntimeException("error instance: " + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException("error instance: " + e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new RuntimeException("error instance: " + e.getTargetException().getMessage(),
e.getTargetException());
}
}
//if custom render not specified
//default: freemarker
return new FreeMarkerRenderer(site);
}
@Override
public PaginationUpdater getPaginationUpdater() {
if (paginationUpdater == null) {
paginationUpdater = getInstance(PaginationUpdater.class);
if (paginationUpdater == null) {
paginationUpdater = new ConfigurablePaginationUpdater();
}
}
return paginationUpdater;
}
@Override
public ResourceBuilder createResourceBuilder(String type) {
ResourceBuilder builder = createInstance(ResourceBuilder.class, type);
if (builder == null) {
builder = ClassUtils.newInstance(type, site.getClassLoader(), site, site.getConfig());
}
return builder;
}
@Override
public Category createCategory(String categoryMeta, String slug, String categoryName, Category parent) {
Category category = constructInstance(Category.class, categoryMeta,
new Class[]{String.class, String.class, Category.class},
new Object[]{slug, categoryName, parent});
if (category != null) {
return category;
}
return new CategoryImpl(slug, categoryName, parent);
}
@Override
public Category createCategory(String categoryMeta, String slug, String categoryName) {
Category category = constructInstance(Category.class, categoryMeta,
new Class[]{String.class, String.class},
new Object[]{slug, categoryName});
if (category != null) {
return category;
}
return new CategoryImpl(slug, categoryName);
}
@Override
public Category createCategory(String categoryMeta, String slugOrName) {
String slug = getSlugHelper().toSlug(slugOrName);
return createCategory(categoryMeta, slug, slugOrName);
}
@Override
public Tag createTag(String tagMeta, String slug, String name) {
Tag tag = constructInstance(Tag.class, tagMeta,
new Class[]{String.class, String.class},
new Object[]{slug, name});
if (tag != null) {
return tag;
}
return new TagImpl(slug, name);
}
@Override
public Tag createTag(String tagMeta, String slugOrName) {
log.debug("Create tag: {} {}", tagMeta, slugOrName);
String slug = getSlugHelper().toSlug(slugOrName);
return createTag(tagMeta, slug, slugOrName);
}
@Override
public <T> T getInstance(Class<T> clazz, String name) {
String cacheKey = clazz.getName();
if (name != null) {
cacheKey += "-" + name;
}
if (instances.containsKey(cacheKey)) {
return (T) instances.get(cacheKey);
} else {
T o = createInstance(clazz, name);
instances.put(cacheKey, o);
return o;
}
}
@Override
public <T> T getInstance(Class<T> clazz) {
return getInstance(clazz, null);
}
@Override
public <T> T createInstance(Class<T> clazz, final String hint) {
ServiceLoader<T> loader = ServiceLoader.load(clazz, site.getClassLoader());
if (hint == null) {
Iterator<T> iterator = loader.iterator();
if (iterator.hasNext()) {
return apply(iterator.next());
}
} else {
T t = null;
for (T tt : loader) {
if (t instanceof Named && hint.equals(((Named) t).getName())) {
t = tt;
break;
}
}
if (t != null) {
log.debug("Find instance in ServiceLoader: {}", clazz.getName());
return apply(t);
}
}
String classKey = clazz.getName();
if (hint != null) {
classKey += "-" + hint;
}
String className = (String) configuration.get(classKey);
if (StringUtils.isBlank(className) || "none".equalsIgnoreCase(className)) {
return null;
}
return newInstance(className);
}
@Override
public <T> T createInstance(Class<T> clazz) {
return createInstance(clazz, null);
}
@Override
public <T> T constructInstance(Class<T> clazz, String hint, Object... args) {
return constructInstance(clazz, hint, null, args);
}
public <T> T constructInstance(Class<T> clazz, String hint, Class<?>[] parameterTypes, Object[] args) {
String classKey = clazz.getName();
if (hint != null) {
classKey += "-" + hint;
}
String className = (String) configuration.get(classKey);
if (StringUtils.isBlank(className) || "none".equalsIgnoreCase(className)) {
return null;
}
return ClassUtils.constructInstance(className, site.getClassLoader(), parameterTypes, args);
}
public <T> T newInstance(String className) {
T t = ClassUtils.newInstance(className, site.getClassLoader(), site, site.getConfig());
//log.debug("Create instance for '{}': {}", className, t.getClass().getName());
return t;
}
@Override
public <T> List<T> instantiateList(Class<T> clazz) {
List<T> list = super.instantiateList(clazz);
Object o = configuration.get(clazz.getName());
if (o instanceof List) {
List<String> classNames = (List<String>) o;
if (!classNames.isEmpty()) {
for (String className : classNames) {
T t = newInstance(className);
log.debug("Create instance: {} => {}", clazz.getName(), className);
list.add(t);
}
}
} else if (o instanceof Map) {
Map<String, String> classNames = (Map<String, String>) o;
if (!classNames.isEmpty()) {
for (Map.Entry<String, String> entry : classNames.entrySet()) {
String name = entry.getKey();
String className = entry.getValue();
T t = newInstance(className);
log.debug("Create instance: {} => {}", clazz.getName(), className);
list.add(t);
}
}
} else if (o != null) {
log.warn("Configuration error: {} => {}", clazz.getName(), o);
}
return list;
}
@Override
public <T> Map<String, T> instantiateMap(Class<T> clazz) {
Map<String, T> map = super.instantiateMap(clazz);
Object o = configuration.get(clazz.getName());
if (o instanceof List) {
List<String> classNames = (List<String>) o;
if (!classNames.isEmpty()) {
for (String className : classNames) {
T t = newInstance(className);
if (t instanceof Named) {
log.debug("Create instance for '{}': {} => {}", ((Named) t).getName(), clazz.getName(), className);
map.put(((Named) t).getName(), t);
}
}
}
} else if (o instanceof Map) {
Map<String, String> classNames = (Map<String, String>) o;
if (!classNames.isEmpty()) {
for (Map.Entry<String, String> entry : classNames.entrySet()) {
String name = entry.getKey();
String className = entry.getValue();
T t = newInstance(className);
log.debug("Create instance for '{}': {} => {}", name, clazz.getName(), className);
map.put(name, t);
}
}
} else if (o != null) {
log.warn("Configuration error: {} => {}", clazz.getName(), o);
}
return map;
}
}
| 33.741509
| 123
| 0.588268
|
ddac426303e8b4552eab7cfc10a283b4cd0089f4
| 2,640
|
/*
* Copyright (C) 2014 Indeed Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.indeed.imhotep.archive;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author jsgroth
*/
public class CopyFilteredDirectoryToLocal {
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("ARGS: from to");
System.exit(1);
}
System.out.println("Copying archives from " + args[0] + " to " + args[1]);
copy(new Path(args[0]), new File(args[1]));
System.out.println("Wrote to: " + args[1]);
}
public static void copy(Path from, File to) throws IOException {
copy(from.getFileSystem(new Configuration()), from, to);
}
public static void copy(FileSystem fs, Path from, File to) throws IOException {
if ((to.exists() && !to.isDirectory())) {
throw new FileNotFoundException(to.getAbsolutePath() + " is not a directory");
} else if (!to.exists() && !to.mkdirs()) {
throw new IOException("unable to create directory " + to.getAbsolutePath());
}
for (final FileStatus status : fs.listStatus(from, new PathFilter() {
@Override
public boolean accept(Path path) {
System.out.println("path.getName() = " + path.getName());
return path.getName().startsWith("index20130709");
}
})) {
if (status.isDir()) {
final Path path = status.getPath();
System.out.println("copying " + path);
final String pathName = path.getName();
final String dirName = pathName.endsWith(".sqar") ? pathName.substring(0, pathName.length() - 5) : pathName;
new SquallArchiveReader(fs, path).copyAllToLocal(new File(to, dirName));
}
}
}
}
| 38.26087
| 124
| 0.635606
|
63ef7f45fa9e815eec3bf507a947d36d3bffa1ff
| 6,930
|
package com.example.rajtalekar.jogman10;
import android.content.ContentUris;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link Section_1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link Section_1#newInstance} factory method to
* create an instance of this fragment.
*/
public class Section_1 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
MainActivity mainActivity=new MainActivity();
HearAlone hearAlone=new HearAlone();
AlbumSongs albumSongs=new AlbumSongs();
ArtistSongs artistSongs=new ArtistSongs();
String[] items;
ArrayList<song> songArrayList;
ListView lv;
static String song_Title_string=new String();
private Uri trackUri;
// private MediaPlayer mp;
public static ArrayList<String> items1;
public String return_song_Title(){
return song_Title_string;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Section_1() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Section_1.
*/
// TODO: Rename and change types and number of parameters
public static Section_1 newInstance(String param1, String param2) {
Section_1 fragment = new Section_1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
songArrayList = mainActivity.return_ArrayList();
items=new String[songArrayList.size()];
items = mainActivity.return_SongList();
items1 = new ArrayList<>();
Collections.addAll(items1,items);
View rootView = inflater.inflate(R.layout.fragment_section_1, container, false);
lv = (ListView) rootView.findViewById(R.id.listView);
MyAdapter myAdapter = new MyAdapter(getContext(), songArrayList);
//final ListView hearAloneList=(ListView)getActivity().findViewById(R.id.listViewSlideHearAlone);
lv.setAdapter(myAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
song_Title_string = songArrayList.get(position).getTitle();
hearAlone.Set_SongDetailes(song_Title_string, songArrayList.get(position).getArtist(), songArrayList.get(position).getAlbumID());
mainActivity.set_SongDetailes(song_Title_string, songArrayList.get(position).getAlbumID());
albumSongs.set_SongDetailes(song_Title_string, songArrayList.get(position).getAlbumID());
artistSongs.set_SongDetailes(song_Title_string, songArrayList.get(position).getAlbumID());
ArrayAdapter<String> adp = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, items1);
HearAlone.listViewHA.setAdapter(adp);
hearAlone.Set_nowPlaying(items1);
trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
songArrayList.get(position).getID());
Player player = new Player(trackUri, getContext());
player.play(items1,position);
hearAlone.Set_playing(true);
mainActivity.Set_Playing(true);
albumSongs.Set_Playing(true);
artistSongs.Set_Playing(true);
((HearAlone)getActivity()).onStart();
}
});
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| 41.497006
| 161
| 0.642713
|
7fe3b4c50f64e850e47acd5951efa91d968db2d6
| 1,382
|
package fr.polytech.myrpg.game.players;
import fr.polytech.myrpg.characters.Character;
/**
* This class represents a player.
*
* @author DELORME Loïc
* @since 1.0.0
*/
public class Player
{
/**
* The name of the player.
*/
private final String name;
/**
* The character which is controlled by the character.
*/
private final Character character;
/**
* Create a player.
*
* @param name
* The name of the player.
* @param character
* The character which is controlled by the character.
*/
public Player(String name, Character character)
{
this.name = name;
this.character = character;
}
/**
* Get the name.
*
* @return The name.
*/
public String getName()
{
return this.name;
}
/**
* Get the character.
*
* @return The character.
*/
public Character getCharacter()
{
return this.character;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
final StringBuilder stringRepresentation = new StringBuilder();
stringRepresentation.append("Player [name=");
stringRepresentation.append(this.name);
stringRepresentation.append(", character=");
stringRepresentation.append(this.character);
stringRepresentation.append("]");
return stringRepresentation.toString();
}
}
| 18.931507
| 67
| 0.630246
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.