text
stringlengths 10
2.72M
|
|---|
package com.oheers.fish;
import com.oheers.fish.competition.AutoRunner;
import com.oheers.fish.competition.Competition;
import com.oheers.fish.competition.JoinChecker;
import com.oheers.fish.competition.reward.LoadRewards;
import com.oheers.fish.competition.reward.Reward;
import com.oheers.fish.competition.reward.gui.GUIClick;
import com.oheers.fish.competition.reward.gui.GUIClose;
import com.oheers.fish.competition.reward.gui.RewardGUI;
import com.oheers.fish.config.FishFile;
import com.oheers.fish.config.MainConfig;
import com.oheers.fish.config.RaritiesFile;
import com.oheers.fish.config.messages.LocaleGen;
import com.oheers.fish.config.messages.MessageFile;
import com.oheers.fish.config.messages.Messages;
import com.oheers.fish.database.Database;
import com.oheers.fish.events.FishEatEvent;
import com.oheers.fish.events.FishInteractEvent;
import com.oheers.fish.events.McMMOTreasureEvent;
import com.oheers.fish.fishing.FishingProcessor;
import com.oheers.fish.fishing.items.Fish;
import com.oheers.fish.fishing.items.Names;
import com.oheers.fish.fishing.items.Rarity;
import com.oheers.fish.selling.GUICache;
import com.oheers.fish.selling.InteractHandler;
import com.oheers.fish.selling.SellGUI;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Level;
public class EvenMoreFish extends JavaPlugin {
public static FishFile fishFile;
public static RaritiesFile raritiesFile;
public static MessageFile messageFile;
public static Messages msgs;
public static MainConfig mainConfig;
public static Permission permission = null;
public static Economy econ = null;
public static Map<Integer, Set<String>> fish = new HashMap<>();
public static Map<Rarity, List<Fish>> fishCollection = new HashMap<>();
public static Map<Integer, List<Reward>> rewards = new HashMap<>();
// ^ <Position in competition, list of rewards to be given>
public static boolean checkingEatEvent;
public static boolean checkingIntEvent;
public static Competition active;
public static ArrayList<SellGUI> guis;
public static ArrayList<RewardGUI> rGuis;
public static boolean isUpdateAvailable;
public static WorldGuardPlugin wgPlugin;
public static String guardPL;
public static boolean papi;
public static final int METRIC_ID = 11054;
public void onEnable() {
snapshotBreaker();
fishFile = new FishFile(this);
raritiesFile = new RaritiesFile(this);
messageFile = new MessageFile(this);
msgs = new Messages();
mainConfig = new MainConfig();
LocaleGen lG = new LocaleGen();
lG.createLocaleFiles(this);
guis = new ArrayList<>();
rGuis = new ArrayList<>();
if (mainConfig.isEconomyEnabled()) {
// could not setup economy.
if (!setupEconomy()) {
Bukkit.getLogger().log(Level.WARNING, "EvenMoreFish won't be hooking into economy. If this wasn't by choice in config.yml, please install Economy handling plugins.");
}
}
if (!setupPermissions()) {
Bukkit.getServer().getLogger().log(Level.SEVERE, "EvenMoreFish couldn't hook into Vault permissions. Disabling to prevent serious problems.");
getServer().getPluginManager().disablePlugin(this);
}
// async check for updates on the spigot page
Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
checkUpdate();
checkConfigVers();
});
// checks against both support region plugins and sets an active plugin (worldguard is priority)
if (checkWG()) {
guardPL = "worldguard";
} else if (checkRP()) {
guardPL = "redprotect";
}
Names names = new Names();
names.loadRarities();
rewards = LoadRewards.load();
listeners();
commands();
getConfig().options().copyDefaults();
saveDefaultConfig();
Help.loadValues();
AutoRunner.init();
wgPlugin = getWorldGuard();
checkPapi();
Metrics metrics = new Metrics(this, METRIC_ID);
if (EvenMoreFish.mainConfig.isDatabaseOnline()) {
// Attempts to connect to the database if enabled
try {
if (!Database.dbExists()) {
Database.createDatabase();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
getServer().getLogger().log(Level.INFO, "EvenMoreFish by Oheers : Enabled");
}
public void onDisable() {
terminateSellGUIS();
if (EvenMoreFish.mainConfig.isDatabaseOnline()) {
try {
Database.closeConnections();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
getServer().getLogger().log(Level.INFO, "EvenMoreFish by Oheers : Disabled");
}
private void listeners() {
getServer().getPluginManager().registerEvents(new JoinChecker(), this);
getServer().getPluginManager().registerEvents(new FishingProcessor(), this);
getServer().getPluginManager().registerEvents(new InteractHandler(this), this);
getServer().getPluginManager().registerEvents(new UpdateNotify(), this);
getServer().getPluginManager().registerEvents(new GUIClick(), this);
getServer().getPluginManager().registerEvents(new GUIClose(), this);
optionalListeners();
}
private void optionalListeners() {
if (checkingEatEvent) {
getServer().getPluginManager().registerEvents(new FishEatEvent(this), this);
}
if (checkingIntEvent) {
getServer().getPluginManager().registerEvents(new FishInteractEvent(this), this);
}
if (Bukkit.getPluginManager().getPlugin("mcMMO") != null) {
if (mainConfig.disableMcMMOTreasure()) {
getServer().getPluginManager().registerEvents(new McMMOTreasureEvent(), this);
}
}
}
private void commands() {
getCommand("evenmorefish").setExecutor(new CommandCentre(this));
CommandCentre.loadTabCompletes();
}
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class);
permission = rsp.getProvider();
return permission != null;
}
private boolean setupEconomy() {
if (mainConfig.isEconomyEnabled()) {
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false;
}
econ = rsp.getProvider();
return econ != null;
} else return false;
}
// gets called on server shutdown to simulate all player's closing their /emf shop GUIs
private void terminateSellGUIS() {
for (SellGUI gui : guis) {
GUICache.attemptPop(gui.getPlayer(), true);
}
guis.clear();
}
public void reload() {
terminateSellGUIS();
setupEconomy();
fish = new HashMap<>();
fishCollection = new HashMap<>();
rewards = new HashMap<>();
reloadConfig();
saveDefaultConfig();
Names names = new Names();
names.loadRarities();
HandlerList.unregisterAll(new FishEatEvent(this));
HandlerList.unregisterAll(new FishInteractEvent(this));
HandlerList.unregisterAll(new McMMOTreasureEvent());
optionalListeners();
msgs = new Messages();
mainConfig = new MainConfig();
rewards = LoadRewards.load();
guis = new ArrayList<>();
}
// Checks for updates, surprisingly
private void checkUpdate() {
if (!getDescription().getVersion().equals(new UpdateChecker(this, 91310).getVersion())) {
isUpdateAvailable = true;
}
}
private void checkConfigVers() {
int MSG_CONFIG_VERSION = 6;
if (msgs.configVersion() > MSG_CONFIG_VERSION) {
getLogger().log(Level.WARNING, "Your messages.yml config is not up to date. Certain new configurable features may have been added, and without" +
" an updated config, you won't be able to modify them. To update, either delete your messages.yml file and restart the server to create a new" +
" fresh one, or go through the recent updates, adding in missing values. https://www.spigotmc.org/resources/evenmorefish.91310/updates/");
}
int MAIN_CONFIG_VERSION = 6;
if (mainConfig.configVersion() > MAIN_CONFIG_VERSION) {
getLogger().log(Level.WARNING, "Your config.yml config is not up to date. Certain new configurable features may have been added, and without" +
" an updated config, you won't be able to modify them. To update, either delete your config.yml file and restart the server to create a new" +
" fresh one, or go through the recent updates, adding in missing values. https://www.spigotmc.org/resources/evenmorefish.91310/updates/");
}
}
/* Gets the worldguard plugin, returns null and assumes the player has this functionality disabled if it
can't find the plugin. */
private WorldGuardPlugin getWorldGuard() {
return (WorldGuardPlugin) this.getServer().getPluginManager().getPlugin("WorldGuard");
}
private void checkPapi() {
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
papi = true;
new PlaceholderReceiver(this).register();
}
}
private boolean checkRP(){
Plugin pRP = Bukkit.getPluginManager().getPlugin("RedProtect");
return (pRP != null && mainConfig.regionWhitelist());
}
private boolean checkWG(){
Plugin pWG = Bukkit.getPluginManager().getPlugin("WorldGuard");
return (pWG != null && mainConfig.regionWhitelist());
}
// This causes the plugin to become unloadable when a new update is released, this is only ever included in snapshot versions
// and official won't use this security measure.
private void snapshotBreaker() {
if (!new UpdateChecker(this, 91310).getVersion().equals("1.3.2")) {
Bukkit.getLogger().log(Level.SEVERE, "This snapshot version has been superseded by a newer version and will no longer function. Please update to the latest version available on the Spigot page.");
getServer().getPluginManager().disablePlugin(this);
}
}
}
|
import java.util.Arrays;
/**
* 最长公共子序列 https://leetcode-cn.com/problems/longest-common-subsequence/
*/
public class 最长公共子序列 {
public static void main(String[] args) {
最长公共子序列 t=new 最长公共子序列();
System.out.println(t.longestCommonSubsequence("aae","abcde"));
}
public int longestCommonSubsequence2(String text1, String text2) {//优化
int m=text1.length()+1;
int n=text2.length()+1;
int[] cur=new int[n];
int temp=0;
for(int i=1;i<m;i++){
int last=cur[0];//每一行开头上一个都是空字符串位置的0
for(int j=1;j<n;j++){
temp=cur[j];//保存前一行当前列的值,后面j+1的时候,这个值就变成列左上角的last
if(text1.charAt(i-1)==text2.charAt(j-1)){
cur[j]=last+1;
}else {
cur[j]=Math.max(cur[j-1],cur[j]);
}
last=temp;
}
}
return cur[n-1];
}
public int longestCommonSubsequence(String text1, String text2) {
int m=text1.length()+1;//+1是因为如果某个字符串为空,则公共子序列肯定为0
int n=text2.length()+1;
int[][] dp=new int[m][n];
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
if(text1.charAt(i-1)==text2.charAt(j-1)){
dp[i][j]=dp[i-1][j-1]+1;
}else {
dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[m-1][n-1];
}
}
|
package net.lantrack.framework.springplugin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurablePropertyResolver;
import java.util.Properties;
/**
* 在spring配置文件中直接读取对应的属性信息的工具类,参考bean id =propertyConfigurer
* @author : lihuadong@lantrack.net
* @description :
* @date : 2017/12/29 16:03
*/
public class PropertyPlaceholder extends PropertySourcesPlaceholderConfigurer {
private static ConfigurablePropertyResolver property;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, ConfigurablePropertyResolver propertyResolver) throws BeansException {
super.processProperties(beanFactoryToProcess, propertyResolver);
PropertyPlaceholder.property = propertyResolver;
}
public static String getProperty(String name) {
return property.getProperty(name)==null?null:property.getProperty(name).toString();
}
}
|
package com.gxtc.huchuan.ui.special;
import android.Manifest;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gxtc.commlibrary.base.BaseActivity;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.RomUtils;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.commlibrary.utils.WindowUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.ChannelPagerAdapter;
import com.gxtc.huchuan.bean.event.EventSelectFriendBean;
import com.gxtc.huchuan.bean.pay.OrdersRequestBean;
import com.gxtc.huchuan.bean.pay.PayBean;
import com.gxtc.huchuan.customemoji.utils.ScreenUtils;
import com.gxtc.huchuan.data.SpecialBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.dialog.ShareDialog;
import com.gxtc.huchuan.dialog.UpdataDialog;
import com.gxtc.huchuan.handler.CircleShareHandler;
import com.gxtc.huchuan.im.ui.ConversationActivity;
import com.gxtc.huchuan.im.ui.ConversationListActivity;
import com.gxtc.huchuan.ui.MainActivity;
import com.gxtc.huchuan.ui.circle.dynamic.IssueDynamicActivity;
import com.gxtc.huchuan.ui.circle.erweicode.ErWeiCodeActivity;
import com.gxtc.huchuan.ui.mine.circle.ReportActivity;
import com.gxtc.huchuan.ui.mine.deal.MyIssueDetailedActivity;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.ui.news.NewsCollectActivity;
import com.gxtc.huchuan.ui.news.NewsCollectPresenter;
import com.gxtc.huchuan.ui.news.NewsWebActivity;
import com.gxtc.huchuan.utils.DialogUtil;
import com.gxtc.huchuan.utils.ImMessageUtils;
import com.gxtc.huchuan.utils.JumpPermissionManagement;
import com.gxtc.huchuan.utils.RIMErrorCodeUtil;
import com.gxtc.huchuan.utils.ReLoginUtil;
import com.gxtc.huchuan.ui.pay.PayActivity;
import com.gxtc.huchuan.utils.RongIMTextUtil;
import com.gxtc.huchuan.utils.StringUtil;
import com.gxtc.huchuan.utils.UMShareUtils;
import com.gxtc.huchuan.widget.ExpandableTextView;
import com.gxtc.huchuan.widget.MPagerSlidingTabStrip;
import com.umeng.socialize.bean.SHARE_MEDIA;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
/**
* Created by laoshiren on 2018/5/12.
* 专题详情
* 上个列表页面已经获取到详情数据了,但是为了以后可能的拓展,在这个页面请求
*/
public class SpecialDetailActivity extends BaseTitleActivity implements SpecialDetailContract.View {
@BindView(R.id.special_detail_tab)
MPagerSlidingTabStrip tab;
@BindView(R.id.vp_specail_detail)
ViewPager viewPager;
@BindView(R.id.expandable_text)
ExpandableTextView expandableText;
@BindView(R.id.rl_special_detail_root)
RelativeLayout relativeLayout;
// @BindView(R.id.iv_back)
// ImageView ivBack;
// @BindView(R.id.toolbar)
// Toolbar toolbar;
@BindView(R.id.tv_special_detail_title)
TextView tvTitle;
@BindView(R.id.tv_special_detail_label)
TextView tvLabel;
@BindView(R.id.btn_read)
Button button;
@BindView(R.id.ll_special_detail_bottom)
LinearLayout llBottom;
private ChannelPagerAdapter mAdapter;
SpecialBean mBean;
int toolBarPositionY = 0;
private String id;//专题id
private int isFee;//是否收费0=免费,1=收费
private String isSubscribe;//是否订阅 0=未订阅,1=已订阅
private boolean playing = false;//是否正在支付
private SpecialDetailContract.Presenter mPresenter;
private AlertDialog mAlertDialog;
private UMShareUtils shareUtils;
private String isCollect;//是否收藏 0没有 1收藏
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_special_detail);
EventBusUtil.register(this);
}
@Override
public void initView() {
}
@Override
public void initData() {
getBaseHeadView().showTitle("专题详情");
getBaseHeadView().showBackButton(new View.OnClickListener() {
@Override
public void onClick(View v) {
SpecialDetailActivity.this.finish();
}
});
id = getIntent().getStringExtra("id");
new SpecialDetailPresenter(this, id);
hideContentView();
mPresenter.getData();
}
private void showShareDialog() {
String[] pers = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
performRequestPermissions(getString(R.string.txt_card_permission), pers, 2200,
new PermissionsResultListener() {
@Override
public void onPermissionGranted() {
shareUtils = new UMShareUtils(SpecialDetailActivity.this);
ShareDialog.Action[] actions = new ShareDialog.Action[0];
if ("0".equals(isCollect)) {//没收藏
actions = new ShareDialog.Action[]{
new ShareDialog.Action(ShareDialog.ACTION_QRCODE, R.drawable.share_icon_erweima, null),
new ShareDialog.Action(ShareDialog.ACTION_COLLECT, R.drawable.share_icon_collect, null),
new ShareDialog.Action(ShareDialog.ACTION_COPY, R.drawable.share_icon_copy, null),
new ShareDialog.Action(ShareDialog.ACTION_CIRCLE, R.drawable.share_icon_my_dynamic, null),
new ShareDialog.Action(ShareDialog.ACTION_FRIENDS, R.drawable.share_icon_friends, null)};
} else if ("1".equals(isCollect)) {//已收藏
actions = new ShareDialog.Action[]{
new ShareDialog.Action(ShareDialog.ACTION_QRCODE, R.drawable.share_icon_erweima, null),
new ShareDialog.Action(ShareDialog.ACTION_CANCLE_COLLECT, R.drawable.share_icon_collect, null),
new ShareDialog.Action(ShareDialog.ACTION_COPY, R.drawable.share_icon_copy, null),
new ShareDialog.Action(ShareDialog.ACTION_CIRCLE, R.drawable.share_icon_my_dynamic, null),
new ShareDialog.Action(ShareDialog.ACTION_FRIENDS, R.drawable.share_icon_friends, null)};
}
//todo 分享地址没有
shareUtils.shareCustom(mBean.getPic(), mBean.getName(), mBean.getAbstracts(), "https://www.hao123.com/", actions, new ShareDialog.OnShareLisntener() {
@Override
public void onShare(@Nullable String key, @Nullable SHARE_MEDIA media) {
switch (key) {
//二维码
case ShareDialog.ACTION_QRCODE:
ToastUtil.showShort(SpecialDetailActivity.this, "跳转二维码页面");
// ErWeiCodeActivity.startActivity(
// SpecialDetailActivity.this,
// ErWeiCodeActivity.TYPE_CLASSROOM,
// Integer.valueOf(mBean.getId()), "");
break;
//收藏
case ShareDialog.ACTION_COLLECT:
case ShareDialog.ACTION_CANCLE_COLLECT:
mPresenter.collectSpecia();
break;
//分享到动态
case ShareDialog.ACTION_CIRCLE:
IssueDynamicActivity.share(
SpecialDetailActivity.this,
String.valueOf(mBean.getId()),
"9",
mBean.getName(),
mBean.getPic());
break;
//分享到好友
case ShareDialog.ACTION_FRIENDS:
ConversationListActivity.startActivity(SpecialDetailActivity.this, ConversationActivity.REQUEST_SHARE_CONTENT, Constant.SELECT_TYPE_SHARE);
break;
}
}
});
}
@Override
public void onPermissionDenied() {
mAlertDialog = DialogUtil.showDeportDialog(SpecialDetailActivity.this,
false, null, getString(R.string.pre_scan_notice_msg),
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.tv_dialog_confirm) {
JumpPermissionManagement.GoToSetting(
SpecialDetailActivity.this);
}
mAlertDialog.dismiss();
}
});
}
});
}
public static void gotoSpecialDetailActivity(Activity activity, String id) {
Intent intent = new Intent(activity, SpecialDetailActivity.class);
intent.putExtra("id", id);
activity.startActivity(intent);
}
@Override
public void showData(SpecialBean bean) {
showContentView();
mBean = bean;
initFragment();
expandableText.setText(mBean.getIntroduce());
tvTitle.setText(mBean.getName());
StringBuffer stringBuffer = new StringBuffer("");
List<SpecialBean.Label> list = mBean.getLabel();
if (list != null & list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
SpecialBean.Label label = list.get(i);
label.setName("#" + list.get(i).getName());
stringBuffer.append(label.getName() + " ");
}
}
tvLabel.setText(stringBuffer.toString());
isSubscribe = mBean.isSubscribe();
isFee = mBean.isFee();
isCollect = mBean.isCollect();
if ("0".equals(isSubscribe)) {//未订阅
llBottom.setVisibility(View.VISIBLE);
if (0 == isFee) {//免费
button.setText("免费订阅专题");
} else if (1 == isFee) {
button.setText("¥" + mBean.getPrice() + "订阅专题");
}
} else if ("1".equals(isSubscribe)) {//已订阅
llBottom.setVisibility(View.GONE);
}
getBaseHeadView().showHeadRightImageButton(R.drawable.navigation_icon_share, new View.OnClickListener() {
@Override
public void onClick(View v) {
if (UserManager.getInstance().isLogin()) {
showShareDialog();
} else {
GotoUtil.goToActivity(SpecialDetailActivity.this, LoginAndRegisteActivity.class);
}
}
});
tab.invalidate();
}
private void initFragment() {
Bundle bundle = new Bundle();
bundle.putString("specialId", String.valueOf(mBean.getId()));
bundle.putString("isPay", mBean.isPay());
Fragment articleFragment = new ArticleSpecialListFragment();
Fragment videoFragment2 = new SpecialVideoFragment();
articleFragment.setArguments(bundle);
videoFragment2.setArguments(bundle);
List<String> datas = new ArrayList<>();
datas.add("专题文章");
datas.add("专题视频");
ArrayList<Fragment> container = new ArrayList<>();
container.add(articleFragment);
container.add(videoFragment2);
mAdapter = new ChannelPagerAdapter(getSupportFragmentManager(), container, datas);
viewPager.setAdapter(mAdapter);
tab.setViewPager(viewPager);
}
/**
* 订阅成功
*/
@Override
public void showSubscription() {
mPresenter.getData();
}
/**
* 收藏成功
*/
@Override
public void collectSpeciaSucc() {
if ("0".equals(isCollect)) {
isCollect = "1";
ToastUtil.showShort(this, "收藏成功");
} else if ("1".equals(isCollect)) {
isCollect = "0";
ToastUtil.showShort(this, "取消收藏成功");
}
}
@OnClick({R.id.btn_read})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_read:
if (UserManager.getInstance().isLogin()) {
if (0 == isFee) {//免费订阅
mPresenter.getSubscription();
} else if (1 == isFee) {//付费订阅
goPay();
}
} else {
Intent intent = new Intent(SpecialDetailActivity.this, LoginAndRegisteActivity.class);
startActivityForResult(intent, Constant.requestCode.SPECIAL_DETAIL_LOGIN);
}
break;
}
}
@Override
public void tokenOverdue() {
mAlertDialog = DialogUtil.showDeportDialog(this, false, null, getResources().getString(R.string.token_overdue), new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.tv_dialog_confirm) {
ReLoginUtil.ReloginTodo(SpecialDetailActivity.this);
}
mAlertDialog.dismiss();
}
});
}
@Override
public void showLoad() {
getBaseLoadingView().showLoading();
}
//跳转支付
private void goPay() {
OrdersRequestBean requestBean = new OrdersRequestBean();
String money = mBean.getPrice().toString();
BigDecimal moneyB = new BigDecimal(money);
double total = moneyB.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
String token = UserManager.getInstance().getToken();
String transType = "ZS";
String extra = "{\"specialId\":\"" + id + "\"}";
requestBean.setTotalPrice(total + "");
requestBean.setToken(token);
requestBean.setTransType(transType);
requestBean.setExtra(extra);
requestBean.setGoodsName("专题收费-" + mBean.getName());
playing = true;
GotoUtil.goToActivity(this, PayActivity.class, 0, requestBean);
}
@Override
public void showLoadFinish() {
getBaseLoadingView().hideLoading();
}
@Override
public void showEmpty() {
getBaseEmptyView().showEmptyContent();
}
@Override
public void showReLoad() {
}
/**
* 支付回调
*
* @param bean
*/
@Subscribe
public void onEvent(PayBean bean) {
if (!playing) return;
if (!bean.isPaySucc) {//支付失败
ToastUtil.showShort(this, "支付失败");
} else {
mPresenter.getSubscription();
}
playing = false;
}
@Override
public void showError(String info) {
ToastUtil.showShort(this, info);
}
@Override
public void showNetError() {
getBaseEmptyView().showNetWorkViewReload(new View.OnClickListener() {
@Override
public void onClick(View v) {
initData();
//记得隐藏
getBaseEmptyView().hideEmptyView();
}
});
}
@Override
public void setPresenter(SpecialDetailContract.Presenter presenter) {
mPresenter = presenter;
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBusUtil.unregister(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Constant.requestCode.SPECIAL_DETAIL_LOGIN == requestCode && resultCode == Constant.ResponseCode.LOGINRESPONSE_CODE) {
initData();
}
if(ConversationActivity.REQUEST_SHARE_CONTENT == requestCode && resultCode == RESULT_OK){
EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA);
shareMessage(bean);
}
if (requestCode == 0 && resultCode == Constant.ResponseCode.CIRCLE_ISSUE) {
ToastUtil.showShort(this, "分享成功");
}
}
private void shareMessage(final EventSelectFriendBean bean){
ImMessageUtils.shareMessage(bean.targetId, bean.mType, id, mBean.getName(), mBean.getPic(), CircleShareHandler.SHARE_SPECIAL,
new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) { }
@Override
public void onSuccess(Message message) {
ToastUtil.showShort(SpecialDetailActivity.this, "分享成功");
if (!TextUtils.isEmpty(bean.liuyan)) {
RongIMTextUtil.INSTANCE.relayMessage(bean.liuyan, bean.targetId, bean.mType);
}
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
ToastUtil.showShort(SpecialDetailActivity.this, "分享失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode));
}
});
}
}
|
package com.bvaleo.testappshop.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Valery on 10.02.2018.
*/
public class User implements Parcelable {
private String login;
private String password;
private String role;
public User(String login, String password, String role) {
this.login = login;
this.password = password;
this.role = role;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", password='" + password + '\'' +
", role='" + role + '\'' +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.login);
dest.writeString(this.password);
dest.writeString(this.role);
}
protected User(Parcel in) {
this.login = in.readString();
this.password = in.readString();
this.role = in.readString();
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
@Override
public User createFromParcel(Parcel source) {
return new User(source);
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
}
|
package com.example.p0611alertdialogprepare;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
final static String LOG_TAG = "myLogs";
final static int DIALOG = 1;
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
showDialog(DIALOG);
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG) {
AlertDialog.Builder abd = new AlertDialog.Builder(this);
abd.setTitle("Current time");
abd.setMessage(getTime());
return abd.create();
} else
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
Log.d(LOG_TAG, "onPrepareDialog");
if (id == DIALOG) {
((AlertDialog) dialog).setMessage(getTime());
}
}
private CharSequence getTime() {
return sdf.format(new Date());
}
}
|
package number;
/**
* Interface <code>GenomicsNumberHolder</code> should be an object that contains a genomics number
* and has changing bp/cb and/or bp/pixel.
*
* A GenomicsNumberHolder is used by a GenomicsNumber to return the proper values from it's methods
* based of the return values of these methods.
*
* @see GenomicsNumber
* @author "Austin Shoemaker" <austin@genome.arizona.edu>
*/
public interface GenomicsNumberHolder {
/**
* Method <code>getBpPerCb</code> should return the current value of the bp/cb of this
* holder.
*
* @return an <code>int</code> value
*/
public int getBpPerCb();
/**
* Method <code>getBpPerPixel</code> should return the current value of the bp/pixel of this holder.
*
* @return a <code>double</code> value
*/
public double getBpPerPixel();
}
|
package org.reactome.web.nursa.client.manager.state;
import org.reactome.web.analysis.client.model.SpeciesFilteredResult;
import org.reactome.web.nursa.analysis.client.model.PseudoAnalysisResult;
import org.reactome.web.pwp.client.manager.state.State;
public class PseudoState extends State {
private SpeciesFilteredResult result;
public PseudoState(State currentState, PseudoAnalysisResult analysisResult) {
super(currentState);
result = analysisResult.asSpeciesFilteredResult();
}
public SpeciesFilteredResult getResult() {
return result;
}
}
|
package refinitiv.TaskA3;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TaskA3 {
private static List<EnergyStatistics> today = new ArrayList<>(24);
private static List<EnergyStatistics> tomorrow = new ArrayList<>(24);
public static void main(String[] args) {
try {
Document doc = Jsoup.connect("http://www.mercado.ren.pt/EN/Electr/MarketInfo/Gen/Pages/Forecast.aspx").timeout(30000).get();
for (Element table : doc.select("tr.trIMPAR, .trPAR")) {
Elements tds = table.select("td");
boolean isToday = tds.size() == 5;
if(tds.size() == 5){
tds.remove(0);
}
EnergyStatistics statistics = new EnergyStatistics(
Integer.parseInt(tds.get(0).text()),
Integer.parseInt(tds.get(1).text()),
Integer.parseInt(tds.get(2).text()),
tds.hasClass("txtPREV"));
if(isToday){
today.add(statistics);
} else {
tomorrow.add(statistics);
}
}
System.out.println("\n\nTODAY STATISTICS:\n");
for(int hr = 0; hr < today.size(); hr++){
EnergyStatistics statistics = today.get(hr);
System.out.println( (statistics.isForecast()? "Forecast:" : "Actual:") + "\t" + printHour(hr+1) + "\t" + statistics);
}
System.out.println("\n\nTOMORROW STATISTICS:\n");
for(int hr = 0; hr < tomorrow.size(); hr++){
EnergyStatistics statistics = tomorrow.get(hr);
System.out.println( (statistics.isForecast()? "Forecast:" : "Actual:") + "\t" + printHour(hr+1) + "\t" + statistics);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String printHour(int hour){
return hour >= 10? "" + hour : "0" + hour;
}
private static class EnergyStatistics{
private int wind;
private int solar;
private int others;
private boolean isForecast;
public EnergyStatistics(int wind, int solar, int others, boolean isForecast) {
this.wind = wind;
this.solar = solar;
this.others = others;
this.isForecast = isForecast;
}
@Override
public String toString() {
return "Wind:" + wind + "\tSolar:" + solar + "\tOthers:" + others;
}
public boolean isForecast() {
return isForecast;
}
}
}
|
package com.ronoco.yodlee.web.controller;
import com.ronoco.yodlee.service.YodleeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.security.Principal;
@RequestMapping("/yodlee/fastlink")
@Controller
public class FastLinkController {
private static final Logger LOGGER = LoggerFactory.getLogger(FastLinkController.class);
private static final String EXTRA_PARAMS = "dataset=%5B%7B%0A%09%22name%22%3A%20%22BASIC_AGG_DATA%22%2C%0A%09%22attribute%22%3A%20%5B%7B%0A%09%09%09%22name%22%3A%20%22ACCOUNT_DETAILS%22%2C%0A%09%09%09%22container%22%3A%20%5B%0A%09%09%09%09%22insurance%22%0A%09%09%09%5D%0A%09%09%7D%2C%0A%09%09%7B%0A%09%09%09%22name%22%3A%20%22HOLDINGS%22%2C%0A%09%09%09%22container%22%3A%20%5B%0A%09%09%09%09%22insurance%22%0A%09%09%09%5D%0A%09%09%7D%2C%0A%09%09%7B%0A%09%09%09%22name%22%3A%20%22STATEMENTS%22%2C%0A%09%09%09%22container%22%3A%20%5B%0A%09%09%09%09%22insurance%22%0A%09%09%09%5D%0A%09%09%7D%2C%0A%09%09%7B%0A%09%09%09%22name%22%3A%20%22TRANSACTIONS%22%2C%0A%09%09%09%22container%22%3A%20%5B%0A%09%09%09%09%22insurance%22%0A%09%09%09%5D%0A%09%09%7D%0A%09%5D%0A%7D%5D";
private static final String APP_ID = "10003600";
private static final String FORM_HTML_CONTENT = "<div style=\"display:none;\">"
+ "<form action='${NODE_URL}' method='post' id='rsessionPost'>"
+ "<input type='text' name='rsession' value='${RSESSION}'/><br/>"
+ "<input type='text' name='app' value='${FINAPP_ID}'/><br/>"
+ "<input type='text' name='redirectReq' value='true'/><br/>"
+ "<input type='text' name='token' value='${TOKEN}'/><br/>"
+ "<input type='text' name='extraParams' value='${EXTRA_PARAMS}'/><br/>"
+ "</form></div><script>document.getElementById('rsessionPost').submit();</script>";
private final String cobrandName;
private final String fastLinkUrl;
private final YodleeService yodleeService;
private final String nodeUrl;
@Autowired
public FastLinkController(@Value("${yodlee.cobrand.name}") String cobrandName,
@Value("${yodlee.fastlink.url}") String fastLinkUrl,
YodleeService yodleeService) {
this.cobrandName = cobrandName;
this.fastLinkUrl = fastLinkUrl;
this.yodleeService = yodleeService;
this.nodeUrl = fastLinkUrl + "/authenticate/" + cobrandName + "/?channelAppName=usyichnnel";
}
@GetMapping("/insurance")
@ResponseBody
public String getInsuranceFastLink(Principal principal) {
String username = principal.getName();
return getFastLinkPage(username, EXTRA_PARAMS);
}
@GetMapping("/finance")
@ResponseBody
public String getFinanceFastLink(Principal principal) {
String username = principal.getName();
return getFastLinkPage(username, "");
}
String getFastLinkPage(String username, String extraParams) {
String cobSession = yodleeService.getCobSession();
String userSession = yodleeService.getUserSession(cobSession, username);
String accessToken = yodleeService.getAccessTokens(cobSession, userSession);
String data = FORM_HTML_CONTENT.replace("${NODE_URL}", nodeUrl)
.replace("${RSESSION}", userSession)
.replace("${TOKEN}", accessToken)
.replace("${EXTRA_PARAMS}", extraParams)
.replace("${FINAPP_ID}", APP_ID);
return data;
}
}
|
/*
* Copyright 2002-2019 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link Param}.
*
* @author Scott Andrews
*/
public class ParamTests {
private final Param param = new Param();
@Test
public void name() {
param.setName("name");
assertThat(param.getName()).isEqualTo("name");
}
@Test
public void value() {
param.setValue("value");
assertThat(param.getValue()).isEqualTo("value");
}
@Test
public void nullDefaults() {
assertThat(param.getName()).isNull();
assertThat(param.getValue()).isNull();
}
}
|
package pl.herbata.project;
import java.awt.Font;
import javax.swing.UIManager;
import pl.herbata.project.database.MainDatabase;
import pl.herbata.project.mvc.mainframe.MainFrameController;
import pl.herbata.project.mvc.mainframe.MainFrameModel;
import pl.herbata.project.mvc.mainframe.MainFrameView;
public class TournamentManager {
public static void main(String[] args) {
UIManager.put("Button.font", new Font("Sans", Font.BOLD, 12));
MainFrameView view = new MainFrameView();
MainFrameModel model = new MainFrameModel();
MainFrameController controller = new MainFrameController(model, view);
controller.initialize();
MainDatabase.getInstance().attachObserver(controller);
}
}
|
package com.example.administrator.userclient.login;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.administrator.userclient.ActivityCollector;
import com.example.administrator.userclient.MainActivity;
import com.example.administrator.userclient.R;
import com.example.administrator.userclient.Utils;
import com.example.administrator.userclient.db.UsersInfo;
import org.litepal.crud.DataSupport;
import java.util.List;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginRegisterView {
private EditText et_username;
private EditText et_password;
private Button btn_login;
private Button btn_register;
private CheckBox cb_rempass;
private ProgressDialog dialog;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
ActivityCollector.addActivity(this);
sp = getSharedPreferences(Utils.LOGIN_SP, Context.MODE_PRIVATE);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_register = (Button) findViewById(R.id.btn_login_register);
cb_rempass = (CheckBox) findViewById(R.id.cb_rempass);
dialog = new ProgressDialog(this);
boolean isRemenber = sp.getBoolean(Utils.LOGIN_REMEMBER,false);
//每次登录必显示上一次账号
String account = sp.getString(Utils.LOGIN_USER,"");
et_username.setText(account);
if(isRemenber){
//将账号和密码都设置到文本中
String password = sp.getString(Utils.LOGIN_PASSWORD,"");
et_password.setText(password);
cb_rempass.setChecked(true);
}
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mUserLoginPresenter.login();
}
});
btn_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// mUserLoginPresenter.register();
toRegisterActivity();
}
});
}
@Override
public String getUserName() {
return et_username.getText().toString();
}
@Override
public String getPassword() {
return et_password.getText().toString();
}
@Override
public String getRepeatPassword() {
return null;
}
@Override
public String getEmail() {
return null;
}
@Override
public void showLoading() {
dialog.show();
}
@Override
public void hideLoading() {
dialog.hide();
}
@Override
public void toMainActivity(User user) {
Toast.makeText(this, user.getUsername() +
" 登录成功", Toast.LENGTH_SHORT).show();
//写入数据到SP
SharedPreferences.Editor editor = sp.edit();
editor.putInt(Utils.LOGIN_STATUS, 1);
editor.putString(Utils.LOGIN_USER,getUserName()); //保存账号
//选择是否保存密码----
if (cb_rempass.isChecked()){
editor.putBoolean(Utils.LOGIN_REMEMBER,true);
editor.putString(Utils.LOGIN_PASSWORD,getPassword()); //保存密码
}else {
editor.remove(Utils.LOGIN_PASSWORD); //删掉密码
editor.remove(Utils.LOGIN_REMEMBER);
}
editor.commit();
Intent intent = new Intent(this,MainActivity.class);
//在Intent对象当中添加一个键值对
intent.putExtra(Utils.LOGIN_USER, getUserName());
//读取数据库
List<UsersInfo> usersInfos = DataSupport.where("username = ?",getUserName()).find(UsersInfo.class);
intent.putExtra(Utils.LOGIN_EMAIL, usersInfos.get(0).getEmail()); //在数据库获取 邮箱地址
startActivity(intent);
ActivityCollector.removeActivity(this);
finish();
}
@Override
public void toMainActivity(UserRegisterInfo user) {
}
@Override
public void showFailedError(String errorStr) {
Toast.makeText(this,
errorStr, Toast.LENGTH_LONG).show();
}
@Override
public void toRegisterActivity() {
//跳转到注册界面
Intent intent = new Intent(UserLoginActivity.this,UserRegisterActivity.class);
startActivity(intent);
}
}
|
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Main {
public static void main(String[] args){
System.out.println("--------------------------------------Practica 9-------------------------------------");
Lectura Archivo = new Lectura("C:\\Users\\Daniel\\Documents\\Codigos\\Practica9\\src\\com\\company\\practica9.csv");
Alumno A1 = new Alumno("Urias Vega Juan Daniel", "1267333", 1);
Alumno A2 = new Alumno("Escudero Valdez Michelle Anette", "1267334", 2);
Alumno A3 = new Alumno("Mi perro Nick", "1267335", 3);
Archivo.calificaciones(A1, A2, A3);
A1.calcularPromedio();
A2.calcularPromedio();
A3.calcularPromedio();
A1.mostrarDatos();
A2.mostrarDatos();
A3.mostrarDatos();
try {
File nuevoArchivo = new File("Calificaciones.txt");
FileWriter escribirArchivo = new FileWriter(nuevoArchivo);
PrintWriter imprimirArchivo = new PrintWriter(escribirArchivo);
imprimirArchivo.println(A1.imprimirDatos());
imprimirArchivo.println(A2.imprimirDatos());
imprimirArchivo.println(A3.imprimirDatos());
imprimirArchivo.close();
System.out.println(" Archivo creado exitosamente.");
}
catch (IOException e){
System.out.println(" Error al crear el archivo.");
}
}
}
|
import com.mzq.pojo.Article;
import com.mzq.pojo.UserInfo;
import com.mzq.service.ArticleService;
import com.mzq.service.UserInfoService;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
//注解才有效果
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test {
@Autowired
UserInfoService userInfoService;
@Autowired
ArticleService articleService;
@org.junit.Test
public void getUserInfoAndArticle() {
UserInfo userInfo = userInfoService.getUserInfoAndArticle(32);
System.out.println(userInfo);
//模式view展示数据
System.out.println(userInfo.getUserName());
//显示作者发布的所有文章
for (Article article : userInfo.getArticleList() ){
System.out.println(article.getArticleTitle());
}
}
@org.junit.Test
public void getArticleInfo() {
List<Article> list = articleService.listArticlesInfo();
for (Article article : list){
System.out.println(article);
}
System.out.println("--模拟view展示数据 文章标题 发表文章的作者------");
//模拟view展示数据 文章标题 发表的作者
for (Article article : list){
System.out.println(article.getArticleTitle() + " --- " + article.getArticleAuthor().getUserName());
}
}
}
|
/* ====================================================================
*
* Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved.
*
* ==================================================================== *
*/
package com.aof.webapp.action.party;
import java.sql.SQLException;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Transaction;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import com.aof.component.domain.party.Party;
import com.aof.component.domain.party.UserLogin;
import com.aof.component.domain.party.UserLoginServices;
import com.aof.core.persistence.hibernate.Hibernate2Session;
import com.aof.webapp.action.ActionErrorLog;
import com.aof.webapp.action.BaseAction;
/**
* @author Jeffrey Liang
* @version 2003-7-2
*
*/
public class EditCustUserLoginAction extends BaseAction{
protected ActionErrors errors = new ActionErrors();
protected ActionErrorLog actionDebug = new ActionErrorLog();
public ActionForward perform(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
// Extract attributes we will need
ActionErrors errors = this.getActionErrors(request.getSession());
Logger log = Logger.getLogger(EditCustUserLoginAction.class.getName());
Locale locale = getLocale(request);
MessageResources messages = getResources();
String action = request.getParameter("action");
log.info("action="+action);
try{
String userLoginId = request.getParameter("userLoginId");
String name = request.getParameter("name");
String enable = request.getParameter("enable");
String role = request.getParameter("role");
String partyId = request.getParameter("partyId");
String password = request.getParameter("password");
String tele_code = request.getParameter("tele_code");
String email_addr = request.getParameter("email_addr");
String mobile_code = request.getParameter("mobile_code");
String note = request.getParameter("note");
if (userLoginId == null) userLoginId = "";
if (enable == null) enable = "";
if (role == null) role = "";
if (partyId == null) partyId = "";
if (password == null) password = "";
if (tele_code == null) tele_code = "";
if (email_addr == null) email_addr = "";
if (mobile_code == null) mobile_code = "";
if (note == null) note = "";
log.info("============>"+name);
net.sf.hibernate.Session hs = Hibernate2Session.currentSession();
Transaction tx = null;
if(action == null)
action = "view";
if(action.equals("view")){
log.info(action);
UserLogin ul = null;
if (!userLoginId.trim().equals(""))
ul = (UserLogin)hs.load(UserLogin.class,userLoginId);
request.setAttribute("userLogin",ul);
return (mapping.findForward("view"));
}
if(action.equals("create")){
if (userLoginId.trim().equals("")) {
UserLoginServices us = new UserLoginServices();
userLoginId = us.getCustUserID(hs);
}
if ((name == null) || (name.length() < 1))
actionDebug.addGlobalError(errors,"error.context.required");
if ((role == null) || (name.length() < 1))
actionDebug.addGlobalError(errors,"error.context.required");
if ((enable == null) || (name.length() < 1))
actionDebug.addGlobalError(errors,"error.context.required");
if ((partyId == null) || (partyId.length() < 1))
actionDebug.addGlobalError(errors,"error.context.required");
if (!errors.empty()) {
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
try{
tx = hs.beginTransaction();
Party party = (Party)hs.load(Party.class,partyId);
UserLogin ul = new UserLogin();
ul.setUserLoginId(userLoginId);
ul.setName(name);
ul.setRole(role);
ul.setEnable(enable);
ul.setParty(party);
ul.setCurrent_password(password);
ul.setEmail_addr(email_addr);
ul.setMobile_code(mobile_code);
ul.setTele_code(tele_code);
ul.setNote(note);
hs.save(ul);
tx.commit();
hs.flush();
request.setAttribute("userLogin",ul);
return (mapping.findForward("view"));
}catch(Exception e){
e.printStackTrace();
}
}
if(action.equals("update")){
if (userLoginId.trim().equals(""))
actionDebug.addGlobalError(errors,"error.context.required");
if (!errors.empty()) {
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
tx = hs.beginTransaction();
UserLogin ul = (UserLogin)hs.load(UserLogin.class,userLoginId);
Party party = (Party)hs.load(Party.class,partyId);
ul.setName(name);
ul.setRole(role);
ul.setEnable(enable);
ul.setParty(party);
ul.setCurrent_password(password);
ul.setEmail_addr(email_addr);
ul.setMobile_code(mobile_code);
ul.setTele_code(tele_code);
ul.setNote(note);
hs.update(ul);
tx.commit();
request.setAttribute("userLogin",ul);
return (mapping.findForward("view"));
}
if(action.equals("delete")){
if (userLoginId.trim().equals(""))
actionDebug.addGlobalError(errors,"error.context.required");
if (!errors.empty()) {
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
tx = hs.beginTransaction();
UserLogin ul = (UserLogin)hs.load(UserLogin.class,userLoginId);
log.info("userloginId="+ul.getUserLoginId());
hs.delete(ul);
tx.commit();
return (mapping.findForward("list"));
}
if (!errors.empty()) {
saveErrors(request, errors);
return (new ActionForward(mapping.getInput()));
}
return (mapping.findForward("view"));
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
return (mapping.findForward("view"));
}finally{
try {
Hibernate2Session.closeSession();
} catch (HibernateException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
} catch (SQLException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
}
}
}
}
|
package com.scf.web.exception;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.BindException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.TypeMismatchException;
import org.springframework.core.Ordered;
import org.springframework.dao.DataAccessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import com.scf.core.exception.AppException;
import com.scf.core.exception.ExCode;
import com.scf.core.persistence.db.dao.DaoException;
import com.scf.utils.ExceptionsUtilies;
import com.scf.utils.JacksonObjectMapper;
import com.scf.utils.UserAgentUtils;
import com.scf.utils.WebUtilies;
import com.scf.web.comp.ace.ResponseMessage;
import com.scf.web.i18n.MessageResolver;
/**
*
* 统一异常处理 默认优先级最高
*
* @author wub
* @version [版本号, 2015年6月23日]
*
* @see org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
* @see AppException
* @since [产品/模块版本]
*/
public class CommonHandlerExceptionResolver extends AbstractHandlerExceptionResolver
{
private final static String CONTENTTYPE_JSON = "application/json";
/** 编码 */
private String encoding = "UTF-8";
private int codeExceptionBase = ExCode.PARAM_001; // 111000
private boolean sameCode = true;
private int codeBindException;
private int codeHttpMessageNotReadableException;
private int codeMissingServletRequestPartException;
private int codeMissingServletRequestParameterException;
private int codeTypeMismatchException = codeExceptionBase;
private int codeMethodArgumentNotValidException = codeExceptionBase;
{
// reCountExceptionCode
this.reCountExceptionCode();
}
public CommonHandlerExceptionResolver()
{
setOrder(Ordered.HIGHEST_PRECEDENCE);
}
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex)
{
try
{
if (ex instanceof DataAccessException)
{
// DataAccessException
return handleApp( DaoException.defaultDBException(ex), request, response, handler);
}
else if (ex instanceof AppException)
{
// AppException
return handleApp((AppException)ex, request, response, handler);
}
else if (ex instanceof TypeMismatchException)
{
// 参数类型不匹配
return handleTypeMismatch((TypeMismatchException)ex, request, response, handler);
}
else if (ex instanceof MethodArgumentNotValidException)
{
// 参数校验失败
return handleMethodArgumentNotValidException((MethodArgumentNotValidException)ex,
request,
response,
handler);
}
else if (ex instanceof MissingServletRequestParameterException)
{
// 缺少必须的参数
return handleMissingServletRequestParameter((MissingServletRequestParameterException)ex,
request,
response,
handler);
}
else if (ex instanceof HttpMessageNotReadableException)
{
// 未知的请求体
return handleHttpMessageNotReadable((HttpMessageNotReadableException)ex, request, response, handler);
}
else if (ex instanceof MissingServletRequestPartException)
{
// 缺少部分请求内容
return handleMissingServletRequestPartException((MissingServletRequestPartException)ex,
request,
response,
handler);
}
else if (ex instanceof ServletRequestBindingException || ex instanceof BindException)
{
// 请求不合法
return handleBindException((BindException)ex, request, response, handler);
}else{
//其他异常处理
return handleOther(ex, request, response, handler);
}
}
catch (Exception handlerException)
{
if (logger.isWarnEnabled())
{
logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
}
}
// for default processing
return null;
}
/**
* ajax to json<br/>
* from to ResponseMapping ERROR
*
* @param result
* @param httpStatus
* @param ex
* @param request
* @param response
* @param handler
* @return
* @throws IOException
*/
private ModelAndView handleException(ResponseMessage result, int httpStatus, Exception ex,
HttpServletRequest request, HttpServletResponse response, Object handler)
throws IOException
{
//移动设备或者浏览器的ajax则使用rest返回
if(UserAgentUtils.isMobileOrTablet(request) || WebUtilies.isAjaxRequest(request) || isHandlerMethodRest(handler)){
response.setStatus(httpStatus);
response.setContentType(CONTENTTYPE_JSON);
response.setCharacterEncoding(encoding);
PrintWriter out = response.getWriter();
out.print( JacksonObjectMapper.toJsonString(result)); // output String
// 记录异常日志
if (logger.isErrorEnabled())
{
logger.error(new StringBuffer("通用异常处理器 :Catch a ").append(ex.getClass().getSimpleName())
.append(" and write to response json errors = ")
.append(JacksonObjectMapper.toJsonString(result))
.append("\r\n==异常堆栈信息如下:\r\n========")
.append(ExceptionsUtilies.exceptionToString(ex))
.toString());
}
out.flush();
return new ModelAndView();
}else{//其他非rest请求留给剩下的其他异常处理器处理
return null;
}
}
/**
* 判断是否HandlerMethod方式的rest请求
* @author wubin
* @return
*/
private boolean isHandlerMethodRest(Object handler){
boolean isIt = false;
if(HandlerMethod.class.isAssignableFrom(handler.getClass())){
HandlerMethod hm= HandlerMethod.class.cast(handler );
ResponseBody mResponseBody = hm.getMethod().getAnnotation(ResponseBody.class);
ResponseBody cResponseBody = hm.getBean().getClass().getAnnotation(ResponseBody.class);
RestController restController = hm.getBean().getClass().getAnnotation(RestController.class);
if(mResponseBody != null || cResponseBody != null || restController != null){
isIt = true;
}
}
return isIt;
}
// handle area
/**
* 500 {ex.code, message{ex.code}}
*
* @param ex
* @param request
* @param response
* @param handler
* @return
* @throws IOException
*/
private ModelAndView handleApp(AppException ex, HttpServletRequest request, HttpServletResponse response,
Object handler)
throws IOException
{
// 记录内部调试异常日志
if (logger.isErrorEnabled())
{
logger.error(new StringBuffer("通用异常处理器 :系统日志调试错误信息 AppException->ExDetail->message: ").append(ex.getExMessage()));
}
ResponseMessage result =
ResponseMessage.error(ex.getExCode() + "",
MessageResolver.getMessage(request, "ex." + ex.getExCode(), ex.getDetail().getPlaceholders()));
int httpStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; // 500
return handleException(result, httpStatus, ex, request, response, handler);
}
/**
* 处理其他异常
*
* @author wubin
* @param ex
* @param request
* @param response
* @param handler
* @return
* @throws IOException
*/
private ModelAndView handleOther(Exception ex, HttpServletRequest request, HttpServletResponse response,
Object handler)
throws IOException
{
ResponseMessage result =
ResponseMessage.error();
int httpStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; // 500
return handleException(result, httpStatus, ex, request, response, handler);
}
private ModelAndView handleMissingServletRequestPartException(MissingServletRequestPartException ex,
HttpServletRequest request, HttpServletResponse response, Object handler)
throws IOException
{
int code = sameCode ? codeExceptionBase : codeMissingServletRequestPartException;
ResponseMessage result = ResponseMessage.error(code + "", MessageResolver.getMessage(request, "ex." + code));
int httpStatus = HttpServletResponse.SC_BAD_REQUEST; // 400
return handleException(result, httpStatus, ex, request, response, handler);
}
private ModelAndView handleBindException(BindException ex, HttpServletRequest request,
HttpServletResponse response, Object handler)
throws IOException
{
int code = sameCode ? codeExceptionBase : codeBindException;
ResponseMessage result = ResponseMessage.error(code + "", MessageResolver.getMessage(request, "ex." + code));
int httpStatus = HttpServletResponse.SC_BAD_REQUEST; // 400
return handleException(result, httpStatus, ex, request, response, handler);
}
private ModelAndView handleMethodArgumentNotValidException(MethodArgumentNotValidException ex,
HttpServletRequest request, HttpServletResponse response, Object handler)
throws IOException
{
int code = sameCode ? codeExceptionBase : codeMethodArgumentNotValidException;
ResponseMessage result = ResponseMessage.error(code + "", MessageResolver.getMessage(request, "ex." + code));
int httpStatus = HttpServletResponse.SC_BAD_REQUEST; // 400
return handleException(result, httpStatus, ex, request, response, handler);
}
private ModelAndView handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpServletRequest request,
HttpServletResponse response, Object handler)
throws IOException
{
int code = sameCode ? codeExceptionBase : codeHttpMessageNotReadableException;
ResponseMessage result = ResponseMessage.error(code + "", MessageResolver.getMessage(request, "ex." + code));
int httpStatus = HttpServletResponse.SC_BAD_REQUEST; // 400
return handleException(result, httpStatus, ex, request, response, handler);
}
private ModelAndView handleTypeMismatch(TypeMismatchException ex, HttpServletRequest request,
HttpServletResponse response, Object handler)
throws IOException
{
int code = sameCode ? codeExceptionBase : codeTypeMismatchException;
ResponseMessage result = ResponseMessage.error(code + "", MessageResolver.getMessage(request, "ex." + code));
int httpStatus = HttpServletResponse.SC_BAD_REQUEST; // 400
return handleException(result, httpStatus, ex, request, response, handler);
}
private ModelAndView handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
HttpServletRequest request, HttpServletResponse response, Object handler)
throws IOException
{
int code = sameCode ? codeExceptionBase : codeMissingServletRequestParameterException;
ResponseMessage result = ResponseMessage.error(code + "", MessageResolver.getMessage(request, "ex." + code));
int httpStatus = HttpServletResponse.SC_BAD_REQUEST; // 400
return handleException(result, httpStatus, ex, request, response, handler);
}
// set property
private void reCountExceptionCode()
{
this.codeBindException = codeExceptionBase + 1; // BindException result code
this.codeHttpMessageNotReadableException = codeExceptionBase + 2; // HttpMessageNotReadableException result code
this.codeMissingServletRequestPartException = codeExceptionBase + 3; // MissingServletRequestPartException
// result code
this.codeMissingServletRequestParameterException = codeExceptionBase + 4; // MissingServletRequestParameterException
// result code
this.codeTypeMismatchException = codeExceptionBase + 5; // TypeMismatchException result code
this.codeMethodArgumentNotValidException = codeExceptionBase + 6; // MethodArgumentNotValidException result code
}
public void setEncoding(String encoding)
{
this.encoding = encoding;
}
public void setCodeExceptionBase(int codeExceptionBase)
{
this.codeExceptionBase = codeExceptionBase;
// reCountExceptionCode
this.reCountExceptionCode();
}
public void setSameCode(boolean sameCode)
{
this.sameCode = sameCode;
}
public void setCodeTypeMismatchException(int codeTypeMismatchException)
{
this.codeTypeMismatchException = codeTypeMismatchException;
}
public void setCodeHttpMessageNotReadableException(int codeHttpMessageNotReadableException)
{
this.codeHttpMessageNotReadableException = codeHttpMessageNotReadableException;
}
public void setCodeMissingServletRequestPartException(int codeMissingServletRequestPartException)
{
this.codeMissingServletRequestPartException = codeMissingServletRequestPartException;
}
public void setCodeMethodArgumentNotValidException(int codeMethodArgumentNotValidException)
{
this.codeMethodArgumentNotValidException = codeMethodArgumentNotValidException;
}
public void setCodeMissingServletRequestParameterException(int codeMissingServletRequestParameterException)
{
this.codeMissingServletRequestParameterException = codeMissingServletRequestParameterException;
}
public void setCodeBindException(int codeBindException)
{
this.codeBindException = codeBindException;
}
}
|
package com.example.android.tourguide;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class West extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_list);
ArrayList<LocationInfo> arrayList = new ArrayList<>();
arrayList.add(new LocationInfo("Greco Roman Museum","Masr Mtation",R.drawable.greco_roman));
arrayList.add(new LocationInfo("Pompey Piller","Kom Eldekka",R.drawable.pompey_piller));
arrayList.add(new LocationInfo("Roman Amphitheater","Masr Station",R.drawable.roman_amphitheater));
ListView listView = (ListView)findViewById(R.id.list_layout);
Adapter adapter = new Adapter(getApplicationContext(),arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DescriptionFragment descriptionFragment = new DescriptionFragment();
if (position==0){
descriptionFragment.description.setText(R.string.greco_roman);
}else if (position==1){
descriptionFragment.description.setText(R.string.pompey);
}
else {
descriptionFragment.description.setText(R.string.roman_amphitheatre);
}
}
});
}
}
|
package example.com.db.nimbuzz_banbot_android_by_db;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class HelpFragment extends ListFragment {
String[] helpitems = new String[] {
"All Available Command List:",
"",
"kick user: .k id",
"member user: .m id",
"ban user: .b id",
"ip-ban user: .bip id",
"visitor user: .v id",
"grant moderator: .mod id",
"grant admin: .a id",
"grant owner: .o id",
"add commander: .addc id",
"remove commander: .remc id",
"Coded By DB~@NC"
};
public HelpFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View view = inflater.inflate(R.layout.fragment_help_list, container, false);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, helpitems);
setListAdapter(adapter);
//
return super.onCreateView(inflater, container, savedInstanceState);
}
}
|
public class CalculatorTest {
public static void main(String[] args) {
Calculator calculator1 = new Calculator();
calculator1.a = 25;
Calculator calculator2 = new Calculator();
calculator2.a = 31;
Calculator calculator3 = new Calculator();
calculator3.r = 1.5;
Calculator calculator4 = new Calculator();
calculator4.k = 4;
System.out.println("Czy liczba całkowita jest parzysta: "
+ calculator1.isEven(25));
System.out.println("Czy liczba całkowita jest nieparzysta: "
+ calculator2.isOdd(31));
System.out.println("Pole koła wynosi: "
+ calculator3.circleField(1.5));
System.out.println(" liczba całkowita podniesiona do drugiej potęgi wynosi: "
+ calculator4.power(4));
}
}
|
package com.myvodafone.android.front.topup;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.myvodafone.android.R;
import com.myvodafone.android.business.managers.MemoryCacheManager;
import com.myvodafone.android.business.managers.PrePayServiceManager;
import com.myvodafone.android.front.VFGRFragment;
import com.myvodafone.android.front.helpers.Dialogs;
import com.myvodafone.android.front.helpers.WrapContentListView;
import com.myvodafone.android.front.home.FragmentHome;
import com.myvodafone.android.front.soasta.OmnitureHelper;
import com.myvodafone.android.model.business.VFAccount;
import com.myvodafone.android.model.business.VFMobileAccount;
import com.myvodafone.android.model.business.VFMobileXGAccount;
import com.myvodafone.android.model.service.Bucket_ppbalance;
import com.myvodafone.android.model.service.PPBalance;
import com.myvodafone.android.model.service.PPExtendedBundle;
import com.myvodafone.android.utils.StaticTools;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by kakaso on 4/7/2016.
*/
public class FragmentMyCard extends VFGRFragment implements PrePayServiceManager.PrePayBalanceListener{
TextView txtMsisdn, txtTarif, txtBalance, txtExpire, txtLastRenewal, msgNoBundles;
WrapContentListView listView;
LinearLayout bundleListContainer;
RelativeLayout toggleExpandableList;
ImageView expandArrow, imgAccountIcon;
View separatorLr;
PPBalance ppBalance;
Button btnTopUp;
@Override
public void onSuccessPrepayBalance(PPBalance ppBalance) {
this.ppBalance = ppBalance;
loadData(ppBalance);
Dialogs.closeProgress();
}
@Override
public void onErrorPrepayBalance(String message, String msisdn) {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, message);
}
@Override
public void onGenericErrorPrepayBalance() {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, getStringSafe(R.string.vf_generic_error));
}
class BundleListModel {
private String bundleName;
private String expirationDate;
public String getBundleName() {
return bundleName;
}
public void setBundleName(String bundleName) {
this.bundleName = bundleName;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
}
ArrayList<String> listMoneyBundles;
ArrayList<BundleListModel> listNonMoneyBundles;
@Override
public BackFragment getPreviousFragment() {
return BackFragment.FragmentHome;
}
@Override
public String getFragmentTitle() {
return getStringSafe(R.string.my_card_balance_header);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_prepay_mycard, container, false);
initViews(v);
//Omniture ** My balance **
OmnitureHelper.trackView("My balance");
return v;
}
private void initViews(View v) {
header = (TextView) v.findViewById(R.id.headerTitle);
setFragmentTitle();
txtMsisdn = (TextView)v.findViewById(R.id.txtPrePayMsisdn);
txtTarif = (TextView) v.findViewById(R.id.txtTarif);
txtBalance = (TextView) v.findViewById(R.id.txtPrePayBalance);
listView = (WrapContentListView) v.findViewById(R.id.listPrePayCard);
toggleExpandableList = (RelativeLayout) v.findViewById(R.id.toggleExpandableList);
bundleListContainer = (LinearLayout) v.findViewById(R.id.moneyBundlesContainer);
bundleListContainer.setVisibility(View.GONE);
expandArrow = (ImageView) v.findViewById(R.id.imgArrow);
txtExpire = (TextView) v.findViewById(R.id.txtExpire);
txtLastRenewal = (TextView) v.findViewById(R.id.txtLastRenewal);
btnTopUp = (Button) v.findViewById(R.id.btnTopup);
imgAccountIcon = (ImageView) v.findViewById(R.id.accountIcon);
separatorLr = v.findViewById(R.id.separatorLr);
msgNoBundles = (TextView) v.findViewById(R.id.msgNoBundles);
toggleExpandableList.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(bundleListContainer.getVisibility()==View.VISIBLE){
bundleListContainer.setVisibility(View.GONE);
expandArrow.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.rotate_clockwise));
}
else{
bundleListContainer.setVisibility(View.VISIBLE);
expandArrow.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.rotate_counter_clockwise));
}
}
});
listView.setFocusable(false);
btnTopUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(MemoryCacheManager.getSelectedAccount().isHybrid()){
//Omniture ** My balance top up Hybrid **
OmnitureHelper.trackEvent("My balance top up Hybrid");
} else {
//Omniture ** My balance top up Prepay **
OmnitureHelper.trackEvent("My balance top up Prepay");
}
if (MemoryCacheManager.getSelectedAccount() != null) {
replaceFragment(FragmentTopUp.newInstanceAndReturnToMyBalance());
}
}
});
VFAccount vfAccount = MemoryCacheManager.getSelectedAccount();
if(vfAccount!=null) {
StaticTools.loadProfileImage(imgAccountIcon, R.drawable.profile_icon, vfAccount.getSelectedAccountNumber(), activity);
if (vfAccount.isHybrid()) {
((TextView) v.findViewById(R.id.txtMyBalance)).setText(getStringSafe(R.string.hybrid_balace));
}
}
}
public static VFGRFragment newInstance() {
return new FragmentMyCard();
}
@Override
public void onResume() {
super.onResume();
activity.sideMenuHelper.setToggle(getView().findViewById(R.id.toggleDrawer));
activity.sideMenuHelper.setBackButton(getView().findViewById(R.id.back), activity);
Dialogs.showProgress(activity);
PrePayServiceManager.getPrepayBalance(activity, MemoryCacheManager.getSelectedAccount(), new WeakReference<PrePayServiceManager.PrePayBalanceListener>(this));
//BG
StaticTools.setAppBackground(getContext(),StaticTools.BACKGROUND_TYPE_INSIDE,(ImageView)getView().findViewById(R.id.insideBG),null);
}
private void buildMoneyBundlesLists(PPBalance ppBalance){
listMoneyBundles.add(getFromCardString(StaticTools.tryParseFloat(ppBalance.getBalance(), 0),StaticTools.tryFormatDate(StaticTools.tryParseDate(ppBalance.getCedate(),"yyyyMMdd",0),"dd/MM/yyyy","")));
if(ppBalance.getExtendedBundles()!=null && ppBalance.getExtendedBundles().size()>0) {
for (PPExtendedBundle extendedBundle : ppBalance.getExtendedBundles()) {
float totalCount = 0;
boolean moneyBucketsFound = false;
if (extendedBundle.getBuckets() != null && extendedBundle.getBuckets().size() > 0){
for (Bucket_ppbalance bucket : extendedBundle.getBuckets()) {
if (ppBalance.getDestinationList().containsKey(bucket.getDestination())
&& ppBalance.getDestinationList().get(bucket.getDestination()).getType().equalsIgnoreCase("MONEY")) {
moneyBucketsFound = true;
totalCount += StaticTools.tryParseFloat(bucket.getValue(), 0);
}
}
}
if (moneyBucketsFound) {
listMoneyBundles.add(getMoneyBucketString(totalCount, extendedBundle.getFriendlyDescr(),
StaticTools.tryFormatDate(StaticTools.tryParseDate(extendedBundle.getBndExpire(), "yyyyMMdd", 0), "dd/MM/yyyy", "")));
} else {
if (!StaticTools.isNullOrEmpty(extendedBundle.getFriendlyDescr())){
listNonMoneyBundles.add(setBunldeListModel(extendedBundle));
}
}
}
}
}
private BundleListModel setBunldeListModel(PPExtendedBundle extendedBundle){
long twoYearsMilliseconds = 63072000000L; // If the expiry date of the bundle is from 2 years and up do not show expiry date but a hyphen
Date bundleExpiryDate = StaticTools.tryParseDate(extendedBundle.getBndExpire(),"yyyyMMdd",0);
Date nowDate = new Date();
BundleListModel model = new BundleListModel();
model.setBundleName(extendedBundle.getFriendlyDescr());
//////////////////////////////////////////////////////////////////////////////////
if (bundleExpiryDate.getTime() - nowDate.getTime() >= twoYearsMilliseconds ||
( extendedBundle.getBndStatus().equals("H") && StaticTools.tryParseDate(extendedBundle.getBndExpire(), "yyyyMMdd", 0).getTime() < nowDate.getTime() ) ) {
model.setExpirationDate(getStringSafe(R.string.no_expiration_date));
} else {
model.setExpirationDate(getStringSafe(R.string.expiry_date_bundle) + " " + StaticTools.tryFormatDate(StaticTools.tryParseDate(extendedBundle.getBndExpire(), "yyyyMMdd", 0), "dd/MM/yyyy", ""));
}
return model;
}
private String getMoneyBucketString(float val, String name, String expDate){
return getStringSafe(R.string.prepay_balance_analysis_from).replace("__X",StaticTools.formatNumber(val, 2)).replace("__Y",expDate).replace("__Z",name);
}
private String getFromCardString(float val, String expDate){
return getStringSafe(R.string.prepay_balance_analysis_from_card).replace("__X",StaticTools.formatNumber(val, 2)).replace("__Y",expDate);
}
private void loadData(PPBalance ppBalance){
StaticTools.setTarifMsisdn(txtTarif, txtMsisdn);
txtBalance.setText(StaticTools.formatNumber(FragmentHome.getTotalPrepayBalance(ppBalance),2)+"€");
listMoneyBundles = new ArrayList<>();
listNonMoneyBundles = new ArrayList<>();
buildMoneyBundlesLists(ppBalance);
buildExpandableList();
buildBundleList();
}
private void buildBundleList() {
if(listNonMoneyBundles!=null && listNonMoneyBundles.size()>0) {
NonMoneyBundlesAdapter adapter = new NonMoneyBundlesAdapter();
listView.setAdapter(adapter);
msgNoBundles.setVisibility(View.GONE);
}
else{
listView.setVisibility(View.GONE);
msgNoBundles.setText(getStringSafe(R.string.msg_no_active_bundles));
msgNoBundles.setVisibility(View.VISIBLE);
}
}
private void buildExpandableList(){
if(listMoneyBundles.size()>1) {
bundleListContainer.removeAllViews();
for (String item : listMoneyBundles) {
bundleListContainer.addView(createMoneyBundleItem(item));
}
bundleListContainer.setVisibility(View.VISIBLE);
toggleExpandableList.setVisibility(View.VISIBLE);
}
else {
if(!StaticTools.isNullOrEmpty(ppBalance.getCedate())) {
if (StaticTools.tryFormatDate(StaticTools.tryParseDate(ppBalance.getCedate(), "yyyyMMdd", 0), "dd/MM/yyyy", "").equalsIgnoreCase("01/01/1970")) {
txtExpire.setText(Html.fromHtml(getStringSafe(R.string.my_balance_expire).
replace("__X", "---") ));
} else {
txtExpire.setText(Html.fromHtml(getStringSafe(R.string.my_balance_expire).
replace("__X", StaticTools.tryFormatDate(StaticTools.tryParseDate(ppBalance.getCedate(), "yyyyMMdd", 0), "dd/MM/yyyy", ""))));
}
}
else {
txtExpire.setText(Html.fromHtml(getStringSafe(R.string.my_balance_expire).
replace("__X", "---") ));
}
txtExpire.setVisibility(View.VISIBLE);
if(!StaticTools.isNullOrEmpty(ppBalance.getLrdate())) {
if (StaticTools.tryFormatDate(StaticTools.tryParseDate(ppBalance.getLrdate(), "yyyyMMddHHmmss", 0), "dd/MM/yyyy", "").equalsIgnoreCase("01/01/1970")) {
txtLastRenewal.setText(Html.fromHtml(getStringSafe(R.string.my_balance_renewal).
replace("__X","---") ));
} else {
txtLastRenewal.setText(Html.fromHtml(getStringSafe(R.string.my_balance_renewal).
replace("__X", StaticTools.tryFormatDate(StaticTools.tryParseDate(ppBalance.getLrdate(), "yyyyMMddHHmmss", 0), "dd/MM/yyyy", ""))));
}
}
else {
txtLastRenewal.setText(Html.fromHtml(getStringSafe(R.string.my_balance_renewal).
replace("__X","---") ));
}
txtLastRenewal.setVisibility(View.VISIBLE);
separatorLr.setVisibility(View.VISIBLE);
bundleListContainer.setVisibility(View.GONE);
toggleExpandableList.setVisibility(View.GONE);
}
}
private View createMoneyBundleItem(String text){
TextView textView = new TextView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Resources res = getResourcesSafe();
if (res != null) {
int margin = (int) res.getDimension(R.dimen.space_small);
lp.setMargins(margin, margin, margin, margin);
}
lp.gravity = Gravity.CENTER;
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER);
textView.setTextColor(ContextCompat.getColor(activity,R.color.white));
textView.setText(Html.fromHtml(text));
return textView;
}
class NonMoneyBundlesAdapter extends BaseAdapter{
@Override
public int getCount() {
return listNonMoneyBundles.size();
}
@Override
public Object getItem(int position) {
return listNonMoneyBundles.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
ViewHolder viewHolder = new ViewHolder();
convertView = activity.getLayoutInflater().inflate(R.layout.item_list_bundle,null);
viewHolder.txtname = (TextView) convertView.findViewById(R.id.txtBundleName);
viewHolder.txtExpDate = (TextView) convertView.findViewById(R.id.txtExpDate);
convertView.setTag(viewHolder);
}
ViewHolder vh = (ViewHolder) convertView.getTag();
vh.txtname.setText(listNonMoneyBundles.get(position).getBundleName());
vh.txtExpDate.setText(listNonMoneyBundles.get(position).getExpirationDate());
return convertView;
}
class ViewHolder{
TextView txtname;
TextView txtExpDate;
}
}
}
|
/*
* Created on Jul 27, 2015
*/
package basics;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
/**
* Show how math can be used in a binding.
*
* @author Mark Lewis
*/
public class BindingExample2 extends Application {
@Override
public void start(Stage stage) {
Rectangle rectangle = new Rectangle(200,200);
Group root = new Group(rectangle);
Scene scene = new Scene(root, 800, 500);
rectangle.layoutXProperty().bind(scene.widthProperty().subtract(rectangle.widthProperty()).divide(2));
rectangle.layoutYProperty().bind(scene.heightProperty().subtract(rectangle.heightProperty()).divide(2));
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.bruce.builder.improve;
public class House {
private String name;
}
|
package com.zhaoyan.ladderball.dao.match;
import com.zhaoyan.ladderball.domain.match.db.TmpMatchPart;
import java.util.List;
public interface TmpMatchPartDao {
/**
* 获取比赛小节信息
*/
List<TmpMatchPart> getMatchParts(long matchId);
/**
* 根据比赛和小节号获取小节
*/
TmpMatchPart getMatchPartByMatchIdPartNumber(long matchId, int partNumber);
/**
* 添加一小节
*/
void addMatchPart(TmpMatchPart matchPart);
/**
* 修改小节
*/
void modifyMatchPart(TmpMatchPart matchPart);
/**
* 删除一小节
*/
void deleteMatchPart(TmpMatchPart matchPart);
}
|
package sample;
import java.beans.EventHandler;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class RegistrationController {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private TextField NameField;
@FXML
private PasswordField passwordField;
@FXML
private Button registrationButton;
@FXML
private TextField loginField;
@FXML
private TextField SurnameField;
@FXML
private CheckBox choiceMale;
@FXML
private CheckBox choiceFemale;
@FXML
private Button backB;
@FXML
void back(ActionEvent event) {
backB.getScene().getWindow().hide();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample/Autentification.fxml"));
try {
loader.load();
}catch (IOException e){
e.printStackTrace();
}
Parent root =loader.getRoot();
Stage stage=new Stage();
stage.setScene(new Scene(root) );
stage.show();
}
@FXML
void register(ActionEvent event) {
DatabaseHandler dbHandler = new DatabaseHandler();
String gender= "";
if(choiceFemale.isSelected()) gender="Female";
else if(choiceMale.isSelected()) gender = "Male";
dbHandler.signUpUser(NameField.getText(), SurnameField.getText(),
loginField.getText(), gender, passwordField.getText());
back(null);
}
@FXML
void initialize() {
choiceMale.setSelected(true);
choiceMale.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
choiceFemale.setSelected(!newValue);
}
});
choiceFemale.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
choiceMale.setSelected(!newValue);
}
});
}
}
|
package com.revature.exceptions;
public class BadInputException extends Exception {
}
|
package homework_5;
import java.util.ArrayList;
import java.util.Collections;
public class Student implements Comparable <Student> {
private String surname;
private Integer course;
private Integer studentAge;
public Student(String surname, int course, int studentAge) {
this.surname = surname;
this.course = course;
this.studentAge = studentAge;
}
public int compareTo(Student o) {
int result = this.surname.compareTo(o.surname);
if (result == 0) {
result = this.course.compareTo(o.course);
}
return result;
}
public static void getStudentsSorted(ArrayList<Student> listOfStudents){
System.out.println("-------Before sorting--------");
for (Student s : listOfStudents) {
System.out.println(s);
}
System.out.println("\n -------After sorting-----");
Collections.sort(listOfStudents);
for (Student s : listOfStudents) {
System.out.println(s);
}
}
@Override
public String toString() {
return "{" +
"surname='" + surname + '\'' +
", course=" + course +
", studentAge='" + studentAge + '\'' +
'}';
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Integer getCourse() {
return course;
}
public void setCourse(Integer course) {
this.course = course;
}
public Integer getStudentAge() {
return studentAge;
}
public void setStudentAge(Integer studentAge) {
this.studentAge = studentAge;
}
}
|
package com.demo.flyweight;
/**
* @author: Maniac Wen
* @create: 2020/5/13
* @update: 8:16
* @version: V1.0
* @detail:
**/
public class IntegerTest {
public static void main(String[] args) {
Integer a = Integer.valueOf(100);
Integer b = 100;
Integer c = Integer.valueOf(1000);
Integer d = 1000;
System.out.println("a == b:" + (a == b));
System.out.println("d == d:" + (c == d));
}
}
|
package CollectionProgram;
import java.util.HashSet;
import java.util.LinkedHashSet;
public class Linkedset {
public static void main(String[] args) {
LinkedHashSet l1= new LinkedHashSet<>();
l1.add(10);
l1.add(20.56);
l1.add('a');
l1.add(true);
l1.add(null);
l1.add(10);
System.out.println(l1);
}
}
|
package com.skyhorse.scs.DAO;
import java.util.List;
import com.skyhorse.scs.Bean.AdminBean;
public interface DaoService
{
public List<AdminBean> loginVerify(String uname);
public String insertData(String UserID,String Uname,String password,String UserEmail,String phone,String Address,String SecQue,String SecAns,String UserRole);
public void updatePassword(String UserId,String oldPassword,String newPassword);
}
|
package util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* @author lucher
* 本类为sql工具类,包括sql无参、有参查询,以及sql更新语句方法
* 该类一般配合DBUtil使用,只是列举了常用的方法,具体使用时稍加修改
*/
public class SQLUtil {
// 无参数的查询语句
private static final String sql1 = "select * from company";
// 有参数的查询语句
private static final String sql2 = "select password from company where name=?";
// 更新语句
private static final String sql3 = "update company set password=? where name=?";
// 删除语句,同时执行
private static final String sql4 = "delete from user where id=?";
private static final String sql5 = "delete from userInfo where id=?";
/**
* 无参数查询,返回类型据情况稍加修改,以sqlserver为例,其他类似
*
* @return 所有记录的名字的list
*/
public static List<String> getAll() {
Connection conn = null;
Statement ps = null;
ResultSet rs = null;
List<String> info = new ArrayList<String>();
try {
conn = DBUtil.getSQLSERVERConnection();
ps = conn.createStatement();
rs = ps.executeQuery(sql1);
while (rs.next()) {
info.add(rs.getString("name")); // 根据具体情况定
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.closeConn(rs, ps, conn);
}
return info;
}
/**
* 有参数查询,返回类型据情况稍加修改,以sqlserver为例,其他类似
*
* @param name
* @param password
* @return 返回指定名字和密码的记录list
*/
public static List<String> getAllByNP(String name, String password) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<String> info = new ArrayList<String>();
try {
conn = DBUtil.getSQLSERVERConnection();
pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, name);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
while (rs.next()) {
info.add(rs.getString(1));
info.add(rs.getString(2));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.closeConn(rs, pstmt, conn);
}
return info;
}
/**
* 更新类方法,只执行一条的情况,以sqlserver为例,其他类似
* @param name
* @param password
* @return 执行更新的结果
*/
public static boolean updatePasswordByName(String name, String password) {
int result = 0;
boolean flag = true;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBUtil.getSQLSERVERConnection();
pstmt = conn.prepareStatement(sql3);
pstmt.setString(1, password);
pstmt.setString(2, name);
result = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.closeConn(pstmt, conn);
}
if (result == 0) {
flag = false;
}
return flag;
}
/**
* 更新类方法,同时执行两条的情况,以sqlserver为例,其他类似
* @param id
* @return 执行删除的结果
*/
public static boolean deleteById(int id) {
int result1 = 0;
int result2 = 0;
boolean flag = true;
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
conn = DBUtil.getSQLSERVERConnection();
conn.setAutoCommit(false);
pstmt1 = conn.prepareStatement(sql4);
pstmt1.setInt(1, id);
pstmt2 = conn.prepareStatement(sql5);
pstmt2.setInt(1, id);
result1 = pstmt1.executeUpdate();
result2 = pstmt2.executeUpdate();
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
DBUtil.closeConn(pstmt1, pstmt2, conn);
}
if (result1 == 0 || result2 == 0) {
flag = false;
}
return flag;
}
}
|
package exercises.chapter6.ex7.access;
/**
* @author Volodymyr Portianko
* @date.created 14.03.2016
*/
public class Widget {
public Widget() {
System.out.println("Creating a widget...");
}
}
|
/*
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.gs.tablasco.adapters;
import com.gs.tablasco.TableTestUtils;
import com.gs.tablasco.TableVerifier;
import com.gs.tablasco.VerifiableTable;
import org.junit.Rule;
import org.junit.Test;
public class TableAdaptersTest
{
@Rule
public final TableVerifier verifier = new TableVerifier()
.withExpectedDir(TableTestUtils.getExpectedDirectory())
.withOutputDir(TableTestUtils.getOutputDirectory())
.withFilePerClass()
.withHideMatchedRows(true)
.withHideMatchedTables(true);
@Test
public void testAllRows()
{
this.verify(
TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5),
TableAdapters.withRows(TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5), i -> true));
}
@Test
public void testNoRows()
{
VerifiableTable table = TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5);
this.verify(
TableTestUtils.createTable(1, "C"),
TableAdapters.withRows(table, i -> false));
}
@Test
public void testSomeRows()
{
VerifiableTable table = TableTestUtils.createTable(1, "C", 1, 2, 3, 4, 5);
this.verify(
TableTestUtils.createTable(1, "C", 2, 4),
TableAdapters.withRows(table, i -> (Integer) table.getValueAt(i, 0) % 2 == 0));
}
@Test
public void testAllColumns()
{
this.verify(
TableTestUtils.createTable(5, "C1", "C2", "C3", "C4", "C5"),
TableAdapters.withColumns(TableTestUtils.createTable(5, "C1", "C2", "C3", "C4", "C5"), name -> true));
}
@Test
public void testSomeColumns()
{
this.verify(
TableTestUtils.createTable(3, "C1", "C3", "C5"),
TableAdapters.withColumns(TableTestUtils.createTable(5, "C1", "C2", "C3", "C4", "C5"), name -> name.matches("C[135]")));
}
@Test
public void composition1()
{
VerifiableTable table = TableTestUtils.createTable(2, "C1", "C2", 1, 2, 3, 4);
VerifiableTable rowFilter = TableAdapters.withRows(TableAdapters.withColumns(table, name -> name.equals("C2")), i -> i > 0);
this.verify(TableTestUtils.createTable(1, "C2", 4), rowFilter);
}
@Test
public void composition2()
{
VerifiableTable table = TableTestUtils.createTable(2, "C1", "C2", 1, 2, 3, 4);
VerifiableTable columnFilter = TableAdapters.withColumns(
TableAdapters.withRows(table, i -> i > 0),
name -> name.equals("C2"));
this.verify(TableTestUtils.createTable(1, "C2", 4), columnFilter);
}
private void verify(VerifiableTable expected, VerifiableTable adaptedActual)
{
this.verifier.verify("table", adaptedActual, expected);
}
}
|
package model.player.details;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import model.player.BatsmanType;
import model.player.Country;
import model.player.Handedness;
import model.player.Player;
import model.player.PlayerType;
import model.player.bowling.BowlerType;
@Entity
public class GeneralDetails
{
private final IntegerProperty id;
private final ObjectProperty<Player> player;
private final ObjectProperty<Handedness> battingHandedness;
private final ObjectProperty<Handedness> bowlingHandedness;
private final ObjectProperty<BatsmanType> batsmanType;
private final ObjectProperty<BowlerType> bowlerType;
private final ObjectProperty<PlayerType> playerType;
private final ObjectProperty<Country> country;
private final IntegerProperty age;
private final IntegerProperty battingAbility;
private final IntegerProperty battingForm;
private final IntegerProperty battingNaturalAgression;
private final IntegerProperty battingAgressionLevel;
private final IntegerProperty battingSettlement;
private final IntegerProperty battingFastBowlingPreference;
private final IntegerProperty battingSlowBallingPreference;
private final IntegerProperty bowlingAbility;
private final IntegerProperty bowlingForm;
private final IntegerProperty bowlingAgressionLevel;
private final IntegerProperty coolHead;
@Id
@GeneratedValue
//@GenericGenerator(name="foreignGenerator", strategy = "foreign", parameters={@Parameter(value="player", name="property")})
public int getId() {
return id.get();
}
public void setId(int id) {
this.id.set(id);
}
@OneToOne(cascade=CascadeType.ALL, mappedBy="generalDetails")
public Player getPlayer()
{
return player.get();
}
public void setPlayer(Player player)
{
this.player.set(player);
}
@Enumerated(EnumType.STRING)
public PlayerType getPlayerType()
{
return this.playerType.get();
}
public void setPlayerType(PlayerType type)
{
this.playerType.set(type);
}
@Enumerated(EnumType.STRING)
public Handedness getBattingHandedness() {
return battingHandedness.get();
}
public void setBattingHandedness(Handedness battingHandedness) {
this.battingHandedness.set(battingHandedness);
}
@Enumerated(EnumType.STRING)
public Handedness getBowlingHandedness() {
return bowlingHandedness.get();
}
public void setBowlingHandedness(Handedness bowlingHandedness) {
this.bowlingHandedness.set(bowlingHandedness);
}
@Enumerated(EnumType.STRING)
public BatsmanType getBatsmanType() {
return batsmanType.get();
}
public void setBatsmanType(BatsmanType batsmanType) {
this.batsmanType.set(batsmanType);
}
@Enumerated(EnumType.STRING)
public BowlerType getBowlerType() {
return bowlerType.get();
}
public void setBowlerType(BowlerType bowlerType) {
this.bowlerType .set(bowlerType);
}
@Enumerated(EnumType.STRING)
public Country getCountry() {
return country.get();
}
public void setCountry(Country country) {
this.country.set(country);
}
public int getAge() {
return age.get();
}
public void setAge(int age) {
this.age.set(age);
}
public int getBattingAbility() {
return battingAbility.get();
}
public void setBattingAbility(int battingAbility) {
this.battingAbility.set(battingAbility);
}
public int getBattingForm() {
return battingForm.get();
}
public void setBattingForm(int battingForm) {
this.battingForm.set(battingForm);
}
public int getBattingNaturalAgression() {
return battingNaturalAgression.get();
}
public void setBattingNaturalAgression(int battingNaturalAgression) {
this.battingNaturalAgression.set(battingNaturalAgression);
}
public int getBattingAgressionLevel() {
return battingAgressionLevel.get();
}
public void setBattingAgressionLevel(int battingAgressionLevel) {
this.battingAgressionLevel.set(battingAgressionLevel);
}
public int getBattingSettlement() {
return battingSettlement.get();
}
public void setBattingSettlement(int battingSettlement) {
this.battingSettlement.set(battingSettlement);
}
public int getBattingFastBowlingPreference() {
return battingFastBowlingPreference.get();
}
public void setBattingFastBowlingPreference(int battingFastBowlingPreference) {
this.battingFastBowlingPreference.set(battingFastBowlingPreference);
}
public int getBattingSlowBallingPreference() {
return battingSlowBallingPreference.get();
}
public void setBattingSlowBallingPreference(int battingSlowBallingPreference) {
this.battingSlowBallingPreference.set(battingSlowBallingPreference);
}
public int getBowlingAbility() {
return bowlingAbility.get();
}
public void setBowlingAbility(int bowlingAbility) {
this.bowlingAbility.set(bowlingAbility);
}
public int getBowlingForm() {
return bowlingForm.get();
}
public void setBowlingForm(int bowlingForm) {
this.bowlingForm.set(bowlingForm);
}
public int getBowlingAgressionLevel() {
return bowlingAgressionLevel.get();
}
public void setBowlingAgressionLevel(int bowlingAgressionLevel) {
this.bowlingAgressionLevel.set(bowlingAgressionLevel);
}
public int getCoolHead() {
return coolHead.get();
}
public void setCoolHead(int coolHead) {
this.coolHead.set(coolHead);
}
public GeneralDetails()
{
id=new SimpleIntegerProperty();
battingHandedness = new SimpleObjectProperty<Handedness>();
bowlingHandedness = new SimpleObjectProperty<Handedness>();
batsmanType = new SimpleObjectProperty<BatsmanType>();
bowlerType= new SimpleObjectProperty<BowlerType>();
playerType = new SimpleObjectProperty<PlayerType>();
country = new SimpleObjectProperty<Country>();
age = new SimpleIntegerProperty();
player = new SimpleObjectProperty<Player>();
battingAbility = new SimpleIntegerProperty();
battingForm= new SimpleIntegerProperty();
battingNaturalAgression= new SimpleIntegerProperty();
battingAgressionLevel= new SimpleIntegerProperty();
battingSettlement= new SimpleIntegerProperty();
battingFastBowlingPreference= new SimpleIntegerProperty();
battingSlowBallingPreference= new SimpleIntegerProperty();
bowlingAbility= new SimpleIntegerProperty();
bowlingForm= new SimpleIntegerProperty();
bowlingAgressionLevel= new SimpleIntegerProperty();
coolHead= new SimpleIntegerProperty();
}
public ObjectProperty<Handedness> battingHandednessProperty() {
return battingHandedness;
}
public ObjectProperty<Handedness> bowlingHandednessProperty() {
return bowlingHandedness;
}
public ObjectProperty<BowlerType> bowlerTypeProperty() {
return bowlerType;
}
public ObjectProperty<PlayerType> playerTypeProperty() {
return playerType;
}
public IntegerProperty idProperty() {
return id;
}
public ObjectProperty<Country> countryProperty() {
return country;
}
public IntegerProperty ageProperty() {
return age;
}
public ObjectProperty<Player> playerProperty() {
return player;
}
public IntegerProperty battingAbilityProperty() {
return battingAbility;
}
public IntegerProperty battingFormProperty() {
return battingForm;
}
public IntegerProperty battingNaturalAgressionProperty() {
return battingNaturalAgression;
}
public IntegerProperty battingAgressionLevelProperty() {
return battingAgressionLevel;
}
public IntegerProperty battingSettlementProperty() {
return battingSettlement;
}
public IntegerProperty battingFastBowlingPreferenceProperty() {
return battingFastBowlingPreference;
}
public IntegerProperty battingSlowBallingPreferenceProperty() {
return battingSlowBallingPreference;
}
public IntegerProperty bowlingAbilityProperty() {
return bowlingAbility;
}
public IntegerProperty bowlingFormProperty() {
return bowlingForm;
}
public IntegerProperty bowlingAgressionLevelProperty() {
return bowlingAgressionLevel;
}
public IntegerProperty coolHeadProperty() {
return coolHead;
}
public ObjectProperty<BatsmanType> batsmanTypeProperty() {
return batsmanType;
}
}
|
package example.com.pyy.activityfragment2;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
public Button one,two;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("PYY", "Activity &&&& onCreate...");
one = (Button)findViewById(R.id.btn_one);
two = (Button)findViewById(R.id.btn_two);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment newFragment1 = new ArrayListFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.list1,newFragment1);
transaction.addToBackStack(null);
transaction.commit();
}
});
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment newFragment = new ArrayListTwoFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.list1,newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
@Override
protected void onStart() {
Log.e("PYY", "Activity &&&& onStart...");
super.onStart();
}
@Override
protected void onResume() {
Log.e("PYY", "Activity &&&& onResume...");
super.onResume();
}
@Override
protected void onStop() {
super.onStop();
Log.e("pyy", "Activity &&&& onStop...");
}
@Override
protected void onPause() {
Log.e("pyy", "Activity &&&& onPause...");
super.onPause();
}
@Override
protected void onDestroy() {
Log.e("PYY", "Activity &&&& onDestroy...");
super.onDestroy();
}
}
|
package com.sevael.lgtool.model;
public class ContactModel {
private String firstname;
private String middlename;
private String lastname;
private String emailid;
private String phonenum;
private String alterphonenum;
private String dateofbirth;
private String gender;
private String placeofbirth;
private String userrole;
private String leadtype;
private String orgname;
private String additionalinfo;
private String empemail;
private String doorno;
private String street;
private String city;
private String state;
private String country;
private String pincode;
private String countryphcode;
private String altercountryphcode;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getAlterphonenum() {
return alterphonenum;
}
public void setAlterphonenum(String alterphonenum) {
this.alterphonenum = alterphonenum;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getDateofbirth() {
return dateofbirth;
}
public void setDateofbirth(String dateofbirth) {
this.dateofbirth = dateofbirth;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPlaceofbirth() {
return placeofbirth;
}
public void setPlaceofbirth(String placeofbirth) {
this.placeofbirth = placeofbirth;
}
public String getUserrole() {
return userrole;
}
public void setUserrole(String userrole) {
this.userrole = userrole;
}
public String getLeadtype() {
return leadtype;
}
public void setLeadtype(String leadtype) {
this.leadtype = leadtype;
}
public String getOrgname() {
return orgname;
}
public void setOrgname(String orgname) {
this.orgname = orgname;
}
public String getAdditionalinfo() {
return additionalinfo;
}
public void setAdditionalinfo(String additionalinfo) {
this.additionalinfo = additionalinfo;
}
public String getEmpemail() {
return empemail;
}
public void setEmpemail(String empemail) {
this.empemail = empemail;
}
public String getDoorno() {
return doorno;
}
public void setDoorno(String doorno) {
this.doorno = doorno;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
/**
* @return the countryphcode
*/
public String getCountryphcode() {
return countryphcode;
}
/**
* @param countryphcode the countryphcode to set
*/
public void setCountryphcode(String countryphcode) {
this.countryphcode = countryphcode;
}
/**
* @return the altercountryphcode
*/
public String getAltercountryphcode() {
return altercountryphcode;
}
/**
* @param altercountryphcode the altercountryphcode to set
*/
public void setAltercountryphcode(String altercountryphcode) {
this.altercountryphcode = altercountryphcode;
}
}
|
package propios;
import java.awt.Graphics;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class graficos {
public static void main(String[] args) {
// TODO Auto-generated method stub
Marcobase mimarco=new Marcobase();
mimarco.setVisible(true);
mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Marcobase extends JFrame{
public Marcobase(){
setSize(400, 400);
setTitle("Marco base");
setLocation(150, 150);
Laminabase milamina=new Laminabase();
add(milamina);
}
}
class Laminabase extends JPanel{
Rectangle2D rectangulo=new Rectangle2D.Double();
}
|
package com.egova.eagleyes.adapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.egova.eagleyes.R;
import com.egova.eagleyes.model.respose.DispositionAlarm;
import com.egova.eagleyes.util.GlideUtil;
import com.egova.eagleyes.util.StringUtil;
import com.egova.eagleyes.util.VehicleUtil;
import java.util.List;
import androidx.annotation.Nullable;
public class DispositionAlarmListAdapter extends BaseQuickAdapter<DispositionAlarm, BaseViewHolder> {
public DispositionAlarmListAdapter(int layoutResId, @Nullable List<DispositionAlarm> data) {
super(layoutResId, data);
}
@Override
protected void convert(BaseViewHolder helper, DispositionAlarm item) {
helper.setText(R.id.index, "第" + (helper.getLayoutPosition() + 1) + "条");
GlideUtil.load(mContext, helper.getView(R.id.carImage), item.getPicture());
helper.setText(R.id.plate, VehicleUtil.formatPlateNo(item.getPlate()));
helper.setText(R.id.time, "时间:" + item.getTimestamp());
helper.setText(R.id.position, "卡口:" + StringUtil.formatNull(item.getTollgateName()));
helper.setText(R.id.brandYearName, item.getVehicleBrandName());
helper.addOnClickListener(R.id.carImage);//点击查看大图
if (item.getHandled()) {
helper.setText(R.id.handleBtn, "已处理");
helper.setBackgroundRes(R.id.handleBtn, R.drawable.btn_red_selector);
} else {
helper.setText(R.id.handleBtn, "置为已处理");
helper.setBackgroundRes(R.id.handleBtn, R.drawable.btn_blue_selector);
}
helper.addOnClickListener(R.id.handleBtn);
}
}
|
package edu.asu.commons;
public class AbstractServerTest {
}
|
package Models;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CompraTest {
@Test
void comprar_deveRetornarFalseAoTentarComprarEExcederOMaximoEstoque() {
var produto = new Produto("teste", 10, 2, 0, 10);
var compra = new Compra("", 1, new Fornecedor("", ""), produto, 1);
assertFalse(compra.comprar(produto, 1));
assertEquals(produto.getQtdeEstoque(), 10);
}
@Test
void comprar_deveRetornarTrueAoTentarRealizarUmaComprarQueNaoExcederOMaximoEstoque() {
var produto = new Produto("teste", 9, 2, 0, 10);
var compra = new Compra("", 1, new Fornecedor("", ""), produto, 1);
assertTrue(compra.comprar(produto, 1));
assertEquals(produto.getQtdeEstoque(), 10);
}
}
|
package learning;
public interface Regressor {
}
|
package com.jgw.supercodeplatform.trace.pojo.certificate;
import java.util.Date;
public class CertificateInfo {
private Long id;
private String certificateInfoId;
private String certificateNumber;
private String certificateName;
private String templateId;
private String templateName;
private String createId;
private String createMan;
private Date createTime;
private Date updateTime;
private Integer disableFlag;
private String certificateInfoData;
private String organizationId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCertificateInfoId() {
return certificateInfoId;
}
public void setCertificateInfoId(String certificateInfoId) {
this.certificateInfoId = certificateInfoId == null ? null : certificateInfoId.trim();
}
public String getCertificateNumber() {
return certificateNumber;
}
public void setCertificateNumber(String certificateNumber) {
this.certificateNumber = certificateNumber == null ? null : certificateNumber.trim();
}
public String getCertificateName() {
return certificateName;
}
public void setCertificateName(String certificateName) {
this.certificateName = certificateName == null ? null : certificateName.trim();
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId == null ? null : templateId.trim();
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName == null ? null : templateName.trim();
}
public String getCreateId() {
return createId;
}
public void setCreateId(String createId) {
this.createId = createId == null ? null : createId.trim();
}
public String getCreateMan() {
return createMan;
}
public void setCreateMan(String createMan) {
this.createMan = createMan == null ? null : createMan.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisableFlag() {
return disableFlag;
}
public void setDisableFlag(Integer disableFlag) {
this.disableFlag = disableFlag;
}
public String getCertificateInfoData() {
return certificateInfoData;
}
public void setCertificateInfoData(String certificateInfoData) {
this.certificateInfoData = certificateInfoData == null ? null : certificateInfoData.trim();
}
public String getOrganizationId() {
return organizationId;
}
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId == null ? null : organizationId.trim();
}
}
|
package com.eussi._01_jca_jce.securitypkg;
import org.junit.Test;
import java.security.Provider;
import java.security.Security;
import java.util.Map;
/**
* Created by wangxueming on 2019/2/20.
*/
public class _02_SecurityTest {
@Test
public void test() {
for(int i=1; i<=Security.getProviders().length; i++) {
Provider provider = Security.getProviders()[i-1];
System.out.println("NO." + i);
//当前提供者信息
System.out.println("Provider:" + provider);
//遍历提供者set实体
System.out.println("\tKey:");
for(Map.Entry<Object, Object> entry : provider.entrySet()) {
System.out.println("\t\t" + entry.getKey());
}
}
}
}
|
package py.edu.unican.facitec.formulario;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import java.awt.Panel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class formDetalle extends JDialog {
private JPanel contentPane;
private JTextField TfNroDetalle;
private JTextField TfNroEstadia;
private JTextField TfCodServicio;
private JTextField TfMontoDetalle;
private Panel panel;
private JButton btnNuevo;
private JButton btnModificar;
private JButton btnEliminar;
private JButton btnGuardar;
private JButton btnCancelar;
private JButton btnSalir;
private JLabel lblBuscar;
private JTextField tfBuscar;
private JScrollPane scrollPane;
private JTable table;
public formDetalle() {
setTitle("Detalle");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 799, 515);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panel = new Panel();
panel.setBounds(451, 27, 322, 322);
contentPane.add(panel);
panel.setLayout(null);
TfNroDetalle = new JTextField();
TfNroDetalle.setBounds(116, 13, 191, 24);
panel.add(TfNroDetalle);
TfNroDetalle.setColumns(10);
JLabel lblNroDetalle = new JLabel("Nro. de Detalle");
lblNroDetalle.setBounds(10, 11, 113, 24);
panel.add(lblNroDetalle);
lblNroDetalle.setFont(new Font("Tahoma", Font.PLAIN, 14));
JLabel lblNroDeEstada = new JLabel("Nro. de Estad\u00EDa");
lblNroDeEstada.setBounds(10, 69, 113, 24);
panel.add(lblNroDeEstada);
lblNroDeEstada.setFont(new Font("Tahoma", Font.PLAIN, 14));
TfNroEstadia = new JTextField();
TfNroEstadia.setBounds(115, 71, 192, 24);
panel.add(TfNroEstadia);
TfNroEstadia.setColumns(10);
JLabel lblCodDeServicio = new JLabel("C\u00F3digo Servicio");
lblCodDeServicio.setBounds(10, 143, 113, 24);
panel.add(lblCodDeServicio);
lblCodDeServicio.setFont(new Font("Tahoma", Font.PLAIN, 14));
TfCodServicio = new JTextField();
TfCodServicio.setBounds(116, 143, 191, 29);
panel.add(TfCodServicio);
TfCodServicio.setColumns(10);
TfMontoDetalle = new JTextField();
TfMontoDetalle.setBounds(116, 207, 191, 24);
panel.add(TfMontoDetalle);
TfMontoDetalle.setColumns(10);
JLabel lblMontoDetalle = new JLabel("Monto Detalle");
lblMontoDetalle.setBounds(10, 205, 102, 24);
panel.add(lblMontoDetalle);
lblMontoDetalle.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnNuevo = new JButton("Nuevo");
btnNuevo.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnNuevo.setBounds(341, 40, 89, 32);
contentPane.add(btnNuevo);
btnModificar = new JButton("Modificar");
btnModificar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnModificar.setBounds(341, 95, 89, 32);
contentPane.add(btnModificar);
btnEliminar = new JButton("Eliminar");
btnEliminar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnEliminar.setBounds(341, 157, 89, 32);
contentPane.add(btnEliminar);
btnGuardar = new JButton("Guardar");
btnGuardar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnGuardar.setBounds(448, 390, 89, 32);
contentPane.add(btnGuardar);
btnCancelar = new JButton("Cancelar");
btnCancelar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnCancelar.setBounds(549, 390, 89, 32);
contentPane.add(btnCancelar);
btnSalir = new JButton("Salir");
btnSalir.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnSalir.setBounds(662, 390, 89, 32);
contentPane.add(btnSalir);
lblBuscar = new JLabel("Buscar");
lblBuscar.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblBuscar.setBounds(20, 401, 46, 21);
contentPane.add(lblBuscar);
tfBuscar = new JTextField();
tfBuscar.setBounds(73, 390, 247, 28);
contentPane.add(tfBuscar);
tfBuscar.setColumns(10);
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 305, 366);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setColumnHeaderView(table);
}
}
|
package ch04;
class Jobs{
}
class Police extends Jobs{
private String name = "°æÂû";
}
class Docter extends Jobs{
private String name = "˂ȍ";
}
public class Array02 {
public static void main(String[] args) {
Jobs[] jobs = new Jobs[2];
jobs[0] = new Police();
jobs[1] = new Docter();
System.out.println(jobs[0]);
System.out.println(jobs[1]);
}
}
|
package es.studium.Login;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConsultaEmpleado implements ActionListener, WindowListener
{
// Ventana Consulta de Empleados
Frame frmConsultaEmpleados = new Frame("Consulta Empleados");
TextArea listadoEmpleados = new TextArea(4, 50);
Button btnPdfEmpleados = new Button("PDF");
BaseDatos bd;
String sentencia = "";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
public ConsultaEmpleado()
{
frmConsultaEmpleados.setLayout(new FlowLayout());
// Conectar
bd = new BaseDatos();
connection = bd.conectar();
// Hacer un SELECT * FROM Empleados
sentencia = "SELECT * FROM empleados";
// La información está en ResultSet
// Recorrer el RS y por cada registro,
// meter una línea en el TextArea
try
{
//Crear una sentencia
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
//Crear un objeto ResultSet para guardar lo obtenido
//y ejecutar la sentencia SQL
rs = statement.executeQuery(sentencia);
listadoEmpleados.selectAll();
listadoEmpleados.setText("");
listadoEmpleados.append("id\tNombre\t\tApellidos\t\tCargo\n");
while(rs.next())
{
listadoEmpleados.append(rs.getInt("idEmpleado")
+"\t"+rs.getString("nombreEmpleado")
+"\t\t"+rs.getString("apellidosEmpleado")
+"\t\t"+rs.getString("cargoEmpleado")
+"\n");
}
}
catch (SQLException sqle)
{
listadoEmpleados.setText("Se ha producido un error en la consulta");
}
finally
{
}
listadoEmpleados.setEditable(false);
frmConsultaEmpleados.add(listadoEmpleados);
frmConsultaEmpleados.add(btnPdfEmpleados);
frmConsultaEmpleados.setSize(400,150);
frmConsultaEmpleados.setResizable(false);
frmConsultaEmpleados.setLocationRelativeTo(null);
frmConsultaEmpleados.addWindowListener(this);
frmConsultaEmpleados.setVisible(true);
}
@Override
public void windowActivated(WindowEvent e)
{}
@Override
public void windowClosed(WindowEvent e)
{}
@Override
public void windowClosing(WindowEvent e)
{
if(frmConsultaEmpleados.isActive())
{
frmConsultaEmpleados.setVisible(false);
}
}
@Override
public void windowDeactivated(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
|
package com.cjkj.insurance.mapper;
import com.cjkj.insurance.entity.Delivery;
public interface DeliveryMapper {
/**
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer deliveryId);
/**
*
* @mbggenerated
*/
int insert(Delivery record);
/**
*
* @mbggenerated
*/
int insertSelective(Delivery record);
/**
*
* @mbggenerated
*/
Delivery selectByPrimaryKey(Integer deliveryId);
/**
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(Delivery record);
/**
*
* @mbggenerated
*/
int updateByPrimaryKey(Delivery record);
/**
* 间距任务号查询信息
*
*/
public Delivery findDeliveryByTaskId(String taskId);
//检查配送信息是否存在
public Delivery findDelivery(Delivery delivery);
}
|
package com.needii.dashboard.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.needii.dashboard.dao.PaymentTransactionDao;
import com.needii.dashboard.model.PaymentTransaction;
@Transactional
@Service("paymentTransactionService")
public class PaymentTransactionServiceImpl implements PaymentTransactionService{
@Autowired
private PaymentTransactionDao dao;
@Override
public PaymentTransaction findOne(long id) {
// TODO Auto-generated method stub
return dao.findOne(id);
}
@Override
public PaymentTransaction findByOrderCode(String orderCode) {
// TODO Auto-generated method stub
return dao.findByOrderCode(orderCode);
}
@Override
public PaymentTransaction findByMerchantOrderId(String merchantOrderId) {
// TODO Auto-generated method stub
return dao.findByMerchantOrderId(merchantOrderId);
}
@Override
public void create(PaymentTransaction entity) {
// TODO Auto-generated method stub
dao.create(entity);
}
@Override
public void update(PaymentTransaction entity) {
// TODO Auto-generated method stub
dao.update(entity);
}
@Override
public void delete(PaymentTransaction entity) {
// TODO Auto-generated method stub
dao.delete(entity);
}
}
|
package com.moran.proj.shared;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.moran.proj.api.GZIPResponseWrapper;
public abstract class AbstractController extends MultiActionController
{
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
@ModelAttribute
protected void beforeExecuting(HttpServletRequest request, HttpServletResponse response)
{
this.request = request;
this.response = response;
this.session = request.getSession();
request("webRoot",request.getContextPath());
//enableGZIP();
}
protected Object request(String key)
{
return request.getAttribute(key);
}
protected void request(String key, Object obj)
{
request.setAttribute(key, obj);
}
protected Object session(String key)
{
return session.getAttribute(key);
}
protected void session(String key, Object obj)
{
session.setAttribute(key, obj);
}
/** 为页面启用GZIP压缩 */
private void enableGZIP()
{
String ae = request.getHeader("accept-encoding");
if (ae != null && ae.indexOf("gzip") != -1)
{
GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(response);
wrappedResponse.finishResponse();
}
}
}
|
package com.comp2601.pullparserapp;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* (c) 2018 LD Nel
*/
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
/**
* (c) 2019 L.D. Nel
*/
public class Exam {
private static final String TAG = Exam.class.getSimpleName();
//XML tags used to define an exam of multiple choice questions.
public static final String XML_EXAM = "exam";
public static ArrayList pullParseFrom(BufferedReader reader){
ArrayList<Question> questions = null;
//ArrayList questions = Question.exampleSet1(); //for now
questions = new ArrayList<Question>();
// Get our factory and create a PullParser
XmlPullParserFactory factory = null;
try {
factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
String CurrTag="";
String CurrQuestion = "";
String CurrEmail = "";
boolean CurrAnswer = false;
xpp.setInput(reader); // set input file for parser
int eventType = xpp.getEventType(); // get initial eventType
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// handle the xml tags encountered
switch (eventType) {
case XmlPullParser.START_TAG: //XML opening tags
Log.i(TAG,"START_TAG: "+xpp.getName());
CurrTag=xpp.getName();
break;
case XmlPullParser.TEXT:
Log.i(TAG,"TEXT: "+xpp.getText());
if (CurrTag.contains("question_text"))
CurrQuestion+=xpp.getText().trim();
else if(CurrTag.contains("email"))
CurrEmail+=xpp.getText().trim();
break;
case XmlPullParser.END_TAG: //XML closing tags
Log.i(TAG,"END_TAG: "+xpp.getName());
if (xpp.getName().trim().contains("question_text"))
{
questions.add(new Question(CurrQuestion,CurrEmail));
CurrQuestion = "";
CurrTag="";
}
break;
default:
break;
}
//iterate
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
return questions;
}
}
|
package InheritancePrograms;
class RBI {
void interest()
{
System.out.println("6 percent");
}
}
class ICICI extends RBI
{
void interest()
{
System.out.println("6 percent");
}
void accountnumber()
{
System.out.println("15151");
}
}
class PNB extends RBI
{
void interest()
{
System.out.println("6 percent");
}
void accountnumberz()
{
System.out.println("151512");
}
}
public class Bank extends RBI
{
void interest()
{
System.out.println("6 percent");
}
public static void main(String args[])
{
Bank b = new Bank();
b.interest();
ICICI i=new ICICI();
i.accountnumber();
PNB p=new PNB();
p.accountnumberz();
}
}
|
package com.shinetech.smartboss;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SmartBossApplicationTests {
@Test
void contextLoads() {
}
}
|
package com.arthur.leetcode;
/**
* @title: No334
* @Author ArthurJi
* @Date: 2021/3/20 12:25
* @Version 1.0
*/
public class No334 {
public static void main(String[] args) {
increasingTriplet(new int[]{2,4,-2,-3});
}
public static boolean increasingTriplet(int[] nums) {
int mid = Integer.MAX_VALUE;
int left = Integer.MAX_VALUE;
for (int num : nums) {
if(num <= left) {
left = num;
// } else if(num <= mid) {
} else if(num < mid) {
mid = num;
} else if(num > mid) {
return true;
}
}
return false;
}
}
/*334. 递增的三元子序列
给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。
如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false 。
示例 1:
输入:nums = [1,2,3,4,5]
输出:true
解释:任何 i < j < k 的三元组都满足题意
示例 2:
输入:nums = [5,4,3,2,1]
输出:false
解释:不存在满足题意的三元组
示例 3:
输入:nums = [2,1,5,0,4,6]
输出:true
解释:三元组 (3, 4, 5) 满足题意,因为 nums[3] == 0 < nums[4] == 4 < nums[5] == 6*/
/*
递增的三元子序列
LeetCode 第 334 题
难度:
中等
tags:
递增子序列查找
巧妙的方法!
题目描述
给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。
数学表达式如下:
如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1,使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。
示例 1:
输入: [1,2,3,4,5]
输出: true
示例 2:
输入: [5,4,3,2,1]
输出: false
思路
本题的思路非常的巧妙!
首先,新建两个变量 small 和 mid ,分别用来保存题目要我们求的长度为 3 的递增子序列的最小值和中间值。
接着,我们遍历数组,每遇到一个数字,我们将它和 small 和 mid 相比,若小于等于 small ,则替换 small;否则,若小于等于 mid,则替换 mid;否则,若大于 mid,则说明我们找到了长度为 3 的递增数组!
上面的求解过程中有个问题:当已经找到了长度为 2 的递增序列,这时又来了一个比 small 还小的数字,为什么可以直接替换 small 呢,这样 small 和 mid 在原数组中并不是按照索引递增的关系呀?
Trick 就在这里了!假如当前的 small 和 mid 为 [3, 5],这时又来了个 1。假如我们不将 small 替换为 1,那么,当下一个数字是 2,后面再接上一个 3 的时候,我们就没有办法发现这个 [1,2,3] 的递增数组了!也就是说,我们替换最小值,是为了后续能够更好地更新中间值!
另外,即使我们更新了 small ,这个 small 在 mid 后面,没有严格遵守递增顺序,但它隐含着的真相是,有一个比 small 大比 mid 小的前·最小值出现在 mid 之前。因此,当后续出现比 mid 大的值的时候,我们一样可以通过当前 small 和 mid 推断的确存在着长度为 3 的递增序列。 所以,这样的替换并不会干扰我们后续的计算!
AC 代码:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int len = nums.size();
if (len < 3) return false;
int small = INT_MAX, mid = INT_MAX;
for (auto num : nums) {
if (num <= small) {
small = num;
} else if (num <= mid) {
mid = num;
}
else if (num > mid) {
return true;
}
}
return false;
}
};
作者:fxxuuu
链接:https://leetcode-cn.com/problems/increasing-triplet-subsequence/solution/c-xian-xing-shi-jian-fu-za-du-xiang-xi-jie-xi-da-b/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
|
package com.distributie.listeners;
public interface EvenimentDialogListener {
public void evenimentDialogProduced();
}
|
package net.colingarvey;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
/**
* Implementation of a LIFO data structure, otherwise known as a Stack. Uses linked-list logic to store a sequence
* of generic T type.
* @param <T>
*/
public class Stack <T> implements Iterable<T>{
private Node top; // top of the stack
private int size; // size (length) of stack
public Iterator<T> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<T> {
private Node active = top;
public boolean hasNext() {
return active !=null;
}
public T next() {
T item = active.item;
active = active.next;
return item;
}
public void remove() {
}
}
private class Node{
/**
* Nested class to store attributes related to items within the linked list.
*
*/
T item;
Node next;
}
/**
* Pops the top-most item on the stack.
*
* @return item Returns item of type T.
*/
public T pop(){
T item = top.item;
top = top.next;
size--;
return item;
}
/**
* Pushes a new item onto the stack.
*
* @param item item of type T to push onto the stack.
*/
public void push(T item) {
Node oldTop = top;
top = new Node();
top.item = item;
top.next = oldTop;
size++;
}
public boolean isEmpty(){ return top == null; }
// returns whether the stack is empty or not
public int size() { return size; }
// returns the size of stack
public static void main(String[] args) {
// Instantiate a stack, push and pop strings from stdin.
Stack<String> stack = new Stack<String>();
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
String line = stdIn.readLine();
if (line == null) {break;}
stack.push(line);
}
} catch (IOException e) {
e.printStackTrace();
}
while (!stack.isEmpty()){
System.out.println(stack.pop());
System.out.printf("Stack has %d items remaining.\n", stack.size());
}
}
}
|
package cn.sange.appserver.dao;
import cn.sange.appserver.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @ program: Appserver
* @ description:
* @ author: Sange
* @ create: 2018-09-05 20:21
**/
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private HibernateTemplate hibernateTemplate;
public User getUser(String phone) {
List<User> list =( List<User>) hibernateTemplate.find("from User where phone = ?", phone);
if (null != list && list.size() > 0){
return list.get(0);
}
return null;
}
public User register(User user) {
hibernateTemplate.save(user);
return this.getUser(user.getPhone());
}
public User login(String phone, String password) {
List<User> users = (List<User>) hibernateTemplate.find("from User where phone = ? and password = ?", phone, password);
if (null != users && users.size() > 0){
return users.get(0);
}else {
return null;
}
}
}
|
package io.nekohasekai.tmicro.utils;
import javolution.io.UTF8StreamReader;
import javolution.io.UTF8StreamWriter;
import java.io.*;
public class IoUtil {
public static final int DEFAULT_BUFFER_SIZE = 2 << 12;
public static final int EOF = -1;
public static DataInputStream getIn(byte[] bytes) {
return new DataInputStream(new ByteArrayInputStream(bytes));
}
public static void close(Reader reader) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(Writer reader) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(InputStream reader) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(OutputStream reader) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static long copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long size = 0;
for (int readSize; (readSize = in.read(buffer)) != EOF; ) {
out.write(buffer, 0, readSize);
size += readSize;
out.flush();
}
return size;
}
public static byte[] readByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out);
return out.toByteArray();
}
public static String readUTF8(InputStream in) throws IOException {
UTF8StreamReader reader = new UTF8StreamReader().setInput(in);
try {
return read(reader);
} finally {
close(reader);
}
}
public static String read(Reader reader) throws IOException {
final StringBuffer builder = new StringBuffer();
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int size;
while (true) {
size = reader.read(buffer);
if (size == -1) break;
builder.append(buffer, 0, size);
}
return builder.toString();
}
public static InputStream getResIn(String path) throws IOException {
if (!path.startsWith("/")) path = "/" + path;
InputStream in = IoUtil.class.getResourceAsStream(path);
if (in == null) {
throw new IOException(path + " not found");
}
return in;
}
public static byte[] readResBytes(String path) throws IOException {
InputStream in = getResIn(path);
try {
return readByteArray(in);
} finally {
close(in);
}
}
public static String readResUTF8(String path) throws IOException {
InputStream in = getResIn(path);
try {
return readUTF8(in);
} finally {
close(in);
}
}
public static void writeUTF8(OutputStream out, String str) throws IOException {
UTF8StreamWriter writer = new UTF8StreamWriter().setOutput(out);
writer.write(str);
writer.flush();
}
public static ByteArrayOutputStream out() {
return new ByteArrayOutputStream();
}
public static DataOutputStream open(OutputStream out) {
return new DataOutputStream(out);
}
}
|
package com.Memento.blackbox;
/**
* Created by Valentine on 2018/5/11.
*/
public interface Memento {
}
|
package us.logr.utils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImageUtils {
private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
public static BufferedImage imageFromByte(byte[] imageInByte){
InputStream in = new ByteArrayInputStream(imageInByte);
try {
BufferedImage bImageFromConvert = ImageIO.read(in);
return bImageFromConvert;
} catch (IOException e){
log.error("Can't parse image from byte", e);
return null;
}
}
public static byte[] getPixels(BufferedImage img) {
DataBufferByte imageData = (DataBufferByte) img
.getRaster()
.getDataBuffer();
byte[] pixels = imageData.getData();
return pixels;
}
public static int[] rgb2yuv(int[] pixel) {
int r = pixel[0];
int g = pixel[1];
int b = pixel[2];
int[] yuv = new int[3];
int y = (int)(0.299 * r + 0.587 * g + 0.114 * b);
int u = (int)((b - y) * 0.492f);
int v = (int)((r - y) * 0.877f);
yuv[0]= y;
yuv[1]= u;
yuv[2]= v;
return yuv;
}
/**
* https://fr.wikipedia.org/wiki/SRGB
*/
public static double luminance(int[] pixel) {
int r = pixel[0];
int g = pixel[1];
int b = pixel[2];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
/**
* http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
*/
public static double contrastRatio(int[] color1, int[] color2) {
double l1 = luminance(color1);
double l2 = luminance(color2);
double max_l = Math.max(l1, l2);
double min_l = Math.min(l1, l2);
double ratio = (max_l + 0.05) / (min_l + 0.05);
return ratio;
}
public static boolean isContrastRatioEnough(int[] color1, int[] color2) {
return contrastRatio(color1, color2) >= 7;
}
public static int[] getLighterColor(int[] color1, int[] color2) {
double l1 = luminance(color1);
double l2 = luminance(color2);
return (l1 > l2) ? color1 : color2;
}
}
|
package lab3;
import java.util.Random;
public class checkPoint1 {
// Integer to string
public static void int2String() {
int x = 42;
String s = "" + x;
System.out.println("int to string: " + s);
}
// String to integer
public static void string2Int() {
String x = "42";
int s = Integer.parseInt(x);
System.out.println("String to int: " + s);
}
// String to int (String is not an int)
public static void string2IntError() {
String x = "42Test";
int s = Integer.parseInt(x);
}
// Max value
public static void maxValue() {
System.out.println("Int max value: " + Integer.MAX_VALUE);
System.out.println("Int max value + 1: " + (Integer.MAX_VALUE + 1));
System.out.println("Int max value + 2: " + (Integer.MAX_VALUE + 2));
System.out.println("Int max value + max value: " + (Integer.MAX_VALUE + Integer.MAX_VALUE));
System.out.println("Int max value + min value: " + (Integer.MAX_VALUE + Integer.MIN_VALUE));
}
// Random number
public static void radNum() {
Random rand = new Random();
System.out.println("Random Num 0-5: " + rand.nextInt(6));
System.out.println("Random Num 0-5: " + rand.nextInt(6));
System.out.println("Random Num 0-5: " + rand.nextInt(6));
System.out.println("Random Num 0-136: " + rand.nextInt(137));
}
public static void main(String[] args) {
System.out.println("-----Part 1-----");
System.out.println("1mil value in pattern: " + (1000000 % 7));
System.out.println("-----Part 3-----");
int2String();
string2Int();
// string2IntError();
System.out.println("-----Part 4-----");
maxValue();
System.out.println("-----Part 5-----");
radNum();
}
}
|
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileFilter;
import java.net.URI;
import java.net.URL;
import javax.swing.DefaultListModel;
import org.junit.Test;
import es.deusto.prog3.cap00.resueltos.edicionSpritesV2.*;
public class cargaFicherosGraficosOrdenados2 {
//TODO preguntar a que se refiere con que la lista tenga la misma canidad de png que elementos tiene el modelo
@Test
public void test() {
VentanaEdicionSprites v = new VentanaEdicionSprites();
DefaultListModel<File>modelo=(DefaultListModel)v.lSprites.getModel();
modelo.clear();
System.out.println(modelo.getSize());
try {
File f= new File("C:\\Users\\cdcol\\git\\practica1\\Practica 1\\test1\\spritesheets\\ninja\\png");
System.out.println(f.getAbsolutePath());
v.getController().cargaFicherosGraficosOrdenados(f);
if (v.lSprites.getModel().getSize()==0) {
fail("error en la carga de fichero");
}else {
int resultado=0;
for (int i=0;i<v.lSprites.getModel().getSize();i++) {
v.lSprites.setSelectedIndex(i);//cojo elemento por elemento toda la lista
//System.out.println(v.lSprites.getSelectedIndex());
if (v.lSprites.getSelectedValue().getName().endsWith(".png") ) {
//System.out.println("es png");//compruebo si acaba con png
//if (v.lSprites.getModel().getElementAt(i).getName().endsWith(".png")) {//si el elemento del modelo acaba con png saldra en lSprites
resultado++;
}
}
//System.out.println(resultado +"resultado");
//System.out.println(v.lSprites.getModel().getSize() + "tamaño");
if (v.lSprites.getModel().getSize()!=resultado) {
// if (v.lSprites.getLastVisibleIndex()!=v.lSprites.getModel().getSize()) {
//System.out.println(v.lSprites.getModel());
fail("lista no es igual de larga");
//}
}
assertEquals(v.lSprites.getModel().getSize(), resultado);
boolean correct=true;
for (int i=0;i<v.lSprites.getModel().getSize()-1;i++) {
if (v.lSprites.getModel().getElementAt(i).getName().compareTo( v.lSprites.getModel().getElementAt(i+1).getName())>0) {
correct=false;
}
}
assertEquals(true, correct);
}
}catch(Exception e) {
e.printStackTrace();
fail("Excepcion");
}
v.getController().cargaFicherosGraficosOrdenados(null);
if (v.lSprites.getModel().getSize()!=0) {
fail("error en la carga de ficheros null");
}
}
}
|
/*
* Copyright 2006-2016 CIRDLES.org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.geosamples;
/**
*
* @author James F. Bowring <bowring at gmail.com>
*/
public class Constants {
public static final String GEOSAMPLES_PRODUCTION_SERVER = "https://app.geosamples.org/";
public static final String GEOSAMPLES_TEST_SAMPLES_SERVER = "https://sesardev.geosamples.org/";
public static final String GEOSAMPLES_TEST_FEATURES_SERVER = "https://sesar3.geosamples.org/";
public static final String GEOSAMPLES_SAMPLE_IGSN_WEBSERVICE_NAME = "sample/IGSN/";
public static final String GEOSAMPLES_CREDENTIALS_WEBSERVICE_NAME = "webservices/credentials_service.php";
public static final String GEOSAMPLES_CREDENTIALS_WEBSERVICE_NAME_V2 = "webservices/credentials_service_v2.php";
public static final String GEOSAMPLES_SAMPLE_UPLOAD_WEBSERVICE_NAME = "webservices/upload.php";
public static final String GEOSAMPLES_SAMPLE_LIST_PER_USERCODE_WEBSERVICE_NAME = "samples/user_code/";
public static final String GEOSAMPLES_SAMPLE_UPDATE_IGSN_WEBSERVICE_NAME = "webservices/update.php";
public static final String GEOSAMPLES_COMPLIANT_XML_HEADER_SAMPLES = "<samples xmlns=\"http://app.geosamples.org\" \n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n"
+ " xsi:schemaLocation=\"https://app.geosamples.org\n"
+ " https://app.geosamples.org/samplev2.xsd \">";
private Constants() {
throw new IllegalAccessError("Utility class");
}
}
|
package com.defrag.code.membership.service;
import com.defrag.code.membership.MembershipVO;
public interface MembershipService {
//회원가입 INSERT
int membershipTrans(MembershipVO membershipvo);
}
|
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.serialization.impl.compact;
import com.hazelcast.internal.nio.ClassLoaderUtil;
import com.hazelcast.internal.util.ExceptionUtil;
import com.hazelcast.nio.serialization.FieldType;
import com.hazelcast.nio.serialization.HazelcastSerializationException;
import com.hazelcast.nio.serialization.compact.CompactReader;
import com.hazelcast.nio.serialization.compact.CompactSerializer;
import com.hazelcast.nio.serialization.compact.CompactWriter;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.hazelcast.nio.serialization.FieldType.BOOLEAN;
import static com.hazelcast.nio.serialization.FieldType.BOOLEAN_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.BYTE;
import static com.hazelcast.nio.serialization.FieldType.BYTE_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.CHAR;
import static com.hazelcast.nio.serialization.FieldType.CHAR_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.COMPOSED;
import static com.hazelcast.nio.serialization.FieldType.COMPOSED_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.DATE;
import static com.hazelcast.nio.serialization.FieldType.DATE_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.DECIMAL;
import static com.hazelcast.nio.serialization.FieldType.DECIMAL_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.DOUBLE;
import static com.hazelcast.nio.serialization.FieldType.DOUBLE_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.FLOAT;
import static com.hazelcast.nio.serialization.FieldType.FLOAT_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.INT;
import static com.hazelcast.nio.serialization.FieldType.INT_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.LONG;
import static com.hazelcast.nio.serialization.FieldType.LONG_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.SHORT;
import static com.hazelcast.nio.serialization.FieldType.SHORT_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.TIME;
import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP;
import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP_WITH_TIMEZONE;
import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP_WITH_TIMEZONE_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.TIME_ARRAY;
import static com.hazelcast.nio.serialization.FieldType.UTF;
import static com.hazelcast.nio.serialization.FieldType.UTF_ARRAY;
import static java.util.stream.Collectors.toList;
/**
* Reflective serializer works for Compact format in zero-config case.
* Specifically when explicit serializer is not given via
* {@link com.hazelcast.config.CompactSerializationConfig#register(Class, String, CompactSerializer)}
* {@link com.hazelcast.config.CompactSerializationConfig#register(Class, CompactSerializer)}
* <p>
* ReflectiveCompactSerializer can de/serialize classes having an accessible empty constructor only.
* Only types in {@link CompactWriter}/{@link CompactReader} interface are supported as fields.
* For any other class as the field type, it will work recursively and try to de/serialize a sub-class.
* Thus, if any sub-fields does not have an accessible empty constructor, deserialization fails with
* HazelcastSerializationException.
*/
public class ReflectiveCompactSerializer implements CompactSerializer<Object> {
private final Map<Class, Writer[]> writersCache = new ConcurrentHashMap<>();
private final Map<Class, Reader[]> readersCache = new ConcurrentHashMap<>();
@Override
public void write(@Nonnull CompactWriter writer, @Nonnull Object object) throws IOException {
Class<?> clazz = object.getClass();
if (writeFast(clazz, writer, object)) {
return;
}
createFastReadWriteCaches(clazz);
writeFast(clazz, writer, object);
}
private boolean writeFast(Class clazz, CompactWriter compactWriter, Object object) throws IOException {
Writer[] writers = writersCache.get(clazz);
if (writers == null) {
return false;
}
for (Writer writer : writers) {
try {
writer.write(compactWriter, object);
} catch (Exception e) {
ExceptionUtil.rethrow(e, IOException.class);
}
}
return true;
}
private boolean readFast(Class clazz, DefaultCompactReader compactReader, Object object) throws IOException {
Reader[] readers = readersCache.get(clazz);
Schema schema = compactReader.getSchema();
if (readers == null) {
return false;
}
for (Reader reader : readers) {
try {
reader.read(compactReader, schema, object);
} catch (Exception e) {
ExceptionUtil.rethrow(e, IOException.class);
}
}
return true;
}
@Nonnull
@Override
public Object read(@Nonnull CompactReader reader) throws IOException {
// We always fed DefaultCompactReader to this serializer.
DefaultCompactReader compactReader = (DefaultCompactReader) reader;
Class associatedClass = compactReader.getAssociatedClass();
Object object;
object = createObject(associatedClass);
try {
if (readFast(associatedClass, compactReader, object)) {
return object;
}
createFastReadWriteCaches(associatedClass);
readFast(associatedClass, compactReader, object);
return object;
} catch (Exception e) {
throw new IOException(e);
}
}
@Nonnull
private Object createObject(Class associatedClass) {
try {
return ClassLoaderUtil.newInstance(associatedClass.getClassLoader(), associatedClass);
} catch (Exception e) {
throw new HazelcastSerializationException("Could not construct the class " + associatedClass, e);
}
}
private static List<Field> getAllFields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.stream(type.getDeclaredFields())
.filter(f -> !Modifier.isStatic(f.getModifiers()))
.filter(f -> !Modifier.isTransient(f.getModifiers()))
.collect(toList()));
if (type.getSuperclass() != null && type.getSuperclass() != Object.class) {
getAllFields(fields, type.getSuperclass());
}
return fields;
}
private boolean fieldExists(Schema schema, String name, FieldType fieldType) {
FieldDescriptor fieldDescriptor = schema.getField(name);
return fieldDescriptor != null && fieldDescriptor.getType().equals(fieldType);
}
private void createFastReadWriteCaches(Class clazz) throws IOException {
//Create object to test if it is empty constructable to fail-fast on the write path
createObject(clazz);
//get inherited fields as well
List<Field> allFields = getAllFields(new LinkedList<>(), clazz);
Writer[] writers = new Writer[allFields.size()];
Reader[] readers = new Reader[allFields.size()];
int index = 0;
for (Field field : allFields) {
field.setAccessible(true);
Class<?> type = field.getType();
String name = field.getName();
if (Byte.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, BYTE)) {
field.setByte(o, reader.readByte(name));
}
};
writers[index] = (w, o) -> w.writeByte(name, field.getByte(o));
} else if (Short.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, SHORT)) {
field.setShort(o, reader.readShort(name));
}
};
writers[index] = (w, o) -> w.writeShort(name, field.getShort(o));
} else if (Integer.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, INT)) {
field.setInt(o, reader.readInt(name));
}
};
writers[index] = (w, o) -> w.writeInt(name, field.getInt(o));
} else if (Long.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, LONG)) {
field.setLong(o, reader.readLong(name));
}
};
writers[index] = (w, o) -> w.writeLong(name, field.getLong(o));
} else if (Float.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, FLOAT)) {
field.setFloat(o, reader.readFloat(name));
}
};
writers[index] = (w, o) -> w.writeFloat(name, field.getFloat(o));
} else if (Double.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, DOUBLE)) {
field.setDouble(o, reader.readDouble(name));
}
};
writers[index] = (w, o) -> w.writeDouble(name, field.getDouble(o));
} else if (Boolean.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, BOOLEAN)) {
field.setBoolean(o, reader.readBoolean(name));
}
};
writers[index] = (w, o) -> w.writeBoolean(name, field.getBoolean(o));
} else if (Character.TYPE.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, CHAR)) {
field.setChar(o, reader.readChar(name));
}
};
writers[index] = (w, o) -> w.writeChar(name, field.getChar(o));
} else if (String.class.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, UTF)) {
field.set(o, reader.readString(name));
}
};
writers[index] = (w, o) -> w.writeString(name, (String) field.get(o));
} else if (BigDecimal.class.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, DECIMAL)) {
field.set(o, reader.readDecimal(name));
}
};
writers[index] = (w, o) -> w.writeDecimal(name, (BigDecimal) field.get(o));
} else if (LocalTime.class.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, TIME)) {
field.set(o, reader.readTime(name));
}
};
writers[index] = (w, o) -> w.writeTime(name, (LocalTime) field.get(o));
} else if (LocalDate.class.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, DATE)) {
field.set(o, reader.readDate(name));
}
};
writers[index] = (w, o) -> w.writeDate(name, (LocalDate) field.get(o));
} else if (LocalDateTime.class.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, TIMESTAMP)) {
field.set(o, reader.readTimestamp(name));
}
};
writers[index] = (w, o) -> w.writeTimestamp(name, (LocalDateTime) field.get(o));
} else if (OffsetDateTime.class.equals(type)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, TIMESTAMP_WITH_TIMEZONE)) {
field.set(o, reader.readTimestampWithTimezone(name));
}
};
writers[index] = (w, o) -> w.writeTimestampWithTimezone(name, (OffsetDateTime) field.get(o));
} else if (type.isArray()) {
Class<?> componentType = type.getComponentType();
if (Byte.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, BYTE_ARRAY)) {
field.set(o, reader.readByteArray(name));
}
};
writers[index] = (w, o) -> w.writeByteArray(name, (byte[]) field.get(o));
} else if (Short.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, SHORT_ARRAY)) {
field.set(o, reader.readShortArray(name));
}
};
writers[index] = (w, o) -> w.writeShortArray(name, (short[]) field.get(o));
} else if (Integer.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, INT_ARRAY)) {
field.set(o, reader.readIntArray(name));
}
};
writers[index] = (w, o) -> w.writeIntArray(name, (int[]) field.get(o));
} else if (Long.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, LONG_ARRAY)) {
field.set(o, reader.readLongArray(name));
}
};
writers[index] = (w, o) -> w.writeLongArray(name, (long[]) field.get(o));
} else if (Float.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, FLOAT_ARRAY)) {
field.set(o, reader.readFloatArray(name));
}
};
writers[index] = (w, o) -> w.writeFloatArray(name, (float[]) field.get(o));
} else if (Double.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, DOUBLE_ARRAY)) {
field.set(o, reader.readDoubleArray(name));
}
};
writers[index] = (w, o) -> w.writeDoubleArray(name, (double[]) field.get(o));
} else if (Boolean.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, BOOLEAN_ARRAY)) {
field.set(o, reader.readBooleanArray(name));
}
};
writers[index] = (w, o) -> w.writeBooleanArray(name, (boolean[]) field.get(o));
} else if (Character.TYPE.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, CHAR_ARRAY)) {
field.set(o, reader.readCharArray(name));
}
};
writers[index] = (w, o) -> w.writeCharArray(name, (char[]) field.get(o));
} else if (String.class.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, UTF_ARRAY)) {
field.set(o, reader.readStringArray(name));
}
};
writers[index] = (w, o) -> w.writeStringArray(name, (String[]) field.get(o));
} else if (BigDecimal.class.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, DECIMAL_ARRAY)) {
field.set(o, reader.readDecimalArray(name));
}
};
writers[index] = (w, o) -> w.writeDecimalArray(name, (BigDecimal[]) field.get(o));
} else if (LocalTime.class.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, TIME_ARRAY)) {
field.set(o, reader.readTimeArray(name));
}
};
writers[index] = (w, o) -> w.writeTimeArray(name, (LocalTime[]) field.get(o));
} else if (LocalDate.class.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, DATE_ARRAY)) {
field.set(o, reader.readDateArray(name));
}
};
writers[index] = (w, o) -> w.writeDateArray(name, (LocalDate[]) field.get(o));
} else if (LocalDateTime.class.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, TIMESTAMP_ARRAY)) {
field.set(o, reader.readTimestampArray(name));
}
};
writers[index] = (w, o) -> w.writeTimestampArray(name, (LocalDateTime[]) field.get(o));
} else if (OffsetDateTime.class.equals(componentType)) {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, TIMESTAMP_WITH_TIMEZONE_ARRAY)) {
field.set(o, reader.readTimestampWithTimezoneArray(name));
}
};
writers[index] = (w, o) -> w.writeTimestampWithTimezoneArray(name, (OffsetDateTime[]) field.get(o));
} else {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, COMPOSED_ARRAY)) {
field.set(o, reader.readObjectArray(name, componentType));
}
};
writers[index] = (w, o) -> w.writeObjectArray(name, (Object[]) field.get(o));
}
} else {
readers[index] = (reader, schema, o) -> {
if (fieldExists(schema, name, COMPOSED)) {
field.set(o, reader.readObject(name));
}
};
writers[index] = (w, o) -> w.writeObject(name, field.get(o));
}
index++;
}
writersCache.put(clazz, writers);
readersCache.put(clazz, readers);
}
interface Reader {
void read(CompactReader reader, Schema schema, Object o) throws Exception;
}
interface Writer {
void write(CompactWriter writer, Object o) throws Exception;
}
}
|
package com.algorithm.trie;
public class KMP {
/**
*
* @param mainStr 主串
* @param mainStrLength 主串长度
* @param pattern 模式串
* @param patternLength 模式串长度
* @return
*/
public static int kmp(char[] mainStr,int mainStrLength,char[] pattern,int patternLength){
int[] next = getNexts(pattern,patternLength);
int j = 0;
for (int i = 0; i < mainStrLength; i++) {
while(j>0 && mainStr[i] != pattern[j]){
j = next[j - 1] + 1;
}
if(mainStr[i] == pattern[j]){
++j;
}
if(j == patternLength){//找到匹配模式串了
return i-patternLength+1;
}
}
return -1;
}
public static int[] getNexts(char[] pattern,int patternLength){
int[] next = new int[patternLength];
next[0] = -1;
int k = -1;
for (int i = 0; i < patternLength; i++) {
while(k!=-1 && pattern[k+1] != pattern[i]){
k = next[k];
}
if(pattern[k+1] == pattern[i]){
++k;
}
next[i]=k;
}
return next;
}
}
|
package com.oodles.controller;
import java.util.Map;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.oodles.dto.MarketDTO;
import com.oodles.mapping.URLMapping;
import com.oodles.util.ResponseHandler;
import com.oodles.services.MarketService;
@RestController
public class MarketController
{
@Autowired
MarketService marketService;
String message="message";
Logger LOGGER=org.slf4j.LoggerFactory.getLogger(MarketController.class);
@RequestMapping(value = URLMapping.SAVE_MARKET, method = RequestMethod.POST)
ResponseEntity<Object> saveMarket(@RequestBody MarketDTO marketForm) {
Map<String, Object> result = null;
try {
LOGGER.info("controller");
LOGGER.info(""+marketForm.getExchangeCountryId());
LOGGER.info(""+marketForm.getMinLimit());
result = marketService.saveMarket(marketForm);
if(result.get("isSuccess").equals(true)){
return ResponseHandler.generateResponse(HttpStatus.OK, true, result.get(message).toString(), result);
}
else
return ResponseHandler.generateResponse(HttpStatus.BAD_REQUEST, false, result.get(message).toString(), result);
} catch (Exception e) {
return ResponseHandler.generateResponse(HttpStatus.BAD_REQUEST, false, e.getMessage(), result);
}
}
@RequestMapping(value = URLMapping.GET_MARKET, method = RequestMethod.GET)
ResponseEntity<Object> getMarket(@RequestParam String marketId) {
Map<String, Object> result = null;
try {
result = marketService.getMarket(marketId);
if(result.get("isSuccess").equals(true)){
return ResponseHandler.generateResponse(HttpStatus.OK, true, result.get(message).toString(), result);
}
else
return ResponseHandler.generateResponse(HttpStatus.BAD_REQUEST, false, result.get(message).toString(), result);
} catch (Exception e) {
return ResponseHandler.generateResponse(HttpStatus.BAD_REQUEST, false, e.getMessage(), result);
}
}
}
|
package com.minhvu.proandroid.sqlite.database.main.presenter.view;
import android.content.Context;
import android.net.Uri;
import com.minhvu.proandroid.sqlite.database.main.model.view.IImageModel;
import com.minhvu.proandroid.sqlite.database.main.view.Adapter.ImageAdapter;
import com.minhvu.proandroid.sqlite.database.main.view.Fragment.view.IDetailFragment;
/**
* Created by vomin on 9/6/2017.
*/
public interface IImagePresenter {
int getImagesCount();
void setModel(IImageModel model);
void bindView(IDetailFragment.ImageView view);
void onBindViewHolder(ImageAdapter.ImageViewHolder holder, int position);
void onImageClick(int position);
void onLoadImages(Context context, Uri noteUri);
void addImage(String path, Uri noteUri);
void onDestroy(boolean isChangingConfiguration);
void notifyView();
void deleteAllImage(Context context, int position);
}
|
package views;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import auxiliary.ClientPOUI;
import connections.ClientServerConnection;
import listeners.BuildCompleteListener;
import listeners.NextButtonListener;
import listeners.PreviousButtonListener;
/**
* This view will display the POUI images as well as provide the basic interface for iterating through
* the different steps.
* @author jameschapman
*/
public class POUIView {
/**
* Local instance of ClientPOUI, will use this copy fetched from the server to be displayed to the user.
*/
private ClientPOUI assemblyPOUI;
/**
* Only instance of JFrame used throughout the class. All components will be added to this frame, and the
* frame will be displayed.
*/
private JFrame mainFrame;
/**
* The pane that contains the buttons. They will be displayed below the images and 'Build Complete' will be
* dynamically displayed.
*/
private JPanel buttonPane;
/**
* A connection with the server that will be passed to Listeners to be used when necessary.
*/
private ClientServerConnection connection;
/**
* Constructs a new instance of POUIView, initializes all local variables and takes in a ClientPOUI object
* that is the POUI that will be displayed.
* @param assemblyPOUI The POUI that the user has requested and is to be displayed, fetched from POUI server.
*/
public POUIView(ClientPOUI assemblyPOUI, ClientServerConnection connection) {
this.connection = connection;
this.assemblyPOUI = assemblyPOUI;
this.mainFrame = new JFrame("POUI");
this.mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.mainFrame.add(createPanels());
this.mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.mainFrame.setUndecorated(true);
this.mainFrame.setVisible(true);
}
/**
* Creates the panels that will be added to the main JFrame and then displayed.
* @return mainPanel The panel that contains all sub-components to be added to the frame.
*/
private JPanel createPanels() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel imagePane = new JPanel();
imagePane.setLayout(new BoxLayout(imagePane, BoxLayout.PAGE_AXIS));
// add image to panel
JLabel poui = new JLabel(assemblyPOUI.startBuild());
poui.setAlignmentX(JLabel.CENTER_ALIGNMENT);
imagePane.add(poui);
// create pane for buttons
buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
// create and add previous button to panel
JButton previous = new JButton("Previous");
previous.setAlignmentX(JButton.LEFT_ALIGNMENT);
buttonPane.add(previous);
buttonPane.add(Box.createHorizontalGlue());
JButton complete = new JButton("Build Complete");
complete.setAlignmentX(JButton.CENTER_ALIGNMENT);
complete.setVisible(false);
buttonPane.add(complete);
buttonPane.add(Box.createHorizontalGlue());
// create and add next button to panel
JButton next = new JButton("Next");
next.setAlignmentX(JButton.RIGHT_ALIGNMENT);
buttonPane.add(next);
// add action listeners to buttons
PreviousButtonListener previousListener = new PreviousButtonListener(assemblyPOUI, poui, complete);
previous.addActionListener(previousListener);
NextButtonListener nextListener = new NextButtonListener(assemblyPOUI, poui, complete, connection);
next.addActionListener(nextListener);
BuildCompleteListener completeListener = new BuildCompleteListener(mainFrame, connection, assemblyPOUI);
complete.addActionListener(completeListener);
// add image and buttons to mainPanel
mainPanel.add(imagePane, BorderLayout.CENTER);
mainPanel.add(buttonPane, BorderLayout.PAGE_END);
return mainPanel;
}
public void setVisible() {
mainFrame.setVisible(true);
}
public void hideView() {
mainFrame.setVisible(false);
}
}
|
package pl.basistam.dataAccess.api;
import pl.basistam.dataAccess.entities.Parking;
import pl.basistam.dataAccess.entities.ParkingSpot;
import pl.basistam.dataAccess.entities.Ticket;
import java.time.LocalDateTime;
import java.util.List;
public interface CarParkDao {
void saveTicket(Ticket ticket);
void saveParking(Integer parkingSpotId, LocalDateTime timeOfParking);
List<Ticket> getTicketsFromArea(int area, LocalDateTime beginning, LocalDateTime end);
Long getParkingSpotNumber();
ParkingSpot getParkingSpot(Integer id);
}
|
package com.sims.bo.impl;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sims.bo.ItemInventoryDetailsBo;
import com.sims.dao.ItemInventoryDetailsDao;
import com.sims.model.ItemInventory;
import com.sims.model.ItemInventoryDetails;
@Service
public class ItemInventoryDetailsBoImpl implements ItemInventoryDetailsBo {
private final static Logger logger = Logger.getLogger(ItemInventoryDetailsBoImpl.class);
@Autowired
ItemInventoryDetailsDao itemInventoryDetailsDao;
public void setItemInventoryDetailsDao(ItemInventoryDetailsDao itemInventoryDetailsDao){
this.itemInventoryDetailsDao = itemInventoryDetailsDao;
}
@Override
@Transactional
public boolean save(ItemInventoryDetails entity) {
entity.setCreatedOn(new java.sql.Timestamp(System.currentTimeMillis()));
entity.setVersion(1);
entity.setActive(true);
logger.info("Save: " + entity.toString());
return itemInventoryDetailsDao.save(entity);
}
@Override
@Transactional
public boolean update(ItemInventoryDetails entity) {
ItemInventoryDetails model = itemInventoryDetailsDao.findById(entity.getId());
//update the fields of the model
model.setPhysicalQty(entity.getPhysicalQty());
model.setInQty(entity.getInQty());
model.setOutQty(entity.getOutQty());
model.setUpdatedQty(entity.getUpdatedQty());
model.setModule(entity.getModule());
model.setTransRefNo(entity.getTransRefNo());
model.setModifiedBy(entity.getModifiedBy());
model.setModifiedOn(new java.sql.Timestamp(System.currentTimeMillis()));
model.setVersion(model.getVersion() + 1);
logger.info("Update: " + model.toString());
return itemInventoryDetailsDao.update(model);
}
@Override
@Transactional
public boolean delete(ItemInventoryDetails entity) {
entity.setActive(false);
entity.setModifiedOn(new java.sql.Timestamp(System.currentTimeMillis()));
entity.setVersion(entity.getVersion() + 1);
logger.info("Delete: id = " + entity.getId());
return itemInventoryDetailsDao.delete(entity);
}
@Override
@Transactional
public List<ItemInventoryDetails> getAllEntity() {
return itemInventoryDetailsDao.getAllEntity();
}
@Override
@Transactional
public ItemInventoryDetails findById(int criteria) {
return itemInventoryDetailsDao.findById(criteria);
}
@Override
public List<ItemInventoryDetails> findByItemInventory(ItemInventory criteria) {
return itemInventoryDetailsDao.findByItemInventory(criteria);
}
}
|
package com.jh.share.web.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.jh.share.model.User;
import com.jh.share.service.SecurityService;
import com.jh.share.service.UserService;
import com.jh.share.validation.UserValidator;
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidator;
private String logoutModel;
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "/registration";
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") User userForm, Model modelt) {
// userValidator.validate(userForm, bindingResult);
// if (bindingResult.hasErrors()) {
// return "registration";
// }
userService.save(userForm);
//securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(@RequestParam(value = "error",required = false) String error ,Model model) {
if (error != null) {
model.addAttribute("error", "Invalid Credentials provided.");
}
return ("login");
}
@RequestMapping(value = { "/welcome" }, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
|
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.User;
import org.pircbotx.PircBotX;
import java.util.Scanner;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Properties;
public class DestHandler extends ListenerAdapter {
private Scanner scanner;
private PermissionsManager pm;
private PircBotX sourceBot;
private PircBotX destBot;
private Properties props;
private SourceHandler sh;
public DestHandler(PircBotX sourceBot, PircBotX destBot, SourceHandler sh, Properties props) {
super();
this.sourceBot = sourceBot;
this.destBot = destBot;
this.sh = sh;
this.props = props;
this.pm = PermissionsManager.getInstance();
System.out.println("PermissionsHandler initialized for DestHandler.");
}
public void onMessage(MessageEvent event) {
String command = event.getMessage();
String commandLower = command.toLowerCase();
scanner = new Scanner(commandLower);
if (scanner.hasNext("!echo")) {
scanner.next();
if (false) {
event.respond("Sorry, you do not have permission to manipulate the echo list.");
return;
} else {
if (scanner.hasNext("add")) {
//add a dude
scanner.next();
if (scanner.hasNext()) {
String target = scanner.next();
sh.addCeleb(target);
event.respond("Added "+target+" to echo list.");
} else {
event.respond("Who am I adding, exactly? Spelling counts.");
}
} else if (scanner.hasNext("purge")) {
//kill the list
sh.purgeCelebs();
event.respond("Purged echo list.");
} else if (scanner.hasNext("list")) {
//who is stalked?
LinkedList<String> celebs = sh.listCelebs();
String peeps ="";
for (String s : celebs) {
peeps += (s+" ");
}
event.respond("Tracking " + peeps);
} else {
event.respond("I am a tiger.");
}
}
}
if (scanner.hasNext("!bootstrap")) {
sh.addCeleb("tiy");
sh.addCeleb("tiyuri");
sh.addCeleb("bartwe");
sh.addCeleb("bartwe_");
sh.addCeleb("mollygos");
sh.addCeleb("kyren");
sh.addCeleb("omnipotententity");
event.respond("Sane echo defaults implemented.");
}
if (scanner.hasNext("!status")) {
event.respond("Oh yeah, I'll get right on that.");
}
}
}
|
/*
* Copyright 2002-2023 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jms;
import jakarta.jms.JMSException;
import org.springframework.core.NestedRuntimeException;
import org.springframework.lang.Nullable;
/**
* Base class for exception thrown by the framework whenever it
* encounters a problem related to JMS.
*
* @author Mark Pollack
* @author Juergen Hoeller
* @since 1.1
*/
@SuppressWarnings("serial")
public abstract class JmsException extends NestedRuntimeException {
/**
* Constructor that takes a message.
* @param msg the detail message
*/
public JmsException(String msg) {
super(msg);
}
/**
* Constructor that takes a message and a root cause.
* @param msg the detail message
* @param cause the cause of the exception. This argument is generally
* expected to be a proper subclass of {@link jakarta.jms.JMSException},
* but can also be a JNDI NamingException or the like.
*/
public JmsException(String msg, @Nullable Throwable cause) {
super(msg, cause);
}
/**
* Constructor that takes a plain root cause, intended for
* subclasses mirroring corresponding {@code jakarta.jms} exceptions.
* @param cause the cause of the exception. This argument is generally
* expected to be a proper subclass of {@link jakarta.jms.JMSException}.
*/
public JmsException(@Nullable Throwable cause) {
super(cause != null ? cause.getMessage() : null, cause);
}
/**
* Convenience method to get the vendor specific error code if
* the root cause was an instance of JMSException.
* @return a string specifying the vendor-specific error code if the
* root cause is an instance of JMSException, or {@code null}
*/
@Nullable
public String getErrorCode() {
Throwable cause = getCause();
if (cause instanceof JMSException jmsException) {
return jmsException.getErrorCode();
}
return null;
}
/**
* Return the detail message, including the message from the linked exception
* if there is one.
* @see jakarta.jms.JMSException#getLinkedException()
*/
@Override
@Nullable
public String getMessage() {
String message = super.getMessage();
Throwable cause = getCause();
if (cause instanceof JMSException jmsException) {
Exception linkedEx = jmsException.getLinkedException();
if (linkedEx != null) {
String linkedMessage = linkedEx.getMessage();
String causeMessage = cause.getMessage();
if (linkedMessage != null && (causeMessage == null || !causeMessage.contains(linkedMessage))) {
message = message + "; nested exception is " + linkedEx;
}
}
}
return message;
}
}
|
package com.stk123.model.bo;
import com.stk123.common.util.JdbcUtils.Column;
import java.io.Serializable;
import java.util.List;
import com.stk123.common.util.JdbcUtils.Table;
@SuppressWarnings("serial")
@Table(name="STK_DATA_PPI_TYPE")
public class StkDataPpiType implements Serializable {
@Column(name="ID", pk=true)
private Integer id;
@Column(name="NAME")
private String name;
@Column(name="PARENT_ID")
private Integer parentId;
@Column(name="URL")
private String url;
private List<StkDataPpi> stkDataPpi;
public Integer getId(){
return this.id;
}
public void setId(Integer id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public Integer getParentId(){
return this.parentId;
}
public void setParentId(Integer parentId){
this.parentId = parentId;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
public List<StkDataPpi> getStkDataPpi(){
return this.stkDataPpi;
}
public void setStkDataPpi(List<StkDataPpi> stkDataPpi){
this.stkDataPpi = stkDataPpi;
}
public String toString(){
return "id="+id+",name="+name+",parentId="+parentId+",url="+url+",stkDataPpi="+stkDataPpi;
}
}
|
package com.redsun.platf.entity.sys;
/**
* Sys109mId generated by hbm2java
*/
public class Sys109mId implements java.io.Serializable {
private String sid;
private String osHost;
public Sys109mId() {
}
public Sys109mId(String sid, String osHost) {
this.sid = sid;
this.osHost = osHost;
}
public String getSid() {
return this.sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getOsHost() {
return this.osHost;
}
public void setOsHost(String osHost) {
this.osHost = osHost;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof Sys109mId))
return false;
Sys109mId castOther = (Sys109mId) other;
return ((this.getSid() == castOther.getSid()) || (this.getSid() != null
&& castOther.getSid() != null && this.getSid().equals(
castOther.getSid())))
&& ((this.getOsHost() == castOther.getOsHost()) || (this
.getOsHost() != null
&& castOther.getOsHost() != null && this.getOsHost()
.equals(castOther.getOsHost())));
}
public int hashCode() {
int result = 17;
result = 37 * result
+ (getSid() == null ? 0 : this.getSid().hashCode());
result = 37 * result
+ (getOsHost() == null ? 0 : this.getOsHost().hashCode());
return result;
}
}
|
package xyz.ieden.config.client.controller;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lianghongwei01
* @date 2018/9/28 10:20
*/
@RestController
@RequestMapping(value = "hello")
public class HelloController {
private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);
// @Value(value = "${un}")
private String username;
// @Value(value = "${up}")
private String password;
@Value("${foo}")
private String foo;
@GetMapping(value = "user", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public JSONObject getUser() {
LOGGER.info("Username:[{}], Password:[{}].", username, password);
LOGGER.info("foo:[{}].", foo);
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("password", password);
LOGGER.info("Response Result:{}.", jsonObj.toJSONString());
return jsonObj;
}
}
|
package com.example.ecommerceapp.sellers;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.ecommerceapp.R;
import com.example.ecommerceapp.buyers.MainActivity;
import com.example.ecommerceapp.model.Products;
import com.example.ecommerceapp.model.SellerViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
public class SellerHomeActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
RecyclerView seller_home_recycle;
DatabaseReference reference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_home);
reference = FirebaseDatabase.getInstance().getReference().child("products");
seller_home_recycle = findViewById(R.id.seller_home_recycle);
seller_home_recycle.setHasFixedSize(true);
seller_home_recycle.setLayoutManager(new LinearLayoutManager(SellerHomeActivity.this));
bottomNavigationView = findViewById(R.id.seller_home_bottom_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
break;
case R.id.nav_add:
Intent cate_intent = new Intent(SellerHomeActivity.this, SellerCategoryActivity.class);
startActivity(cate_intent);
break;
case R.id.nav_logout:
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signOut();
Intent intent = new Intent(SellerHomeActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
break;
}
return true;
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options = new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(reference.orderByChild("sellerId").equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid()), Products.class)
.build();
FirebaseRecyclerAdapter<Products, SellerViewHolder> adapter = new FirebaseRecyclerAdapter<Products, SellerViewHolder>(options) {
@NonNull
@Override
public SellerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new SellerViewHolder(getLayoutInflater().inflate(R.layout.seller_item_layout, parent, false));
}
@Override
protected void onBindViewHolder(@NonNull SellerViewHolder holder, int position, @NonNull Products model) {
holder.seller_tv_productName.setText(model.getName());
holder.seller_tv_productPrice.setText(model.getPrice());
holder.seller_tv_productDes.setText(model.getDescription());
holder.seller_tv_productStatus.setText("Status :" + model.getProductState());
Picasso.with(SellerHomeActivity.this).load(model.getImage()).into(holder.seller_iv_productImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(SellerHomeActivity.this);
builder.setTitle("Do you need delete this product? Are you sure?");
builder.setCancelable(false);
CharSequence[] items = new CharSequence[]{"Yes", "No"};
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
reference.child(model.getPid()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(SellerHomeActivity.this, "deleted Done", Toast.LENGTH_SHORT).show();
}
}
});
} else if (which == 1) {
}
}
});
builder.show();
}
});
}
};
seller_home_recycle.setAdapter(adapter);
adapter.startListening();
}
}
|
package org.juxtasoftware.resource.sidebyside;
import java.util.Iterator;
import java.util.List;
import org.juxtasoftware.resource.sidebyside.SideBySideView.Change;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class TranspositionInjector implements OverlapInjector<Change> {
private List<Change> transpositions;
private Iterator<Change> transpositionItr;
private Change currTrans = null;
private boolean tagStarted = false;
@Override
public void initialize(List<Change> data) {
this.transpositions = data;
this.transpositionItr = this.transpositions.iterator();
if ( this.transpositionItr.hasNext() ) {
this.currTrans = this.transpositionItr.next();
}
}
@Override
public List<Change> getData() {
return this.transpositions;
}
@Override
public boolean hasContent(long pos) {
if ( this.currTrans == null) {
return false;
}
if ( this.currTrans.getRange().getStart() == pos && this.tagStarted == false ||
this.currTrans.getRange().getEnd() == pos && this.tagStarted == true ) {
return true;
}
return false;
}
@Override
public void restartContent( StringBuilder line ) {
if ( this.tagStarted ) {
line.append("</span>");
line.append("<span id=\"move-").append(this.currTrans.getId()).append("-continued\"");
line.append(" class=\"move\" title=\"Tranposition\"");
line.append(" juxta:connect-to=\"").append(this.currTrans.getConnectedId()).append("\"");
line.append(">");
}
}
@Override
public boolean injectContentStart(StringBuilder line, long currPositon) {
if ( this.currTrans != null && this.tagStarted == false ) {
if ( this.currTrans.getRange().getStart() == currPositon) {
line.append("<span id=\"move-").append(currTrans.getId()).append("\"");
line.append(" class=\"move\" title=\"Tranposition\"");
line.append(" juxta:connect-to=\"").append(currTrans.getConnectedId()).append("\"");
line.append(">");
this.tagStarted = true;
return true;
}
}
return false;
}
@Override
public boolean injectContentEnd(StringBuilder line, long currPosition) {
if ( this.currTrans != null && this.tagStarted == true ) {
if ( this.currTrans.getRange().getEnd() == currPosition) {
line.append("</span>");
this.tagStarted = false;
this.currTrans = null;
if ( this.transpositionItr.hasNext() ) {
this.currTrans = this.transpositionItr.next();
}
return true;
}
}
return false;
}
}
|
package com.zxt.compplatform.formengine.service;
import org.jdom.Document;
import com.zxt.compplatform.formengine.entity.view.BasePage;
/**
*
* xml对象解析
*
* @author 007
*/
public interface IResolveObjectDefService {
/**
* 解析xml对象
*
* @param doc
* @return
* @throws Exception
*/
public BasePage resolveObject(Document doc) throws Exception;
/**
* 根据表单id解析
*
* @param formId
* @return
*/
public BasePage resolveObject(String formId);
}
|
package commonwealth.game;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import commonwealth.game.Game.STATE;
import commonwealth.nations.Democracy;
import commonwealth.nations.Fanatics;
import commonwealth.nations.ID;
import commonwealth.nations.NewOrder;
import commonwealth.nations.Traders;
import commonwealth.nations.Tribals;
public class NationName extends KeyAdapter{
public String nation = "THE LOST COLONY";
BufferedImageLoader loader = new BufferedImageLoader();
BufferedImage paper = null, border = null, back = null;
Game game;
//16 max
public NationName(Game game){
this.game = game;
try{
paper = loader.loadImage("/tex/Paper.png");
border = loader.loadImage("/tex/Border.png");
back = loader.loadImage("/tex/Left.png");
}catch(Exception e){
e.printStackTrace();
}
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(Game.gameState == STATE.naming){
if(key != KeyEvent.VK_ENTER && key != KeyEvent.VK_BACK_SPACE && (KeyEvent.getKeyText(key).length() == 1 ||key == KeyEvent.VK_SPACE)){
if(nation.length() < 16){
if(key != KeyEvent.VK_SPACE){
nation += KeyEvent.getKeyText(key).toUpperCase();
}else if(key == KeyEvent.VK_SPACE){
nation += " ";
}
}
}
if(key == KeyEvent.VK_ENTER){
if(nation.length() > 0){
Map.nationName = nation;
Game.gameState = STATE.origin;
Map.nationList.add(new NewOrder(50, (int)(Math.random() * 10) + 57, (int)(Math.random() * 10) + 77, (int)(Math.random() * 10) + 25, (int)(Math.random() * 10) + 35, ID.order, game));
Map.nationList.add(new Tribals(50, (int)(Math.random() * 10) + 57, (int)(Math.random() * 10) + 57, (int)(Math.random() * 10) + 35, (int)(Math.random() * 10) + 35, ID.tribal, game));
Map.nationList.add(new Fanatics(50, (int)(Math.random() * 10) + 35, (int)(Math.random() * 10) + 25, (int)(Math.random() * 10) + 77, (int)(Math.random() * 10) + 57, ID.fanatic, game));
Map.nationList.add(new Democracy(50, (int)(Math.random() * 10) + 35, (int)(Math.random() * 10) + 45, (int)(Math.random() * 10) + 47, (int)(Math.random() * 10) + 47, ID.democrat, game));
Map.nationList.add(new Traders(50, (int)(Math.random() * 10) + 67, (int)(Math.random() * 10) + 45, (int)(Math.random() * 10) + 35, (int)(Math.random() * 10) + 57, ID.trader, game));
}
}if(key == KeyEvent.VK_BACK_SPACE){
if(nation.length() > 0){
nation = nation.substring(0, nation.length() - 1);
}
}
}
}
public void tick(){
}
public void render(Graphics g){
g.setColor(Color.black);
g.drawImage(paper, 0, 0, Game.width, Game.height, null);
g.setColor(new Color(50, 30, 20));
g.drawImage(border, 95, 185, 600, 100, null);
g.setFont(new Font("Courier New", 0, 40));
g.drawString(nation, 220, 245);
g.setFont(new Font("Courier New", 0, 25));
g.drawString("*Press <Enter> to confirm name", 200, 450);
g.drawString("*Name must contain something", 200, 480);
g.drawImage(back, 50, 50, 64, 64, null);
}
}
|
package com.design.pattern.iterator;
/**
* @Author: 98050
* @Time: 2019-01-14 17:36
* @Feature: 迭代器接口
*/
public interface Iterator {
/**
* 是否存在下一个元素
* @return
*/
boolean hasNext();
/**
* 获取下一个元素
* @return
*/
Object next();
}
|
package behavioral.template_method;
public class TemplateB extends ATemplate{
@Override
public void doA() {
System.out.println("TempatB:doA");
}
@Override
public void doB() {
System.out.println("TempatB:doB");
}
}
|
package com.netcracker.controllers;
import com.netcracker.DTO.NotificationDTO;
import com.netcracker.DTO.mappers.NotificationMapper;
import com.netcracker.entities.Notification;
import com.netcracker.services.ApplicationNotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/notification")
public class ApplicationNotificationController {
private static final Logger LOG = LoggerFactory.getLogger(ApplicationNotificationController.class);
@Autowired
private ApplicationNotificationService applicationNotificationService;
@Autowired
private NotificationMapper notificationMapper;
public ApplicationNotificationController() {
}
@GetMapping("/all")
public Map<String, Collection<NotificationDTO>> getAllNotifications() {
LOG.debug("get all notifications");
Map<String, Collection<NotificationDTO>> maps = new HashMap();
Collection<NotificationDTO> notifications = applicationNotificationService.getAllNotifications()
.stream()
.map(notificationMapper::toDto)
.collect(Collectors.toCollection(LinkedList::new));
maps.put("response" , notifications);
return maps;
}
@GetMapping("/currently")
public Map<String, Collection<NotificationDTO>> getNotifications() {
LOG.debug("getNotifications");
Map<String, Collection<NotificationDTO>> maps = new HashMap();
Collection<NotificationDTO> notifications = applicationNotificationService.getNotificationsUser()
.stream()
.map(notificationMapper::toDto)
.collect(Collectors.toCollection(LinkedList::new));
maps.put("response" , notifications);
return maps;
}
@GetMapping("/topic")
public Map<String, Integer> getTopicNotification() {
LOG.debug("Input");
Map<String, Integer> maps = new HashMap<String, Integer>();
int result = applicationNotificationService.getCountTopicNotification();
LOG.debug("count : " + String.valueOf(result));
maps.put( "count" , applicationNotificationService.getCountTopicNotification() );
LOG.debug("Output");
return maps;
}
}
|
package org.usfirst.frc.team3243.robot;
import edu.wpi.first.wpilibj.Talon;
import com.ctre.phoenix.motorcontrol.can.*;
import edu.wpi.first.wpilibj.VictorSP;
public class MotorController
{
WPI_TalonSRX driveM1 = new WPI_TalonSRX(0);
WPI_TalonSRX driveM2 = new WPI_TalonSRX(1);
VictorSP driveM3 = new VictorSP(0);
VictorSP driveM4 = new VictorSP(1);
public void drive(Double [] val) {
driveM1.set(-val[0]);
driveM2.set(val[1]);
driveM3.set(-val[0]);
driveM4.set(val[1]);
}
}
|
package org.stoevesand.brain.auth;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.logging.Logger;
import org.stoevesand.brain.BrainSession;
import org.stoevesand.brain.BrainSystem;
import org.stoevesand.brain.exceptions.DBException;
import org.stoevesand.brain.model.IUserLesson;
import org.stoevesand.brain.persistence.BrainDB;
import org.stoevesand.util.SendMailUsingAuthentication;
import org.stoevesand.util.StringUtils;
public class Authorization {
private static final int PWC_NONE = 0;
private static final int PWC_OK = 1;
private static final int PWC_DBERROR = 2;
private static final int PWC_NOMATCH = 3;
private static final int PWC_EMPTY = 4;
private static final int PWC_USED = 5;
private static final int PWC_UNCHANGED = 6;
// private static org.apache.log4j.Logger log =
// Logger.getLogger("Authorization.class");
private static Logger log = Logger.getLogger(Authorization.class);
String username = "";
String password = "";
String passnew = "";
String emailAddress = "";
String unlock = "";
String passconfirm = "";
String captext = "";
int statusCode = 0;
String nickMsg = "";
String nicknew = "";
String prefixnew = "";
public String getPrefixnew() {
return prefixnew;
}
public void setPrefixnew(String prefixnew) {
this.prefixnew = prefixnew;
}
private boolean loggedIn;
public String getEmail() {
return emailAddress;
}
public String getUnlock() {
return "";
}
public void setUnlock(String unlock) {
this.unlock = unlock;
}
public void setEmail(String email) {
this.emailAddress = email;
}
public String getPassconfirm() {
return passconfirm;
}
public void setPassconfirm(String passconfirm) {
this.passconfirm = passconfirm;
}
public String getCaptext() {
return "";
}
public void setCaptext(String captext) {
this.captext = captext;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public String remind() {
// FacesContext context = FacesContext.getCurrentInstance();
BrainSystem bs = BrainSystem.getBrainSystem();
BrainDB db = bs.getBrainDB();
String pw = db.getUserPassword(getEmail());
if (pw != null) {
String emailSubjectTxt = "Your Request at notonto.";
String emailMsgTxt = bs.getReminderText();
emailMsgTxt = StringUtils.replaceSubstring(emailMsgTxt, "@PASSWORD@", pw);
// SendMailUsingAuthentication.sendConfirmationMail(email, unlock);
SendMailUsingAuthentication.sendConfirmationMail(emailAddress, emailSubjectTxt, emailMsgTxt);
log.info("Reminder sent: " + getEmail());
} else
log.error("Reminder requested: " + getEmail());
emailAddress = "";
return "reminded";
}
public String login() {
FacesContext context = FacesContext.getCurrentInstance();
BrainSystem bs = BrainSystem.getBrainSystem();
BrainSession bss = bs.getBrainSession();
BrainDB db = bs.getBrainDB();
String ret = "login";
User user = null;
try {
user = db.getUser(username);
if (user != null) {
bss.setCurrentUser(user);
if (user.getPassword().equals(password)) {
if (user.unlocked) {
ret=userLoggedIn(user, bss, context);
return ret;
} else {
loggedIn = false;
log.info("User still locked:" + user.getName());
emailAddress = username;
return "unlock";
}
} else {
log.info("User wrong PW: " + user.getName());
}
} else {
log.info("user " + username + " invalid.");
}
} catch (DBException e) {
return "fatal_DB";
}
ResourceBundle bundle = ResourceBundle.getBundle("org.stoevesand.brain.i18n.MessagesBundle", context.getViewRoot().getLocale());
context.addMessage(null, new FacesMessage(bundle.getString("loginfailed")));
bss.incrementLoginCounter();
return "logout";
}
/*
* Verbinden eines bestehenden notonto accounts mit einem Facebook account
*/
public String fb_link() {
FacesContext context = FacesContext.getCurrentInstance();
BrainSystem bs = BrainSystem.getBrainSystem();
BrainSession bss = bs.getBrainSession();
BrainDB db = bs.getBrainDB();
//String ret = "login";
User user = null;
try {
user = db.getUser(username);
if (user != null) {
if (user.getPassword().equals(password)) {
return "user";
} else {
log.info("User wrong PW: " + user.getName());
}
} else {
log.info("user " + username + " invalid.");
}
} catch (DBException e) {
return "fatal_DB";
}
ResourceBundle bundle = ResourceBundle.getBundle("org.stoevesand.brain.i18n.MessagesBundle", context.getViewRoot().getLocale());
context.addMessage(null, new FacesMessage(bundle.getString("loginfailed")));
bss.incrementLoginCounter();
return null;
}
// alles was man erledigen muss, wenn ein user richtig ist.
public String userLoggedIn(User user, BrainSession bss, FacesContext context) {
String ret = "login";
loggedIn = true;
try {
user.storeLastLogin();
user.storeScore();
bss.login();
log.info("User logged in: " + user.getName());
log.info("Browser: " + getBrowser(context));
// Sonderfall direkteinstieg. Wenn eine Userlesson ID übergeben
// wurde
// dann wird sie geladen und gleich auf die lesson.jsf verzweigt.
String sulid = bss.getParameter("ulid");
System.out.println("ULID: " + sulid);
long ulid = 0;
if (sulid != null) {
try {
ulid = Long.parseLong(sulid);
IUserLesson userLesson = (IUserLesson) user.getUserLesson(ulid);
if (userLesson != null) {
bss.learnLesson(userLesson);
ret = "lesson";
} else
ret = "user";
} catch (Exception e) {
}
}
// Ende: Direkteinstieg
System.out.println("RET: "+ret);
if (user.getIsAdmin()) {
return "admin_user";
}
} catch (DBException e) {
return "fatal_DB";
}
return ret;
}
private String getBrowser(FacesContext context) {
String browser = "unknown";
try {
HttpServletRequest sr = (HttpServletRequest) context.getExternalContext().getRequest();
browser = sr.getHeader("User-Agent");
} catch (Exception e) {
}
return browser;
}
public String logout() {
loggedIn = false;
username = "";
// try {
// BrainSystem.getBrainSystem().getBrainSession().getFacebookClient().logout();
// } catch(Exception e){};
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext ectx = context.getExternalContext();
HttpSession session = (HttpSession) ectx.getSession(false);
session.invalidate();
return "logout";
}
public String register() {
log.debug("register");
BrainDB db = BrainSystem.getBrainSystem().getBrainDB();
try {
if (!passwordsMatch()) {
FacesContext context = FacesContext.getCurrentInstance();
UIComponent root = context.getViewRoot();
UIComponent passinput = root.findComponent("regform:passinput");
UIComponent passconfinput = root.findComponent("regform:passconfinput");
log.debug("passinput: " + passinput);
if ((passinput != null) && (passconfinput != null)) {
String message = "pdm";
context.addMessage(passinput.getClientId(context), new FacesMessage(message));
context.addMessage(passconfinput.getClientId(context), new FacesMessage(message));
}
return "passnomatch";
}
if (db.emailIsAlreadyUsed(emailAddress)) {
return "emailused";
}
} catch (DBException e) {
e.printStackTrace();
return "fatal_DB";
}
return "captcha";
}
public String deleteAccount() {
BrainSystem bs = BrainSystem.getBrainSystem();
BrainSession bss = bs.getBrainSession();
String testpass = passnew;
passnew = "";
String ret = null;
if (testpass.length() > 0) {
BrainDB db = bs.getBrainDB();
User cu = bss.getCurrentUser();
try {
if (cu.getPassword().equals(testpass)) {
db.deleteAccount(cu);
ret = logout();
} else {
bss.getBrainMessage().setPwErrorText("Wrong password!");
ret = null;
}
} catch (DBException e) {
}
} else {
bss.getBrainMessage().setPwErrorText("Please enter your password!");
}
return ret;
}
public String alterPassword() {
if (passnew.length() == 0) {
setStatusCode(PWC_EMPTY);
} else if (passnew.equals(passconfirm)) {
BrainSystem bs = BrainSystem.getBrainSystem();
BrainDB db = bs.getBrainDB();
User cu = bs.getBrainSession().getCurrentUser();
try {
db.changePassword(cu, passnew);
} catch (DBException e) {
setStatusCode(PWC_DBERROR);
}
setStatusCode(PWC_OK);
} else {
setStatusCode(PWC_NOMATCH);
}
return null;
}
public String alterStatusMailFreq() {
BrainSystem bs = BrainSystem.getBrainSystem();
BrainDB db = bs.getBrainDB();
User cu = bs.getBrainSession().getCurrentUser();
try {
db.changeStatusMailFreq(cu);
} catch (DBException e) {
}
return null;
}
public String alterNickname() {
BrainSystem bs = BrainSystem.getBrainSystem();
setNickMsg("");
if (nicknew.length() == 0) {
setStatusCode(PWC_EMPTY);
setNickMsg(bs.getBrainSession().getResourceBundle().getString("msg_required"));
} else if ((nicknew.length() > 15) || (nicknew.length() < 5)) {
setStatusCode(PWC_NOMATCH);
setNickMsg(bs.getBrainSession().getResourceBundle().getString("msg_nicklong"));
} else if (!nicknew.matches("[a-zA-Z0-9]*")) {
setStatusCode(PWC_NOMATCH);
setNickMsg(bs.getBrainSession().getResourceBundle().getString("msg_nickregex"));
} else {
BrainDB db = bs.getBrainDB();
User cu = bs.getBrainSession().getCurrentUser();
if (nicknew.equals(cu.getNick())) {
setStatusCode(PWC_UNCHANGED);
} else {
try {
if (db.checkNickname(cu, nicknew)) {
cu.setNick(nicknew);
db.changeNickname(cu, nicknew);
bs.updateTop5(cu);
// setStatusCode(PWC_OK);
} else {
setStatusCode(PWC_USED);
setNickMsg(bs.getBrainSession().getResourceBundle().getString("msg_nickused"));
}
} catch (DBException e) {
setStatusCode(PWC_DBERROR);
}
}
}
nicknew = "";
return null;
}
public String alterPrefix() {
BrainSystem bs = BrainSystem.getBrainSystem();
BrainSession bss = bs.getBrainSession();
if (prefixnew.length() == 0) {
bss.getBrainMessage().setPrefixErrorText(bs.getBrainSession().getResourceBundle().getString("msg_required"));
} else if ((prefixnew.length() > 5) || (prefixnew.length() < 2)) {
bss.getBrainMessage().setPrefixErrorText(bs.getBrainSession().getResourceBundle().getString("msg_prefixlong"));
} else if (!prefixnew.matches("[a-zA-Z0-9]*")) {
bss.getBrainMessage().setPrefixErrorText(bs.getBrainSession().getResourceBundle().getString("msg_prefixregex"));
} else {
BrainDB db = bs.getBrainDB();
User cu = bs.getBrainSession().getCurrentUser();
if (!prefixnew.equals(cu.getPrefix())) {
try {
if (db.checkUserPrefix(cu, prefixnew)) {
cu.setPrefix(prefixnew);
db.changePrefix(cu, prefixnew);
} else {
bss.getBrainMessage().setPrefixErrorText(bs.getBrainSession().getResourceBundle().getString("msg_prefixused"));
}
} catch (DBException e) {
setStatusCode(PWC_DBERROR);
}
}
}
prefixnew = "";
return null;
}
public String prepareOptions() {
passnew = "";
passconfirm = "";
setStatusCode(0);
return "options";
}
public String confirm() {
try {
FacesContext context = FacesContext.getCurrentInstance();
BrainSystem bs = BrainSystem.getBrainSystem();
// BrainDB db = BrainSystem.getBrainSystem().getBrainDB();
log.debug("confirm");
unlock = randomUnlockString();
String emailSubjectTxt = "Your Registration at notonto.";
String emailMsgTxt = bs.getRegisterText();
emailMsgTxt = StringUtils.replaceSubstring(emailMsgTxt, "@CODE@", unlock);
String rcp = context.getExternalContext().getRequestContextPath();
String unlockLink = "http://www.notonto.de" + rcp + "/unlock/" + emailAddress + "/" + unlock;
emailMsgTxt = StringUtils.replaceSubstring(emailMsgTxt, "@LINK@", unlockLink);
// SendMailUsingAuthentication.sendConfirmationMail(email, unlock);
SendMailUsingAuthentication.sendConfirmationMail(emailAddress, emailSubjectTxt, emailMsgTxt);
User user = new User(emailAddress, password, unlock, false);
user.store();
BrainSystem.debug("bs: registeredUser -> " + user.getName());
} catch (DBException e) {
e.printStackTrace();
return "fatal_DB";
}
return "unlock";
}
public String sendCode() {
FacesContext context = FacesContext.getCurrentInstance();
User user = (User) context.getExternalContext().getRequestMap().get("user");
System.out.println("sendCode -> " + user.getName());
System.out.println("sendCode -> " + user.getUnlock());
reconfirm(user);
return null;
}
public void reconfirm(User user) {
FacesContext context = FacesContext.getCurrentInstance();
BrainSystem bs = BrainSystem.getBrainSystem();
// BrainDB db = BrainSystem.getBrainSystem().getBrainDB();
log.debug("reconfirm");
String emailSubjectTxt = "Your Registration at notonto.";
String emailMsgTxt = "### Aufgrund eines Fehler im Mailsystem wurde Ihr Freischaltcode nicht verschickt. \n";
emailMsgTxt += "### Wir schicken Ihnen den Code daher erneut zu.\n";
emailMsgTxt += "### Wir bitten die Verzögerung zu entschuldigen. - Ihr notonto-Team.\n\n";
emailMsgTxt += bs.getRegisterText();
emailMsgTxt = StringUtils.replaceSubstring(emailMsgTxt, "@CODE@", unlock);
String rcp = context.getExternalContext().getRequestContextPath();
String unlockLink = "http://www.notonto.de" + rcp + "/unlock/" + user.getName() + "/" + user.getUnlock();
emailMsgTxt = StringUtils.replaceSubstring(emailMsgTxt, "@LINK@", unlockLink);
// SendMailUsingAuthentication.sendConfirmationMail(email, unlock);
SendMailUsingAuthentication.sendConfirmationMail(user.getName(), emailSubjectTxt, emailMsgTxt);
BrainSystem.debug("reconfirmation -> " + user.getName());
}
public String unlock() {
log.debug("Vcode");
// String message = "Dieser Code ist leider nicht richtig!";
BrainDB db = BrainSystem.getBrainSystem().getBrainDB();
boolean unlocked;
try {
unlocked = db.unlockUser(emailAddress, unlock);
if (!unlocked) {
// ((UIInput) toValidate).setValid(false);
// context.addMessage(toValidate.getClientId(context), new
// FacesMessage(message));
log.debug("wrong unlock key");
return "unlock";
}
} catch (DBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "unlocked";
}
String randomUnlockString() {
String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy23456789";
char[] chars = elegibleChars.toCharArray();
int charsToPrint = 5;
StringBuffer finalString = new StringBuffer();
for (int i = 0; i < charsToPrint; i++) {
double randomValue = Math.random();
int randomIndex = (int) Math.round(randomValue * (chars.length - 1));
char characterToShow = chars[randomIndex];
finalString.append(characterToShow);
}
return finalString.toString();
}
public void validateEmail(FacesContext context, UIComponent toValidate, Object value) {
log.debug("VE");
String message = "Wrong email";
String email = (String) value;
if (email.indexOf('@') < 1) {
((UIInput) toValidate).setValid(false);
context.addMessage(toValidate.getClientId(context), new FacesMessage(message));
}
}
public boolean passwordsMatch() {
log.debug("VP: compare " + password + " - " + passconfirm);
return password.equals(passconfirm);
}
public void validateRights(FacesContext context, UIComponent toValidate, Object value) {
log.debug("VR");
String message = "Bitte stimmen Sie den Benutzungshinweisen zu!";
Boolean rights = (Boolean) value;
if (!rights.booleanValue()) {
((UIInput) toValidate).setValid(false);
context.addMessage(toValidate.getClientId(context), new FacesMessage(message));
}
}
public void validateCaptcha(FacesContext context, UIComponent toValidate, Object value) {
log.debug("VC");
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
String lastcap = "" + request.getSession().getAttribute("captcha");
String message = "Wrong captcha";
String captext = (String) value;
if (!lastcap.trim().toUpperCase().equals(captext.trim().toUpperCase())) {
((UIInput) toValidate).setValid(false);
context.addMessage(toValidate.getClientId(context), new FacesMessage(message));
}
}
public boolean getIsLoggedIn() {
return loggedIn;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getPassnew() {
return passnew;
}
public void setPassnew(String passnew) {
this.passnew = passnew;
}
public String getNicknew() {
return "";
}
public void setNicknew(String nicknew) {
this.nicknew = nicknew.trim();
}
public String getNickMsg() {
return nickMsg;
}
public void setNickMsg(String nickMsg) {
this.nickMsg = nickMsg;
}
}
|
//Copyright 2016 Yahoo Inc.
//Licensed under the terms of the Apache version 2.0 license. See LICENSE file for terms.
package com.yahoo.rdl.maven;
import javax.inject.Provider;
public class OSNameProvider implements Provider<String> {
private String configuredOSName;
public OSNameProvider(String configuredOSName) {
this.configuredOSName = configuredOSName;
}
@Override
public String get() {
String name = configuredOSName != null ? configuredOSName : System.getProperty("os.name");
String result = name.startsWith("Mac") ? "darwin" : name;
return result;
}
}
|
package com.proiectSCD.proiectSCD.service;
import com.proiectSCD.proiectSCD.exceptionHandlers.UserException;
import com.proiectSCD.proiectSCD.dal.model.dto.UserCreationDTO;
import com.proiectSCD.proiectSCD.dal.model.dto.UserLoginDTO;
import com.proiectSCD.proiectSCD.dal.model.entity.UserEntity;
import com.proiectSCD.proiectSCD.dal.repository.RoleRepository;
import com.proiectSCD.proiectSCD.dal.repository.UserRepository;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Service
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final BCryptPasswordEncoder encodedPassword;
public UserServiceImpl(UserRepository userRepository, RoleRepository roleRepository, BCryptPasswordEncoder encodedPassword) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.encodedPassword = encodedPassword;
}
@Override
public List<UserEntity> getUsers() {
return (List<UserEntity>) userRepository.findAll();
}
@Override
public UserEntity userLogin(UserLoginDTO userLoginDTO) throws UserException {
if (Objects.isNull(userLoginDTO)) {
throw new UserException(401, "The request body is null!");
}
if (Objects.isNull(userLoginDTO.getEmail())) {
throw new UserException(400, "An email address must be provided!");
}
if (Objects.isNull(userLoginDTO.getPassword())) {
throw new UserException(400, "A password must be provided!");
}
final UserEntity userEntity = userRepository.findByEmail(userLoginDTO.getEmail());
if (Objects.isNull(userEntity)) {
throw new UserException(401, "The provided credentials are invalid!");
}
if (!encodedPassword.matches(userLoginDTO.getPassword(), userEntity.getPassword())) {
throw new UserException(401, "The provided credentials are invalid!");
}
return userEntity;
}
@Override
public UserEntity userRegistration(UserCreationDTO userCreationDTO) throws UserException{
if(Objects.isNull(userCreationDTO)){
throw new UserException(401, "The request body is null!");
}
if(userCreationDTO.getFirstName().isEmpty()){
throw new UserException(400, "First name field cannot be empty!");
}
if(userCreationDTO.getLastName().isEmpty()){
throw new UserException(400, "Last name field cannot be empty!");
}
if(userCreationDTO.getEmail().isEmpty()){
throw new UserException(400, "Email field cannot be empty!");
}
if(userCreationDTO.getPassword().isEmpty()){
throw new UserException(400, "Password field cannot be empty!");
}
if(!Objects.isNull(userRepository.findByEmail(userCreationDTO.getEmail()))){
throw new UserException(409, "The email you have inserted is already in use!");
}
if(!userCreationDTO.getPassword().equals(userCreationDTO.getConfirmedPassword())){
throw new UserException(401, "The inserted passwords don't match!");
}
UserEntity userEntity = new UserEntity();
userEntity.setFirstName(userCreationDTO.getFirstName());
userEntity.setLastName(userCreationDTO.getLastName());
userEntity.setEmail(userCreationDTO.getEmail());
userEntity.setPassword(encodedPassword.encode(userCreationDTO.getPassword()));
userEntity.setRoles(roleRepository.findByRole("BASIC_USER"));
return userRepository.save(userEntity);
}
}
|
package org.silverpeas.looks.aurora.servlets;
import org.silverpeas.core.admin.component.model.ComponentInst;
import org.silverpeas.core.admin.component.model.ComponentInstLight;
import org.silverpeas.core.admin.component.model.Parameter;
import org.silverpeas.core.admin.component.model.WAComponent;
import org.silverpeas.core.admin.service.Administration;
import org.silverpeas.core.util.StringUtil;
import org.silverpeas.core.util.URLUtil;
import org.silverpeas.core.util.logging.SilverLogger;
import org.silverpeas.core.web.http.HttpRequest;
import org.silverpeas.core.web.look.LookHelper;
import org.silverpeas.looks.aurora.AuroraSpaceHomePage;
import org.silverpeas.looks.aurora.LookAuroraHelper;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
public class GoToSpaceHomepageBackOffice extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {
doPost(req, res);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) {
try {
HttpRequest request = HttpRequest.decorate(req);
String spaceId = request.getParameter("SpaceId");
LookAuroraHelper lookHelper =
(LookAuroraHelper) LookHelper.getLookHelper(req.getSession(false));
String destination = "admin/jsp/accessForbidden.jsp";
if (lookHelper.isSpaceAdmin(spaceId)) {
ComponentInstLight backOfficeApp = lookHelper.getConfigurationApp(spaceId);
if (backOfficeApp == null) {
createConfigurationApp(spaceId, lookHelper);
backOfficeApp = lookHelper.getConfigurationApp(spaceId);
}
if (backOfficeApp != null) {
// go to app
destination =
URLUtil.getApplicationURL() + URLUtil.getComponentInstanceURL(backOfficeApp.getId()) +
"Edit";
res.sendRedirect(destination);
} else {
req.getRequestDispatcher("/admin/jsp/errorpageMain.jsp").forward(req, res);
}
} else {
req.getRequestDispatcher(destination).forward(req, res);
}
} catch (ServletException | IOException e) {
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
private String createConfigurationApp(String spaceId, LookAuroraHelper lookHelper) {
String componentName = "webPages";
Optional<WAComponent> existingComponent = WAComponent.getByName(componentName);
if (existingComponent.isPresent()) {
List<Parameter> parameters = existingComponent.get().getAllParameters();
// set specific parameter values
ComponentInst component = new ComponentInst();
component.setCreatorUserId(lookHelper.getUserId());
component.setInheritanceBlocked(false);
component.setLabel("Page d'accueil");
component.setName(componentName);
component.setDomainFatherId(spaceId);
component.setHidden(true);
for (Parameter parameter : parameters) {
if (parameter.getName().equals("useSubscription")) {
parameter.setValue("no");
} else if (parameter.getName().equals("xmlTemplate")) {
parameter.setValue(AuroraSpaceHomePage.TEMPLATE_NAME);
} else if (parameter.getName().equals("xmlTemplate2")) {
// check if a custom template is defined for this space or a parent
String template = lookHelper.getSpaceHomePageCustomTemplate(spaceId);
if (StringUtil.isDefined(template)) {
parameter.setValue(template);
}
}
}
component.setParameters(parameters);
try {
return Administration.get().addComponentInst(lookHelper.getUserId(), component);
} catch (Exception e) {
SilverLogger.getLogger(this).error(e);
}
}
return null;
}
}
|
package com.driva.drivaapi.mapper;
import com.driva.drivaapi.mapper.dto.UserDTO;
import com.driva.drivaapi.model.user.User;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Component
public class UserMapper {
public UserDTO entityToUserDTO(User user) {
return new UserDTO(user);
}
public List<UserDTO> entitiesToUserDTOs(List<User> users) {
return users.stream().filter(Objects::nonNull).map(this::entityToUserDTO).collect(Collectors.toList());
}
public User userDTOtoEntity(UserDTO userDTO) {
return new User(userDTO);
}
public User updateUser(UserDTO userDTO, User user) {
return user.updateUser(userDTO);
}
}
|
package design_pattern.singleton;
public class C_LazyInitialization {
private static C_LazyInitialization instance;
private C_LazyInitialization() {}
// the issue in case of multi-threaded application
// multiple thread can be inside if condition at same time
// and multiple thread will get different instance of the singleton class
// this is how you can break singleton
public static C_LazyInitialization getInstance() {
if(instance == null) {
instance = new C_LazyInitialization();
}
return instance;
}
}
|
package ydtak.grapeguice;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Main {
// Steps to enable linking for auto-generated files (for Autofactory) in IDEA:
// File > Settings > Build, Execution, Development > Compiler > Annotation Processors
// - Enable annotation processing
// - Module content root
// - Production sources directory: "generated"
// - Test sources directory: "generated_tests"
// Build > Rebuild Project (this should create auto-generated files in "generated" directory)
// File > Project Structure > Modules > Sources
// - Mark "generated" and "generated_tests" as "Sources"
//
// Rerun Build > Rebuild Project as necessary to update auto-generated files.
public static void main(String[] args) {
Injector injector = Guice.createInjector(new ApplicationModule());
Application application = injector.getInstance(Application.class);
application.run();
}
}
|
package com.akgundemirbas.odev.mdd.codegen.template;
import com.akgundemirbas.mdd.gui.Frame;
import com.akgundemirbas.mdd.gui.HorizontalLayout;
import com.akgundemirbas.mdd.gui.Layout;
import com.akgundemirbas.mdd.gui.VerticalLayout;
public class Helper {
public String getAligment(Frame f) {
Layout uses = f.getUses();
if (uses instanceof VerticalLayout) {
return "javax.swing.BoxLayout.Y_AXIS";
} else if (uses instanceof HorizontalLayout) {
return "javax.swing.BoxLayout.X_AXIS";
}
System.out.println(uses);
return "";
}
}
|
package com.comp3617.assignment2.data;
/**
* Created by Jason Lai on 2017-11-04.
*/
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.EditText;
import android.widget.TimePicker;
import com.comp3617.assignment2.R;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* Created by jasonchih-yuan on 2017-11-05.
*/
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
TimePickerDialog timePicker = new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
return timePicker;
}
@Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
EditText etDueTime = (EditText) getActivity().findViewById(R.id.etDueTime);
EditText etDueDate = (EditText) getActivity().findViewById(R.id.etDueDate);
SimpleDateFormat sdfDueDate = new SimpleDateFormat("yyyy-MM-dd");
Date dueDate = null;
try {
if(etDueDate.getText()==null || etDueDate.getText().toString().equals("")){
etDueTime.setTextColor(Color.RED);
etDueTime.setText("Please Set Date First");
}else {
dueDate = sdfDueDate.parse(etDueDate.getText().toString());
SimpleDateFormat sdfDueDateYear = new SimpleDateFormat("yyyy");
SimpleDateFormat sdfDueDateMonth = new SimpleDateFormat("MM");
SimpleDateFormat sdfDueDateDay = new SimpleDateFormat("dd");
Calendar dueDateCalendar = new GregorianCalendar();
dueDateCalendar.setTime(dueDate);
Calendar myCalendar = Calendar.getInstance();
Calendar c = Calendar.getInstance();
myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
myCalendar.set(Calendar.MINUTE, minute);
myCalendar.set(Calendar.DAY_OF_MONTH, dueDateCalendar.get(Calendar.DAY_OF_MONTH));
myCalendar.set(Calendar.MONTH, dueDateCalendar.get(Calendar.MONTH));
myCalendar.set(Calendar.YEAR, dueDateCalendar.get(Calendar.YEAR));
if (myCalendar.getTimeInMillis() >= c.getTimeInMillis()) {
etDueTime.setTextColor(Color.BLACK);
String myFormat = "HH:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
etDueTime.setText(sdf.format(myCalendar.getTime()));
} else {
etDueTime.setTextColor(Color.RED);
etDueTime.setText("Expired Due Time");
}
}
} catch (ParseException e) {
e.printStackTrace();
}
getActivity().invalidateOptionsMenu();
}
}
|
package com.example.sudhanshrana.clientexcel;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends BaseActivity implements ChildEventListener, View.OnClickListener {
String s,s1;
Spinner sp,sp1;
ArrayAdapter<String> adapt,adapt1;
Button b1;
FirebaseDatabase db=FirebaseDatabase.getInstance();
DatabaseReference myRef=db.getReference();
DatabaseReference myRef1=db.getReference();
List<String> l1=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(this);
/*
SharedPreferences spp=getSharedPreferences("user",MODE_PRIVATE);
String pp=spp.getString("Year","0");
if(!pp.equals("0"))
{
Intent in=new Intent(MainActivity.this,Main2Activity.class);
startActivity(in);
}
else{
// Intent in=new Intent(MainActivity.this,branchSelect.class);
// startActivity(in);
}*/
sp=(Spinner)findViewById(R.id.spinner4);
sp1=(Spinner)findViewById(R.id.spinner5);
l1.add("Select Year");
adapt=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,l1);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapt1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item);
adapt1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapt);
adapt1.add("Select Branch");
sp1.setAdapter(adapt1);
sp1.setVisibility(View.GONE);
myRef.addChildEventListener(this);
sp.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
s = l1.get(position);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Year", s);
editor.commit();
sp1.setVisibility(View.VISIBLE);
myRef1 = myRef.child(s);
myRef1.addChildEventListener(ch);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
sp1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
s1=adapt1.getItem(position);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Branch", s1);
editor.commit();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
);
showProgressDialog();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
hideProgressDialog();
l1.add(dataSnapshot.getKey().toString());
adapt.notifyDataSetChanged();
}
ChildEventListener ch =new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
adapt1.add(dataSnapshot.getKey().toString());
adapt.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
@Override
public void onClick(View v) {
Intent in=new Intent(MainActivity.this,Main2Activity.class);
startActivity(in);
}
}
|
package uz.pdp.appcodingbat.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import uz.pdp.appcodingbat.entity.TaskCategory;
import uz.pdp.appcodingbat.entity.User;
public interface TaskCategoryRepository extends JpaRepository<TaskCategory, Integer> {
boolean existsByNameAndLanguageId(String name, Integer language_id);
boolean existsByNameAndLanguageIdAndIdNot(String name, Integer language_id, Integer id);
}
|
package com.myapplicationdev.android.p05_ps;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class ThirdActivity extends AppCompatActivity {
TextView tvID;
EditText etTitle,etSinger,etYear;
RadioGroup rg;
Button btnUpdate, btnDelete,btnCancel;
Song data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
tvID = findViewById(R.id.tvId);
etTitle = findViewById(R.id.etSongTitle);
etYear = findViewById(R.id.etYearText);
etSinger = findViewById(R.id.etSingersText);
btnCancel = findViewById(R.id.btnCancel);
btnUpdate = findViewById(R.id.btnUpdate);
btnDelete = findViewById(R.id.btnDelete);
Intent i = getIntent();
data = (Song) i.getSerializableExtra("data");
tvID.setText(""+data.get_id());
etTitle.setText(data.getTitle());
etSinger.setText(data.getSingers());
etYear.setText("" +data.getYears());
//Integer num = data.getStar();
//rg.check(num);
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
data.setTitle(etTitle.getText().toString());
data.setSingers(etSinger.getText().toString());
data.setYears(Integer.parseInt(etYear.getText().toString()));
data.setStars(getStars());
DBHelper dbh = new DBHelper(ThirdActivity.this);
dbh.updateSong(data);
setResult(RESULT_OK);
finish();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DBHelper dbh = new DBHelper(ThirdActivity.this);
dbh.deleteSong(data.get_id());
dbh.close();
setResult(RESULT_OK);
finish();
}
});
}
private int getStars() {
int stars = 1;
switch (rg.getCheckedRadioButtonId()) {
case R.id.radio1:
stars = 1;
break;
case R.id.radio2:
stars = 2;
break;
case R.id.radio3:
stars = 3;
break;
case R.id.radio4:
stars = 4;
break;
case R.id.radio5:
stars = 5;
break;
}
return stars;
}
}
|
package com.sun.ability;
import com.lmax.disruptor.EventHandler;
import org.springframework.util.StopWatch;
/**
* @create: 2020-01-19 16:05
*/
public class TestDataHandler implements EventHandler<TestData> {
StopWatch stopWatch;
public TestDataHandler() {
stopWatch = new StopWatch();
stopWatch.start();
}
private long i = 0;
@Override
public void onEvent(TestData event, long sequence, boolean endOfBatch) throws Exception {
i++;
if (i == Constants.MAX_NUM_FM) {
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
}
}
}
|
package com.netcracker.CustomException;
public class JourneyNotFound extends Exception {
}
|
package com.beike.common.bean.trx;
import com.beike.util.Configuration;
/* *
*类名:AlipayConfig
*功能:基础配置类
*详细:设置帐户有关信息及返回路径
*版本:3.2
*日期:2011-09-01
*/
public class AlipayConfig {
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 签约支付宝账号或卖家收款支付宝帐户
public static String seller_email = Configuration.getInstance().getValue("alipaySeller");
// 支付宝服务器通知的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数
// 必须保证其地址能够在互联网中访问的到
public static String notify_url = "http://www.qianpin.com//pay/aliCallBack.do";
// 当前页面跳转后的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数
// 域名不能写成http://localhost/create_direct_pay_by_user_jsp_utf8/return_url.jsp ,否则会导致return_url执行无效
public static String return_url = "http://www.qianpin.com//pay/aliCallBack.do";
// 支付宝WAP: 商户(MD5)KEY
public static final String ALIPAY_WAP_KEY = "";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
// 字符编码格式 目前支持 gbk 或 utf-8
public static String input_charset = "UTF-8";
// 签名方式 不需修改
public static String sign_type = "MD5";
//访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
public static String transport = "http";
}
|
package com.maliang.core.arithmetic.function;
import java.util.Map;
import com.maliang.core.arithmetic.AE;
import com.maliang.core.arithmetic.ArithmeticExpression;
import com.maliang.core.util.Utils;
public class AggregationFunction {
public static Object max(Function function,Map<String,Object> params){
return doCompare(function,params,"max");
}
public static Object min(Function function,Map<String,Object> params){
return doCompare(function,params,"min");
}
private static Object doCompare(Function function,Map<String,Object> params,String match){
Object operatedObj = readOperand(function,params);
Object[] dataList = Utils.toArray(operatedObj);
if(!Utils.isEmpty(dataList)){
Object result = null;
for(Object obj : dataList){
if(result == null){
result = obj;
continue;
}
if(obj instanceof Map){
Comparable lastValue = (Comparable)ArithmeticExpression.execute(function.expression, (Map)result);
Comparable currValue = (Comparable)ArithmeticExpression.execute(function.expression, (Map)obj);
if(match(currValue,lastValue,match)){
result = obj;
}
}else if(obj instanceof Comparable){
if(match((Comparable)obj,(Comparable)result,match)){
result = obj;
}
}
}
return result;
}
return null;
}
private static boolean match(Comparable c1,Comparable c2,String match){
int result = compare(c1,c2);
if("max".equals(match)){
return result > 0;
}
if("min".equals(match)){
return result < 0;
}
if("eq".equals(match)){
return result == 0;
}
return false;
}
private static int compare(Comparable c1,Comparable c2){
if(c1 instanceof String || c2 instanceof String){
return c1.toString().compareTo(c2.toString());
}
if(c1 instanceof Number && c2 instanceof Number){
return new Double(((Number)c1).doubleValue()).compareTo(new Double(((Number)c2).doubleValue()));
}
return -1;
}
private static Object readOperand(Function fun,Map<String,Object> params){
if(fun.useKeyValue()){
return fun.getKeyValue();
}else {
return fun.executeExpression(params);
}
}
public static void main(String[] args) {
String s = "max([1.00,2.99,3,5,6])";
Object v = AE.execute(s);
System.out.println(v);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.