text stringlengths 10 2.72M |
|---|
package com.example.zhubangshopingtest1;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.RadioGroup;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.example.zhubangshopingtest1.base.BaseFragment;
import com.example.zhubangshopingtest1.home.fragment.CircleFragment;
import com.example.zhubangshopingtest1.home.fragment.HomeFragment;
import com.example.zhubangshopingtest1.home.fragment.ShoppingFragment;
import com.example.zhubangshopingtest1.home.fragment.UserFragment;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.frameLayout)
FrameLayout frameLayout;
@BindView(R.id.rg_main)
RadioGroup rgMain;
private ArrayList<BaseFragment> fragments;
private int position = 0;
private Fragment tempFragemnt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
HideTitle(); //隐藏标题;
initFragment(); //初始化Fragment
initListener(); //监听切换
}
private void HideTitle() {
ActionBar actionbarr = getSupportActionBar();
if (actionbarr != null) {
actionbarr.hide();
} //隐藏标题;
}
private void initFragment() {
fragments = new ArrayList<>();
fragments.add(new HomeFragment());
fragments.add(new CircleFragment());
fragments.add(new ShoppingFragment());
fragments.add(new UserFragment());
}
private void initListener() {
rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_home:
position = 0;
break;
case R.id.rb_circle:
position = 1;
break;
case R.id.rb_cart:
position = 2;
break;
case R.id.rb_user:
position = 3;
break;
default:
position = 0; //如果都不是初始为0,及主页;
break;
}
/*根据位置取不同位置的fragment*/
BaseFragment baseFragment = getFragment(position);
/*切换fragment(上次显示的fragment,当前要显示的fragment)*/
switchFragment(tempFragemnt, baseFragment);
}
});
rgMain.check(R.id.rb_home); //设置默认加载项home为首页
}
/*根据位置得到对应的 Fragment*/
private BaseFragment getFragment(int position) {
if (fragments != null && fragments.size() > 0) {
BaseFragment baseFragment = fragments.get(position);
return baseFragment;
}
return null;
}
/*切换fragment,tempFragment 是缓存的fragment*/
private void switchFragment(Fragment fromFragment, BaseFragment nextFragment) {
if (tempFragemnt != nextFragment) {
tempFragemnt = nextFragment;
if (nextFragment != null) {
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
//判断 nextFragment 是否添加
if (!nextFragment.isAdded()) {
//隐藏当前 Fragment
if (fromFragment != null) {
transaction.hide(fromFragment);
}
transaction.add(R.id.frameLayout, nextFragment).commit();
} else {
//隐藏当前 Fragment
if (fromFragment != null) {
transaction.hide(fromFragment);
}
transaction.show(nextFragment).commit();
}
}
}
}
} |
package com.bjsxt.wsk.springbootjdbc.controller;
import com.bjsxt.wsk.springbootjdbc.pojo.Users;
import com.bjsxt.wsk.springbootjdbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UsersController {
@Autowired
private UserService usersService;
/**
* 添加用户
* @return
*/
@PostMapping("/addUser")
public String addUser(Users users){
try{
this.usersService.addUser(users);
}catch(Exception e){
e.printStackTrace();
return "error";
}
return "redirect:/ok";
}
/**
* 查询全部用户
* @param model
* @return
*/
@GetMapping("/findUserAll")
public String finUserAll(Model model){
List<Users> list = null;
try{
list = this.usersService.findUserAll();
model.addAttribute("list",list);
}catch (Exception e){
e.printStackTrace();
return "error";
}
return "showUser";
}
/**
* 预更新操作
* @param id
* @param model
* @return
*/
@GetMapping("preUpdateUser")
public String preUpdateUser(Integer id, Model model){
try {
Users users = this.usersService.findUserById(id);
model.addAttribute("users",users);
}catch (Exception e){
e.printStackTrace();
return "error";
}
return "updateUser";
}
/**
* 修改用户信息
* @param users
* @return
*/
@PostMapping("updateUser")
public String updateUser(Users users){
try{
this.usersService.modifyUser(users);
}catch (Exception e){
e.printStackTrace();
return "error";
}
return "redirect:/ok";
}
@GetMapping("deleteUser")
public String deleteUser(Integer id){
try{
this.usersService.dropUser(id);
}catch(Exception e){
e.printStackTrace();
return "error";
}
return "redirect:/ok";
}
}
|
package com.wuyan.masteryi.mall.service;
/*
*project:master-yi
*file:OrderService
*@author:wsn
*date:2021/7/6 15:38
*/
import java.util.Map;
public interface OrderService {
Map<String,Object> getOrdersByUID(int u_id);
Map<String,Object> getOrdersById(int order_id);
Map<String,Object> getOrderStatu(int order_id);
Map<String,Object> creatOrder(int[] goods,int[]num,float[] singlePrice,int u_id,int status,float price,String address);
String orderNoGen();
int delOrder(int order_id,String orderNo);
void stockChange(int []id,int[] num,String flag);
}
|
package com.company;
import java.util.Scanner;
import java.util.Random;
public class Number_Guessing_with_counting {
public static void main(String[] args) { //SORRRRRR???
Scanner scanner = new Scanner(System.in);
Random random= new Random();
int guess;
int tries=1;
int right=random.nextInt(10);
System.out.println("I have chosen a number between 1 and 10. Try to guess it.");
System.out.print("Your guess: ");
guess=scanner.nextInt();
tries++;
while(guess != right){
System.out.println("That is incorrect. Guess again.");
tries++;
System.out.print("Your guess: ");
guess=scanner.nextInt();
}
if(tries==right){
System.out.println("That's right! You're a good guesser.");
}
System.out.println("It only took you "+tries+" tries.");
}
}
|
package bnorm.robocode.robot;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import bnorm.robocode.robot.listener.BattleEndedEventListener;
import bnorm.robocode.robot.listener.BulletHitBulletEventListener;
import bnorm.robocode.robot.listener.BulletHitEventListener;
import bnorm.robocode.robot.listener.BulletMissedEventListener;
import bnorm.robocode.robot.listener.CustomEventListener;
import bnorm.robocode.robot.listener.DeathEventListener;
import bnorm.robocode.robot.listener.HitByBulletEventListener;
import bnorm.robocode.robot.listener.HitRobotEventListener;
import bnorm.robocode.robot.listener.HitWallEventListener;
import bnorm.robocode.robot.listener.KeyEventListener;
import bnorm.robocode.robot.listener.MessageEventListener;
import bnorm.robocode.robot.listener.MouseEventListener;
import bnorm.robocode.robot.listener.MouseWheelListener;
import bnorm.robocode.robot.listener.PaintListener;
import bnorm.robocode.robot.listener.RobocodeEventListener;
import bnorm.robocode.robot.listener.RobotDeathEventListener;
import bnorm.robocode.robot.listener.RoundEndedEventListener;
import bnorm.robocode.robot.listener.ScannedRobotEventListener;
import bnorm.robocode.robot.listener.SkippedTurnListener;
import bnorm.robocode.robot.listener.StatusEventListener;
import bnorm.robocode.robot.listener.WinEventListener;
import robocode.BattleEndedEvent;
import robocode.BulletHitBulletEvent;
import robocode.BulletHitEvent;
import robocode.BulletMissedEvent;
import robocode.CustomEvent;
import robocode.DeathEvent;
import robocode.HitByBulletEvent;
import robocode.HitRobotEvent;
import robocode.HitWallEvent;
import robocode.MessageEvent;
import robocode.RobotDeathEvent;
import robocode.RoundEndedEvent;
import robocode.ScannedRobotEvent;
import robocode.SkippedTurnEvent;
import robocode.StatusEvent;
import robocode.TeamRobot;
import robocode.WinEvent;
public class RegisterRobot extends TeamRobot {
private final List<BulletHitEventListener> bulletHitEventListeners;
private final List<BulletHitBulletEventListener> bulletHitBulletEventListeners;
private final List<BulletMissedEventListener> bulletMissedEventListeners;
private final List<HitByBulletEventListener> hitByBulletEventListeners;
private final List<HitRobotEventListener> hitRobotEventListeners;
private final List<HitWallEventListener> hitWallEventListeners;
private final List<RobotDeathEventListener> robotDeathEventListeners;
private final List<ScannedRobotEventListener> scannedRobotEventListeners;
private final List<WinEventListener> winEventListeners;
private final List<RoundEndedEventListener> roundEndedEventListeners;
private final List<BattleEndedEventListener> battleEndedEventListeners;
private final List<StatusEventListener> statusEventListeners;
private final List<MouseWheelListener> mouseWheelListeners;
private final List<MouseEventListener> mouseEventListeners;
private final List<KeyEventListener> keyEventListeners;
private final List<PaintListener> paintListeners;
private final List<DeathEventListener> deathEventListeners;
private final List<SkippedTurnListener> skippedTurnListeners;
private final List<CustomEventListener> customEventListeners;
private final List<MessageEventListener> messageEventListeners;
public RegisterRobot() {
this.bulletHitEventListeners = new ArrayList<>();
this.bulletHitBulletEventListeners = new ArrayList<>();
this.bulletMissedEventListeners = new ArrayList<>();
this.hitByBulletEventListeners = new ArrayList<>();
this.hitRobotEventListeners = new ArrayList<>();
this.hitWallEventListeners = new ArrayList<>();
this.robotDeathEventListeners = new ArrayList<>();
this.scannedRobotEventListeners = new ArrayList<>();
this.winEventListeners = new ArrayList<>();
this.roundEndedEventListeners = new ArrayList<>();
this.battleEndedEventListeners = new ArrayList<>();
this.statusEventListeners = new ArrayList<>();
this.mouseWheelListeners = new ArrayList<>();
this.mouseEventListeners = new ArrayList<>();
this.keyEventListeners = new ArrayList<>();
this.paintListeners = new ArrayList<>();
this.deathEventListeners = new ArrayList<>();
this.skippedTurnListeners = new ArrayList<>();
this.customEventListeners = new ArrayList<>();
this.messageEventListeners = new ArrayList<>();
}
public void register(RobocodeEventListener... listeners) {
register(Arrays.asList(listeners));
}
public void register(Iterable<? extends RobocodeEventListener> listeners) {
for (RobocodeEventListener listener : listeners) {
register(listener);
}
}
public void register(RobocodeEventListener listener) {
if (listener instanceof BulletHitEventListener) {
addBulletHitEventListener((BulletHitEventListener) listener);
}
if (listener instanceof BulletHitBulletEventListener) {
addBulletHitBulletEventListener((BulletHitBulletEventListener) listener);
}
if (listener instanceof BulletMissedEventListener) {
addBulletMissedEventListener((BulletMissedEventListener) listener);
}
if (listener instanceof HitByBulletEventListener) {
addHitByBulletEventListener((HitByBulletEventListener) listener);
}
if (listener instanceof HitRobotEventListener) {
addHitRobotEventListener((HitRobotEventListener) listener);
}
if (listener instanceof HitWallEventListener) {
addHitWallEventListener((HitWallEventListener) listener);
}
if (listener instanceof RobotDeathEventListener) {
addRobotDeathEventListener((RobotDeathEventListener) listener);
}
if (listener instanceof ScannedRobotEventListener) {
addScannedRobotEventListener((ScannedRobotEventListener) listener);
}
if (listener instanceof WinEventListener) {
addWinEventListener((WinEventListener) listener);
}
if (listener instanceof RoundEndedEventListener) {
addRoundEndedEventListener((RoundEndedEventListener) listener);
}
if (listener instanceof BattleEndedEventListener) {
addBattleEndedEventListener((BattleEndedEventListener) listener);
}
if (listener instanceof StatusEventListener) {
addStatusEventListener((StatusEventListener) listener);
}
if (listener instanceof MouseWheelListener) {
addMouseWheelListener((MouseWheelListener) listener);
}
if (listener instanceof MouseEventListener) {
addMouseEventListener((MouseEventListener) listener);
}
if (listener instanceof KeyEventListener) {
addKeyEventListener((KeyEventListener) listener);
}
if (listener instanceof PaintListener) {
addPaintListener((PaintListener) listener);
}
if (listener instanceof DeathEventListener) {
addDeathEventListener((DeathEventListener) listener);
}
if (listener instanceof SkippedTurnListener) {
addSkippedTurnListener((SkippedTurnListener) listener);
}
if (listener instanceof CustomEventListener) {
addCustomEventListener((CustomEventListener) listener);
}
if (listener instanceof MessageEventListener) {
addMessageEventListener((MessageEventListener) listener);
}
}
public boolean addBulletHitEventListener(BulletHitEventListener listener) {
return bulletHitEventListeners.add(listener);
}
public boolean removeBulletHitEventListener(BulletHitEventListener listener) {
return bulletHitEventListeners.remove(listener);
}
public boolean addBulletHitBulletEventListener(BulletHitBulletEventListener listener) {
return bulletHitBulletEventListeners.add(listener);
}
public boolean removeBulletHitBulletEventListener(BulletHitBulletEventListener listener) {
return bulletHitBulletEventListeners.remove(listener);
}
public boolean addBulletMissedEventListener(BulletMissedEventListener listener) {
return bulletMissedEventListeners.add(listener);
}
public boolean removeBulletMissedEventListener(BulletMissedEventListener listener) {
return bulletMissedEventListeners.remove(listener);
}
public boolean addHitByBulletEventListener(HitByBulletEventListener listener) {
return hitByBulletEventListeners.add(listener);
}
public boolean removeHitByBulletEventListener(HitByBulletEventListener listener) {
return hitByBulletEventListeners.remove(listener);
}
public boolean addHitRobotEventListener(HitRobotEventListener listener) {
return hitRobotEventListeners.add(listener);
}
public boolean removeHitRobotEventListener(HitRobotEventListener listener) {
return hitRobotEventListeners.remove(listener);
}
public boolean addHitWallEventListener(HitWallEventListener listener) {
return hitWallEventListeners.add(listener);
}
public boolean removeHitWallEventListener(HitWallEventListener listener) {
return hitWallEventListeners.remove(listener);
}
public boolean addRobotDeathEventListener(RobotDeathEventListener listener) {
return robotDeathEventListeners.add(listener);
}
public boolean removeRobotDeathEventListener(RobotDeathEventListener listener) {
return robotDeathEventListeners.remove(listener);
}
public boolean addScannedRobotEventListener(ScannedRobotEventListener listener) {
return scannedRobotEventListeners.add(listener);
}
public boolean removeScannedRobotEventListener(ScannedRobotEventListener listener) {
return scannedRobotEventListeners.remove(listener);
}
public boolean addWinEventListener(WinEventListener listener) {
return winEventListeners.add(listener);
}
public boolean removeWinEventListener(WinEventListener listener) {
return winEventListeners.remove(listener);
}
public boolean addRoundEndedEventListener(RoundEndedEventListener listener) {
return roundEndedEventListeners.add(listener);
}
public boolean removeRoundEndedEventListener(RoundEndedEventListener listener) {
return roundEndedEventListeners.remove(listener);
}
public boolean addBattleEndedEventListener(BattleEndedEventListener listener) {
return battleEndedEventListeners.add(listener);
}
public boolean removeBattleEndedEventListener(BattleEndedEventListener listener) {
return battleEndedEventListeners.remove(listener);
}
public boolean addStatusEventListener(StatusEventListener listener) {
return statusEventListeners.add(listener);
}
public boolean removeStatusEventListener(StatusEventListener listener) {
return statusEventListeners.remove(listener);
}
public boolean addMouseWheelListener(MouseWheelListener listener) {
return mouseWheelListeners.add(listener);
}
public boolean removeMouseWheelListener(MouseWheelListener listener) {
return mouseWheelListeners.remove(listener);
}
public boolean addMouseEventListener(MouseEventListener listener) {
return mouseEventListeners.add(listener);
}
public boolean removeMouseEventListener(MouseEventListener listener) {
return mouseEventListeners.remove(listener);
}
public boolean addKeyEventListener(KeyEventListener listener) {
return keyEventListeners.add(listener);
}
public boolean removeKeyEventListener(KeyEventListener listener) {
return keyEventListeners.remove(listener);
}
public boolean addPaintListener(PaintListener listener) {
return paintListeners.add(listener);
}
public boolean removePaintListener(PaintListener listener) {
return paintListeners.remove(listener);
}
public boolean addDeathEventListener(DeathEventListener listener) {
return deathEventListeners.add(listener);
}
public boolean removeDeathEventListener(DeathEventListener listener) {
return deathEventListeners.remove(listener);
}
public boolean addSkippedTurnListener(SkippedTurnListener listener) {
return skippedTurnListeners.add(listener);
}
public boolean removeSkippedTurnListener(SkippedTurnListener listener) {
return skippedTurnListeners.remove(listener);
}
public boolean addCustomEventListener(CustomEventListener listener) {
return customEventListeners.add(listener);
}
public boolean removeCustomEventListener(CustomEventListener listener) {
return customEventListeners.remove(listener);
}
public boolean addMessageEventListener(MessageEventListener listener) {
return messageEventListeners.add(listener);
}
public boolean removeMessageEventListener(MessageEventListener listener) {
return messageEventListeners.remove(listener);
}
@Override
public final void onBulletHit(BulletHitEvent event) {
for (BulletHitEventListener bulletHitEventListener : bulletHitEventListeners) {
bulletHitEventListener.onBulletHitEvent(event);
}
}
@Override
public final void onBulletHitBullet(BulletHitBulletEvent event) {
for (BulletHitBulletEventListener bulletHitBulletEventListener : bulletHitBulletEventListeners) {
bulletHitBulletEventListener.onBulletHitBulletEvent(event);
}
}
@Override
public final void onBulletMissed(BulletMissedEvent event) {
for (BulletMissedEventListener bulletMissedEventListener : bulletMissedEventListeners) {
bulletMissedEventListener.onBulletMissedEvent(event);
}
}
@Override
public final void onHitByBullet(HitByBulletEvent event) {
for (HitByBulletEventListener hitByBulletEventListener : hitByBulletEventListeners) {
hitByBulletEventListener.onHitByBulletEvent(event);
}
}
@Override
public final void onHitRobot(HitRobotEvent event) {
for (HitRobotEventListener hitRobotEventListener : hitRobotEventListeners) {
hitRobotEventListener.onHitRobotEvent(event);
}
}
@Override
public final void onHitWall(HitWallEvent event) {
for (HitWallEventListener hitWallEventListener : hitWallEventListeners) {
hitWallEventListener.onHitWallEvent(event);
}
}
@Override
public final void onRobotDeath(RobotDeathEvent event) {
for (RobotDeathEventListener robotDeathEventListener : robotDeathEventListeners) {
robotDeathEventListener.onRobotDeathEvent(event);
}
}
@Override
public final void onScannedRobot(ScannedRobotEvent event) {
for (ScannedRobotEventListener scannedRobotEventListener : scannedRobotEventListeners) {
scannedRobotEventListener.onScannedRobotEvent(event);
}
}
@Override
public final void onWin(WinEvent event) {
for (WinEventListener winEventListener : winEventListeners) {
winEventListener.onWinEvent(event);
}
}
@Override
public final void onRoundEnded(RoundEndedEvent event) {
for (RoundEndedEventListener roundEndedEventListener : roundEndedEventListeners) {
roundEndedEventListener.onRoundEndedEvent(event);
}
}
@Override
public final void onBattleEnded(BattleEndedEvent event) {
for (BattleEndedEventListener battleEndedEventListener : battleEndedEventListeners) {
battleEndedEventListener.onBattleEndedEvent(event);
}
}
@Override
public final void onStatus(StatusEvent e) {
for (StatusEventListener statusEventListener : statusEventListeners) {
statusEventListener.onStatusEvent(e);
}
}
@Override
public final void onMouseWheelMoved(MouseWheelEvent e) {
for (MouseWheelListener mouseWheelListener : mouseWheelListeners) {
mouseWheelListener.onMouseWheelEvent(e);
}
}
@Override
public final void onMouseDragged(MouseEvent e) {
for (MouseEventListener mouseEventListener : mouseEventListeners) {
mouseEventListener.onMouseEvent(e);
}
}
@Override
public final void onMouseMoved(MouseEvent e) {
for (MouseEventListener mouseEventListener : mouseEventListeners) {
mouseEventListener.onMouseEvent(e);
}
}
@Override
public final void onMouseReleased(MouseEvent e) {
for (MouseEventListener mouseEventListener : mouseEventListeners) {
mouseEventListener.onMouseEvent(e);
}
}
@Override
public final void onMousePressed(MouseEvent e) {
for (MouseEventListener mouseEventListener : mouseEventListeners) {
mouseEventListener.onMouseEvent(e);
}
}
@Override
public final void onMouseExited(MouseEvent e) {
for (MouseEventListener mouseEventListener : mouseEventListeners) {
mouseEventListener.onMouseEvent(e);
}
}
@Override
public final void onMouseEntered(MouseEvent e) {
for (MouseEventListener mouseEventListener : mouseEventListeners) {
mouseEventListener.onMouseEvent(e);
}
}
@Override
public final void onMouseClicked(MouseEvent e) {
for (MouseEventListener mouseEventListener : mouseEventListeners) {
mouseEventListener.onMouseEvent(e);
}
}
@Override
public final void onKeyTyped(KeyEvent e) {
for (KeyEventListener keyEventListener : keyEventListeners) {
keyEventListener.onKeyEvent(e);
}
}
@Override
public final void onKeyReleased(KeyEvent e) {
for (KeyEventListener keyEventListener : keyEventListeners) {
keyEventListener.onKeyEvent(e);
}
}
@Override
public final void onKeyPressed(KeyEvent e) {
for (KeyEventListener keyEventListener : keyEventListeners) {
keyEventListener.onKeyEvent(e);
}
}
@Override
public final void onPaint(Graphics2D g) {
for (PaintListener paintListener : paintListeners) {
paintListener.onPaint(g);
}
}
@Override
public final void onDeath(DeathEvent event) {
for (DeathEventListener deathEventListener : deathEventListeners) {
deathEventListener.onDeathEvent(event);
}
}
@Override
public final void onSkippedTurn(SkippedTurnEvent event) {
for (SkippedTurnListener skippedTurnListener : skippedTurnListeners) {
skippedTurnListener.onSkippedTurnEvent(event);
}
}
@Override
public final void onCustomEvent(CustomEvent event) {
for (CustomEventListener customEventListener : customEventListeners) {
customEventListener.onCustomEvent(event);
}
}
@Override
public final void onMessageReceived(MessageEvent event) {
for (MessageEventListener messageEventListener : messageEventListeners) {
messageEventListener.onMessageEvent(event);
}
}
}
|
package com.ncst.du;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
public class FirstTaskTestActivity extends AppCompatActivity {
private static final String TAG = "TASK_TEST";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_task_test);
Log.d(TAG, "onCreate: "+toString()+" "+getTaskId());
}
public void startSecond(View v){
Intent intent=new Intent(FirstTaskTestActivity.this,SecondTaskTestActivity.class);
startActivity(intent);
}
public void startFirst(View view){
Intent intent =new Intent(this,FirstTaskTestActivity.class);
startActivity(intent);
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: "+toString());
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: "+toString());
}
}
|
package com.example.easymodbus_project.service;
import com.example.easymodbus_project.model.Device;
import java.util.List;
import java.util.Optional;
public interface DeviceService {
Device findById(int id);
List<Device> findAll();
void save(Device device);
void delete(int id);
}
|
package com.facebook.react.views.scroll;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.u;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.OverScroller;
import android.widget.ScrollView;
import com.facebook.i.a.a;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.uimanager.MeasureSpecAssertions;
import com.facebook.react.uimanager.ReactClippingViewGroup;
import com.facebook.react.uimanager.ReactClippingViewGroupHelper;
import com.facebook.react.uimanager.events.NativeGestureUtil;
import com.facebook.react.views.view.ReactViewBackgroundManager;
import java.lang.reflect.Field;
public class ReactScrollView extends ScrollView implements View.OnLayoutChangeListener, ViewGroup.OnHierarchyChangeListener, ReactClippingViewGroup {
private static Field sScrollerField;
private static boolean sTriedToGetScrollerField;
private Rect mClippingRect;
private View mContentView;
public boolean mDoneFlinging;
private boolean mDragging;
private Drawable mEndBackground;
private int mEndFillColor = 0;
public boolean mFlinging;
private FpsListener mFpsListener = null;
private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper();
private ReactViewBackgroundManager mReactBackgroundManager;
private boolean mRemoveClippedSubviews;
private boolean mScrollEnabled = true;
private String mScrollPerfTag;
private final OverScroller mScroller;
private boolean mSendMomentumEvents;
private final VelocityHelper mVelocityHelper = new VelocityHelper();
public ReactScrollView(ReactContext paramReactContext) {
this(paramReactContext, (FpsListener)null);
}
public ReactScrollView(ReactContext paramReactContext, FpsListener paramFpsListener) {
super((Context)paramReactContext);
this.mFpsListener = paramFpsListener;
this.mReactBackgroundManager = new ReactViewBackgroundManager((View)this);
this.mScroller = getOverScrollerFromParent();
setOnHierarchyChangeListener(this);
setScrollBarStyle(33554432);
}
private void enableFpsListener() {
if (isScrollPerfLoggingEnabled()) {
a.b(this.mFpsListener);
a.b(this.mScrollPerfTag);
this.mFpsListener.enable(this.mScrollPerfTag);
}
}
private int getMaxScrollY() {
return Math.max(0, this.mContentView.getHeight() - getHeight() - getPaddingBottom() - getPaddingTop());
}
private OverScroller getOverScrollerFromParent() {
if (!sTriedToGetScrollerField) {
sTriedToGetScrollerField = true;
try {
Field field1 = ScrollView.class.getDeclaredField("mScroller");
sScrollerField = field1;
field1.setAccessible(true);
} catch (NoSuchFieldException noSuchFieldException) {}
}
Field field = sScrollerField;
if (field != null)
try {
Object object = field.get(this);
if (object instanceof OverScroller)
return (OverScroller)object;
} catch (IllegalAccessException illegalAccessException) {
throw new RuntimeException("Failed to get mScroller from ScrollView!", illegalAccessException);
}
return null;
}
private boolean isScrollPerfLoggingEnabled() {
if (this.mFpsListener != null) {
String str = this.mScrollPerfTag;
if (str != null && !str.isEmpty())
return true;
}
return false;
}
public void disableFpsListener() {
if (isScrollPerfLoggingEnabled()) {
a.b(this.mFpsListener);
a.b(this.mScrollPerfTag);
this.mFpsListener.disable(this.mScrollPerfTag);
}
}
public void draw(Canvas paramCanvas) {
if (this.mEndFillColor != 0) {
View view = getChildAt(0);
if (this.mEndBackground != null && view != null && view.getBottom() < getHeight()) {
this.mEndBackground.setBounds(0, view.getBottom(), getWidth(), getHeight());
this.mEndBackground.draw(paramCanvas);
}
}
super.draw(paramCanvas);
}
public void flashScrollIndicators() {
awakenScrollBars();
}
public void fling(int paramInt) {
if (this.mScroller != null) {
int i = getHeight();
int j = getPaddingBottom();
int k = getPaddingTop();
paramInt = (int)(Math.abs(paramInt) * Math.signum(this.mOnScrollDispatchHelper.getYFlingVelocity()));
this.mScroller.fling(getScrollX(), getScrollY(), 0, paramInt, 0, 0, 0, 2147483647, 0, (i - j - k) / 2);
u.d((View)this);
} else {
super.fling(paramInt);
}
if (this.mSendMomentumEvents || isScrollPerfLoggingEnabled()) {
this.mFlinging = true;
enableFpsListener();
ReactScrollViewHelper.emitScrollMomentumBeginEvent((ViewGroup)this, 0, paramInt);
u.a((View)this, new Runnable() {
public void run() {
if (ReactScrollView.this.mDoneFlinging) {
ReactScrollView reactScrollView1 = ReactScrollView.this;
reactScrollView1.mFlinging = false;
reactScrollView1.disableFpsListener();
ReactScrollViewHelper.emitScrollMomentumEndEvent((ViewGroup)ReactScrollView.this);
return;
}
ReactScrollView reactScrollView = ReactScrollView.this;
reactScrollView.mDoneFlinging = true;
u.a((View)reactScrollView, this, 20L);
}
}20L);
}
}
public void getClippingRect(Rect paramRect) {
paramRect.set((Rect)a.b(this.mClippingRect));
}
public boolean getRemoveClippedSubviews() {
return this.mRemoveClippedSubviews;
}
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (this.mRemoveClippedSubviews)
updateClippingRect();
}
public void onChildViewAdded(View paramView1, View paramView2) {
this.mContentView = paramView2;
this.mContentView.addOnLayoutChangeListener(this);
}
public void onChildViewRemoved(View paramView1, View paramView2) {
this.mContentView.removeOnLayoutChangeListener(this);
this.mContentView = null;
}
public boolean onInterceptTouchEvent(MotionEvent paramMotionEvent) {
if (!this.mScrollEnabled)
return false;
try {
if (super.onInterceptTouchEvent(paramMotionEvent)) {
NativeGestureUtil.notifyNativeGestureStarted((View)this, paramMotionEvent);
ReactScrollViewHelper.emitScrollBeginDragEvent((ViewGroup)this);
this.mDragging = true;
enableFpsListener();
return true;
}
return false;
} catch (IllegalArgumentException illegalArgumentException) {
return false;
}
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
scrollTo(getScrollX(), getScrollY());
}
public void onLayoutChange(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, int paramInt6, int paramInt7, int paramInt8) {
if (this.mContentView == null)
return;
paramInt1 = getScrollY();
paramInt2 = getMaxScrollY();
if (paramInt1 > paramInt2)
scrollTo(getScrollX(), paramInt2);
}
protected void onMeasure(int paramInt1, int paramInt2) {
MeasureSpecAssertions.assertExplicitMeasureSpec(paramInt1, paramInt2);
setMeasuredDimension(View.MeasureSpec.getSize(paramInt1), View.MeasureSpec.getSize(paramInt2));
}
protected void onOverScrolled(int paramInt1, int paramInt2, boolean paramBoolean1, boolean paramBoolean2) {
OverScroller overScroller = this.mScroller;
int i = paramInt2;
if (overScroller != null) {
i = paramInt2;
if (!overScroller.isFinished()) {
i = paramInt2;
if (this.mScroller.getCurrY() != this.mScroller.getFinalY()) {
int j = getMaxScrollY();
i = paramInt2;
if (paramInt2 >= j) {
this.mScroller.abortAnimation();
i = j;
}
}
}
}
super.onOverScrolled(paramInt1, i, paramBoolean1, paramBoolean2);
}
protected void onScrollChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
super.onScrollChanged(paramInt1, paramInt2, paramInt3, paramInt4);
if (this.mOnScrollDispatchHelper.onScrollChanged(paramInt1, paramInt2)) {
if (this.mRemoveClippedSubviews)
updateClippingRect();
if (this.mFlinging)
this.mDoneFlinging = false;
ReactScrollViewHelper.emitScrollEvent((ViewGroup)this, this.mOnScrollDispatchHelper.getXFlingVelocity(), this.mOnScrollDispatchHelper.getYFlingVelocity());
}
}
protected void onSizeChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
super.onSizeChanged(paramInt1, paramInt2, paramInt3, paramInt4);
if (this.mRemoveClippedSubviews)
updateClippingRect();
}
public boolean onTouchEvent(MotionEvent paramMotionEvent) {
if (!this.mScrollEnabled)
return false;
this.mVelocityHelper.calculateVelocity(paramMotionEvent);
if ((paramMotionEvent.getAction() & 0xFF) == 1 && this.mDragging) {
ReactScrollViewHelper.emitScrollEndDragEvent((ViewGroup)this, this.mVelocityHelper.getXVelocity(), this.mVelocityHelper.getYVelocity());
this.mDragging = false;
disableFpsListener();
}
return super.onTouchEvent(paramMotionEvent);
}
public void setBackgroundColor(int paramInt) {
this.mReactBackgroundManager.setBackgroundColor(paramInt);
}
public void setBorderColor(int paramInt, float paramFloat1, float paramFloat2) {
this.mReactBackgroundManager.setBorderColor(paramInt, paramFloat1, paramFloat2);
}
public void setBorderRadius(float paramFloat) {
this.mReactBackgroundManager.setBorderRadius(paramFloat);
}
public void setBorderRadius(float paramFloat, int paramInt) {
this.mReactBackgroundManager.setBorderRadius(paramFloat, paramInt);
}
public void setBorderStyle(String paramString) {
this.mReactBackgroundManager.setBorderStyle(paramString);
}
public void setBorderWidth(int paramInt, float paramFloat) {
this.mReactBackgroundManager.setBorderWidth(paramInt, paramFloat);
}
public void setEndFillColor(int paramInt) {
if (paramInt != this.mEndFillColor) {
this.mEndFillColor = paramInt;
this.mEndBackground = (Drawable)new ColorDrawable(this.mEndFillColor);
}
}
public void setRemoveClippedSubviews(boolean paramBoolean) {
if (paramBoolean && this.mClippingRect == null)
this.mClippingRect = new Rect();
this.mRemoveClippedSubviews = paramBoolean;
updateClippingRect();
}
public void setScrollEnabled(boolean paramBoolean) {
this.mScrollEnabled = paramBoolean;
}
public void setScrollPerfTag(String paramString) {
this.mScrollPerfTag = paramString;
}
public void setSendMomentumEvents(boolean paramBoolean) {
this.mSendMomentumEvents = paramBoolean;
}
public void updateClippingRect() {
if (!this.mRemoveClippedSubviews)
return;
a.b(this.mClippingRect);
ReactClippingViewGroupHelper.calculateClippingRect((View)this, this.mClippingRect);
View view = getChildAt(0);
if (view instanceof ReactClippingViewGroup)
((ReactClippingViewGroup)view).updateClippingRect();
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\scroll\ReactScrollView.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
public class Steward extends Personeelslid{
public Steward(String naam, int leeftijd, String adres) {
super(naam, leeftijd, adres);
}
}
|
package org.browsexml.timesheetjob.service;
import java.text.ParseException;
public interface Activate {
void setActivate(String activeId, String strCheck) throws ParseException;
}
|
package com.expidia.test;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import com.expidia.domain.HotelDeals;
import com.expidia.services.OffersService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
public class OffersServiceTest {
@Test
public void offersServiceTest() throws JsonParseException, JsonMappingException, IOException{
OffersService offersService = new OffersService();
assertNotNull(offersService.offersHotelList());
}
@Test
public void hotelJsonPareserTest() throws JsonParseException, JsonMappingException, IOException{
OffersService offersService = new OffersService();
HotelDeals hotelDeals = offersService.HotelJsonPareser();
assertNotNull(hotelDeals);
}
}
|
package com.snake.game;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Window extends JFrame{
private Scene myScene ;
public Window() {
initParts();
initWindow();
initListener();
this.setVisible(true);
}
private void initParts() {
myScene = new Scene();
}
private void initWindow() {
this.setTitle("SNAKE ... by Micky");
this.setSize(600,522);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setAlwaysOnTop(false);
this.setLocationRelativeTo(null);
this.add(myScene , BorderLayout.CENTER);
}
private void initListener() {
keyboardListener clavierListener = new keyboardListener();
this.addKeyListener(clavierListener);
}
class keyboardListener implements KeyListener{
public void keyPressed(KeyEvent event) {
//System.out.println("Code touche relâchée : " + event.getKeyCode() + " - caractère touche relâchée : " + event.getKeyChar());
}
public void keyReleased(KeyEvent event) {
if(event.getKeyCode() == 37) {
if(!(myScene.getSnakeDirection() == "E")) {
myScene.setSnakeDirection("O");
}
}
else if (event.getKeyCode() == 38) {
if(!(myScene.getSnakeDirection() == "S")) {
myScene.setSnakeDirection("N");
}
}
else if (event.getKeyCode() == 39) {
if(!(myScene.getSnakeDirection() == "O")) {
myScene.setSnakeDirection("E");
}
}
else {
if(!(myScene.getSnakeDirection() == "N")) {
myScene.setSnakeDirection("S");
}
}
}
public void keyTyped(KeyEvent event) {}
}
}
|
package com.github.emailtohl.integration.core.role;
import static com.github.emailtohl.integration.core.role.Authority.AUDIT_ROLE;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import com.github.emailtohl.lib.jpa.AuditedRepository.RevTuple;
/**
* 审计角色的历史记录
* @author HeLei
*/
@PreAuthorize("hasAuthority('" + AUDIT_ROLE + "')")
public interface RoleAuditedService {
/**
* 查询角色所有的历史记录
* @param id 角色
* @return 元组列表,元组中包含版本详情,实体在该版本时的状态以及该版本的操作(增、改、删)
*/
List<RevTuple<Role>> getRoleRevision(Long id);
/**
* 查询角色在某个修订版时的历史记录
* @param id 角色id
* @param revision 版本号,通过AuditReader#getRevisions(Employee.class, ID)获得
* @return
*/
Role getRoleAtRevision(Long id, Number revision);
}
|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package tests;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
/**
*
* A generator for jmods, jars and images.
*/
public class JImageGenerator {
public static final String LOAD_ALL_CLASSES_TEMPLATE = "package PACKAGE;\n"
+ "\n"
+ "import java.net.URI;\n"
+ "import java.nio.file.FileSystems;\n"
+ "import java.nio.file.Files;\n"
+ "import java.nio.file.Path;\n"
+ "import java.util.function.Function;\n"
+ "\n"
+ "public class CLASS {\n"
+ " private static long total_time;\n"
+ " private static long num_classes;\n"
+ " public static void main(String[] args) throws Exception {\n"
+ " Function<Path, String> formatter = (path) -> {\n"
+ " String clazz = path.toString().substring(\"modules/\".length()+1, path.toString().lastIndexOf(\".\"));\n"
+ " clazz = clazz.substring(clazz.indexOf(\"/\") + 1);\n"
+ " return clazz.replaceAll(\"/\", \"\\\\.\");\n"
+ " };\n"
+ " Files.walk(FileSystems.getFileSystem(URI.create(\"jrt:/\")).getPath(\"/modules/\")).\n"
+ " filter((p) -> {\n"
+ " return Files.isRegularFile(p) && p.toString().endsWith(\".class\")\n"
+ " && !p.toString().endsWith(\"module-info.class\");\n"
+ " }).\n"
+ " map(formatter).forEach((clazz) -> {\n"
+ " try {\n"
+ " long t = System.currentTimeMillis();\n"
+ " Class.forName(clazz, false, Thread.currentThread().getContextClassLoader());\n"
+ " total_time+= System.currentTimeMillis()-t;\n"
+ " num_classes+=1;\n"
+ " } catch (IllegalAccessError ex) {\n"
+ " // Security exceptions can occur, this is not what we are testing\n"
+ " System.err.println(\"Access error, OK \" + clazz);\n"
+ " } catch (Exception ex) {\n"
+ " System.err.println(\"ERROR \" + clazz);\n"
+ " throw new RuntimeException(ex);\n"
+ " }\n"
+ " });\n"
+ " double res = (double) total_time / num_classes;\n"
+ " // System.out.println(\"Total time \" + total_time + \" num classes \" + num_classes + \" average \" + res);\n"
+ " }\n"
+ "}\n";
private static final String OUTPUT_OPTION = "--output";
private static final String POST_PROCESS_OPTION = "--post-process-path";
private static final String MAIN_CLASS_OPTION = "--main-class";
private static final String CLASS_PATH_OPTION = "--class-path";
private static final String MODULE_PATH_OPTION = "--module-path";
private static final String ADD_MODULES_OPTION = "--add-modules";
private static final String LIMIT_MODULES_OPTION = "--limit-modules";
private static final String PLUGIN_MODULE_PATH = "--plugin-module-path";
private static final String LAUNCHER = "--launcher";
private static final String CMDS_OPTION = "--cmds";
private static final String CONFIG_OPTION = "--config";
private static final String HASH_MODULES_OPTION = "--hash-modules";
private static final String LIBS_OPTION = "--libs";
private static final String MODULE_VERSION_OPTION = "--module-version";
private JImageGenerator() {}
private static String optionsPrettyPrint(String... args) {
return Stream.of(args).collect(Collectors.joining(" "));
}
public static File getJModsDir(File jdkHome) {
File jdkjmods = new File(jdkHome, "jmods");
if (!jdkjmods.exists()) {
return null;
}
return jdkjmods;
}
public static Path addFiles(Path module, InMemoryFile... resources) throws IOException {
Path tempFile = Files.createTempFile("jlink-test", "");
try (JarInputStream in = new JarInputStream(Files.newInputStream(module));
JarOutputStream out = new JarOutputStream(new FileOutputStream(tempFile.toFile()))) {
ZipEntry entry;
while ((entry = in.getNextEntry()) != null) {
String name = entry.getName();
out.putNextEntry(new ZipEntry(name));
copy(in, out);
out.closeEntry();
}
for (InMemoryFile r : resources) {
addFile(r, out);
}
}
Files.move(tempFile, module, StandardCopyOption.REPLACE_EXISTING);
return module;
}
private static void copy(InputStream in, OutputStream out) throws IOException {
int len;
byte[] buf = new byte[4096];
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
public static JModTask getJModTask() {
return new JModTask();
}
public static JLinkTask getJLinkTask() {
return new JLinkTask();
}
public static JImageTask getJImageTask() {
return new JImageTask();
}
private static void addFile(InMemoryFile resource, JarOutputStream target) throws IOException {
String fileName = resource.getPath();
fileName = fileName.replace("\\", "/");
String[] ss = fileName.split("/");
Path p = Paths.get("");
for (int i = 0; i < ss.length; ++i) {
if (i < ss.length - 1) {
if (!ss[i].isEmpty()) {
p = p.resolve(ss[i]);
JarEntry entry = new JarEntry(p.toString() + "/");
target.putNextEntry(entry);
target.closeEntry();
}
} else {
p = p.resolve(ss[i]);
JarEntry entry = new JarEntry(p.toString());
target.putNextEntry(entry);
copy(resource.getBytes(), target);
target.closeEntry();
}
}
}
public static Path createNewFile(Path root, String pathName, String extension) {
Path out = root.resolve(pathName + extension);
int i = 1;
while (Files.exists(out)) {
out = root.resolve(pathName + "-" + (++i) + extension);
}
return out;
}
public static Path generateSources(Path output, String moduleName, List<InMemorySourceFile> sources) throws IOException {
Path moduleDir = output.resolve(moduleName);
Files.createDirectory(moduleDir);
for (InMemorySourceFile source : sources) {
Path fileDir = moduleDir;
if (!source.packageName.isEmpty()) {
String dir = source.packageName.replace('.', File.separatorChar);
fileDir = moduleDir.resolve(dir);
Files.createDirectories(fileDir);
}
Files.write(fileDir.resolve(source.className + ".java"), source.source.getBytes());
}
return moduleDir;
}
public static Path generateSourcesFromTemplate(Path output, String moduleName, String... classNames) throws IOException {
List<InMemorySourceFile> sources = new ArrayList<>();
for (String className : classNames) {
String packageName = getPackageName(className);
String simpleName = getSimpleName(className);
String content = LOAD_ALL_CLASSES_TEMPLATE
.replace("CLASS", simpleName);
if (packageName.isEmpty()) {
content = content.replace("package PACKAGE;", packageName);
} else {
content = content.replace("PACKAGE", packageName);
}
sources.add(new InMemorySourceFile(packageName, simpleName, content));
}
return generateSources(output, moduleName, sources);
}
public static void generateModuleInfo(Path moduleDir, List<String> packages, String... dependencies) throws IOException {
StringBuilder moduleInfoBuilder = new StringBuilder();
Path file = moduleDir.resolve("module-info.java");
String moduleName = moduleDir.getFileName().toString();
moduleInfoBuilder.append("module ").append(moduleName).append("{\n");
for (String dep : dependencies) {
moduleInfoBuilder.append("requires ").append(dep).append(";\n");
}
for (String pkg : packages) {
if (!pkg.trim().isEmpty()) {
moduleInfoBuilder.append("exports ").append(pkg).append(";\n");
}
}
moduleInfoBuilder.append("}");
Files.write(file, moduleInfoBuilder.toString().getBytes());
}
public static void compileSuccess(Path source, Path destination, String... options) throws IOException {
if (!compile(source, destination, options)) {
throw new AssertionError("Compilation failed.");
}
}
public static boolean compile(Path source, Path destination, String... options) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null)) {
List<Path> sources
= Files.find(source, Integer.MAX_VALUE,
(file, attrs) -> file.toString().endsWith(".java"))
.collect(Collectors.toList());
Files.createDirectories(destination);
jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singleton(destination));
List<String> opts = Arrays.asList(options);
JavaCompiler.CompilationTask task
= compiler.getTask(null, jfm, null, opts, null,
jfm.getJavaFileObjectsFromPaths(sources));
List<String> list = new ArrayList<>(opts);
list.addAll(sources.stream()
.map(Path::toString)
.collect(Collectors.toList()));
System.err.println("javac options: " + optionsPrettyPrint(list.toArray(new String[list.size()])));
return task.call();
}
}
public static Path createJarFile(Path jarfile, Path dir) throws IOException {
return createJarFile(jarfile, dir, Paths.get("."));
}
public static Path createJarFile(Path jarfile, Path dir, Path file) throws IOException {
// create the target directory
Path parent = jarfile.getParent();
if (parent != null)
Files.createDirectories(parent);
List<Path> entries = Files.find(dir.resolve(file), Integer.MAX_VALUE,
(p, attrs) -> attrs.isRegularFile())
.map(dir::relativize)
.collect(Collectors.toList());
try (OutputStream out = Files.newOutputStream(jarfile);
JarOutputStream jos = new JarOutputStream(out)) {
for (Path entry : entries) {
// map the file path to a name in the JAR file
Path normalized = entry.normalize();
String name = normalized
.subpath(0, normalized.getNameCount()) // drop root
.toString()
.replace(File.separatorChar, '/');
jos.putNextEntry(new JarEntry(name));
Files.copy(dir.resolve(entry), jos);
}
}
return jarfile;
}
public static Set<String> getModuleContent(Path module) {
Result result = JImageGenerator.getJModTask()
.jmod(module)
.list();
result.assertSuccess();
return Stream.of(result.getMessage().split("\r?\n"))
.collect(Collectors.toSet());
}
public static void checkModule(Path module, Set<String> expected) throws IOException {
Set<String> actual = getModuleContent(module);
if (!Objects.equals(actual, expected)) {
Set<String> unexpected = new HashSet<>(actual);
unexpected.removeAll(expected);
Set<String> notFound = new HashSet<>(expected);
notFound.removeAll(actual);
System.err.println("Unexpected files:");
unexpected.forEach(s -> System.err.println("\t" + s));
System.err.println("Not found files:");
notFound.forEach(s -> System.err.println("\t" + s));
throw new AssertionError("Module check failed.");
}
}
public static class JModTask {
static final java.util.spi.ToolProvider JMOD_TOOL =
java.util.spi.ToolProvider.findFirst("jmod").orElseThrow(() ->
new RuntimeException("jmod tool not found")
);
private final List<Path> classpath = new ArrayList<>();
private final List<Path> libs = new ArrayList<>();
private final List<Path> cmds = new ArrayList<>();
private final List<Path> config = new ArrayList<>();
private final List<Path> jars = new ArrayList<>();
private final List<Path> jmods = new ArrayList<>();
private final List<String> options = new ArrayList<>();
private Path output;
private String hashModules;
private String mainClass;
private String moduleVersion;
public JModTask addNativeLibraries(Path cp) {
this.libs.add(cp);
return this;
}
public JModTask hashModules(String hash) {
this.hashModules = hash;
return this;
}
public JModTask addCmds(Path cp) {
this.cmds.add(cp);
return this;
}
public JModTask addClassPath(Path cp) {
this.classpath.add(cp);
return this;
}
public JModTask addConfig(Path cp) {
this.config.add(cp);
return this;
}
public JModTask addJars(Path jars) {
this.jars.add(jars);
return this;
}
public JModTask addJmods(Path jmods) {
this.jmods.add(jmods);
return this;
}
public JModTask jmod(Path output) {
this.output = output;
return this;
}
public JModTask moduleVersion(String moduleVersion) {
this.moduleVersion = moduleVersion;
return this;
}
public JModTask mainClass(String mainClass) {
this.mainClass = mainClass;
return this;
}
public JModTask option(String o) {
this.options.add(o);
return this;
}
private String modulePath() {
// This is expect FIRST jmods THEN jars, if you change this, some tests could fail
String jmods = toPath(this.jmods);
String jars = toPath(this.jars);
return jmods + File.pathSeparator + jars;
}
private String toPath(List<Path> paths) {
return paths.stream()
.map(Path::toString)
.collect(Collectors.joining(File.pathSeparator));
}
private String[] optionsJMod(String cmd) {
List<String> options = new ArrayList<>();
options.add(cmd);
if (!cmds.isEmpty()) {
options.add(CMDS_OPTION);
options.add(toPath(cmds));
}
if (!config.isEmpty()) {
options.add(CONFIG_OPTION);
options.add(toPath(config));
}
if (hashModules != null) {
options.add(HASH_MODULES_OPTION);
options.add(hashModules);
}
if (mainClass != null) {
options.add(MAIN_CLASS_OPTION);
options.add(mainClass);
}
if (!libs.isEmpty()) {
options.add(LIBS_OPTION);
options.add(toPath(libs));
}
if (!classpath.isEmpty()) {
options.add(CLASS_PATH_OPTION);
options.add(toPath(classpath));
}
if (!jars.isEmpty() || !jmods.isEmpty()) {
options.add(MODULE_PATH_OPTION);
options.add(modulePath());
}
if (moduleVersion != null) {
options.add(MODULE_VERSION_OPTION);
options.add(moduleVersion);
}
options.addAll(this.options);
if (output != null) {
options.add(output.toString());
}
return options.toArray(new String[options.size()]);
}
public Result create() {
return cmd("create");
}
public Result list() {
return cmd("list");
}
public Result call() {
return cmd("");
}
private Result cmd(String cmd) {
String[] args = optionsJMod(cmd);
System.err.println("jmod options: " + optionsPrettyPrint(args));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
int exitCode = JMOD_TOOL.run(ps, ps, args);
String msg = new String(baos.toByteArray());
return new Result(exitCode, msg, output);
}
}
public static String getPackageName(String canonicalName) {
int index = canonicalName.lastIndexOf('.');
return index > 0 ? canonicalName.substring(0, index) : "";
}
public static String getSimpleName(String canonicalName) {
int index = canonicalName.lastIndexOf('.');
return canonicalName.substring(index + 1);
}
public static class JImageTask {
private final List<Path> pluginModulePath = new ArrayList<>();
private final List<String> options = new ArrayList<>();
private Path dir;
private Path image;
public JImageTask pluginModulePath(Path p) {
this.pluginModulePath.add(p);
return this;
}
public JImageTask image(Path image) {
this.image = image;
return this;
}
public JImageTask dir(Path dir) {
this.dir = dir;
return this;
}
public JImageTask option(String o) {
this.options.add(o);
return this;
}
private String toPath(List<Path> paths) {
return paths.stream()
.map(Path::toString)
.collect(Collectors.joining(File.pathSeparator));
}
private String[] optionsJImage(String cmd) {
List<String> options = new ArrayList<>();
options.add(cmd);
if (dir != null) {
options.add("--dir");
options.add(dir.toString());
}
if (!pluginModulePath.isEmpty()) {
options.add(PLUGIN_MODULE_PATH);
options.add(toPath(pluginModulePath));
}
options.addAll(this.options);
options.add(image.toString());
return options.toArray(new String[options.size()]);
}
private Result cmd(String cmd, Path returnPath) {
String[] args = optionsJImage(cmd);
System.err.println("jimage options: " + optionsPrettyPrint(args));
StringWriter writer = new StringWriter();
int exitCode = jdk.tools.jimage.Main.run(args, new PrintWriter(writer));
return new Result(exitCode, writer.toString(), returnPath);
}
public Result extract() {
return cmd("extract", dir);
}
}
public static class JLinkTask {
static final java.util.spi.ToolProvider JLINK_TOOL =
java.util.spi.ToolProvider.findFirst("jlink").orElseThrow(() ->
new RuntimeException("jlink tool not found")
);
private final List<Path> jars = new ArrayList<>();
private final List<Path> jmods = new ArrayList<>();
private final List<Path> pluginModulePath = new ArrayList<>();
private final List<String> addMods = new ArrayList<>();
private final List<String> limitMods = new ArrayList<>();
private final List<String> options = new ArrayList<>();
private String modulePath;
// if you want to specifiy repeated --module-path option
private String repeatedModulePath;
// if you want to specifiy repeated --limit-modules option
private String repeatedLimitMods;
private Path output;
private Path existing;
private String launcher; // optional
public JLinkTask modulePath(String modulePath) {
this.modulePath = modulePath;
return this;
}
public JLinkTask launcher(String cmd) {
launcher = Objects.requireNonNull(cmd);
return this;
}
public JLinkTask repeatedModulePath(String modulePath) {
this.repeatedModulePath = modulePath;
return this;
}
public JLinkTask addJars(Path jars) {
this.jars.add(jars);
return this;
}
public JLinkTask addJmods(Path jmods) {
this.jmods.add(jmods);
return this;
}
public JLinkTask pluginModulePath(Path p) {
this.pluginModulePath.add(p);
return this;
}
public JLinkTask addMods(String moduleName) {
this.addMods.add(moduleName);
return this;
}
public JLinkTask limitMods(String moduleName) {
this.limitMods.add(moduleName);
return this;
}
public JLinkTask repeatedLimitMods(String modules) {
this.repeatedLimitMods = modules;
return this;
}
public JLinkTask output(Path output) {
this.output = output;
return this;
}
public JLinkTask existing(Path existing) {
this.existing = existing;
return this;
}
public JLinkTask option(String o) {
this.options.add(o);
return this;
}
private String modulePath() {
// This is expect FIRST jmods THEN jars, if you change this, some tests could fail
String jmods = toPath(this.jmods);
String jars = toPath(this.jars);
return jmods + File.pathSeparator + jars;
}
private String toPath(List<Path> paths) {
return paths.stream()
.map(Path::toString)
.collect(Collectors.joining(File.pathSeparator));
}
private String[] optionsJLink() {
List<String> options = new ArrayList<>();
if (output != null) {
options.add(OUTPUT_OPTION);
options.add(output.toString());
}
if (!addMods.isEmpty()) {
options.add(ADD_MODULES_OPTION);
options.add(addMods.stream().collect(Collectors.joining(",")));
}
if (!limitMods.isEmpty()) {
options.add(LIMIT_MODULES_OPTION);
options.add(limitMods.stream().collect(Collectors.joining(",")));
}
if (repeatedLimitMods != null) {
options.add(LIMIT_MODULES_OPTION);
options.add(repeatedLimitMods);
}
if (!jars.isEmpty() || !jmods.isEmpty()) {
options.add(MODULE_PATH_OPTION);
options.add(modulePath());
}
if (modulePath != null) {
options.add(MODULE_PATH_OPTION);
options.add(modulePath);
}
if (repeatedModulePath != null) {
options.add(MODULE_PATH_OPTION);
options.add(repeatedModulePath);
}
if (!pluginModulePath.isEmpty()) {
options.add(PLUGIN_MODULE_PATH);
options.add(toPath(pluginModulePath));
}
if (launcher != null && !launcher.isEmpty()) {
options.add(LAUNCHER);
options.add(launcher);
}
options.addAll(this.options);
return options.toArray(new String[options.size()]);
}
private String[] optionsPostProcessJLink() {
List<String> options = new ArrayList<>();
if (existing != null) {
options.add(POST_PROCESS_OPTION);
options.add(existing.toString());
}
options.addAll(this.options);
return options.toArray(new String[options.size()]);
}
public Result call() {
String[] args = optionsJLink();
System.err.println("jlink options: " + optionsPrettyPrint(args));
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
int exitCode = JLINK_TOOL.run(pw, pw, args);
return new Result(exitCode, writer.toString(), output);
}
public Result callPostProcess() {
String[] args = optionsPostProcessJLink();
System.err.println("jlink options: " + optionsPrettyPrint(args));
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
int exitCode = JLINK_TOOL.run(pw, pw, args);
return new Result(exitCode, writer.toString(), output);
}
}
public static class InMemorySourceFile {
public final String packageName;
public final String className;
public final String source;
public InMemorySourceFile(String packageName, String simpleName, String source) {
this.packageName = packageName;
this.className = simpleName;
this.source = source;
}
}
public static class InMemoryFile {
private final String path;
private final byte[] bytes;
public String getPath() {
return path;
}
public InputStream getBytes() {
return new ByteArrayInputStream(bytes);
}
public InMemoryFile(String path, byte[] bytes) {
this.path = path;
this.bytes = bytes;
}
public InMemoryFile(String path, InputStream is) throws IOException {
this(path, readAllBytes(is));
}
}
public static byte[] readAllBytes(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
while (true) {
int n = is.read(buf);
if (n < 0) {
break;
}
baos.write(buf, 0, n);
}
return baos.toByteArray();
}
}
|
package com.example.shami.moviedb.Fragments;
/**
* Created by Shami on 2/10/2017.
*/
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.shami.moviedb.Adapters.ReviewsAdapter;
import com.example.shami.moviedb.Adapters.TrailersAdapter;
import com.example.shami.moviedb.Data.MovieContract;
import com.example.shami.moviedb.Data.ReviewsData;
import com.example.shami.moviedb.Data.TrailerData;
import com.example.shami.moviedb.Loaders.reviewsloader;
import com.example.shami.moviedb.Loaders.trailerLoader;
import com.example.shami.moviedb.R;
import com.example.shami.moviedb.Utilities.MovieUtil;
import com.squareup.picasso.Picasso;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class fragmentDetail extends Fragment {
public static final String Log_Tag="[DM]Shami "+fragmentDetail.class.getSimpleName();
TextView title;
TextView year;
TextView ratings;
TextView overView;
ImageView poster;
Button markfavourite;
ListView trailer;
ListView reviews;
TrailersAdapter T_adapter;
ReviewsAdapter R_adapter;
// public static String[] movieData;
ArrayList<String> movieDataList;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View DetialView=inflater.inflate(R.layout.fragmentdetail,container,false);
movieDataList = getArguments().getStringArrayList("movieData");
title=(TextView)DetialView.findViewById(R.id.txtTitle);
year=(TextView)DetialView.findViewById(R.id.txtyear);
ratings=(TextView)DetialView.findViewById(R.id.txtratings);
overView=(TextView)DetialView.findViewById(R.id.txtoverview);
poster=(ImageView)DetialView.findViewById(R.id.thumbnail);
poster.setDrawingCacheEnabled(true);
poster.buildDrawingCache();
trailer=(ListView)DetialView.findViewById(R.id.trialerslist);
reviews=(ListView)DetialView.findViewById(R.id.reviewlist);
T_adapter=new TrailersAdapter(getActivity(),new ArrayList<TrailerData>());
R_adapter=new ReviewsAdapter(getActivity(),new ArrayList<ReviewsData>());
trailer.setAdapter(T_adapter);
reviews.setAdapter(R_adapter);
markfavourite=(Button)DetialView.findViewById(R.id.favouritebtn);
title.setText(movieDataList.get(1));
year.setText(movieDataList.get(3));
overView.setText(movieDataList.get(4));
ratings.setText(movieDataList.get(5));
Picasso.with(getActivity()).load("http://image.tmdb.org/t/p/w500/"+movieDataList.get(2)).into(poster);
trailer.setAdapter(T_adapter);
reviews.setAdapter(R_adapter);
trailer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
TrailerData currentTrailer=T_adapter.getItem(position);
String url="https://www.youtube.com/watch?v="+currentTrailer.getTrailer_source();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
reviews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
ReviewsData currentreview=R_adapter.getItem(position);
///Will code it later
}
});
markfavourite=(Button)DetialView.findViewById(R.id.favouritebtn);
markfavourite.setOnClickListener(new AdapterView.OnClickListener() {
@Override
public void onClick(View view) {
MarkFavourite();
markfavourite.setText("Unmark");
}
});
new loadTrailer().TrigerLoader();
new LoadReviews().TrigerLoader();
return DetialView;
}
public void MarkFavourite()
{
byte[] poster=ImagetoByte();
ContentValues values=new ContentValues();
values.put(MovieContract.MoviesData.mid,movieDataList.get(0));
values.put(MovieContract.MoviesData.mtitle,movieDataList.get(1));
values.put(MovieContract.MoviesData.mposter,poster);
values.put(MovieContract.MoviesData.mreleaseDate,movieDataList.get(3));
values.put(MovieContract.MoviesData.moverview,movieDataList.get(4));
values.put(MovieContract.MoviesData.muser_ratings,movieDataList.get(5));
Uri uri =getActivity().getContentResolver().insert(MovieContract.MoviesData.Content_Uri,values);
Log.v(Log_Tag,"The Record with "+ ContentUris.parseId(uri)+" has been saved");
}
public byte[] ImagetoByte()
{
Bitmap b=poster.getDrawingCache() ;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] img = bos.toByteArray();
return img;
}
public class loadTrailer implements LoaderManager.LoaderCallbacks<List<TrailerData>>
{
public void TrigerLoader()
{
getActivity().getSupportLoaderManager().initLoader(0,null,this);
}
@Override
public Loader<List<TrailerData>> onCreateLoader(int id, Bundle args) {
String api="ded925ce33137ca8ee5927b65bdb26db";
URL uri= MovieUtil.crateUrl("http://api.themoviedb.org/3/movie/"+movieDataList.get(0)+"/trailers?",api);
return new trailerLoader(getActivity(),uri);
}
@Override
public void onLoadFinished(Loader<List<TrailerData>> loader, List<TrailerData> data) {
T_adapter.clear();
if (data != null && !data.isEmpty()) {
T_adapter.addAll(data);
Log.v(Log_Tag,"The size of Data is "+data.size());
}
}
@Override
public void onLoaderReset(Loader<List<TrailerData>> loader) {
T_adapter.clear();
}
}
public class LoadReviews implements LoaderManager.LoaderCallbacks<List<ReviewsData>>
{
public void TrigerLoader()
{
getActivity().getSupportLoaderManager().initLoader(1,null,this);
}
@Override
public Loader<List<ReviewsData>> onCreateLoader(int id, Bundle args) {
String api="ded925ce33137ca8ee5927b65bdb26db";
URL uri=MovieUtil.crateUrl("http://api.themoviedb.org/3/movie/"+movieDataList.get(0)+"/reviews?",api);
return new reviewsloader(getActivity(),uri);
}
@Override
public void onLoadFinished(Loader<List<ReviewsData>> loader, List<ReviewsData> data) {
R_adapter.clear();
if(data!=null&&!data.isEmpty())
{
R_adapter.addAll(data);
}
}
@Override
public void onLoaderReset(Loader<List<ReviewsData>> loader) {
R_adapter.clear();
}
}
}
|
package com.github.marenwynn.waypoints.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.Action;
import com.github.marenwynn.waypoints.WaypointManager;
import com.github.marenwynn.waypoints.data.PlayerData;
public class BeaconUseEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
private Player p;
private Action a;
public BeaconUseEvent(Player p, Action a) {
this.p = p;
this.a = a;
}
public Player getPlayer() {
return p;
}
public PlayerData getPlayerData() {
return WaypointManager.getManager().getPlayerData(p.getUniqueId());
}
public Action getAction() {
return a;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
|
// Sun Certified Java Programmer
// Chapter 2, P131
// Object Orientation
class Foo {
Foo() {
} // The constructor for the Foo class
int size;
String name;
Foo(String name, int size) {
this.name = name;
this.size = size;
}
}
|
package solution;
/**
* User: jieyu
* Date: 6/19/16.
*/
public class BulbSwitcher319 {
public int bulbSwitch(int n) {
if (n == 0) return 0;
int i = 2;
while (n >= Math.pow(i, 2)) {
i++;
}
return i - 1;
}
public int bulbSwitch2(int n) {
return (int)Math.sqrt(n);
}
public static void main(String[] args) {
BulbSwitcher319 bs = new BulbSwitcher319();
bs.bulbSwitch(99999);
}
}
|
package com.example.administrator.utils;
import android.os.Looper;
/**
* Created by Administrator on 2017/8/25.
*/
public final class Utils {
private Utils(){}
public static void checkNotMain() {
if(isMain()) {
throw new IllegalStateException("Method call should not happen from the main thread.");
}
}
static void checkMain() {
if(!isMain()) {
throw new IllegalStateException("Method call should happen from the main thread.");
}
}
static boolean isMain() {
return Looper.getMainLooper().getThread() == Thread.currentThread();
}
}
|
package chap09.sec05.exam01_anonymous_extends;
public class AnonymousExample {
public static void main(String[] args) {
Anonymous a = new Anonymous();
a.field.wake();
System.out.println("----------------");
a.method1();
System.out.println("----------------");
// 매개변수에 익명자식객체도 넣을 수 있다.
a.method2(new Person() {
void work() {
System.out.println("여전히 출근합니다.");
}
@Override
void wake() {
System.out.println("또 7시에 일어납니다.");
work();
}
});
}
}
|
package com.java.smart_garage.contracts.repoContracts;
import com.java.smart_garage.models.WorkService;
import java.util.List;
import java.util.Optional;
public interface WorkServiceRepository {
List<WorkService> getAllWorkServices();
WorkService getById(int id);
WorkService getByName(String name);
WorkService create(WorkService service);
WorkService update(WorkService service);
void delete(int id);
List<WorkService> filterWorkServicesByNameAndPrice(Optional<String> name,
Optional<Double> price);
}
|
/**
*
*/
package com.goodhealth.design.demo.DecorativePattern;
/**
* @author 24663
* @date 2018年10月27日
* @Description
*/
public class MyStore extends IStore {
/* (non-Javadoc)
* @see CommandPattern.DecorativePattern.IStore#selll()
*/
@Override
public void sell() {
// TODO Auto-generated method stub
System.out.println("店里卖衣服");
}
}
|
package com.springhibernatedemo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AppDAO {
@Autowired
SessionFactory sessionFactory;
public void saveStudent(Student student) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(student);
System.out.println("student data saved");
}
}
|
package fr.umlv.escape.front;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Class that an explosion sprite
*/
public class SpriteAnimation extends Sprite{
private int currentImage;
private long lastImageChange;
private final int speed;
private boolean isGrowing;
private final int x;
private final int y;
/**
* constructor
* @param speed the speed of the sprite
* @param x the position x where the explosion is spawn
* @param y the position y where the explosion is spawn
*/
public SpriteAnimation(int speed, int x, int y, Bitmap image){
super(null, image);
if(speed<0){
throw new IllegalArgumentException("speed cannot be negative");
}
this.currentImage=1;
this.speed=speed;
isGrowing=true;
this.x=x;
this.y=y;
}
public Bitmap getNextImage() {
String imageName = "explosion"+currentImage;
long currentTime=System.currentTimeMillis();
if(isGrowing){
if(currentTime-lastImageChange>speed){
currentImage++;
lastImageChange=currentTime;
}
if(currentImage==11){
isGrowing=false;
}
}
else{
if(currentTime-lastImageChange>speed){
currentImage--;
lastImageChange=currentTime;
}
if(currentImage==0){
return null;
}
}
return FrontApplication.frontImage.getImage(imageName);
}
@Override
public void onDrawSprite(Canvas canvas){
if(image==null) return;
canvas.drawBitmap(image, x - image.getWidth()/2 , y - image.getHeight()/2, new Paint());
this.image = getNextImage();
}
@Override
public boolean isStillDisplayable(){
return (this.image != null);
}
/**
* Get the x position of the current explosion
* @return the x position of the current explosion
*/
@Override
public int getPosXCenter() {
return x;
}
/**
* Get the y position of the current explosion
* @return the y position of the current explosion
*/
@Override
public int getPosYCenter() {
return y;
}
}
|
package de.unitrier.st.soposthistory.gt.util;
import java.util.logging.Logger;
public class GTLogger{
public final static Logger logger = Logger.getLogger((GTLogger.class.getName()));
}
|
package aws_horizontal_scaling;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.*;
public class RunInstance {
private static String tag_key = "Project";
private static String tag_value = "2.1";
private static String key_name = "15619demo";
/*
* Create instance and return its DNS
*/
public static String createInstance
(AmazonEC2Client ec2, String security_group, String ami, String instance_type) throws Exception {
// Create instance request
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
// Configure instance request
runInstancesRequest.withImageId(ami)
.withInstanceType(instance_type)
.withMinCount(1)
.withMaxCount(1)
.withKeyName(key_name)
.withSecurityGroups(security_group);
// Launch instance
RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
// Get instance id
Instance instance = runInstancesResult.getReservation().getInstances().get(0);
System.out.println("Just launched an instance with id: " + instance.getInstanceId());
String instance_id = instance.getInstanceId();
// Add tags
CreateTagsRequest createTagsRequest = new CreateTagsRequest();
createTagsRequest.withResources(instance.getInstanceId()).withTags(new Tag(tag_key,tag_value));
ec2.createTags(createTagsRequest);
// Get DNS
String dns = "";
do {
Thread.sleep(5000);
// Get DNS, referenced from stack overflow
DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
List<Reservation> reservations = describeInstancesRequest.getReservations();
for (Reservation reservation : reservations) {
for (Instance instance0 : reservation.getInstances()) {
if (instance0.getInstanceId().equals(instance_id))
return instance0.getPublicDnsName();
}
}
} while(dns == null);
return dns;
}
}
|
package com.kunsoftware.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.kunsoftware.entity.Ground;
import com.kunsoftware.entity.ValueSet;
import com.kunsoftware.page.PageInfo;
public interface GroundMapper {
int deleteByPrimaryKey(Integer id);
int insert(Ground record);
int insertSelective(Ground record);
Ground selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Ground record);
int updateByPrimaryKey(Ground record);
List<Ground> getGroundListPage(@Param("destination") Integer destination,@Param("page") PageInfo page);
List<ValueSet> selectValueSetList();
List<ValueSet> getValueSetListByDestination(@Param("destination") Integer destination);
List<Ground> getGroundByDestinationListPage(@Param("destination") Integer destination,@Param("page") PageInfo page);
} |
package com.ola.cabbooking.service;
import com.ola.cabbooking.dto.RiderDto;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
@Service
public interface RiderService extends UserDetailsService {
RiderDto createRider(RiderDto riderDto);
RiderDto getUser(String email);
RiderDto getUserByUserId(String Id);
}
|
package sps;
import java.util.Arrays;
public class InsertionSort {
int data[]={5,4,6,7,9};
public int [] sortInsert(int [] unsorted){
for(int i=1;i<unsorted.length;i++){
int current =unsorted[i];
int j=i;
while(j>0 && unsorted[j-1]> current){
unsorted[j]=unsorted[j-i];
j--;
}
unsorted[j]=current;
}
return unsorted;
}
public static void main(String[] args) {
InsertionSort ss= new InsertionSort();
System.out.println(Arrays.toString(ss.sortInsert(ss.data)));
}
}
|
package com.tencent.mm.model;
import com.tencent.mm.platformtools.h;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.ay;
import com.tencent.mm.storage.ay.a;
class au$4 implements a {
final /* synthetic */ au dBL;
au$4(au auVar) {
this.dBL = auVar;
}
public final void a(ay ayVar, ab abVar) {
String str = abVar.field_username;
if (ab.gY(abVar.field_username)) {
abVar.setUsername(ab.XV(abVar.field_username));
}
if (bi.oW(abVar.wP())) {
abVar.dy(h.oJ(abVar.field_nickname));
}
if (bi.oW(abVar.wQ())) {
abVar.dz(h.oI(abVar.field_nickname));
}
if (bi.oW(abVar.field_conRemarkPYShort)) {
abVar.dC(h.oJ(abVar.field_conRemark));
}
if (bi.oW(abVar.field_conRemarkPYFull)) {
abVar.dB(h.oI(abVar.field_conRemark));
}
if (s.d(abVar)) {
abVar.eD(43);
abVar.dy(h.oJ(abVar.BK()));
abVar.dz(h.oI(abVar.BK()));
abVar.dB(h.oI(abVar.BL()));
abVar.dC(abVar.BL());
return;
}
if (s.hO(str)) {
ab abVar2;
abVar.Bb();
abVar.eI(4);
abVar.eD(33);
if (abVar == null) {
abVar2 = new ab();
} else {
abVar2 = abVar;
}
abVar2.setUsername(str);
abVar2.Bb();
aa.x(abVar2);
abVar2.Bk();
}
if (abVar.BC()) {
abVar.eD(abVar.AY());
}
if (s.hE(str)) {
x.i("MicroMsg.MMCore", "update official account helper showhead %d", new Object[]{Integer.valueOf(31)});
abVar.eD(31);
}
if (abVar.BA()) {
au.HU();
c.FW().d(new String[]{str}, "@blacklist");
}
x.d("MicroMsg.MMCore", "onPreInsertContact2: %s, %s", new Object[]{abVar.field_username, abVar.wP()});
}
}
|
package org.totalbeginner.tutorial;
import static org.junit.Assert.*;
import org.junit.Test;
public class BookTest {
@Test
public void testBook() {
Book b1 = new Book("Great Expectations");
assertEquals("Great Expectations", b1.title);
assertEquals("unknown author", b1.author);
}
@Test
public void testGetPerson() {
Book b2 = new Book("War and Peace");
Person p2 = new Person();
p2.SetName("Elvis");
//new method to set the Person
b2.setPerson(p2);
//get the name of the person who has the book
Person testPerson = b2.getPerson();
String testPersonName = testPerson.GetName();
assertEquals("Elvis", testPersonName);
}
}
|
package Minggu12.Teori;
public class Elektronik {
protected int voltase;
public Elektronik() {
this.voltase = 220;
}
public int getVoltase() {
return this.voltase;
}
}
|
package com.example.healthmanage.ui.activity.delegate.ui;
import androidx.lifecycle.MutableLiveData;
import com.example.healthmanage.base.BaseApplication;
import com.example.healthmanage.base.BaseViewModel;
import com.example.healthmanage.bean.UsersInterface;
import com.example.healthmanage.bean.UsersRemoteSource;
import com.example.healthmanage.data.network.exception.ExceptionHandle;
import com.example.healthmanage.ui.activity.delegate.response.CreateDelegateResponse;
import com.example.healthmanage.ui.activity.delegate.response.DelegateBean;
import com.example.healthmanage.ui.activity.delegate.response.DelegateListResponse;
import com.example.healthmanage.ui.activity.team.response.TeamMemberResponse;
import java.util.List;
public class DelegateViewModel extends BaseViewModel {
private UsersRemoteSource usersRemoteSource;
public MutableLiveData<String> dateChoose = new MutableLiveData<>();
public MutableLiveData<List<DelegateListResponse.DataBean>> delegateLiveData = new MutableLiveData<>();
public MutableLiveData<String> delegateDetail = new MutableLiveData<>("");
public MutableLiveData<String> delegateSpecificTime = new MutableLiveData<>("");
public MutableLiveData<String> delegateAddress = new MutableLiveData<>("");
public MutableLiveData<String> delegateTime = new MutableLiveData<>("");
public MutableLiveData<List<TeamMemberResponse.DataBean>> doctorMutableLiveData = new MutableLiveData<>();
public MutableLiveData<Boolean> addSucceed = new MutableLiveData<>();
public DelegateViewModel() {
usersRemoteSource = new UsersRemoteSource();
}
public void getBusineService(String date){
usersRemoteSource.getBusineService(BaseApplication.getToken(), date, new UsersInterface.GetBusineServiceCallback() {
@Override
public void getSucceed(DelegateListResponse delegateListResponse) {
if (delegateListResponse.getData()!=null && delegateListResponse.getData().size()>0){
delegateLiveData.setValue(delegateListResponse.getData());
}else {
delegateLiveData.setValue(null);
}
}
@Override
public void getFailed(String msg) {
delegateLiveData.setValue(null);
}
@Override
public void error(ExceptionHandle.ResponseException e) {
delegateLiveData.setValue(null);
}
});
}
public void getDoctorList(int roleId){
usersRemoteSource.getDoctorTeamList(BaseApplication.getToken(), roleId,new UsersInterface.GetDoctorTeamListCallback() {
@Override
public void getSucceed(TeamMemberResponse teamMemberResponse) {
if (teamMemberResponse.getData()!=null && teamMemberResponse.getData().size()>0){
doctorMutableLiveData.postValue(teamMemberResponse.getData());
}else {
doctorMutableLiveData.postValue(null);
}
}
@Override
public void getFailed(String msg) {
doctorMutableLiveData.postValue(null);
}
@Override
public void error(ExceptionHandle.ResponseException e) {
}
});
}
public void addBusineService(DelegateBean delegateBean){
usersRemoteSource.addBusineService(delegateBean, new UsersInterface.AddBusineServiceCallback() {
@Override
public void addSucceed(CreateDelegateResponse createDelegateResponse) {
addSucceed.setValue(true);
}
@Override
public void addFailed(String msg) {
addSucceed.setValue(false);
getUiChangeEvent().getToastTxt().setValue(msg);
}
@Override
public void error(ExceptionHandle.ResponseException e) {
addSucceed.setValue(false);
}
});
}
}
|
package MultidimensionalArrays;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(
System.in
)
);
int[] dimensions = Arrays.stream(in.readLine().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
int firstMatrixRows = dimensions[0];
int firstMatrixCols = dimensions[1];
int[][] firstMatrix = new int[firstMatrixRows][];
for (int i = 0; i < firstMatrixRows; i++) {
int[] arr = Arrays.stream(in.readLine().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
firstMatrix[i] = arr;
}
System.out.println();
}
}
|
package com.byterefinery.rmbench.operations;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import com.byterefinery.rmbench.EventManager;
import com.byterefinery.rmbench.RMBenchPlugin;
import com.byterefinery.rmbench.model.schema.Schema;
/**
* an operation that changes a schemas name
*
* @author cse
*/
public class SchemaNameOperation extends RMBenchOperation {
private Schema schema;
private String oldName;
private String newName;
public SchemaNameOperation(Schema schema) {
super(Messages.Operation_ChangeSchemaName);
setSchema(schema);
}
public SchemaNameOperation(Schema schema, String newName) {
super(Messages.Operation_ChangeSchemaName);
setSchema(schema);
setNewName(newName);
}
public void setSchema(Schema schema) {
this.schema=schema;
oldName = (schema!=null) ? schema.getName() : null;
}
public void setNewName(String newName) {
this.newName=newName;
}
public IStatus execute(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
return setName(this, newName);
}
public IStatus undo(IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
return setName(this, oldName);
}
private IStatus setName(Object eventSource, String name) {
schema.setName(name);
RMBenchPlugin.getEventManager().fireSchemaModified(
eventSource, EventManager.Properties.NAME, schema);
return Status.OK_STATUS;
}
}
|
package com.abraham.dj;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.abraham.dj.model.Article;
import com.abraham.dj.model.User;
import com.abraham.dj.service.IUserService;
import net.sf.json.JSONObject;
/**
* Handles requests for the application home page.
*/
@Controller
@RequestMapping(value="/user")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Resource
private IUserService userService;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "home";
}
@RequestMapping(value = "/check", method = RequestMethod.GET)
public String login(User user, Model model) {
int userId = userService.checkUser(user);
model.addAttribute("userId", userId);
return "home";
}
@ResponseBody
@RequestMapping(value="delete",method= RequestMethod.POST)
public JSONObject delete(User user){
JSONObject result = new JSONObject();
boolean flag = userService.delete(user);
result.put("flag", flag);
return result;
}
@ResponseBody
@RequestMapping(value="/deleteMore",method = RequestMethod.POST)
public void deleteMore(int[] ids){
for (int id:ids) {
User user = new User();
user.setId(id);
userService.delete(user);
}
}
@ResponseBody
@RequestMapping(value = "/save", method = RequestMethod.GET)
public JSONObject save(User user) {
JSONObject result = new JSONObject();
boolean flag = false;
if(user.getId() > 0)
flag = userService.save(user);
else {
flag = userService.update(user);
}
result.put("flag", flag);
return result;
}
@ResponseBody
@RequestMapping(value="/get",method= RequestMethod.GET)
public JSONObject get(User user){
JSONObject result = new JSONObject();
User user2 = (User)userService.get(user);
result.put("admin", user2);
return result;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public @ResponseBody JSONObject list() {
JSONObject result = new JSONObject();
@SuppressWarnings("unchecked")
List<User> list = (List<User>) userService.getAll();
result.put("array", list);
return result;
}
}
|
package com.awg.j20.bplake;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = {"comp-local", "computator"})
class ContextLoadComputatorTests {
@Test
void contextLoads() {
}
}
|
package com.blog.text;
import static org.junit.Assert.*;
import java.util.Date;
import java.util.List;
import javax.imageio.spi.ServiceRegistry;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.sql.Insert;
import org.junit.Test;
import com.blog.bean.MsgBoard;
import com.blog.dao.impl.MsgBoardDaoImpl;
import com.blog.server.MsgBoardService;
import com.blog.server.Impl.MsgBoardServiceImpl;
import com.blog.util.HibernateSessionFactory;
public class Demo {
private static MsgBoardService dao = new MsgBoardServiceImpl();
private static Date date = new Date();
public static void main(String[] args) {
// MsgBoardDaoImpl msgBoardDaoImpl = new MsgBoardDaoImpl();
// List<MsgBoard> msgBoards = msgBoardDaoImpl.selsetMsgBoard(1);
// for(MsgBoard msgBoard:msgBoards) {
// System.out.println(msgBoard.getNo());
// }
List<MsgBoard> mList = dao.findMsgBoard(1);
for(MsgBoard list:mList) {
System.out.println(list.getNo());
}
}
}
|
package br.com.helpdev.quaklog.dataprovider.entity;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class PlayerStatusEntity {
private String gameTime;
private String connectStatus;
}
|
package com.czy.demos.springbootdeadletterdemo.RabbitmqTTLWithPlugin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class DelayedMessageSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(String msg, Integer seconds){
System.out.println("插件发送时间: " + new Date() + " 内容: " + msg + " 间隔: " + seconds);
this.rabbitTemplate.convertAndSend(DelayedRabbitMQConfig.DELAYED_EXCHANGE_NAME, DelayedRabbitMQConfig.DELAYED_ROUTING_KEY_NAME,
msg, a -> {
//用插件时调用setDelay
a.getMessageProperties().setDelay(1000*seconds);
return a;
});
}
}
|
/*!
* \brief
* вычисления
* \details
* \author Artem
* \date 15.01.2021
*/
package com.startjava.lesson_2_3_4.game;
import java.util.Scanner;
public class GuessNumberTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Введите имя первого игрока: ");
String name1 = scan.nextLine();
System.out.print("Введите имя второго игрока: ");
String name2 = scan.nextLine();
Player player1 = new Player(name1);
Player player2 = new Player(name2);
GuessNumber guessNum = new GuessNumber(player1, player2);
String answer;
do {
System.out.println("Игра началась!!!");
System.out.println("У вас 10 попыток");
guessNum.start();
do {
System.out.print("Хотите продолжить? [yes/no]: ");
answer = scan.nextLine();
} while(!answer.equals("yes") && !answer.equals("no"));
} while(answer.equals("yes"));
}
} |
package com.mycompany.app;
import org.apache.storm.Config;
import org.apache.storm.LocalCluster;
import org.apache.storm.StormSubmitter;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.tuple.Fields;
public class TwitterHashtagStorm {
public static void main(String[] args) throws Exception {
String consumerKey = "QzjpEe7Mk4c8W9mmrppPfEazI";
String consumerSecret = "QBcRBN8HJIKT5nm5ngWD9rl4s3FPV2Wpoava0tX1MjYTEaLAC9";
String accessToken = "906367537159573504-qH0zLIw0Av7ig6NLL75zwW6Qk42KIkE";
String accessTokenSecret = "WlOYHBBz9ce99fmyi9j78SAH8MzZ9g0UYarWm18wW5I5v";
String[] keyWords = { "trump", "Trump", "TRUMP" };
Config conf = new Config();
// config.setDebug(true);
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("twitter-spout",new TwitterSampleSpout(consumerKey, consumerSecret, accessToken, accessTokenSecret, keyWords), 12);
builder.setBolt("twitter-hashtag-reader-bolt", new HashtagReaderBolt(),9).shuffleGrouping("twitter-spout");
builder.setBolt("twitter-hashtag-counter-bolt", new HashtagCounterBolt()).fieldsGrouping("twitter-hashtag-reader-bolt", new Fields("hashtag"));
// LocalCluster cluster = new LocalCluster();
StormSubmitter.submitTopology("TwitterHashtagStorm", conf,builder.createTopology());
// Thread.sleep(30000);
// cluster.shutdown();
}
} |
package com.example.mostafahassan.tabbar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Tab2Content extends Fragment implements View.OnClickListener {
public EditText childName, date, weight, gender, idNum, BirthDay;
public Button AddUser;
DatabaseReference databaseReferance;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_add_baby, container, false);
childName = (EditText) rootView.findViewById(R.id.ChildNam_baby);
childName.setOnClickListener(this);
date = (EditText) rootView.findViewById(R.id.Date_baby);
date.setOnClickListener(this);
weight = (EditText) rootView.findViewById(R.id.Weight_baby);
weight.setOnClickListener(this);
gender = (EditText) rootView.findViewById(R.id.Gender_baby);
gender.setOnClickListener(this);
idNum = (EditText) rootView.findViewById(R.id.IdNum_baby);
idNum.setOnClickListener(this);
BirthDay = (EditText) rootView.findViewById(R.id.BirthDay_baby);
BirthDay.setOnClickListener(this);
// AddUser = (Button) rootView.findViewById(R.id.Add_user);
// AddUser.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Add_user:
databaseReferance.child("IdNum").setValue(idNum.getText().toString());
databaseReferance.child("Date").setValue(date.getText().toString());
databaseReferance.child("Weight").setValue(weight.getText().toString());
databaseReferance.child("Gender").setValue(gender.getText().toString());
databaseReferance.child("ChildName").setValue(childName.getText().toString());
databaseReferance.child("BirthDay").setValue(BirthDay.getText().toString());
break;
}
}
}
|
package org.github.chajian.matchgame.gui;
import com.github.stefvanschie.inventoryframework.gui.GuiItem;
import com.github.stefvanschie.inventoryframework.gui.type.ChestGui;
import com.github.stefvanschie.inventoryframework.pane.Pane;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import java.util.ArrayList;
import java.util.List;
/**
* 基本的Gui抽象类
* @author Chajian
*/
public abstract class BaseGui {
protected ChestGui chestGui;
protected Pane pane;
protected List<GuiItem> list = new ArrayList<>();
abstract void initGui();
abstract void initGuiItem();
abstract void initPane();
public abstract void showPlayer(Player player);
void bindPaneClick(){
pane.setOnClick(this::PaneClick);
}
//避免玩家作弊或者拖拽物品
public void PaneClick(InventoryClickEvent event){
if(event.getClick() != ClickType.LEFT)
event.setCancelled(true);
if(event.getAction() != InventoryAction.NOTHING)
event.setCancelled(true);
}
}
|
package cn.cnmua.car.domian;
import lombok.Data;
@Data
//订单信息
public class OrderInfo {
private Integer id;
private String orderNum;//订单号
private String userId;//用户id
private String state;//订单状态
private String time;//下单时间
private String message;//备注留言
public OrderInfo() {
}
public OrderInfo(Integer id, String orderNum, String userId, String state, String time, String message) {
this.id = id;
this.orderNum = orderNum;
this.userId = userId;
this.state = state;
this.time = time;
this.message = message;
}
public OrderInfo(String orderNum, String userId, String state, String time, String message) {
this.orderNum = orderNum;
this.userId = userId;
this.state = state;
this.time = time;
this.message = message;
}
}
|
package com.accp.pub.mapper;
import com.accp.pub.pojo.Functionandrole;
public interface FunctionandroleMapper {
int insert(Functionandrole record);
int insertSelective(Functionandrole record);
} |
package com.rx.rxmvvmlib.util;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import com.rx.rxmvvmlib.R;
/**
* Created by wuwei
* 2018/12/29
* 佛祖保佑 永无BUG
*/
public class IgnoreBatteryOptUtil {
/**
* 小米:
* 自启动:授权管理--自启动管理--ZAI--开启 //完成
* 省电策略:MIUI9/10:设置--电量和性能--应用配置--无限制 //完成
*
*
*
* 华为:
* 自启动:设置--电池--启动管理--ZAI--手动管理 //完成
* 省电策略:无
*
* oppo:自启动:手机管家--自启动管理--ZAI //完成
* 省电策略:主流:设置--电池--耗电保护--关闭后台冻结和自动优化 //无法唤起
* 新版:设置--电池--关闭深度省电和智能保护--自定义耗电保护--ZAI--允许后台运行--智能省电场景--关闭睡眠模式 //暂无
*
*
* vivo:自启动:i管家--应用管理--权限管理--自启动--ZAI //无法唤起
* 省电策略:设置--电池--后台高耗电--ZAI //可以唤起
*
*
* 三星:自启动:智能管理器--自动运行应用程序--ZAI //无法唤起
* 省电策略:智能管理器--电池--未监视的应用程序--添加应用程序--ZAI //无法唤起
*/
/**
* Get Mobile Type
*
* @return
*/
private static String getMobileType() {
return Build.MANUFACTURER;
}
/**
* Compatible Mainstream Models 兼容市面主流机型
*
* @param context
*/
public static void openIgnoreBatteryOpt(Context context) {
Intent intent = new Intent();
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ComponentName componentName = null;
if (RomUtil.isXiaomi()) {
componentName = new ComponentName("com.miui.powerkeeper",
"com.miui.powerkeeper.ui.HiddenAppsConfigActivity");
intent.putExtra("package_name", context.getPackageName());
intent.putExtra("package_label", context.getResources().getString(R.string.app_name));
} else if (RomUtil.isHuawei()) {
//无
} else if (RomUtil.isOppo()) {
String property = AppUtil.getSystemProperty("ro.build.version.opporom");
if (RomUtil.getOppoVer(property) < 5.0) {
componentName = new ComponentName("com.coloros.oppoguardelf",
"com.coloros.powermanager.fuelgaue.PowerConsumptionActivity");
} else {
intent = new Intent(Settings.ACTION_SETTINGS);
context.startActivity(intent);
}
} else if (RomUtil.isVivo()) {
componentName = new ComponentName("com.vivo.abe",
"com.vivo.applicationbehaviorenginev4.ui.ExcessivePowerManagerActivity");
} else if (RomUtil.isSamsung()) {
componentName = new ComponentName("com.samsung.android.sm_cn",
"com.samsung.android.sm.ui.battery.BatteryActivity");
} else {
intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
}
intent.setComponent(componentName);
context.startActivity(intent);
} catch (Exception e) {
//抛出异常就直接打开设置页面
intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
}
}
/**
* GoTo Open Self Setting Layout
* Compatible Mainstream Models 兼容市面主流机型
*
* @param context
*/
public static void openSelfStart(Context context) {
Intent intent = new Intent();
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ComponentName componentName = null;
if (RomUtil.isXiaomi()) {
componentName = new ComponentName("com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity");
} else if (RomUtil.isHuawei()) {
componentName = ComponentName.unflattenFromString("com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity");//跳自启动管理
} else if (RomUtil.isOppo()) {
componentName = ComponentName.unflattenFromString("com.oppo.safe/.permission.startup.StartupAppListActivity");
Intent intentOppo = new Intent();
intentOppo.setClassName("com.oppo.safe/.permission.startup", "StartupAppListActivity");
if (context.getPackageManager().resolveActivity(intentOppo, 0) == null) {
componentName = ComponentName.unflattenFromString("com.coloros.safecenter" + "/.startupapp.StartupAppListActivity");
}
} else if (RomUtil.isVivo()) {
componentName = new ComponentName("com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.PurviewTabActivity");
} else if (RomUtil.isSamsung()) {
componentName = new ComponentName("com.samsung.android.sm_cn",
"com.samsung.android.sm.ui.cstyleboard.SmartManagerDashBoardActivity");
} else if (RomUtil.isMeizu()) {
componentName = ComponentName.unflattenFromString("com.meizu.safe/.permission.SmartBGActivity");
} else if (RomUtil.isLetv()) {
intent.setAction("com.letv.android.permissionautoboot");
} else if (RomUtil.is360()) {
componentName = new ComponentName("com.yulong.android.coolsafe", ".ui.activity.autorun.AutoRunListActivity");
} else {
intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
}
intent.setComponent(componentName);
context.startActivity(intent);
} catch (Exception e) {
//抛出异常就直接打开设置页面
intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(intent);
}
}
}
|
package pe.gob.trabajo.repository.search;
import pe.gob.trabajo.domain.Regimenlab;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data Elasticsearch repository for the Regimenlab entity.
*/
public interface RegimenlabSearchRepository extends ElasticsearchRepository<Regimenlab, Long> {
}
|
/*
* Copyright (c) 2016. Universidad Politecnica de Madrid
*
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*
*/
package org.librairy.modeler.lda.functions;
import com.google.common.primitives.Doubles;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.sql.Row;
import org.librairy.modeler.lda.dao.ShapeRow;
import java.io.Serializable;
import java.util.List;
/**
* Created on 26/06/16:
*
* @author cbadenes
*/
public class RowToArray implements Serializable, Function<Row, double[]> {
@Override
public double[] call(Row row) throws Exception {
List<Double> list = row.getList(4);
double[] array = Doubles.toArray(list);
return array;
}
}
|
package com.vm.samples;
public class Example {
public static void main(String[] args) {
System.out.println("krishna Kumar");
System.out.println("Value Minds IT Services Pvt Ltd");
int s=6;
s++;
System.out.println(s);
//ggggggg
}
}
|
package schr0.tanpopo.item;
import net.minecraft.item.Item;
public class ItemMaterialPetal extends Item
{
public ItemMaterialPetal()
{
// none
}
}
|
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final int[] array = {1,2,3,4,5};
array[0] = 9; //ок, т.к. изменяем содержимое массива – {9,2,3,4,5}
array = new int[5]; //ошибка компиляции
}
}
class Example{
public final Integer strFinal;
public String str;
public Example() {
String str1 = new String("Hello");
String str2 = new String("Bye");
Integer i = new Integer(5);
strFinal = i;
System.out.println(strFinal);
i = 6;
System.out.println(strFinal);
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.caisa.planilla.entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.codehaus.jackson.annotate.JsonIgnore;
/**
*
* @author NCN00973
*/
@Entity
@Table(name = "cargos")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Cargos.findAll", query = "SELECT c FROM Cargos c")})
public class Cargos implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Column(name = "Nombre")
private String nombre;
@Column(name = "Descripcion")
private String descripcion;
@Column(name = "Usuario_id_creo")
private Integer usuarioidcreo;
@Column(name = "fecha_creacion")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaCreacion;
@OneToMany(mappedBy = "idCargo")
private Collection<Usuarios> usuariosCollection;
public Cargos() {
}
public Cargos(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Integer getUsuarioidcreo() {
return usuarioidcreo;
}
public void setUsuarioidcreo(Integer usuarioidcreo) {
this.usuarioidcreo = usuarioidcreo;
}
public Date getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
@XmlTransient
@JsonIgnore
public Collection<Usuarios> getUsuariosCollection() {
return usuariosCollection;
}
public void setUsuariosCollection(Collection<Usuarios> usuariosCollection) {
this.usuariosCollection = usuariosCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cargos)) {
return false;
}
Cargos other = (Cargos) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.caisa.planilla.entity.Cargos[ id=" + id + " ]";
}
}
|
package rubrica12.repository;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import rubrica12.model.Author;
import rubrica12.model.Book;
@org.springframework.stereotype.Repository
public class RepositoryBook extends Repository {
public void insertBook(Book book) {
Connection conn = manager.open(jdbcUrl);
PreparedStatement preparedStatement = null;
try {
preparedStatement = conn.prepareStatement("INSERT INTO BOOK (TITLE,ISBN,IDAUTHOR)" + "VALUES (?,?,?)");
preparedStatement.setString(1, book.getTitle());
preparedStatement.setInt(2, book.getIsbn());
preparedStatement.setInt(3, book.getIdAuthor());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
close(preparedStatement);
manager.close(conn);
}
public ArrayList<Book> findBooksByidAuthor(int idAuthor) {
ArrayList<Book> list = new ArrayList<Book>();
Connection conn = manager.open(jdbcUrl);
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = conn.prepareStatement("SELECT * FROM BOOK WHERE IDAUTHOR = ?");
preparedStatement.setInt(1, idAuthor);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Book book = new Book();
book.setIdBook(resultSet.getInt(1));
book.setTitle(resultSet.getString(2));
book.setIsbn(resultSet.getInt(3));
book.setIdAuthor(resultSet.getInt(4));
list.add(book);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return list;
}
public List findBooks(Book book) {
ArrayList<Book> list = new ArrayList<Book>();
Connection conn = manager.open(jdbcUrl);
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
StringBuffer sb = new StringBuffer();
sb.append("SELECT * FROM BOOK WHERE TITLE like ?");
if (book.getIsbn() != 0) {
sb.append("OR ISBN like '%?%'");
}
preparedStatement = conn.prepareStatement(sb.toString());
preparedStatement.setString(1, "%" + book.getTitle() + "%");
if (book.getIsbn() != 0) {
preparedStatement.setInt(2, book.getIsbn());
}
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Book bookTmp = new Book();
bookTmp.setIdBook(resultSet.getInt(1));
bookTmp.setTitle(resultSet.getString(2));
bookTmp.setIsbn(resultSet.getInt(3));
bookTmp.setIdAuthor(resultSet.getInt(4));
list.add(bookTmp);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return list;
}
}
|
package com.mimi.mimigroup.model;
public class DM_Tree_Disease {
int DiseaseID;
int TreeID;
String DiseaseCode;
String DiseaseName;
String TreeName;
public DM_Tree_Disease() {
}
public DM_Tree_Disease(int diseaseID, int treeID,String diseaseCode, String diseaseName) {
this.TreeID = treeID;
this.DiseaseID = diseaseID;
this.DiseaseName = diseaseName;
this.DiseaseCode=diseaseCode;
}
public int getTreeID() {
return TreeID;
}
public void setTreeID(int treeID) {
TreeID = treeID;
}
public int getDiseaseID() {
return DiseaseID;
}
public void setDiseaseID(int diseaseID) {
DiseaseID = diseaseID;
}
public String getDiseaseName() {
return DiseaseName;
}
public String getDiseaseCode() {
return DiseaseCode;
}
public void setDiseaseCode(String diseaseCode) {
DiseaseCode = diseaseCode;
}
public void setDiseaseName(String diseaseName) {
DiseaseName = diseaseName;
}
public String getTreeName() {
return TreeName;
}
public void setTreeName(String treeName) {
TreeName = treeName;
}
}
|
package eg.edu.guc.parkei.exceptions;
public class OutOfOrderException extends CannotOperateException {
/**
*
*/
private static final long serialVersionUID = 1L;
public OutOfOrderException() {
super();
}
public OutOfOrderException(String x) {
super(x);
}
}
|
package br.input;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyManager implements KeyListener {
private boolean[] keys = new boolean[256];
public static boolean w, s, i, k;
public void update() {
w = keys[KeyEvent.VK_W];
s = keys[KeyEvent.VK_S];
i = keys[KeyEvent.VK_I];
k = keys[KeyEvent.VK_K];
}
@Override
public void keyPressed(KeyEvent k) {
if (k.getKeyCode() < 0 || k.getKeyCode() > 255) {
return;
}
keys[k.getKeyCode()] = true;
}
@Override
public void keyReleased(KeyEvent k) {
if (k.getKeyCode() < 0 || k.getKeyCode() > 255) {
return;
}
keys[k.getKeyCode()] = false;
}
@Override
public void keyTyped(KeyEvent keyEvent) {
}
}
|
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import java.net.URL;
import java.util.ResourceBundle;
public class ControllerSees implements Initializable
{
@FXML TableView<Products> table;
@FXML private TableColumn<Products, String> name;
@FXML private TableColumn<Products, Double> price;
@FXML private TableColumn<Products, Integer> stock;
@Override public void initialize(URL url, ResourceBundle resourceBundle)
{
Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Query qry = session.createQuery("from Products where stock>0");
ObservableList l = FXCollections.observableArrayList(qry.list());
name.setCellValueFactory(new PropertyValueFactory<Products, String>("name"));
price.setCellValueFactory(new PropertyValueFactory<Products, Double>("price"));
stock.setCellValueFactory(new PropertyValueFactory<Products, Integer>("stock"));
table.getItems().addAll(l);
session.close(); factory.close();
}
}
|
package tree;
/**
* 二叉树中的一个节点
* 保存了学生信息和左右孩子信息
*/
class StuNode {
int id;
String name;
StuNode left;
StuNode right;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public StuNode getLeft() {
return left;
}
public void setLeft(StuNode left) {
this.left = left;
}
public StuNode getRight() {
return right;
}
public void setRight(StuNode right) {
this.right = right;
}
public StuNode(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "StuNode{" +
"id=" + id +
", name='" + name + '\'' +
", left=" + left +
", right=" + right +
'}';
}
/**
* 前序遍历
*/
public void preTraverse() {
//父节点的位置
System.out.println(this);
if (left != null) {
left.preTraverse();
}
if (right != null) {
right.preTraverse();
}
}
/**
* 中序遍历
*/
public void midTraverse() {
if (left != null) {
left.midTraverse();
}
//父节点的位置
System.out.println(this);
if (right != null) {
right.midTraverse();
}
}
/**
* 后序遍历
*/
public void lastTraverse() {
if (left != null) {
left.lastTraverse();
}
if (right != null) {
right.lastTraverse();
}
//父节点的位置
System.out.println(this);
}
}
|
public class ContaBancaria2 {
int agencia, contaCorrente;
double saldo, limiteExtra;
String titularConta;
public void imprimirSaldo(){
System.out.println ("Saldo: " + this.saldo);
}
public void imprimirSaldoTotal(){
double soma = this.saldo+this.limiteExtra;
System.out.println("Saldo: " + soma);
}
public void imprimirAgencia(){
System.out.println ("A agencia e: " + this.agencia);
}
public void imprimirContaCorrente(){
System.out.println("A conta-corrente e: " + this.contaCorrente);
}
public void imprimirTitular(){
System.out.println ("O titular da conta e: " + this.titularConta);
}
public static void main (String args []){
ContaBancaria2 cb1 = new ContaBancaria2();
cb1.agencia = 3610;
cb1.contaCorrente = 15766;
cb1.saldo = 35.54;
cb1.limiteExtra = 50;
cb1.titularConta = "Thaminy";
cb1.imprimirTitular();
cb1.imprimirAgencia();
cb1.imprimirContaCorrente();
cb1.imprimirSaldo();
cb1.imprimirSaldoTotal();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.mutabene.controller.admin;
import cz.mutabene.model.entity.AppConfigEntity;
import cz.mutabene.model.entity.UserEntity;
import cz.mutabene.model.form.admin.ConfigForm;
import cz.mutabene.service.info.InfoMessages;
import cz.mutabene.service.manager.AppConfigManager;
import cz.mutabene.service.manager.UserManager;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
/**
*
* @author novakst6
*/
@Controller
@RequestMapping(value={"admin"})
public class ConfigureControllerAdmin {
private AppConfigManager appConfigManager;
private UserManager userManager;
private InfoMessages infoMessages;
@RequestMapping(value={"config.htm"},method={RequestMethod.GET})
public String configGET(
@ModelAttribute(value="confFormModel")
ConfigForm formModel,
ModelMap m
) throws Exception
{
AppConfigEntity conf = appConfigManager.findById(1L);
m.addAttribute("conf", conf);
return "admin/config/show";
}
@RequestMapping(value={"config.htm"},method={RequestMethod.POST})
public String configPOST(
@ModelAttribute(value="confFormModel")
@Valid ConfigForm formModel,
BindingResult errors,
ModelMap m
) throws Exception
{
try {
if(!errors.hasErrors()){
AppConfigEntity conf = appConfigManager.findById(1L);
if(conf == null){
conf = new AppConfigEntity();
appConfigManager.add(conf);
}
String contentModerator = formModel.getContentModerator();
UserEntity user = userManager.findByEmail(contentModerator);
if(user == null){
infoMessages.setWarnMessage("Nepodařilo se najít uživatele.");
return "redirect:config.htm";
}
conf.setContentModerator(user);
appConfigManager.edit(conf);
infoMessages.setInfoMessage("Záznam byl uložen.");
return "redirect:config.htm";
} else {
AppConfigEntity conf = appConfigManager.findById(1L);
m.addAttribute("conf", conf);
return "admin/config/show";
}
} catch (Exception e) {
infoMessages.setErrorMessage("ERROR "+e.getMessage());
return "redirect:index.htm";
}
}
public @Autowired void setAppConfigManager(AppConfigManager appConfigManager) {
this.appConfigManager = appConfigManager;
}
public @Autowired void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
public @Autowired void setInfoMessages(InfoMessages infoMessages) {
this.infoMessages = infoMessages;
}
}
|
package com.example.railway.service.Passenger;
import com.example.railway.model.Passenger;
import com.example.railway.repository.Passenger.PassengerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class PassengerServiceImpl implements IPassengerService {
@Autowired
PassengerRepository repository;
@Override
public Passenger update(Passenger passenger) {
passenger.setModifiedAt(new Date());
passenger.setCreatedAt(repository.findById(passenger.getId())
.orElse(null)
.getCreatedAt());
repository.save(passenger);
return passenger;
}
@Override
public Passenger delete(String id) {
repository.deleteById(id);
return repository.findById(id).orElse(null);
}
@Override
public Passenger getById(String id) {
return repository.findById(id).orElse(null);
}
@Override
public Passenger create(Passenger passenger) {
passenger.setCreatedAt(new Date());
return repository.save(passenger);
}
@Override
public List<Passenger> getAll() {
return repository.findAll();
}
}
|
package com.dzz.policy.service.service;
import com.dzz.policy.api.service.PolicyService;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author dzz
* @version 1.0.0
* @since 2019年08月19 09:54
*/
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class PolicyServiceImplTest extends TestCase {
@Autowired
private PolicyService policyService;
@Test
public void testSavePolicy() {
}
@Test
public void testListPolicy() {
}
@Test
public void testDetailPolicy() {
}
@Test
public void testSendInsurance() {
}
} |
package gugutech.elseapp.dao;
import gugutech.elseapp.model.LookupT;
import java.util.List;
public interface LookupTMapper {
int deleteByPrimaryKey(Integer lookupId);
int insert(LookupT record);
LookupT selectByPrimaryKey(Integer lookupId);
List<LookupT> selectAll();
int updateByPrimaryKey(LookupT record);
} |
package com.tencent.mm.plugin.webview.ui.tools;
import com.tencent.mm.plugin.webview.ui.tools.WebViewUI.i;
class WebViewUI$i$1 implements Runnable {
final /* synthetic */ i qaJ;
final /* synthetic */ String val$url;
WebViewUI$i$1(i iVar, String str) {
this.qaJ = iVar;
this.val$url = str;
}
public final void run() {
this.qaJ.pZJ.Do(this.val$url);
}
}
|
package com.designpattern.createpattern.prototype;
import java.io.*;
public class Student implements Serializable,Cloneable {
private static final long serialVersionUID = 8703027563434375744L;
public Student( ) { }
public Student(String name, Integer age, String addr, Student gf) {
this.name = name;
this.age = age;
this.addr = addr;
this.gf = gf;
}
private String name;//姓名
private Integer age;//年龄
private String addr;//地址
private Student gf;//girlfriend
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public String getAddr() { return addr; }
public void setAddr(String addr) { this.addr = addr; }
public Student getGf() { return gf; }
public void setGf(Student gf) { this.gf = gf; }
@Override
public String toString() {
return "Student{name='" + name + '\'' + ", age=" + age + ", addr='" + addr + '\'' + ", gf=" + gf + '}';
}
//深克隆
public Object deepClone() throws IOException,
ClassNotFoundException {
// 将对象写到流里
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 从流里读出来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
}
public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
Student gf = new Student("小芳", 18, "帝都", null);
Student xiaoming = new Student("小明", 18, "帝都", gf);
//浅克隆
Student shallowCopy = (Student)xiaoming.clone();
//深克隆
Student deeoCopy = (Student)xiaoming.deepClone();
xiaoming.setName("小明同胞兄弟");
gf.setName("小芳的闺蜜");
System.out.println(shallowCopy); // Student{name='小明', age=18, addr='帝都', gf=Student{name='小芳的闺蜜', age=18, addr='帝都', gf=null}}
System.out.println(deeoCopy); // Student{name='小明', age=18, addr='帝都', gf=Student{name='小芳', age=18, addr='帝都', gf=null}}
}
}
|
package com.x.model.weixin;
import com.x.model.XObject;
/**
* <p>
* Description:图文消息
* </p>
*
* @Author Chenkangming
* @Date 2014-7-9
* @version 1.0
*/
public class WeixinMessageNews extends XObject {
private static final long serialVersionUID = -3905654453753481018L;
/**
* 自增长id
*/
private int id;
/**
* 标题
*/
private String title;
/**
* 描述
*/
private String description;
/**
* 图片,支持JPS、PNG格式
*/
private String picUrl;
/**
* 点击图文消息跳转链接
*/
private String url;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
|
package com.example.demo.domain.bo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
/**
* @author :ls05
* @date :Created in 2020/11/10 12:46
*/
@Component
public class WeatherData extends ApplicationEvent {
private int temp =0;
private int humidity=0;
private int windPower=0;
public WeatherData(ApplicationContext source) {
super(source);
}
@Autowired
MyPublisher myPublisher;
public void measurementsChanged(int temp, int humidity, int windPower) {
this.temp = temp;
this.humidity = humidity;
this.windPower = windPower;
myPublisher.publisherEvent(this);
}
public int getTemp() {
return temp;
}
} |
package com.tencent.mm.plugin.wallet.balance.ui;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.wallet.a.p;
import com.tencent.mm.plugin.wallet.balance.b;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.a;
import com.tencent.mm.wallet_core.ui.e;
import java.util.ArrayList;
class WalletBalanceManagerUI$8 implements OnClickListener {
final /* synthetic */ WalletBalanceManagerUI pax;
WalletBalanceManagerUI$8(WalletBalanceManagerUI walletBalanceManagerUI) {
this.pax = walletBalanceManagerUI;
}
public final void onClick(View view) {
p.bNp();
ArrayList bPF = p.bNq().bPF();
if (bPF == null || bPF.size() == 0) {
x.i("MicroMsg.WalletBalanceManagerUI", "mBankcardList is empty, do bind card to fetch");
WalletBalanceManagerUI.b(this.pax);
return;
}
x.i("MicroMsg.WalletBalanceManagerUI", "mBankcardList is valid, to do fetch");
a.a(this.pax, b.class, null, null);
e.He(15);
}
}
|
package com.sinata.rwxchina.component_basic.basic.basiccashcoupon;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.sinata.rwxchina.basiclib.base.BaseActivity;
import com.sinata.rwxchina.basiclib.base.BaseGoodsInfo;
import com.sinata.rwxchina.basiclib.entity.BaseShopInfo;
import com.sinata.rwxchina.basiclib.payment.utils.StartPayMentUtils;
import com.sinata.rwxchina.basiclib.utils.immersionutils.ImmersionUtils;
import com.sinata.rwxchina.component_basic.R;
import com.sinata.rwxchina.component_basic.basic.basicbanner.BannerUtils;
import com.sinata.rwxchina.basiclib.basic.basiccashcouponbuy.GroupDetailUtils;
import com.sinata.rwxchina.component_basic.basic.basicinformation.InformationUtils;
import com.sinata.rwxchina.component_basic.basic.basicname.NameUtils;
import com.sinata.rwxchina.component_basic.basic.basicnearby.NearByUtils;
import com.sinata.rwxchina.component_basic.basic.basicnotice.NoticeUtils;
/**
* @author HRR
* @datetime 2017/12/21
* @describe 代金券详情页面,可直接购买
* @modifyRecord
*/
public class CashCouponBuyActivity extends BaseActivity {
private BaseShopInfo shopInfo;
private BaseGoodsInfo goodsInfo;
/**banner*/
private View bannerView;
/**代金券信息*/
private TextView name,explain,price,original_price;
private Button panicBuy;
/**商家信息*/
private View shopView;
private View informationView;
/**附近店铺*/
private View nearByView;
/**服务内容或套餐*/
private View serviceView;
/**购买须知*/
private View noticeView;
/**titleBar*/
private View titleBarView;
private View statusBar;
private NestedScrollView scrollView;
@Override
public void initParms(Bundle params) {
String shop=params.getString("shop");
String cashCoupon=params.getString("cashCoupon");
if (!TextUtils.isEmpty(shop)){
shopInfo=new Gson().fromJson(shop,BaseShopInfo.class);
}
if (!TextUtils.isEmpty(cashCoupon)){
goodsInfo=new Gson().fromJson(cashCoupon,BaseGoodsInfo.class);
}
setSetStatusBar(true);
}
@Override
public View bindView() {
return null;
}
@Override
public int bindLayout() {
return R.layout.activity_voucher_buy;
}
@Override
public void initView(View view, Bundle savedInstanceState) {
titleBarView=findViewById(R.id.voucher_buy_title);
statusBar = findViewById(R.id.title_bar_fakeview);
scrollView = findViewById(R.id.voucher_buy_scrollview);
bannerView=findViewById(R.id.voucher_buy_banner);
name=findViewById(R.id.voucher_buy_name);
explain=findViewById(R.id.voucher_buy_explain);
price=findViewById(R.id.voucher_buy_present_price);
original_price=findViewById(R.id.voucher_buy_original_price);
panicBuy=findViewById(R.id.voucher_buy_panicBuy);
shopView=findViewById(R.id.voucher_shop);
informationView=findViewById(R.id.voucher_address);
nearByView=findViewById(R.id.voucher_nerBy);
serviceView=findViewById(R.id.voucher_service);
noticeView=findViewById(R.id.voucher_notice);
}
@Override
public void setListener() {
panicBuy.setOnClickListener(this);
}
@Override
public void widgetClick(View v) {
int id=v.getId();
if (id==R.id.voucher_buy_panicBuy){
StartPayMentUtils.startPayment(this,goodsInfo,shopInfo);
}
}
@Override
public void doBusiness(Context mContext) {
setShop();
setCashCoupon();
setService();
setNotice();
setNearBy();
}
@Override
protected void onResume() {
super.onResume();
setTitleBarView();
}
/**
* 设置代金券信息
*/
private void setCashCoupon(){
name.setText(goodsInfo.getGoods_name());
explain.setText(goodsInfo.getVolume_description());
price.setText("¥"+goodsInfo.getGoods_price());
original_price.setText("最高门市价: ¥"+goodsInfo.getGoods_market_price());
}
/**
* 设置店铺基本信息
*/
private void setShop(){
BannerUtils.setBanner(bannerView,this,goodsInfo);
NameUtils.setName(shopView,shopInfo);
InformationUtils.setInformation(informationView,this,shopInfo);
}
/**
* 设置附近店铺
*/
public void setNearBy(){
NearByUtils.getNearBy(nearByView,this,shopInfo);
}
/**
* 设置服务内容
*/
public void setService(){
GroupDetailUtils.setCashCouponGroup(serviceView,this,shopInfo.getShop_type(),goodsInfo.getGoods_group_data());
}
/**
* 设置用户须知
*/
private void setNotice(){
NoticeUtils.setNotice(noticeView,this,goodsInfo);
}
/**
* 设置标题栏
*/
private void setTitleBarView(){
ImmersionUtils.setTitleBar(this,titleBarView,goodsInfo.getGoods_name());
ImmersionUtils.setImmersionCanBack(getWindow(),this,scrollView,titleBarView,statusBar);
}
@Override
public void setSetStatusBar(boolean setStatusBar) {
super.setSetStatusBar(setStatusBar);
StatusBarUtil.setTranslucentForImageViewInFragment(CashCouponBuyActivity.this, null);
}
}
|
package valoeghese.metera;
import java.util.List;
import io.netty.buffer.Unpooled;
import net.fabricmc.fabric.api.network.ClientSidePacketRegistry;
import net.fabricmc.fabric.api.network.ServerSidePacketRegistry;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
@SuppressWarnings("deprecation")
public class Network {
public static final Identifier SYNC_ID = new Identifier("metera", "sync");
// doesn't touch client only classes shell be right mate
public static void init() {
ClientSidePacketRegistry.INSTANCE.register(SYNC_ID, (context, data) -> {
WorldData.clientDaySpeed = data.readLong();
});
}
public static void syncs2c(List<ServerPlayerEntity> players, long speed) {
PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer());
buf.writeLong(speed);
for (ServerPlayerEntity player : players) {
ServerSidePacketRegistry.INSTANCE.sendToPlayer(player, Network.SYNC_ID, buf);
}
}
}
|
package com.lvym.ack;
import java.util.HashMap;
import java.util.Map;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Procuder {
public static void main(String[] args) throws Exception{
//1.创建工厂
ConnectionFactory factory=new ConnectionFactory();
factory.setHost("192.168.168.128");
factory.setPort(5672);
factory.setVirtualHost("/");
//2.连接工厂
Connection connection = factory.newConnection();
//3.创建通道
Channel channel = connection.createChannel();
//5.声明交换机,路由
String exchangeName="test-ack-exchange";
String routingKey="ack.kk.save";
//6.发送
for (int i = 0; i < 6; i++) {
Map<String,Object> headers=new HashMap<String, Object>();
headers.put("num", i);
AMQP.BasicProperties properties=new AMQP.BasicProperties().builder()
.deliveryMode(2)
.contentEncoding("utf-8")
.headers(headers)
.build();
String msg="hello-ack模式"+i;
channel.basicPublish(exchangeName, routingKey, properties,msg.getBytes());
}
}
}
|
package game;
/**
* Created by TAWEESOFT on 4/28/16 AD.
*/
public class Player {
private int px,py,vx,vy;
private final int SPEED = 5;
public Player() {
reset();
}
public void reset() {
px = 200;
py = 200;
vx = 0;
vy = -SPEED;
}
public void move() {
px += vx;
py += vy;
}
public void up() {
vx = 0;
vy = -SPEED;
}
public void down() {
vx = 0;
vy = SPEED;
}
public void left() {
vx = -SPEED;
vy = 0;
}
public void right() {
vx = SPEED;
vy = 0;
}
public int getPx() {
return px;
}
public int getPy() {
return py;
}
}
|
package com.example.joypad;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends Activity {
EditText email;
EditText password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
startActivity(new Intent(this, Splash_Activity.class));
Button loginBtn = (Button) findViewById(R.id.loginBtn);
email = (EditText) findViewById(R.id.idInput);
password = (EditText) findViewById(R.id.passwordInput);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Thread thread = new Thread() {
public void run() {
HttpClient httpClient = new DefaultHttpClient();
String urlString = "http://210.118.74.117:3000/LOGINMOBILE";
try {
URI url = new URI(urlString);
HttpPost httpPost = new HttpPost();
httpPost.setURI(url);
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("userId",
email.getText().toString()));
nameValuePairs.add(new BasicNameValuePair(
"password", password.getText().toString()));
httpPost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
HttpResponse response = httpClient
.execute(httpPost);
String responseString = EntityUtils.toString(
response.getEntity(), HTTP.UTF_8);
JSONObject responseJSON = new JSONObject(
responseString);
Log.d("Test", responseJSON.get("status").toString());
if (responseJSON.get("status").toString()
.equals("200")) {
setPreference();
Intent i = new Intent();
i.setClassName("com.example.joypad",
"com.example.joypad.MainActivity");
startActivity(i);
finish();
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
}
private void setPreference() {
SharedPreferences prefs = getSharedPreferences("userId", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("userId", email.getText().toString());
editor.commit();
}
}
|
/**
* ************************************************************************
* Copyright (C) 2010 Atlas of Living Australia All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* *************************************************************************
*/
package au.org.ala.spatial.analysis.user;
/**
* Analyse the log4j (useractions.log) file and send generate reports
*
* @author ajay
*/
public class LogAnalyser {
private void startAnalysis() {
try {
// start by loading the up useractions.log
} catch (Exception e) {
System.out.println("Unable to analyse useractions");
e.printStackTrace(System.out);
}
}
}
|
/*
* $HeadURL: $
* $Id: $
* Copyright (c) 2016 by Riversoft System, all rights reserved.
*/
package com.riversoft.nami.session;
import javax.servlet.http.HttpServletRequest;
import com.riversoft.weixin.common.oauth2.OpenUser;
/**
* @author woden
*
*/
public class SessionHelper {
/**
* 设置用户
*
* @param request
* @param user
*/
public static void setMpUser(HttpServletRequest request, OpenUser user) {
request.getSession().setAttribute("mp_user", user);
}
/**
* 校验有没登录
*
* @param request
* @return
*/
public static boolean checkMpLogin(HttpServletRequest request) {
return request.getSession().getAttribute("mp_user") != null;
}
/**
* 获取用户
*
* @param request
* @return
*/
public static OpenUser getMpUser(HttpServletRequest request) {
return (OpenUser) request.getSession().getAttribute("mp_user");
}
}
|
package org.dmonix.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* This is a void outputstream that doesn't write anything. The result is the same as to write to <code>/dev/null/</code> on Solaris/Linux, i.e. all data is
* written to void.
* <p>
* Copyright: Copyright (c) 2005
* </p>
* <p>
* Company: dmonix.org
* </p>
*
* @author Peter Nerg
* @since 1.0
*/
public class NullOutputStream extends OutputStream {
/**
* Does nothing.
*
* @param b
* The data
* @throws IOException
*/
public void write(int b) throws IOException {
}
/**
* Does nothing.
*
* @param b
* The data
* @throws IOException
*/
public void write(byte[] b) throws IOException {
}
/**
* Does nothing.
*
* @throws IOException
*/
public void flush() throws IOException {
}
/**
* Does nothing. No checks will be made that the either the offset or the length is within the size of the input data array.
*
* @param b
* The data
* @param offset
* The offset in the array
* @param length
* The amount of data to write
* @throws IOException
*/
public void write(byte[] b, int offset, int length) throws IOException {
}
} |
package com.lijingyao.dp.design.state;
/**
* Created by lijingyao on 2017/11/7 11:00.
*/
public class TVRemote {
public static void main(String[] args) {
TVContext sc = new TVContext();
// State tvStartState = new TVStartState();
// State tvStopState = new TVStopState();
sc.writeName("Monday");
sc.writeName("Tuesday");
sc.writeName("Wednesday");
sc.writeName("Thursday");
sc.writeName("Friday");
sc.writeName("Saturday");
sc.writeName("Sunday");
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lappa.smsbanking.IDao.Impl;
import com.douwe.generic.dao.DataAccessException;
import com.douwe.generic.dao.impl.GenericDao;
import lappa.smsbanking.Entities.SmsCompte;
import lappa.smsbanking.IDao.ISmsCompte;
/**
*
* @author lappa
*/
public class ISmsCompteImpl extends GenericDao<SmsCompte, Long> implements ISmsCompte {
@Override
public SmsCompte findByIdS(Long id) throws DataAccessException {
return (SmsCompte) getManager().createQuery("SELECT s FROM SmsCompte s WHERE s.id = :id")
.setParameter("id", id).getSingleResult();
}
@Override
public SmsCompte findByMobile(String mobile) throws DataAccessException {
return (SmsCompte) getManager().createQuery("SELECT s FROM SmsCompte s WHERE s.mobile = :mobile")
.setParameter("mobile", mobile).getSingleResult();
}
@Override
public SmsCompte findByTypeCompte(String typeCompte) throws DataAccessException {
return (SmsCompte) getManager().createQuery("SELECT s FROM SmsCompte s WHERE s.typeCompte = :typeCompte")
.setParameter("typeCompte", typeCompte).getSingleResult();
}
@Override
public SmsCompte findByIdClient(String idClient) throws DataAccessException {
return (SmsCompte) getManager().createQuery("SELECT s FROM SmsCompte s WHERE s.idClient = :idClient")
.setParameter("idClient", idClient).getSingleResult();
}
public SmsCompte findByPin(int pin) throws DataAccessException {
return (SmsCompte) getManager().createQuery("SELECT s FROM SmsCompte s WHERE s.pin = :pin")
.setParameter("pin", pin).getSingleResult();
}
} |
package com.tyss.javacloud.loanproject.beans;
import java.io.Serializable;
import lombok.Data;
@Data
@SuppressWarnings("serial")
public class LoanApplicationBean implements Serializable {
private String applicationId;
private String email;
private String loanType;
private String timePeriod;
private String accountNo;
private String applicantFirstName;
private String applicantMiddleName;
private String applicantLastName;
private String coapplicantFirstName;
private String coapplicantMiddleName;
private String coapplicantLastName;
private String dateOfBirth;
private String loanChoice;
private String branchCode;
private String branchName;
private String loanAmount;
private String formStatus;
}
|
package 문제풀이;
import java.util.Date;
import javax.swing.JOptionPane;
public class 문제풀이이 {
public static void main(String[] args) {
// 1 사원번호 입력 : 기103
// 사원번호 중 첫글자가 '기'인 경우 '기획부이군요'
// '인'인 경우 '인사부이군요'
// '개'인 경우 '개발부이군요'
// 사원번호 중 두번째 글자가 '1' 또는 '2'인 경우 '임원'
// '3'인 경우 '부장'
// '4'또는 '5'인 경우 '평사원'
// 나머지 '해당 직급이 없음'
String a = JOptionPane.showInputDialog("사원번호 입력");
char mun = a.charAt(0);
char mun1 = a.charAt(1);
switch (mun) {
case '기':
System.out.println("기획부이군요");
break;
case '인':
System.out.println("인사부이군요");
break;
default:
System.out.println("개발부이군요");
break;
}
if (mun1 == '1' || mun1 == '2') {
System.out.println("임원");
} else if (mun1 == '3'){
System.out.println("부장");
} else if (mun1 == '4' || mun1 == '5'){
System.out.println("회사원");
} else {
System.out.println("해당 직급이 없음");
}
// 2 나이를 입력: 2
// 태어난 연도는 2020년(Date이용)
// 태어난 시각: 10
// 오전에 태어나셨군요(오전, 오후, 밤, 새벽,...)
//자동import 컨트롤 + 쉬프트 + o, f2
Date date = new Date();
String b = JOptionPane.showInputDialog("나이를 입력");
String c = JOptionPane.showInputDialog("태어난 시각은?");
int d = Integer.parseInt(b);
int e = Integer.parseInt(c);
int day = date.getYear() + 1901;
int result = day - d;
System.out.println("태어난 연도는 " + result + "년");
if (e > 6) {
System.out.println("오전에 태어났군요");
} else if (e > 13){
System.out.println("오후에 태어났군요");
} else if (e < 24){
System.out.println("밤에 태어났군요");
} else {
System.out.println("새벽에 태어났군요");
}
}
}
|
package com.design.pattern.abstractFactory.wordTxt;
/**
* @author zhangbingquan
* @desc Unix系统下的文本框 实现类,用来展示一段文字的文本框。Unix系统中使用
* @time 2019/7/28 18:40
*/
public class UnixText implements Text {
@Override
public void display() {
System.out.println("Unix系统下的文本框实现类,用来展示一段在Unix系统下的文字");
}
}
|
package com.smclaughlin.tps.security;
import com.smclaughlin.tps.IntegrationTest;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
/**
* Created by sineadmclaughlin on 22/11/2016.
*/
public class LoginTestController extends IntegrationTest {
@Override
@Before
public void setup(){
mockMvc= MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
}
@Test
public void redirectToLoginWhenNotAuthenticated() throws Exception{
mockMvc.perform(get("/dashboard"))
.andExpect(status().is3xxRedirection())
.andExpect(unauthenticated())
.andExpect(redirectedUrl(ABSOLUTE_PATH+"login"));
}
@Test
public void testInValidLoginDetails() throws Exception{
mockMvc.perform(formLogin("/login")
.user("user")
.password("password2"))
.andExpect(status().is3xxRedirection())
.andExpect(unauthenticated())
.andExpect(redirectedUrl("/login?error"));
}
@Test
public void testValidLoginDetails() throws Exception{
mockMvc.perform(formLogin("/login")
.user("user")
.password("password"))
.andExpect(status().is3xxRedirection())
.andExpect(authenticated().withRoles("USER"))
.andExpect(redirectedUrl("/"));
}
@Test
@WithMockUser(username="user", roles = "USER")
public void testLoginPage() throws Exception{
mockMvc.perform(get("/login"))
.andExpect(view().name("login"));
}
@Test
@WithMockUser(username="user", roles = "USER")
public void testOnRootRequest() throws Exception{
mockMvc.perform(get("/"))
.andExpect(redirectedUrl("/dashboard"))
.andExpect(view().name("redirect:/dashboard"));
}
@Test
@WithMockUser(username="user", roles = "USER")
public void testLogout() throws Exception{
mockMvc.perform(get("/logout"))
.andExpect(unauthenticated())
.andExpect(redirectedUrl("/login?logout"));
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.widgets.menu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
/**
* 自定义菜单项
* Style可以是CHECK, RADIO, PUSH, SEPARATOR, CASCADE
*
* @author luma
*/
public class CMenuItem {
private int style;
private CMenu parent;
private CMenu child;
private String text;
private Image image;
private boolean selected;
private boolean enabled;
private boolean visible;
private List<ISelectionListener> listeners;
private Map<String, Object> datas;
private static final String DEFAULT_DATA = "default_data";
public CMenuItem(CMenu menu, int style) {
this(menu, style, menu.getItemCount());
}
public CMenuItem(CMenu menu, int style, int index) {
checkStyle(style);
parent = menu;
parent.addItem(this, index);
listeners = new ArrayList<ISelectionListener>();
enabled = true;
selected = false;
visible = true;
}
public void setMenu(CMenu menu) {
child = menu;
}
private void checkStyle(int style) {
style &= (SWT.CHECK | SWT.RADIO | SWT.PUSH | SWT.SEPARATOR | SWT.CASCADE);
if(style == 0)
style = SWT.PUSH;
this.style = style;
}
public void setData(Object data) {
if(datas == null)
datas = new HashMap<String, Object>();
datas.put(DEFAULT_DATA, data);
}
public void setData(String key, Object data) {
if(datas == null)
datas = new HashMap<String, Object>();
datas.put(key, data);
}
public Object getData() {
if(datas == null)
return null;
else
return datas.get(DEFAULT_DATA);
}
public Object getData(String key) {
if(datas == null)
return null;
else
return datas.get(key);
}
void fireSelectionEvent() {
SelectionEvent e = new SelectionEvent(this);
for(ISelectionListener sl : listeners)
sl.widgetSelected(e);
}
public void addSelectionListener(ISelectionListener sl) {
listeners.add(sl);
}
public void dispose() {
parent.removeItem(this);
}
/**
* @return Returns the child.
*/
public CMenu getChild() {
return child;
}
/**
* @param child The child to set.
*/
public void setChild(CMenu child) {
this.child = child;
}
/**
* @return Returns the image.
*/
public Image getImage() {
return image;
}
/**
* @param image The image to set.
*/
public void setImage(Image image) {
this.image = image;
}
/**
* @return Returns the name.
*/
public String getText() {
return text;
}
/**
* @param name The name to set.
*/
public void setText(String name) {
this.text = name;
}
/**
* @return Returns the selected.
*/
public boolean isSelected() {
return selected;
}
/**
* @param selected The selected to set.
*/
public void setSelected(boolean selected) {
this.selected = selected;
}
/**
* @return Returns the style.
*/
public int getStyle() {
return style;
}
/**
* @return Returns the enabled.
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param enabled The enabled to set.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @return Returns the visible.
*/
public boolean isVisible() {
return visible;
}
/**
* @param visible The visible to set.
*/
public void setVisible(boolean visible) {
this.visible = visible;
parent.setSizeDirty(true);
}
}
|
package io.wizzie.bootstrapper.builder;
public interface Listener {
public void updateConfig(SourceSystem sourceSystem, String config);
}
|
package salesTaxes.utils;
import java.text.DecimalFormat;
import java.text.ParseException;
public class NumericUtils
{
private static final DecimalFormat percFormat = new DecimalFormat( "0.00%" );
public static double parsePerc(final String s) throws ParseException
{
return percFormat.parse( s ).doubleValue();
}
public static double roundTo05( double d )
{
return Math.round( d * 20.0 ) / 20.0;
}
}
|
package cn.bs.zjzc.model.impl;
import com.zhy.http.okhttp.callback.StringCallback;
import cn.bs.zjzc.App;
import cn.bs.zjzc.model.INewsCenterModel;
import cn.bs.zjzc.model.callback.HttpTaskCallback;
import cn.bs.zjzc.model.response.BaseResponse;
import cn.bs.zjzc.model.response.NewsListResponse;
import cn.bs.zjzc.net.GsonCallback;
import cn.bs.zjzc.net.PostHttpTask;
import cn.bs.zjzc.net.RequestUrl;
/**
* Created by Ming on 2016/6/17.
*/
public class NewsCenterModel implements INewsCenterModel {
@Override
public void getNewsList(String page, String number, final HttpTaskCallback<NewsListResponse.DataBean> callback) {
String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.newsList);
PostHttpTask<NewsListResponse> httpTask = new PostHttpTask<>(url);
httpTask.addParams("token", App.LOGIN_USER.getToken())
.addParams("page", page)
.addParams("number", number)
.execute(new GsonCallback<NewsListResponse>() {
@Override
public void onFailed(String errorInfo) {
callback.onTaskFailed(errorInfo);
}
@Override
public void onSuccess(NewsListResponse response) {
callback.onTaskSuccess(response.data);
}
});
}
@Override
public void setNewsRead(String id, final HttpTaskCallback<BaseResponse> callback) {
String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.setNewsRead);
PostHttpTask<BaseResponse> httpTask = new PostHttpTask<>(url);
httpTask.addParams("token", App.LOGIN_USER.getToken())
.addParams("number", id)
.execute(new GsonCallback<BaseResponse>() {
@Override
public void onFailed(String errorInfo) {
callback.onTaskFailed(errorInfo);
}
@Override
public void onSuccess(BaseResponse response) {
callback.onTaskSuccess(response);
}
});
}
@Override
public void deleteNews(final String id, final HttpTaskCallback<BaseResponse> callback) {
String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.deleteNews);
PostHttpTask<BaseResponse> httpTask = new PostHttpTask<>(url);
httpTask.addParams("token", App.LOGIN_USER.getToken())
.addParams("number", id)
.execute(new GsonCallback<BaseResponse>() {
@Override
public void onFailed(String errorInfo) {
callback.onTaskFailed(errorInfo);
}
@Override
public void onSuccess(BaseResponse response) {
callback.onTaskSuccess(response);
}
});
}
}
|
package com.hawk.application.service;
import java.util.List;
import com.hawk.application.model.Sdk;
public interface SdkService {
List<Sdk> findAllSdks();
}
|
/*
* 文 件 名: OperatorDao.java
* 描 述: OperatorDao.java
* 时 间: 2013-8-1
*/
package com.babyshow.operator.dao;
import com.babyshow.operator.bean.Operator;
/**
* <一句话功能简述>
*
* @author ztc
* @version [BABYSHOW V1R1C1, 2013-8-1]
*/
public interface OperatorDao
{
public Operator findOperatorByLoginName(String loginName);
}
|
package com.charith.hackerrank.RecursionAndBacktracking.RecursiveDigitSum;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void superDigit() {
Assertions.assertEquals(3, Solution.superDigit("148", 3));
Assertions.assertEquals(8, Solution.superDigit("9875", 4));
Assertions.assertEquals(9, Solution.superDigit("123", 3));
}
} |
package com.appc.report.service;
import com.appc.report.model.UserCard;
/**
* UserCardService
*
* @version : Ver 1.0
* @author : panda
* @date : 2017-9-14
*/
public interface UserCardService extends CommonService<UserCard>{
}
|
/**
* Copyright 2013-present febit.org (support@febit.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.febit.schedule.cron;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Cron Parser
*
* @author zqq90
*/
public class CronParser {
private final char[] buffer;
CronParser(final char[] cron) {
this.buffer = cron != null ? cron : new char[0];
}
CronParser(final String cron) {
this.buffer = cron != null ? cron.toCharArray() : new char[0];
}
/**
* Parse cron string.
*
* @param cron
* @return Matcher
* @throws InvalidCronException
*/
public static Matcher parse(String cron) throws InvalidCronException {
return new CronParser(cron).parse();
}
/**
* Parse cron char array.
*
* @param cron
* @return Matcher
* @throws InvalidCronException
*/
public static Matcher parse(final char[] cron) throws InvalidCronException {
return new CronParser(cron).parse();
}
/**
* Parse cron string.
*
* @return
* @throws InvalidCronException
*/
public Matcher parse() throws InvalidCronException {
final int buff_len = buffer.length;
final List<Matcher> matchers = new ArrayList<>();
int start = 0;
int next;
Matcher matcher;
while (start < buff_len) {
next = nextIndexOf('|', start, buff_len);
matcher = parseSingleMatcher(start, next);
if (matcher != null
&& matcher != Matcher.MATCH_ALL) {
matchers.add(matcher);
} else {
//NOTE: if one matcher is null, it means match all.
return Matcher.MATCH_ALL;
}
start = next + 1;
}
//export
switch (matchers.size()) {
case 0:
return Matcher.MATCH_ALL;
case 1:
return matchers.get(0);
case 2:
return new OrMatcher(matchers.get(0), matchers.get(1));
default:
return new OrMatcherGroup(matchers.toArray(new Matcher[matchers.size()]));
}
}
private int skipRepeatChar(char c, int offset, final int to) {
while (offset < to) {
if (buffer[offset] == c) {
offset++;
} else {
return offset;
}
}
return to;
}
private Matcher parseSingleMatcher(final int offset, final int to) {
if (offset >= to) {
throw createInvalidCronException("Invalid cron-expression", offset);
}
final List<Matcher> matchers = new ArrayList<>();
int start = skipRepeatChar(' ', offset, to);
if (start >= to) {
throw createInvalidCronException("Invalid cron-expression", offset);
}
int next;
Atom atom;
int step = 0;
while (true) {
next = nextIndexOf(' ', start, to);
final List<AtomProto> atomProtos = parseAtoms(start, next);
switch (step) {
case 0: //minute
atom = warpToOrAtom(atomProtos, 0, 59);
if (atom != null) {
matchers.add(new MinuteMatcher(atom));
}
break;
case 1: //hour
atom = warpToOrAtom(atomProtos, 0, 23);
if (atom != null) {
matchers.add(new HourMatcher(atom));
}
break;
case 2: //Day
atom = warpToOrAtom(atomProtos, 1, 31);
if (atom != null) {
matchers.add(new DayOfMonthMatcher(atom));
}
break;
case 3: //month
atom = warpToOrAtom(atomProtos, 1, 12);
if (atom != null) {
matchers.add(new MonthMatcher(atom));
}
break;
case 4: //year
atom = warpToOrAtom(atomProtos, 1, 99999);
if (atom != null) {
matchers.add(new YearMatcher(atom));
}
break;
case 5: //dayofweek
atom = warpToOrAtom(atomProtos, 1, 7);
if (atom != null) {
matchers.add(new DayOfWeekMatcher(atom));
}
break;
default:
return wrapToSingleAndMatcher(matchers);
}
step++;
start = skipRepeatChar(' ', next, to);
if (start == to) {
return wrapToSingleAndMatcher(matchers);
}
}
}
private Matcher wrapToSingleAndMatcher(final List<Matcher> matchers) {
//XXX: sort by performance
switch (matchers.size()) {
case 0:
return null;
case 1:
return matchers.get(0);
case 2:
return new AndMatcher(matchers.get(0), matchers.get(1));
default:
return new AndMatcherGroup(matchers.toArray(new Matcher[matchers.size()]));
}
}
private List<AtomProto> parseAtoms(final int offset, final int to) {
if (buffer[to - 1] == ',') {
throw createInvalidCronException("Invalid chat ','", to);
}
final List<AtomProto> atoms = new ArrayList<>();
int start = offset;
int next;
AtomProto atom;
while (start < to) {
next = nextIndexOf(',', start, to);
atom = parseSingleAtom(start, next);
if (atom != null) {
atoms.add(atom);
}
start = next + 1;
}
return atoms;
}
private Atom warpToOrAtom(List<AtomProto> atomProtos, final int min, final int max) {
final int protoSize = atomProtos.size();
if (protoSize == 1) {
return atomProtos.get(0);
} else if (protoSize == 0) {
return null;
} else {
final List<Atom> atoms = new ArrayList<>(protoSize);
final IntSet list = new IntSet();
AtomProto atomProto;
for (Iterator<AtomProto> it = atomProtos.iterator(); it.hasNext();) {
atomProto = it.next();
if (atomProto.maxNumber(min, max) <= 6) {
atomProto.render(list, min, max);
} else {
atoms.add(atomProto);
}
}
switch (list.size()) {
case 0:
break;
case 1:
atoms.add(0, new ValueAtom(list.get(0)));
break;
case 2:
atoms.add(0, new OrValueAtom(list.get(0), list.get(1)));
break;
case 3:
atoms.add(0, new OrThreeValueAtom(list.get(0), list.get(1), list.get(2)));
break;
default:
atoms.add(0, new ArrayAtom(list.toSortedArray()));
}
//export
switch (atoms.size()) {
case 0:
return null;
case 1:
return atoms.get(0);
case 2:
return new OrAtom(atoms.get(0), atoms.get(1));
default:
return new OrAtomGroup(atoms.toArray(new Atom[atoms.size()]));
}
}
}
private AtomProto parseSingleAtom(final int offset, final int to) {
if (offset >= to) {
throw createInvalidCronException("Invalid cron-expression", offset);
}
int rangeChar = nextIndexOf('-', offset, to);
if (rangeChar != to) {
int divChar = nextIndexOf('/', rangeChar + 1, to);
if (divChar != to) {
return new RangeDivAtom(parseNumber(offset, rangeChar),
parseNumber(rangeChar + 1, divChar),
parseNumber(divChar + 1, to));
} else {
return new RangeAtom(parseNumber(offset, rangeChar),
parseNumber(rangeChar + 1, to));
}
} else if (buffer[offset] == '*') {
final int offset_1;
if ((offset_1 = offset + 1) == to) {
return null; //TRUE_ATOM;
} else if (buffer[offset_1] == '/') {
return new DivAtom(parseNumber(offset_1 + 1, to));
} else {
throw createInvalidCronException("Invalid char '" + buffer[offset_1] + '\'', offset_1);
}
} else {
int divChar = nextIndexOf('/', offset + 1, to);
if (divChar != to) {
return new RangeDivAtom(parseNumber(offset, divChar),
Integer.MAX_VALUE,
parseNumber(divChar + 1, to));
} else {
return new ValueAtom(parseNumber(offset, to));
}
}
}
private int parseNumber(int offset, final int to) throws InvalidCronException {
if (offset >= to) {
throw createInvalidCronException("Need a number", offset);
}
int value = 0;
char c;
while (offset < to) {
c = buffer[offset++];
if (c >= '0' && c <= '9') {
value = value * 10 + ((int) c - (int) '0');
} else {
throw createInvalidCronException("Invalid numberic char '" + c + '\'', offset);
}
}
return value;
}
private InvalidCronException createInvalidCronException(String message, int offset) {
return new InvalidCronException(new StringBuilder(message)
.append(", at ").append(offset)
.append(" of cron '").append(buffer).append("'.")
.toString());
}
private int nextIndexOf(char c, int offset, int to) {
final char[] buf = buffer;
for (; offset < to; offset++) {
if (buf[offset] == c) {
return offset;
}
}
return to;
}
}
|
package poc.api.interfaces.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@Service
public class RequestBuilder {
@Autowired
private RestTemplate restTemplate;
public <T> ResponseEntity<T> executeRequest(String url, HttpMethod method, Class<T> returnType,
MultiValueMap<String, String> headerParams){
HttpEntity<T> request = new HttpEntity<T>(headerParams);
ResponseEntity<T> response = restTemplate.exchange(url, method, request, returnType);
return response;
}
}
|
package compiler;
import java.util.HashMap;
public class Bexp extends Expression{
Bexp(Expression e1, Expression e2, String operator){
this.e1 = e1;
this.e2 = e2;
this.operator = operator;
}
Bexp(Expression e1, String operator){
this.e1 = e1;
this.operator = operator;
}
int eval(HashMap<String, Integer> map) throws Exception{
if (operator.equals("Equals"))
return e1.eval(map)==e2.eval(map)?1:0;
else if (operator.equals("LessThan"))
return e1.eval(map)<e2.eval(map)?1:0;
else if (operator.equals("GreaterThan"))
return e1.eval(map)>e2.eval(map)?1:0;
else if (operator.equals("And"))
return e1.eval(map)==1 && e2.eval(map)==1?1:0;
else if (operator.equals("Or"))
return e1.eval(map)==1 || e2.eval(map)==1?1:0;
else if (operator.equals("Not"))
return e1.eval(map)==0?1:0;
else{
throw new Exception("Operator not found");
}
}
}
|
package com.pangpang6.books.functions;
import java.util.function.Function;
/**
* Created by jiangjiguang on 2017/12/10.
*/
public class FunctionTest {
public static void main(String[] args) {
test();
}
private static void test(){
Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e;
int i1= times2.compose(squared).apply(4);
// Returns 32
System.out.println(i1);
int i2 = times2.andThen(squared).apply(4);
// Returns 64
System.out.println(i2);
}
}
|
/*
* Copyright (C) 2018 askaeks
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package restaurant.models;
import db.DBConnection;
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 javax.swing.JOptionPane;
import restaurant.interfaces.ModelInterface;
import restaurant.objects.MenuObject;
/**
*
* @author askaeks
*/
public final class MenuModel extends javax.swing.table.AbstractTableModel
implements ModelInterface {
private final ArrayList<MenuObject> data;
private final String[] columns = {"Menu Id", "Nama", "Kategori", "Harga", "Stock Kosong"};
private final String[] category;
public MenuModel() {
category = new String[]{"Hidangan Pembuka", "Hidangan Utama", "Hidangan Penutup", "Minuman"};
data = new ArrayList<>();
initialize();
}
public MenuObject update(int index, MenuObject newData) {
try {
MenuObject oldData = data.get(index);
data.set(index, newData);
PreparedStatement statement = DBConnection.getConnection().prepareStatement("UPDATE Menu SET nama =?, kategori = ?, harga = ?, stock = ? WHERE id = ?");
statement.setString(1, newData.getNama());
statement.setInt(2, newData.getKategori());
statement.setInt(3, newData.getHarga());
statement.setBoolean(4, newData.getStock());
statement.setInt(5, newData.getId());
if (statement.executeUpdate() == 1) {
fireTableRowsUpdated(index, index);
return newData;
}
} catch (ArrayIndexOutOfBoundsException e) {
} catch (SQLException err) {
JOptionPane.showMessageDialog(null, "Terjadi masalah ketika mengeksekusi perintah. State : " + err.getSQLState(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
}
return null;
}
public MenuObject remove(int index) {
// TODO: Remove from database!
MenuObject forReturn = data.remove(index);
try {
PreparedStatement statement = DBConnection.getConnection().prepareStatement("DELETE FROM Menu WHERE id = ?");
statement.setInt(1, forReturn.getId());
if (statement.executeUpdate() == 1) {
fireTableRowsDeleted(index, index);
return forReturn;
}
} catch (SQLException err) {
JOptionPane.showMessageDialog(null, "Terjadi masalah ketika mengeksekusi perintah. State : " + err.getSQLState(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
}
return null;
}
public MenuObject get(int index) {
return data.get(index);
}
public boolean add(MenuObject e) {
try {
PreparedStatement statement = DBConnection.getConnection().prepareStatement("INSERT INTO `Menu`(`nama`, `kategori`, `harga`, `stock`) VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
statement.setString(1, e.getNama());
statement.setInt(2, e.getKategori());
statement.setInt(3, e.getHarga());
statement.setBoolean(4, e.getStock());
if (statement.executeUpdate() == 1) {
int candidateId = 0;
ResultSet rs = statement.getGeneratedKeys();
if(rs.next())
candidateId = rs.getInt(1);
e.setId(candidateId);
boolean forReturn = data.add(e);
fireTableRowsInserted(data.size() - 1, data.size() - 1);
return forReturn;
}
} catch (SQLException err) {
JOptionPane.showMessageDialog(null, "Terjadi masalah ketika mengeksekusi perintah. State : " + err.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
}
return false;
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public Class getColumnClass(int col) {
switch (col) {
case 0:
case 3:
return Integer.class;
case 4:
return Boolean.class;
default:
return String.class;
}
}
@Override
public Object getValueAt(int arg0, int arg1) {
switch (arg1) {
case 0:
return data.get(arg0).getId();
case 1:
return data.get(arg0).getNama();
case 2:
return category[data.get(arg0).getKategori()];
case 3:
return data.get(arg0).getHarga();
case 4:
return !data.get(arg0).getStock();
default:
return null;
}
}
@Override
public String getColumnName(int arg0) {
return columns[arg0];
}
public static ArrayList<MenuObject> getMenu(boolean onlyOnStock) {
ArrayList<MenuObject> forReturn = new ArrayList<>();
Connection conn = DBConnection.getConnection();
try {
Statement query = conn.createStatement();
ResultSet tableInitialData = query.executeQuery("SELECT * FROM Menu");
while (tableInitialData.next()) {
if (onlyOnStock && !tableInitialData.getBoolean("stock")) continue;
forReturn.add(new MenuObject(tableInitialData.getInt("Id"), tableInitialData.getString("nama"),
tableInitialData.getInt("kategori"), tableInitialData.getInt("harga"), tableInitialData.getBoolean("stock")));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Terjadi masalah ketika mengeksekusi perintah. State : " + e.getSQLState(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
}
return forReturn;
}
public static MenuObject getMenu(Integer id) {
Connection conn = DBConnection.getConnection();
try {
Statement query = conn.createStatement();
ResultSet tableInitialData = query.executeQuery("SELECT * FROM Menu WHERE id = '"+ id +"'");
while (tableInitialData.next()) {
return new MenuObject(tableInitialData.getInt("Id"), tableInitialData.getString("nama"),
tableInitialData.getInt("kategori"), tableInitialData.getInt("harga"), tableInitialData.getBoolean("stock"));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Terjadi masalah ketika mengeksekusi perintah. State : " + e.getSQLState(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
}
return null;
}
@Override
public void initialize() {
data.addAll(getMenu(false));
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.rest.endpoint;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.module.ModuleManager;
import com.openkm.module.PropertyModule;
import com.openkm.rest.GenericException;
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class PropertyService {
private static Logger log = LoggerFactory.getLogger(PropertyService.class);
@POST
@Path("/addCategory")
public void addCategory(@QueryParam("nodeId") String nodeId, @QueryParam("catId") String catId) throws GenericException {
try {
log.debug("addCategory({}, {})", nodeId, catId);
PropertyModule pm = ModuleManager.getPropertyModule();
pm.addCategory(null, nodeId, catId);
log.debug("addCategory: void");
} catch (Exception e) {
throw new GenericException(e);
}
}
@DELETE
@Path("/removeCategory")
public void removeCategory(@QueryParam("nodeId") String nodeId, @QueryParam("catId") String catId) throws GenericException {
try {
log.debug("removeCategory({}, {})", nodeId, catId);
PropertyModule pm = ModuleManager.getPropertyModule();
pm.removeCategory(null, nodeId, catId);
log.debug("removeCategory: void");
} catch (Exception e) {
throw new GenericException(e);
}
}
@POST
@Path("/addKeyword")
public void addKeyword(@QueryParam("nodeId") String nodeId, @QueryParam("keyword") String keyword) throws GenericException {
try {
log.debug("addKeyword({}, {})", nodeId, keyword);
PropertyModule pm = ModuleManager.getPropertyModule();
pm.addKeyword(null, nodeId, keyword);
log.debug("addKeyword: void");
} catch (Exception e) {
throw new GenericException(e);
}
}
@DELETE
@Path("/removeKeyword")
public void removeKeyword(@QueryParam("nodeId") String nodeId, @QueryParam("keyword") String keyword) throws GenericException {
try {
log.debug("removeKeyword({}, {})", nodeId, keyword);
PropertyModule pm = ModuleManager.getPropertyModule();
pm.removeKeyword(null, nodeId, keyword);
log.debug("removeKeyword: void");
} catch (Exception e) {
throw new GenericException(e);
}
}
} |
package com.tencent.mm.plugin.mmsight.ui;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.media.MediaMetadataRetriever;
import com.tencent.mm.c.g;
import com.tencent.mm.modelsfs.FileOp;
import com.tencent.mm.plugin.mmsight.a.a.b;
import com.tencent.mm.plugin.mmsight.segment.m;
import com.tencent.mm.plugin.sight.base.a;
import com.tencent.mm.plugin.sight.base.d;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class a$4 implements Runnable {
final /* synthetic */ Bitmap abc;
final /* synthetic */ a lpk;
a$4(a aVar, Bitmap bitmap) {
this.lpk = aVar;
this.abc = bitmap;
}
public final void run() {
int i;
int i2;
int i3;
a Lo = d.Lo(this.lpk.videoPath);
if (Lo != null) {
i = Lo.width;
i2 = Lo.height;
i3 = Lo.videoBitrate;
} else {
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this.lpk.videoPath);
i = bi.getInt(mediaMetadataRetriever.extractMetadata(18), -1);
i2 = bi.getInt(mediaMetadataRetriever.extractMetadata(19), -1);
i3 = bi.getInt(mediaMetadataRetriever.extractMetadata(20), -1);
mediaMetadataRetriever.release();
}
if (i <= 0 || i2 <= 0 || i3 <= 0) {
x.e("MicroMsg.MMSightVideoEditor", "doRemuxVideo, retrieve video metadata error, width: %s, height: %s, bitrate: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3)});
return;
}
int min;
String str;
if (this.lpk.lpe && this.lpk.lfT != null) {
Point point;
if (i3 > this.lpk.lfT.videoBitrate) {
i3 = this.lpk.lfT.videoBitrate;
}
int i4 = this.lpk.lfT.width;
int i5 = this.lpk.lfT.height;
x.d("MicroMsg.MMSightVideoEditor", "scale() called with: decoderOutputWidth = [" + i + "], decoderOutputHeight = [" + i2 + "], specWidth = [" + i4 + "], specHeight = [" + i5 + "]");
if (i > i4 || i2 > i5) {
int max = Math.max(i, i2);
min = Math.min(i, i2);
int max2 = Math.max(i4, i5);
int min2 = Math.min(i4, i5);
if (max % 16 == 0 && Math.abs(max - max2) < 16 && min % 16 == 0 && Math.abs(min - min2) < 16) {
x.i("MicroMsg.MMSightVideoEditor", "calc scale, same len divide by 16, no need scale");
point = null;
} else if (max / 2 == max2 && min / 2 == min2) {
x.i("MicroMsg.MMSightVideoEditor", "calc scale, double ratio");
i4 = i / 2;
i5 = i2 / 2;
if (i4 % 2 != 0) {
i4++;
}
if (i5 % 2 != 0) {
i5++;
}
point = new Point(i4, i5);
} else {
max /= 2;
min /= 2;
if (max % 16 != 0 || Math.abs(max - max2) >= 16 || min % 16 != 0 || Math.abs(min - min2) >= 16) {
Point point2 = new Point();
if (i < i2) {
i5 = Math.min(i4, i5);
i4 = (int) (((double) i2) / ((1.0d * ((double) i)) / ((double) i5)));
} else {
i4 = Math.min(i4, i5);
i5 = (int) (((double) i) / ((1.0d * ((double) i2)) / ((double) i4)));
}
if (i4 % 2 != 0) {
i4++;
}
if (i5 % 2 != 0) {
i5++;
}
x.i("MicroMsg.MMSightVideoEditor", "calc scale, outputsize: %s %s", new Object[]{Integer.valueOf(i5), Integer.valueOf(i4)});
point2.x = i5;
point2.y = i4;
point = point2;
} else {
x.i("MicroMsg.MMSightVideoEditor", "calc scale, double ratio divide by 16");
i4 = i / 2;
i5 = i2 / 2;
if (i4 % 2 != 0) {
i4++;
}
if (i5 % 2 != 0) {
i5++;
}
point = new Point(i4, i5);
}
}
} else {
x.i("MicroMsg.MMSightVideoEditor", "calc scale, small or equal to spec size");
point = null;
}
if (point != null) {
i = point.x;
i2 = point.y;
min = i3;
str = this.lpk.videoPath + "remuxOutput.mp4";
if (!bi.oW(this.lpk.lph)) {
str = this.lpk.lph;
}
if (this.lpk.loV >= 0 || this.lpk.loW <= 0) {
if (this.lpk.lpi == -1 && (this.lpk.lpi == 1 || this.lpk.lpi == 2)) {
this.lpk.lpb = com.tencent.mm.plugin.mmsight.api.a.leA.a(this.lpk.lpi, this.lpk.videoPath, str, i, i2, min, this.lpk.lfT.fps);
} else {
this.lpk.lpb = com.tencent.mm.plugin.mmsight.api.a.leA.b(this.lpk.videoPath, str, i, i2, min, this.lpk.lfT.fps);
}
} else if (this.lpk.lpi == -1 || !(this.lpk.lpi == 1 || this.lpk.lpi == 2)) {
this.lpk.lpb = com.tencent.mm.plugin.mmsight.api.a.leA.a(this.lpk.videoPath, str, i, i2, min, this.lpk.lfT.fps, (long) this.lpk.loV, (long) this.lpk.loW);
} else {
this.lpk.lpb = com.tencent.mm.plugin.mmsight.api.a.leA.a(this.lpk.lpi, this.lpk.videoPath, str, i, i2, min, this.lpk.lfT.fps, (long) this.lpk.loV, (long) this.lpk.loW);
}
x.i("MicroMsg.MMSightVideoEditor", "created remuxer, type: %s, remuxer: %s", new Object[]{Integer.valueOf(this.lpk.lpi), this.lpk.lpb});
if (this.lpk.lpb != null) {
ah.A(new 1(this));
}
m.sX(this.lpk.lpb.getType());
long VG = bi.VG();
if (this.abc != null) {
this.lpk.lpb.B(this.abc);
}
if (this.lpk.lpb.bdG() < 0) {
x.e("MicroMsg.MMSightVideoEditor", "remux failed, ret: %s", new Object[]{Integer.valueOf(this.lpk.lpb.bdG())});
ah.A(new 2(this));
m.sY(this.lpk.lpb.getType());
return;
}
if (bi.oW(this.lpk.lph)) {
FileOp.av(str, this.lpk.videoPath);
}
m.C(this.lpk.lpb.getType(), bi.bI(VG));
this.lpk.bKg = g.cu(this.lpk.videoPath);
b bVar = this.lpk.lpj;
boolean z = this.lpk.loV >= 0 && this.lpk.loW > 0;
bVar.lkD = z;
this.lpk.lpj.lkA = this.lpk.loW - this.lpk.loV;
this.lpk.lpj.lkz = Lo == null ? 0 : Lo.jdD;
ah.A(new 3(this));
return;
}
}
min = i3;
str = this.lpk.videoPath + "remuxOutput.mp4";
if (bi.oW(this.lpk.lph)) {
str = this.lpk.lph;
}
if (this.lpk.loV >= 0) {
}
if (this.lpk.lpi == -1) {
}
this.lpk.lpb = com.tencent.mm.plugin.mmsight.api.a.leA.b(this.lpk.videoPath, str, i, i2, min, this.lpk.lfT.fps);
x.i("MicroMsg.MMSightVideoEditor", "created remuxer, type: %s, remuxer: %s", new Object[]{Integer.valueOf(this.lpk.lpi), this.lpk.lpb});
if (this.lpk.lpb != null) {
m.sX(this.lpk.lpb.getType());
long VG2 = bi.VG();
if (this.abc != null) {
this.lpk.lpb.B(this.abc);
}
if (this.lpk.lpb.bdG() < 0) {
x.e("MicroMsg.MMSightVideoEditor", "remux failed, ret: %s", new Object[]{Integer.valueOf(this.lpk.lpb.bdG())});
ah.A(new 2(this));
m.sY(this.lpk.lpb.getType());
return;
}
if (bi.oW(this.lpk.lph)) {
FileOp.av(str, this.lpk.videoPath);
}
m.C(this.lpk.lpb.getType(), bi.bI(VG2));
this.lpk.bKg = g.cu(this.lpk.videoPath);
b bVar2 = this.lpk.lpj;
boolean z2 = this.lpk.loV >= 0 && this.lpk.loW > 0;
bVar2.lkD = z2;
this.lpk.lpj.lkA = this.lpk.loW - this.lpk.loV;
this.lpk.lpj.lkz = Lo == null ? 0 : Lo.jdD;
ah.A(new 3(this));
return;
}
ah.A(new 1(this));
}
}
|
package com.example.demo.socket;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
/**
*
* @author Adam M. Gamboa G
*/
public class SocketHelper {
private static final Logger LOGGER = Logger.getLogger(SocketHelper.class.getName());
private final static Map<String,SocketHelper> socketPools = new HashMap<>();
private final SocketPool socketPool;
/**
* Constructor privado para ocultarlo
*/
private SocketHelper(SocketPool socketPool){
this.socketPool = socketPool;
}
//<<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>>
//<<>><<>><<>><<>><<>> METODOS SINGLETON <<>><<>><<>><<>><<>><<>><<>><<>>
//<<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>>
/**
* Método encargado de obtener una instancia unica en la cual se encuentra
* el pool de clients sockets.
*
* @param host Host del socket a conectarse
* @param port Puerto del socket a conectarse
* @return Instancia unica del helper
*/
public static SocketHelper getInstance(String host, int port){
String key = host+":"+port;
if(!socketPools.containsKey(key)){
synchronized(SocketHelper.class){
SocketFactory factory = new SocketFactory(host, port);
GenericObjectPoolConfig config = getDefaultConfig();
SocketPool newPool = new SocketPool(factory, config);
try {
newPool.preparePool();
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Pool prepare error", ex);
}
SocketHelper newInstance = new SocketHelper(newPool);
socketPools.put(key, newInstance);
}
}
return socketPools.get(key);
}
public void shutDown(){
String key = ((SocketFactory)socketPool.getFactory()).getHost()+":"+
((SocketFactory)socketPool.getFactory()).getPort();
socketPools.remove(key);
}
/**
* Genera un objeto con la configuración por defecto que se desea para los
* pools de sockets generados
* @return Configuración
*/
private static GenericObjectPoolConfig getDefaultConfig(){
GenericObjectPoolConfig defaultConfig = new GenericObjectPoolConfig();
//Setear aqui la configuración por defecto que se desea
return defaultConfig;
}
//<<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>>
//<<>><<>><<>><<>><<>> METODOS HELPER <<>><<>><<>><<>><<>><<>><<>><<>>
//<<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>><<>>
/**
* Obtiene una instancia de un cliente de socket.
* @return Instancia del cliente de socket.
*/
public SocketClient getSocket(){
try {
return this.socketPool.borrowObject();
} catch (Exception ex) {
Logger.getLogger(SocketHelper.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
/**
* Regresa la instancia de cliente de socket al pool.
*
* @param socketClient Instancia a ser devuelta.
*/
public void returnSocket(SocketClient socketClient){
this.socketPool.returnObject(socketClient);
}
/**
* Setea valores de configuración en el pool.
* @param config Propiedades de configuración
*/
public void setConfiguration(GenericObjectPoolConfig config){
this.socketPool.setConfig(config);
try{
this.socketPool.preparePool();
}catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Error tratanto de resetear el pool", ex);
}
}
/**
* Registra en el log el estado actual del pool.
*/
public void logStatus(){
StringBuilder sb = new StringBuilder();
sb.append("\n-------------------------------------").append("\n")
.append("[Tamano Máximo:").append(this.socketPool.getMaxTotal()).append("]")
.append("[Tamano Minimo:").append(this.socketPool.getMinIdle()).append("]")
.append("[Instancias utilizadas:").append(this.socketPool.getNumActive()).append("]")
.append("[Instancias no utilizadas: ").append(this.socketPool.getNumIdle()).append("]")
.append("[Total Instancias: ").append(this.socketPool.getNumIdle()+this.socketPool.getNumActive()).append("]")
.append("[Peticiones en cola: ").append(this.socketPool.getNumWaiters()).append("]")
.append("\n-------------------------------------").append("\n");
LOGGER.log(Level.INFO, sb.toString());
}
/**
* Las caracteristicas son configuraciones o estados actuales del pool.
*
* @param feature Caracteristica del pool a consultar
* @return Valor encontrado
*/
public int getFeature(StatusPoolFeature feature){
switch(feature){
case NUM_ACTIVE:
return this.socketPool.getNumActive();
case NUM_IDLE:
return this.socketPool.getNumIdle();
case NUM_WAITERS:
return this.socketPool.getNumWaiters();
case MAX_TOTAL:
return this.socketPool.getMaxTotal();
}
return -1;
}
/**
* Enumerado con las carateristicas del Pool que se permiten consultar
*/
public enum StatusPoolFeature{
NUM_ACTIVE,
NUM_IDLE,
NUM_WAITERS,
MAX_TOTAL;
}
}
|
package org.cheng.login.service;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import org.cheng.login.MyApp;
import org.cheng.login.entity.User;
public class PreferencesService {
private static Context context= MyApp.getContext();
public PreferencesService(Context context) {
this.context = context;
}
public static void saveUser(User user) {
//���SharedPreferences����
SharedPreferences preferences = context.getSharedPreferences("denglu", Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name",user.getName());
editor.putString("pwd", user.getPass());
editor.putLong("invite",user.getInvite());
editor.putInt("Permission",user.getPermission());
MyApp.setUser(user);
editor.commit();
}
/**
* 获取偏好设置的用户信息
* @return
*/
public static User getUserPerferences() {
User user=new User();
SharedPreferences preferences = context.getSharedPreferences("denglu", Context.MODE_PRIVATE);
user.setName(preferences.getString("name", ""));
user.setPass(preferences.getString("pwd", ""));
user.setInvite(preferences.getLong("invite",-1));
user.setPermission(preferences.getInt("Permission",0));
if (!user.getName().equals("")&&user!=null){
MyApp.setUser(user);
}
return user;
}
public Boolean getFristState() {
SharedPreferences sharedPreferences = context.getSharedPreferences("frist_state",Context.MODE_PRIVATE);
boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun",true);
return isFirstRun;
}
/**
* ��ȡ�������
* @return
*/
public void saveFristState(boolean isFrist) {
SharedPreferences sharedPreferences = context.getSharedPreferences("frist_state",Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putBoolean("isFirstRun", isFrist);
editor.commit();
}
/**
* 从偏好设置获取第一次登陆状态
* @return
*/
public static Boolean getLoginState() {
SharedPreferences sharedPreferences = context.getSharedPreferences("login_state",Context.MODE_PRIVATE);
boolean isFirstRun = sharedPreferences.getBoolean("isLogin",false);
return isFirstRun;
}
/**
* 将登录状态保存在偏好设置和MyApp里面
* @return
*/
public static void saveLoginState(boolean Login) {
SharedPreferences sharedPreferences = context.getSharedPreferences("login_state",Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putBoolean("isLogin", Login);
MyApp.isLogin=true;
editor.commit();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.