text
stringlengths
10
2.72M
package de.madjosz.adventofcode.y2015; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Day24 { private final int[] packages; public Day24(List<String> input) { this.packages = input.stream().mapToInt(Integer::parseInt).toArray(); } public long a1() { return splitThePackages(3); } private int getPackagesPerGroup(int groups) { int total = Arrays.stream(packages).sum(); if (total % groups != 0) throw new IllegalArgumentException(); return total / groups; } private long splitThePackages(int groups) { int perGroup = getPackagesPerGroup(groups); for (int i = 1; i < packages.length / 3; ++i) { long quantum = Long.MAX_VALUE; for (int[] combi : combinations(packages.length, i)) { long result = checkCombination(packages, combi, perGroup, groups - 1); if (result < quantum) quantum = result; } if (quantum != Long.MAX_VALUE) return quantum; } throw new IllegalArgumentException(); } private static List<int[]> combinations(int n, int r) { List<int[]> combinations = new ArrayList<>(); int[] combination = new int[r]; for (int i = 0; i < r; i++) combination[i] = i; while (combination[r - 1] < n) { combinations.add(combination.clone()); int t = r - 1; while (t != 0 && combination[t] == n - r + t) t--; combination[t]++; for (int i = t + 1; i < r; i++) combination[i] = combination[i - 1] + 1; } return combinations; } private static long checkCombination(int[] packs, int[] indices, int perGroup, int groupsToGo) { if (weight(indices, packs) == perGroup) { int[] rest = remove(packs, indices); for (int i = 1; i < rest.length / 2; ++i) for (int[] combi : combinations(rest.length, i)) if (weight(combi, rest) == perGroup && (groupsToGo == 2 || checkCombination(rest, combi, perGroup, groupsToGo - 1) != Long.MAX_VALUE)) return quantum(packs, indices); } return Long.MAX_VALUE; } private static int[] remove(int[] packs, int[] indices) { int[] rest = new int[packs.length - indices.length]; for (int i = 0, k = 0; i < packs.length; ++i) { if (Arrays.binarySearch(indices, i) >= 0) rest[k++] = packs[i]; } return rest; } private static int weight(int[] indices, int[] packs) { return Arrays.stream(indices).map(i -> packs[i]).sum(); } private static long quantum(int[] packs, int[] indices) { return Arrays.stream(indices).map(i -> packs[i]).mapToLong(i -> i).reduce((a, b) -> a * b).getAsLong(); } public long a2() { return splitThePackages(4); } }
package br.com.unifil.huffman.algoritmo; /** * Classe abstrata que implementa uma árvore. Essa classe serve como um modelo para * classe concreta, ou seja, para as classes Nó e Folha * @author Fernando Ortiz */ abstract class HuffmanArvore implements Comparable<HuffmanArvore>{ // frequência da árvore public final int frequencia; /** * Construtor padrão da classe. * @param frequencia */ public HuffmanArvore(int frequencia){ this.frequencia = frequencia; } /** * Método que compara as frequencias. Essa classe implementa a Interface * Comparable para ordenação na Fila de Prioridades. * @param arvore * @return */ @Override public int compareTo(HuffmanArvore arvore){ return frequencia - arvore.frequencia; } }
package com.tencent.mm.ui.bizchat; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.ak.o; import com.tencent.mm.bp.a; import com.tencent.mm.plugin.fts.ui.m; import com.tencent.mm.plugin.selectcontact.a.e; import com.tencent.mm.plugin.selectcontact.a.f; import com.tencent.mm.ui.contact.a.a.b; public class a$b extends b { final /* synthetic */ a tEf; public a$b(a aVar) { this.tEf = aVar; super(aVar); } public final View a(Context context, ViewGroup viewGroup) { View inflate; if (a.fi(context)) { inflate = LayoutInflater.from(context).inflate(f.select_ui_listcontactitem_large, viewGroup, false); } else { inflate = LayoutInflater.from(context).inflate(f.select_ui_listcontactitem, viewGroup, false); } a.a aVar = this.tEf.tEe; aVar.eCl = (ImageView) inflate.findViewById(e.avatar_iv); aVar.eTm = (TextView) inflate.findViewById(e.title_tv); aVar.eCn = (TextView) inflate.findViewById(e.desc_tv); aVar.eCn.setVisibility(8); inflate.setTag(aVar); return inflate; } public final void a(Context context, com.tencent.mm.ui.contact.a.a.a aVar, com.tencent.mm.ui.contact.a.a aVar2, boolean z, boolean z2) { a aVar3 = (a) aVar2; a.a aVar4 = (a.a) aVar; m.a(aVar3.eCh, aVar4.eTm); o.Pj().a(aVar3.tEb, aVar4.eCl, a.aae(aVar3.username)); } public final boolean Wi() { return false; } }
package com.mx.profuturo.bolsa.model.vo.home; import com.mx.profuturo.bolsa.model.service.dto.ContenidoHomeDTO; import com.mx.profuturo.bolsa.model.vo.search.BuscadorVacanteVO; public class ContenidoVO extends ContenidoHomeDTO { }
package leecode.bfs; import zuoshen.list.Node; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; //一般就是解决两点之间最短距离,从start开始到target的最短距离 public class bfs框架 { int BFS(Node start,Node target){ Queue<Node>q = new LinkedList<>();//核心数据结构,队列 Set<Node> visited = new HashSet<>();//避免走回头路,标记访问 q.offer(start); //起点加入队列 visited.add(start); //标记访问 int step=0;//记录扩散的步数 while (!q.isEmpty()){ int size=q.size(); for (int i = 0; i <size ; i++) { Node cur = q.poll(); if(cur.equals(target)){ return step; } /* for(Node x : cur.adj()){ //cur.adj()指cur相邻的节点,比如二维数组中该点的上下左右 // visit 防止走回头路,但是一般的二叉树结构,没有子节点到父节点指针,不需要visit if(x not in visited){ q.offer(x); visited.add(x); } } */ step++; } } return step; } }
package org.mym.featuredshowcase.advanced; import android.content.Context; import android.graphics.Canvas; import android.graphics.RectF; /** * This interface allow user to customize background drawing. */ public interface BackgroundDrawer { /** * Called on each onDraw(), before drawing alpha area and after drawing mask color. * Do not do too much work in this method, be careful for 60 FPS! * @param context the context object associated of view, maybe helpful for retrieving resources. * @param canvas the canvas to draw. * @param targetRect this parameter is provided for layout bitmaps. */ void drawBackground(Context context, Canvas canvas, RectF targetRect); /** * Called when ShowcaseView is dismissed, etc. */ void recycle(); }
package algorithm.baekjoon; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class _1697_HideAndSeek { static int n, k; static int answer; static boolean[] visit = new boolean[100001]; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); // 수빈 위치 k = Integer.parseInt(st.nextToken()); // 동생 위치 answer = 0; Queue<Integer> q = new LinkedList<>(); q.offer(n); int level = 0; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { int polled = q.poll(); if (polled == k) { System.out.println(level); return; } if (polled * 2 <= 100000 && !visit[polled * 2]) { q.offer(polled * 2); visit[polled * 2] = true; } if (polled + 1 <= 100000 && !visit[polled + 1]) { q.offer(polled + 1); visit[polled + 1] = true; } if (polled - 1 >= 0 && !visit[polled - 1]) { q.offer(polled - 1); visit[polled - 1] = true; } } level++; } } }
/* Author: ME */ // something is wrong with this code. cba to check it soz public class Doctor { Hospital hospital; public Doctor (Hospital hospital) { this.hospital = hospital; } public void run() { try { while (true) { Random random = new Random(); Patient patient = hospital.nextPatient(); Thread.sleep(random.nextInt(2) * 1000); int temperature = patient.getTemperature(); if (temperature > 40) { patient.prescribe("Tamiflu"); } else { patient.prescribe("General painkiler") } } } catch (InterruptedException e) { System.err.println(e.stackTrace()); } } }
package com.worldbank.service.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.worldbank.model.Result; import com.worldbank.model.Student; import com.worldbank.service.TestService; @RestController @RequestMapping("/api/v1/") public class studentController { TestService testService; @Autowired studentController(TestService testService) { this.testService = testService; } @PostMapping("/test") public Result testMethod(@RequestBody Student student) { return testService.method1(student); } }
package com.tencent.mm.plugin.card.ui.view; import android.text.TextUtils; import android.view.View; import android.view.ViewStub; import android.widget.TextView; import com.tencent.mm.plugin.card.a.d; import com.tencent.mm.plugin.card.base.b; import com.tencent.mm.protocal.c.kz; import com.tencent.mm.sdk.platformtools.x; public final class e extends i { private View hHx; public final void initView() { } public final void update() { b ayu = this.hHF.ayu(); kz kzVar = ayu.awm().rnU; if (kzVar != null) { x.i("MicroMsg.CardAnnoucementView", "card tp annoucement endtime: " + kzVar.mXw); x.i("MicroMsg.CardAnnoucementView", "card tp annoucement text: " + kzVar.text); x.i("MicroMsg.CardAnnoucementView", "card tp annoucement thumb_url: " + kzVar.rnt); } if (kzVar != null && !TextUtils.isEmpty(kzVar.text) && ayu.awk()) { if (this.hHx == null) { this.hHx = ((ViewStub) findViewById(d.card_annoucement_layout_stub)).inflate(); } ((TextView) this.hHx.findViewById(d.public_notice)).setText(kzVar.text); this.hHx.setOnClickListener(this.hHF.ayy()); } else if (this.hHx != null) { this.hHx.setVisibility(8); } } public final void azI() { if (this.hHx != null) { this.hHx.setVisibility(8); } } }
package P2; /** * This class implements the doorman's part of the * Barbershop thread synchronization example. */ import P2.Globals; public class Doorman implements Runnable{ /** * Creates a new doorman. * @param queue The customer queue. * @param gui A reference to the GUI interface. */ CustomerQueue queue ; Gui gui ; Thread thread; public Doorman(CustomerQueue queue, Gui gui) { this.gui = gui; this.queue = queue; this.thread = new Thread(this, "doorman"); } /** * Starts the doorman running as a separate thread. */ public void startThread() { thread.start(); } /** * Stops the doorman thread. */ public void stopThread() { } @Override public void run() { Customer c; while(true){ c = new Customer(); queue.add(); queue.produce(c); gui.println("Customer added to queue"); try { Thread.sleep(Globals.doormanSleep); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // Add more methods as needed }
package io; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class BufferReaderApp { public static void main(String[] args) { File file=new File("src/io/test.txt"); try(FileReader fileReader=new FileReader(file)) { BufferedReader bufferedReader=new BufferedReader(fileReader); String line=null; while((line=bufferedReader.readLine())!=null) { System.out.println(line); } } catch (Exception e) { // TODO: handle exception } } }
package com.angrykings; import java.util.ArrayList; /** * IPlayerTurnListener * * @author Shivan Taher <zn31415926535@gmail.com> * @date 21.11.13 */ public interface IPlayerTurnListener { void onHandleTurn(int x, int y, ArrayList<Keyframe> keyframes); void onEndTurn(); void onKeyframe(float time); void onUpdate(float dt); }
package com.tencent.recovery; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import com.tencent.recovery.handler.RecoveryMessageHandler; import com.tencent.recovery.log.RecoveryLog; import com.tencent.recovery.option.OptionFactory; import com.tencent.recovery.util.Util; public class Recovery { private static Application application; private static Context context; private static RecoveryMessageHandler vgZ; private static long vha; private static String vhb; private static boolean vhc = false; private static boolean vhd = false; private static int vhe = 0; private static ActivityLifecycleCallbacks vhf = new ActivityLifecycleCallbacks() { public final void onActivityCreated(Activity activity, Bundle bundle) { if (!Recovery.vhd && !Recovery.vgZ.hasMessages(3)) { Recovery.vgZ.removeCallbacksAndMessages(null); String hm = Util.hm(Recovery.context); Editor edit = Recovery.context.getSharedPreferences(Recovery.vhb, 0).edit(); edit.putInt("KeyComponentOnCreateForeground", 1); edit.putInt("KeyComponentOnCreateExceptionType", 4096); edit.apply(); Recovery.vgZ.sendEmptyMessageDelayed(3, (long) OptionFactory.dA(hm, 1).dkb); RecoveryLog.i("Recovery", "%s markActivityOnCreated %s", hm, Long.valueOf(System.currentTimeMillis() - Recovery.vha)); } } public final void onActivityStarted(Activity activity) { Recovery.cEU(); } public final void onActivityResumed(Activity activity) { } public final void onActivityPaused(Activity activity) { } public final void onActivityStopped(Activity activity) { Recovery.cEV(); if (Recovery.vhe == 0) { RecoveryLog.i("Recovery", "%s onActivityStopped: activityForegroundCount is 0", Util.hm(Recovery.context)); Recovery.Hj(16); } } public final void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } public final void onActivityDestroyed(Activity activity) { } }; static /* synthetic */ int cEU() { int i = vhe; vhe = i + 1; return i; } static /* synthetic */ int cEV() { int i = vhe; vhe = i - 1; return i; } public static void cEO() { if (!vhd && !vhc) { vhc = true; String hm = Util.hm(context); int bG = RecoveryLogic.bG(context, hm); RecoveryLog.i("Recovery", "%s markApplicationOnCreateNormal %d", hm, Long.valueOf(System.currentTimeMillis() - vha)); Editor edit = context.getSharedPreferences(vhb, 0).edit(); edit.remove("KeyAppOnCreateExceptionType"); edit.putInt("KeyAppOnCreateNormalType", 256); if (RecoveryLogic.bG(context, hm) == 16) { edit.putInt("KeyComponentOnCreateForeground", bG); edit.putInt("KeyComponentOnCreateExceptionType", 4096); vgZ.sendEmptyMessageDelayed(2, (long) OptionFactory.dA(hm, bG).dkb); } edit.apply(); } } private static void destroy() { if (application != null) { application.unregisterActivityLifecycleCallbacks(vhf); } } public static void cEP() { if (context != null && !vhd) { cER(); RecoveryLog.i("Recovery", "%s Recovery.crash %d", Util.hm(context), Long.valueOf(System.currentTimeMillis() - vha)); Editor edit = context.getSharedPreferences(vhb, 0).edit(); if (vhc) { edit.putInt("KeyComponentOnCreateExceptionType", 65536); } else { edit.putInt("KeyAppOnCreateExceptionType", 65536); } edit.apply(); destroy(); } } public static void cEQ() { if (context != null && !vhd) { cER(); RecoveryLog.i("Recovery", "%s Recovery.anr %d", Util.hm(context), Long.valueOf(System.currentTimeMillis() - vha)); Editor edit = context.getSharedPreferences(vhb, 0).edit(); if (vhc) { edit.putInt("KeyComponentOnCreateExceptionType", 1048576); } else { edit.putInt("KeyAppOnCreateExceptionType", 1048576); } edit.apply(); destroy(); } } public static void Hj(int i) { if (context != null && !vhd) { cER(); String hm = Util.hm(context); SharedPreferences sharedPreferences = context.getSharedPreferences(vhb, 0); RecoveryLog.i("Recovery", "%s Recovery.normal %s %d", hm, Integer.toHexString(i), Long.valueOf(System.currentTimeMillis() - vha)); vgZ.removeCallbacksAndMessages(null); Editor edit = sharedPreferences.edit(); edit.remove("KeyComponentOnCreateExceptionType"); edit.putInt("KeyComponentOnCreateNormalType", i); edit.apply(); destroy(); } } public static Context getContext() { return context; } private static void cER() { if (context != null && !vhd) { RecoveryLog.i("Recovery", "%s markFinalStatus", Util.hm(context)); vhd = true; } } }
package com.LoginTest.server.controller; import com.LoginTest.server.model.User; import com.LoginTest.server.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ReturnUserController { @Autowired private BCryptPasswordEncoder passwordEncoder; @Autowired private UserService userService; @RequestMapping("/get/{email}") public User returnUser(@PathVariable("email") String email) { if(userService.getUserByEmail(email)!=null) return userService.getUserByEmail(email); else return null; } }
public class Main{ public static void main(String[] args){ Rectangle rectangle = new Rectangle(); Circle circle = new Circle(); Point2D point = new Point2D(); System.out.println(); System.out.println(); } }
package com.tencent.mm.protocal; import com.tencent.mm.plugin.appbrand.jsapi.ad; import com.tencent.mm.protocal.c.g; public class c$cc extends g { public c$cc() { super(ad.NAME, "network_type", 16, false); } }
package com.timmy.project.launch; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.timmy.R; import com.timmy.home.MainActivity; /** * App启动的第一个界面-实现在该界面中倒计时3秒开启或者直接点击跳过开启下一个界面 * 1.全屏 * a.在styles文件中设置样式 -- 推荐 * b.代码添加Flag,在setContentView方法调用之前处理 * 2.倒计时 * 使用Handler和Runnable实现 * 3.跳转 * 跳转到首页,首页的启动模式为SingleTask * 4.应用按Home键,重新启动界面的时候也会有一个界面,这个界面也有三秒倒计时消失 * 该界面销毁时,需要处理Handler引用 */ public class WelcomeActivity extends AppCompatActivity implements View.OnClickListener { private int second = 3; private TextView time; private Handler mHandler = new Handler(); private Runnable runnable = new Runnable() { @Override public void run() { time.setText(second + "s"); second--; if (second < 0) { gotoNextActivity(); } mHandler.postDelayed(runnable, 1000); } }; private void gotoNextActivity() { Intent mainIntent = new Intent(WelcomeActivity.this, MainActivity.class); WelcomeActivity.this.startActivity(mainIntent); WelcomeActivity.this.finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置界面全屏 // getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏 // getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); // getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); setContentView(R.layout.activity_start); time = (TextView) findViewById(R.id.tv_time); LinearLayout mTimeContainer = (LinearLayout) findViewById(R.id.ll_time); mTimeContainer.setOnClickListener(this); mHandler.postDelayed(runnable, 16); } @Override public void onClick(View v) { if (v.getId() == R.id.ll_time) { gotoNextActivity(); } } @Override protected void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(runnable); } }
package com.tencent.mm.plugin.game.model; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import com.tencent.mm.plugin.game.d.ak; import com.tencent.mm.plugin.game.d.db; import com.tencent.mm.plugin.game.e.c; import com.tencent.mm.plugin.game.ui.tab.GameTabHomeUI; import com.tencent.mm.sdk.platformtools.bi; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; public class GameTabData implements Parcelable { public static final Creator<GameTabData> CREATOR = new 1(); public LinkedHashMap<String, TabItem> jOi; public StatusBar jOj; /* synthetic */ GameTabData(Parcel parcel, byte b) { this(parcel); } public final List<TabItem> aUC() { List<TabItem> arrayList = new ArrayList(); if (this.jOi != null) { arrayList.addAll(this.jOi.values()); } return arrayList; } public GameTabData() { this.jOi = new LinkedHashMap(); this.jOj = new StatusBar(); } private GameTabData(Parcel parcel) { g(parcel); } public int describeContents() { return 0; } private void g(Parcel parcel) { int readInt = parcel.readInt(); if (this.jOi == null) { this.jOi = new LinkedHashMap(); } for (int i = 0; i < readInt; i++) { TabItem tabItem = (TabItem) parcel.readParcelable(TabItem.class.getClassLoader()); if (tabItem != null) { this.jOi.put(tabItem.jOl, tabItem); } } this.jOj = (StatusBar) parcel.readParcelable(StatusBar.class.getClassLoader()); } public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(this.jOi.size()); for (Entry value : this.jOi.entrySet()) { parcel.writeParcelable((Parcelable) value.getValue(), i); } parcel.writeParcelable(this.jOj, i); } public static GameTabData bn(List<ak> list) { if (bi.cX(list)) { return null; } GameTabData gameTabData = new GameTabData(); db aTN = h.aTL().aTN(); if (aTN != null) { gameTabData.jOj.jOk = aTN.jOk; gameTabData.jOj.color = c.parseColor(aTN.dxh); } int i = 0; for (ak akVar : list) { if (!(akVar == null || bi.oW(akVar.jQM))) { TabItem tabItem = new TabItem(); tabItem.jOl = akVar.jQM; tabItem.title = akVar.bHD; tabItem.jOm = akVar.jQN; tabItem.jOn = akVar.jQO; tabItem.jumpUrl = akVar.jOU; tabItem.jOq = akVar.jQP; tabItem.jOr = akVar.jQQ; if (tabItem.jOn) { tabItem.jOs = GameTabHomeUI.class.getName(); } else { int i2 = i + 1; i %= 3; tabItem.jOs = "com.tencent.mm.plugin.game.ui.tab.GameTabWebUI" + (i != 0 ? String.valueOf(i) : ""); i = i2; } tabItem.jOt = false; tabItem.bYq = akVar.jQR; tabItem.jOu = akVar.jPC; tabItem.jLt = akVar.jPA; gameTabData.jOi.put(tabItem.jOl, tabItem); } } return gameTabData; } }
package com.duanxr.yith.easy; import com.duanxr.yith.define.treeNode.TreeNode; import java.util.Stack; /** * @author 段然 2021/3/11 */ public class ErChaShuDeZuiJinGongGongZuXianLcof { /** * English description is not available for the problem. * * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 * * 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” * * 例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4] * * * *   * * 示例 1: * * 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 * 输出: 3 * 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 * 示例 2: * * 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 * 输出: 5 * 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。 *   * * 说明: * * 所有节点的值都是唯一的。 * p、q 为不同节点且均存在于给定的二叉树中。 * 注意:本题与主站 236 题相同:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/ * */ class Solution1 { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { Stack<TreeNode> sp = new Stack<>(); Stack<TreeNode> sq = new Stack<>(); findNode(root, p, q, sp, sq); while (sp.size() > sq.size()) { sp.pop(); } while (sq.size() > sp.size()) { sq.pop(); } while (!sq.isEmpty()) { TreeNode sqn = sq.pop(); TreeNode spn = sp.pop(); if (isEqual(spn, sqn)) { return spn; } } return null; } private void findNode(TreeNode root, TreeNode p, TreeNode q, Stack<TreeNode> sp, Stack<TreeNode> sq) { if (isFound(p, sp) && isFound(q, sq)) { return; } if (!isFound(p, sp)) { sp.push(root); } if (!isFound(q, sq)) { sq.push(root); } if (root.left != null) { findNode(root.left, p, q, sp, sq); } if (root.right != null) { findNode(root.right, p, q, sp, sq); } if (!isFound(p, sp)) { sp.pop(); } if (!isFound(q, sq)) { sq.pop(); } } private boolean isFound(TreeNode target, Stack<TreeNode> s) { return !s.isEmpty() && isEqual(s.peek(), target); } private boolean isEqual(TreeNode a, TreeNode b) { return a.val == b.val; } } }
package pv260.customeranalysis; import static com.googlecode.catchexception.CatchException.catchException; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import pv260.customeranalysis.entities.Customer; import pv260.customeranalysis.entities.Offer; import pv260.customeranalysis.entities.Product; import pv260.customeranalysis.exceptions.CantUnderstandException; import pv260.customeranalysis.exceptions.GeneralException; import pv260.customeranalysis.interfaces.AnalyticalEngine; import pv260.customeranalysis.interfaces.ErrorHandler; import pv260.customeranalysis.interfaces.NewsList; import pv260.customeranalysis.interfaces.Storage; import java.util.List; import static org.assertj.core.api.Assertions.in; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.isA; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class CustomerAnalysisTest { /** * Verify the ErrorHandler is invoked when one of the AnalyticalEngine methods * throws exception and the exception is not re-thrown from the CustomerAnalysis. * The exception is passed to the ErrorHandler directly, not wrapped. */ @Test public void testErrorHandlerInvokedWhenEngineThrows() throws GeneralException { ErrorHandler handler = mock(ErrorHandler.class); Product product = mock(Product.class); AnalyticalEngine engine = mock(AnalyticalEngine.class); when(engine.interesetingCustomers(product)).thenThrow(new CantUnderstandException()); Storage storage = mock(Storage.class); NewsList newsList = mock(NewsList.class); CustomerAnalysis analysis = new CustomerAnalysis(asList(engine),storage, newsList, handler); catchException(() -> analysis.findInterestingCustomers(product)); verify(handler).handle(isA(CantUnderstandException.class)); } /** * Verify that if first AnalyticalEngine fails by throwing an exception, * subsequent engines are tried with the same input. * Ordering of engines is given by their order in the List passed to * constructor of AnalyticalEngine */ @Test public void testSubsequentEnginesTriedIfOneFails() throws GeneralException { Product product = mock(Product.class); ErrorHandler handler = mock(ErrorHandler.class); AnalyticalEngine engine1 = mock(AnalyticalEngine.class); AnalyticalEngine engine2 = mock(AnalyticalEngine.class); when(engine1.interesetingCustomers(product)).thenThrow(new CantUnderstandException()); when(engine2.interesetingCustomers(product)).thenReturn(asList(mock(Customer.class))); Storage storage = mock(Storage.class); NewsList newsList = mock(NewsList.class); CustomerAnalysis analysis = new CustomerAnalysis(asList(engine1, engine2), storage, newsList, handler); catchException(() -> analysis.findInterestingCustomers(product)); verify(engine2).interesetingCustomers(product); } /** * Verify that as soon as the first AnalyticalEngine succeeds, * this result is returned as result and no subsequent * AnalyticalEngine is invoked for this input */ @Test public void testNoMoreEnginesTriedAfterOneSucceeds() throws GeneralException { Product product = mock(Product.class); ErrorHandler handler = mock(ErrorHandler.class); AnalyticalEngine engine1 = mock(AnalyticalEngine.class); when(engine1.interesetingCustomers(product)).thenReturn(asList(new Customer(1,"test",2))); AnalyticalEngine engine2 = mock(AnalyticalEngine.class); AnalyticalEngine engine3 = mock(AnalyticalEngine.class); Storage storage = mock(Storage.class); NewsList newsList = mock(NewsList.class); CustomerAnalysis analysis = new CustomerAnalysis(asList(engine1, engine2, engine3), storage, newsList, handler); List<Customer> result = analysis.findInterestingCustomers(product); assertEquals("test",result.get(0).getName()); assertEquals(2,result.get(0).getCredit()); assertEquals(1,result.get(0).getId()); verify(engine1).interesetingCustomers(product); verify(engine2,never()).interesetingCustomers(product); verify(engine3,never()).interesetingCustomers(product); } /** * Verify that once Offer is created for the Customer, * this order is persisted in the Storage before being * added to the NewsList * HINT: you might use mockito InOrder */ @Test public void testOfferIsPersistedBefreAddedToNewsList() throws GeneralException { ErrorHandler handler = mock(ErrorHandler.class); Product product = mock(Product.class); Customer customer = mock(Customer.class); AnalyticalEngine engine = mock(AnalyticalEngine.class); Storage storage = mock(Storage.class); when(storage.find(Product.class, 0)).thenReturn(product); when(engine.interesetingCustomers(product)).thenReturn(asList(customer)); NewsList newsList = mock(NewsList.class); CustomerAnalysis analysis = new CustomerAnalysis(asList(engine),storage, newsList, handler); analysis.prepareOfferForProduct(0); ArgumentCaptor<Offer> offerCaptor1= ArgumentCaptor.forClass(Offer.class); ArgumentCaptor<Offer> offerCaptor2= ArgumentCaptor.forClass(Offer.class); InOrder inOrder = inOrder(storage, newsList); inOrder.verify(storage).persist(offerCaptor1.capture()); inOrder.verify(newsList).sendPeriodically(offerCaptor2.capture()); Offer offer1 = offerCaptor1.getValue(); assertEquals(customer, offer1.getCustomer()); Offer offer2 = offerCaptor2.getValue(); assertEquals(customer, offer2.getCustomer()); assertEquals(offer1, offer2); } /** * Verify that Offer is created for every selected Customer for the given Product * test with at least two Customers selected by the AnalyticalEngine * HINT: you might use mockito ArgumentCaptor */ @Test public void testOfferContainsProductAndCustomer() throws GeneralException { ErrorHandler handler = mock(ErrorHandler.class); Product product = mock(Product.class); Customer customer1 = mock(Customer.class); Customer customer2 = mock(Customer.class); AnalyticalEngine engine = mock(AnalyticalEngine.class); Storage storage = mock(Storage.class); when(storage.find(Product.class, 0)).thenReturn(product); when(engine.interesetingCustomers(product)).thenReturn(asList(customer1,customer2)); NewsList newsList = mock(NewsList.class); CustomerAnalysis analysis = new CustomerAnalysis(asList(engine),storage, newsList, handler); analysis.prepareOfferForProduct(0); ArgumentCaptor<Offer> offerCaptor= ArgumentCaptor.forClass(Offer.class); verify(storage,times(2)).persist(offerCaptor.capture()); List<Offer> offers = offerCaptor.getAllValues(); assertEquals(customer1, offers.get(0).getCustomer()); assertEquals(customer2, offers.get(1).getCustomer()); } }
/** * 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.module.jcr.stuff; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.jcr.AccessDeniedException; import javax.jcr.ItemNotFoundException; import javax.jcr.NoSuchWorkspaceException; import javax.jcr.RepositoryException; import javax.security.auth.Subject; import org.apache.jackrabbit.core.HierarchyManager; import org.apache.jackrabbit.core.ItemId; import org.apache.jackrabbit.core.RepositoryImpl; import org.apache.jackrabbit.core.XASessionImpl; import org.apache.jackrabbit.core.config.WorkspaceConfig; import org.apache.jackrabbit.core.security.AMContext; import org.apache.jackrabbit.core.security.AccessManager; import org.apache.jackrabbit.core.security.SystemPrincipal; import org.apache.jackrabbit.core.security.authorization.AccessControlProvider; import org.apache.jackrabbit.core.security.authorization.WorkspaceAccessManager; import org.apache.jackrabbit.spi.Name; import org.apache.jackrabbit.spi.Path; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A <code>SystemSession</code> ... * * @author pavila */ public class SystemSession extends XASessionImpl { private static Logger log = LoggerFactory.getLogger(SystemSession.class); private static final boolean DEBUG = false; /** * Package private factory method * * @param rep * @param wspConfig * @return * @throws RepositoryException */ public static SystemSession create(RepositoryImpl rep, WorkspaceConfig wspConfig) throws RepositoryException { if (DEBUG) log.debug("create()"); // create subject with SystemPrincipal Set<SystemPrincipal> principals = new HashSet<SystemPrincipal>(); principals.add(new SystemPrincipal()); Subject subject = new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); SystemSession oss = new SystemSession(rep, subject, wspConfig); if (DEBUG) log.debug("create: "+oss); return oss; } /** * private constructor * * @param rep * @param wspConfig */ private SystemSession(RepositoryImpl rep, Subject subject, WorkspaceConfig wspConfig) throws RepositoryException { super(rep, subject, wspConfig); } /* (non-Javadoc) * @see javax.jcr.Session#logout() */ public synchronized void logout() { if (DEBUG) log.warn("logout()"); super.logout(); if (DEBUG) log.warn("logout: void"); } @Override protected AccessManager createAccessManager(Subject subject, HierarchyManager hierMgr) throws AccessDeniedException, RepositoryException { /** * use own AccessManager implementation rather than relying on * configurable AccessManager to handle SystemPrincipal privileges * correctly */ return new SystemAccessManager(); //return super.createAccessManager(subject, hierMgr); } //--------------------------------------------------------< inner classes > private class SystemAccessManager implements AccessManager { SystemAccessManager() { } //----------------------------------------------------< AccessManager > @Override public void init(AMContext context) throws AccessDeniedException, Exception { // none } @Override public void init(AMContext arg0, AccessControlProvider arg1, WorkspaceAccessManager arg2) throws AccessDeniedException, Exception { // none } @Override public void close() throws Exception { // none } @Override public void checkPermission(ItemId id, int permissions) throws AccessDeniedException, ItemNotFoundException, RepositoryException { // allow everything } @Override public boolean isGranted(ItemId id, int permissions) throws ItemNotFoundException, RepositoryException { // allow everything return true; } @Override public boolean canAccess(String workspaceName) throws NoSuchWorkspaceException, RepositoryException { // allow everything return true; } @Override public boolean canRead(Path itemPath) throws RepositoryException { // allow everything return true; } @Override public boolean isGranted(Path absPath, int permissions) throws RepositoryException { // allow everything return true; } @Override public boolean isGranted(Path parentPath, Name childName, int permissions) throws RepositoryException { // allow everything return true; } // @Override // TODO Enable @Override when use jackrabbit 1.6 public void checkPermission(Path absPath, int permissions) throws AccessDeniedException, RepositoryException { // allow everything } } }
package sample.helpers; import org.sqlite.JDBC; import java.sql.*; import java.util.*; public class DbHandler { // Константа, в которой хранится адрес подключения private static final String CON_STR = "jdbc:sqlite:task.db"; private static DbHandler instance = null; public static synchronized Connection getInstance() throws SQLException { if (instance == null) instance = new DbHandler(); return instance.connection; } // Объект, в котором будет храниться соединение с БД private Connection connection; private DbHandler() throws SQLException { DriverManager.registerDriver(new JDBC()); this.connection = DriverManager.getConnection(CON_STR); } }
package hello; /** * Created by Javier on 07/04/2017. */ public class Significado { private String contexto; private String texto; public String getContexto() { return contexto; } public Significado(String contexto, String texto) { this.contexto = contexto; this.texto = texto; } public Significado() { } public void setContexto(String contexto) { this.contexto = contexto; } public String getTexto() { return texto; } public void setTexto(String texto) { this.texto = texto; } }
package com.zhouyi.business.core.service; import com.zhouyi.business.core.common.ReturnCode; import com.zhouyi.business.core.dao.BuffBaseMapper; import com.zhouyi.business.core.dao.LedenEquipmentMapper; import com.zhouyi.business.core.dao.SysUnitMapper; import com.zhouyi.business.core.dao.SysUserMapper; import com.zhouyi.business.core.exception.ExceptionCast; import com.zhouyi.business.core.model.*; import com.zhouyi.business.core.utils.ResponseUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; public class BaseServiceImpl<T, V> implements BaseService<T, V> { @Autowired private BuffBaseMapper<T, V> buffBaseMapper; @Autowired private SysUserMapper sysUserMapper; @Autowired private SysUnitMapper sysUnitMapper; @Autowired private LedenEquipmentMapper ledenEquipmentMapper; private Class clazz; private Field[] fields; public BaseServiceImpl() { //获取父类的Class对象 Class clazz = this.getClass(); //通过子类的Class对象获取参数化类型 Type type = clazz.getGenericSuperclass(); ParameterizedType pType = (ParameterizedType) type; //获取实际化参数 Type[] types = pType.getActualTypeArguments(); //实际化参数的实现类是Class,可以把参数强转问Class对象,得到了子类中泛型的Class对象 this.clazz = (Class) types[1]; try { fields = this.clazz.getDeclaredFields(); } catch (Exception e) { e.printStackTrace(); } } @Override public Response findDataById(String id) { T t = buffBaseMapper.selectByPrimaryKey(id); //根据业务需求查询关联表信息 if (t == null) { ExceptionCast.cast(ResponseUtil.getResponseInfo(false)); } return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, t); } @Override public Response findDataList(V v) { Integer page = null; Integer size = null; //设置默认情况下的分页参数 for (Field field : fields) { if (field != null) { field.setAccessible(true); if (field.getName().equals("page")) { try { page = (Integer) field.get(v); if (page == null || page < 1) { field.set(v, 1); page = (Integer) field.get(v); } } catch (Exception e1) { e1.printStackTrace(); } } if (field.getName().equals("size")) { try { size = (Integer) field.get(v); if (size == null || size < 1) { field.set(v, 20); size = (Integer) field.get(v); } } catch (Exception e1) { e1.printStackTrace(); } } } } Integer startNo = (page - 1) * size + 1; Integer endNo = startNo + size; for (Field field : fields) { if (field != null) { field.setAccessible(true); if (field.getName().equals("startNo")) { try { field.set(v, startNo); } catch (IllegalAccessException e) { e.printStackTrace(); } } if (field.getName().equals("endNo")) { try { field.set(v, endNo); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } List<T> list = buffBaseMapper.selectByModel((T) v); int total = buffBaseMapper.findTotal(v); HashMap<String, Object> map = new HashMap<>(); map.put("total", total); map.put("list", list); return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, map); } @Override @Transactional public Response saveData(T t) { //buffBaseMapper.insertSelective(t); try { buffBaseMapper.insertSelective(t); } catch (Exception e) { e.printStackTrace(); ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_01)); } return ResponseUtil.getResponseInfo(true); } @Override @Transactional public Response updateData(T t) { try { buffBaseMapper.updateByPrimaryKeySelective(t); } catch (Exception e) { ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_1015)); } return ResponseUtil.getResponseInfo(true); } @Override @Transactional public Response deleteData(String id) { try { buffBaseMapper.deleteByPrimaryKey(id); } catch (Exception e) { ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_05)); } return ResponseUtil.getResponseInfo(true); } //设备权限校验 @Override public boolean checkHead(Head head) { if (head == null) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_11)); if (StringUtils.isEmpty(head.getUserCode())) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_1001)); SysUser sysUser = sysUserMapper.selectByPrimaryKey(head.getUserCode()); if (sysUser == null) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_1014)); if (StringUtils.isEmpty(head.getUserUnitCode())) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_11)); SysUnit sysUnit = sysUnitMapper.selectByPrimaryKey(head.getUserUnitCode()); if (sysUnit == null) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_12)); if(!sysUnit.getUnitCode().equals(head.getUserUnitCode())) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_1037)); if (StringUtils.isEmpty(head.getEquipmentCode())) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_11)); LedenEquipment ledenEquipment = new LedenEquipment(); ledenEquipment.setEquipmentCode(head.getEquipmentCode()); Integer count = ledenEquipmentMapper.selectEquipmentByCodeTotal(ledenEquipment); if (count < 1) ExceptionCast.cast(ResponseUtil.returnError(ReturnCode.ERROR_13)); return true; } @Override public int resoveSaveData(T t) { return buffBaseMapper.insertSelective(t); } }
package br.com.scd.demo.api.exception; import static org.hamcrest.Matchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import br.com.scd.demo.exception.InvalidArgumentException; import br.com.scd.demo.topic.TopicForInsert; import br.com.scd.demo.topic.TopicService; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class RestResponseEntityExceptionHandlerTest { private static final String VOTE_URL = "/votes"; private static final String TOPIC_URL = "/topics"; @Autowired private MockMvc mockMvc; @MockBean private TopicService topicService; @Test public void shouldHandleMethodArgumentNotValidException() throws Exception { String expectedMsg = "{\"message\":\"Assunto deve ser informado.\",\"status\":400,\"error\":\"Bad Request\"}"; mockMvc.perform(post(TOPIC_URL).accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) .content("{}")).andExpect(status().isBadRequest()).andExpect(content().string(expectedMsg)); } @Test public void shouldHandleInvalidArgumentException() throws Exception { String expectedMsg = "Exception xyz"; when(topicService.save(any(TopicForInsert.class))).thenThrow(new InvalidArgumentException(expectedMsg)); mockMvc.perform(post(TOPIC_URL).accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) .content("{\"subject\":\"123\"}")).andExpect(status().isBadRequest()) .andExpect(content().string(containsString(expectedMsg))); } @Test public void shouldHandleHttpMessageNotReadable() throws Exception { String expectedMsg = "Voto invalido: xxyy"; mockMvc.perform(post(VOTE_URL).accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) .content("{\"sessionId\":123, \"associatedId\":12, \"vote\":\"xxyy\"}")).andExpect(status().isBadRequest()) .andExpect(content().string(containsString(expectedMsg))); } }
package model.dao.impl; import model.dao.connection.ConnectionFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import java.sql.ResultSet; import java.sql.SQLException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; public class AdminDAOImplTest { @Mock private ResultSet resultSet; @Mock private ConnectionFactory connectionFactory; private AdminDAOImpl adminDAO; @Before public void setUp() throws Exception { initMocks(this); adminDAO = new AdminDAOImpl(connectionFactory); } @After public void tearDown() throws Exception { } @Test public void parseToOneElement() throws SQLException { when(resultSet.getInt(any())).thenReturn(1); when(resultSet.getString(any())).thenReturn("test"); assertEquals(new Integer(1), adminDAO.parseToOneElement(resultSet).getId()); assertEquals("test", adminDAO.parseToOneElement(resultSet).getName()); assertNotNull(adminDAO.parseToOneElement(resultSet)); } @Test public void getAdminByUserId() { } }
package com.thoughtworks.presentation.view_cart; import com.thoughtworks.domain.cart.CartDetails; import com.thoughtworks.presentation.product_list.Mapper; /** * Created on 16-06-2018. */ class CartDetailDataMapper implements Mapper<CartDetails, CartDetailViewModel> { @Override public CartDetailViewModel map(final CartDetails input) { return new CartDetailViewModel( new CartItemListMapper().map(input.getCartItems()), input.getAmount()); } }
package com.tencent.mm.plugin.luckymoney.b; import com.tencent.mm.kernel.g; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.storage.aa.a; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; public final class u extends r { public String ceR; public int ceS; public int ceT; public String kLZ; public int kPI; public String kPJ; public String kQH; public String kQI; public int kQL; public String kQM; public String kQN; public int kQO; public int kQQ; public String kQR; public String kQS; public int kQT = 1; public String kQU = null; public String kQV = null; public String kQW = null; public String kQX = null; public String kQY = null; public long kQZ = 0; public ai kQa; public String kQb; public u(String str, String str2, int i, String str3) { this.ceR = str2; this.kLZ = str; this.kQQ = i; Map hashMap = new HashMap(); hashMap.put("sendId", str); if (!bi.oW(str2)) { hashMap.put("nativeUrl", URLEncoder.encode(str2)); } hashMap.put("way", String.valueOf(i)); hashMap.put("channelId", "2"); hashMap.put("package", str3); g.Ek(); long longValue = ((Long) g.Ei().DT().get(a.sTd, Long.valueOf(0))).longValue(); if (longValue > 0) { if (System.currentTimeMillis() < longValue) { hashMap.put("agreeDuty", "0"); } else { StringBuilder stringBuilder = new StringBuilder(); g.Ek(); hashMap.put("agreeDuty", stringBuilder.append((Integer) g.Ei().DT().get(a.sTe, Integer.valueOf(1))).toString()); } } F(hashMap); } public final int aBM() { return 0; } public final void a(int i, String str, JSONObject jSONObject) { this.kQR = jSONObject.optString("spidLogo"); this.kQS = jSONObject.optString("spidWishing"); this.kQH = jSONObject.optString("spidName"); this.kQR = jSONObject.optString("spidLogo"); this.ceS = jSONObject.optInt("hbStatus"); this.ceT = jSONObject.optInt("receiveStatus"); this.kPJ = jSONObject.optString("statusMess"); this.kQI = jSONObject.optString("hintMess"); this.kQb = jSONObject.optString("watermark"); this.kLZ = jSONObject.optString("sendId"); this.kQL = jSONObject.optInt("focusFlag"); this.kQM = jSONObject.optString("focusWording"); this.kQN = jSONObject.optString("focusAppidUserName"); this.kQO = jSONObject.optInt("isFocus"); this.kPI = jSONObject.optInt("hbType"); JSONObject optJSONObject = jSONObject.optJSONObject("agree_duty"); if (optJSONObject != null) { this.kQU = optJSONObject.optString("agreed_flag", "-1"); this.kQV = optJSONObject.optString("title", ""); this.kQW = optJSONObject.optString("service_protocol_wording", ""); this.kQX = optJSONObject.optString("service_protocol_url", ""); this.kQY = optJSONObject.optString("button_wording", ""); this.kQZ = optJSONObject.optLong("delay_expired_time", 0); } if (this.kQZ > 0) { g.Ek(); g.Ei().DT().a(a.sTd, Long.valueOf(System.currentTimeMillis() + (this.kQZ * 1000))); } this.kQa = m.O(jSONObject.optJSONObject("operationTail")); } }
package models; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.ManyToOne; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import java.util.ArrayList; import java.util.List; import play.db.jpa.Model; import play.db.jpa.Blob; import play.Logger; @Entity public class Blog extends Model { @ManyToOne public User user; public String title; public boolean embeddedPosts=true; public int embeddedPostsPerPage=5; public Blob bgImage; public boolean visibleMembers=true; public boolean visiblePublic=true; // @ManyToMany(mappedBy = "blog", cascade = CascadeType.ALL) @OneToMany(mappedBy = "blog", cascade = CascadeType.ALL) public List<Post> posts = new ArrayList<Post>(); //not meant as for storage, more as helper object for ember public boolean isMine=false; public Blog(User user, String title, boolean embeddedPosts, int embeddedPostsPerPage, boolean visibleMembers, boolean visiblePublic) { this.user = user; this.title = title; this.embeddedPosts=embeddedPosts; this.embeddedPostsPerPage=embeddedPostsPerPage; this.visibleMembers=visibleMembers; this.visiblePublic=visiblePublic; } public static List<Blog> userBlogs(User user) { return Blog.find("user",user).fetch(); } public String toString() { return this.title; } }
/* 1: */ package com.kaldin.test.scheduletest.action; /* 2: */ /* 3: */ import com.google.gson.Gson; /* 4: */ import com.google.gson.JsonArray; /* 5: */ import com.google.gson.JsonObject; /* 6: */ import com.google.gson.JsonPrimitive; /* 7: */ import com.kaldin.common.security.EncryptionManager; /* 8: */ import com.kaldin.common.util.MailSend; /* 9: */ import com.kaldin.common.util.PagingBean; /* 10: */ import com.kaldin.email.dao.impl.EmailTemplateImplementor; /* 11: */ import com.kaldin.email.dto.EmailTemplateDTO; /* 12: */ import com.kaldin.test.scheduletest.dao.ExamDAO; /* 13: */ import com.kaldin.test.scheduletest.dto.ExamListDTO; /* 14: */ import com.kaldin.test.scheduletest.dto.TestScheduleDTO; /* 15: */ import com.kaldin.test.scheduletest.form.SendMailForm; /* 16: */ import com.kaldin.user.register.dao.impl.CandidateImpl; /* 17: */ import java.io.PrintStream; /* 18: */ import java.io.PrintWriter; /* 19: */ import java.util.ArrayList; /* 20: */ import java.util.List; /* 21: */ import javax.servlet.http.HttpServletRequest; /* 22: */ import javax.servlet.http.HttpServletResponse; /* 23: */ import javax.servlet.http.HttpSession; /* 24: */ import org.apache.commons.lang.StringUtils; /* 25: */ import org.apache.struts.action.Action; /* 26: */ import org.apache.struts.action.ActionForm; /* 27: */ import org.apache.struts.action.ActionForward; /* 28: */ import org.apache.struts.action.ActionMapping; /* 29: */ /* 30: */ public class SendMailAction /* 31: */ extends Action /* 32: */ { /* 33: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) /* 34: */ throws Exception /* 35: */ { /* 36: 49 */ String hostPath = request.getScheme() + "://" + request.getServerName(); /* 37: 50 */ //if (request.getServerName().equals("localhost")) { /* 38: 51 */ hostPath = hostPath + ":" + request.getServerPort(); /* 39: */ //} /* 40: 53 */ String result = "success"; /* 41: 54 */ String searchString = ""; /* 42: 55 */ SendMailForm mailForm = (SendMailForm)form; /* 43: 56 */ List<TestScheduleDTO> userList = new ArrayList(); /* 44: 57 */ List<TestScheduleDTO> totalUserList = new ArrayList(); /* 45: 58 */ SendMailAction$OPTIONS option = SendMailAction$OPTIONS.get(mailForm.getOperation()); /* 46: 59 */ PagingBean pagingBean = null; /* 47: 60 */ ExamDAO examDAO = new ExamDAO(); /* 48: 61 */ int companyid = ((Integer)request.getSession().getAttribute("CompanyId")).intValue(); /* 49: */ try /* 50: */ { /* 51: 64 */ if ((request.getParameter("spage") == null) || (request.getParameter("spage").equals(""))) /* 52: */ { /* 53: 65 */ if ((null == mailForm.getStartPage()) || ("".equals(mailForm.getStartPage()))) { /* 54: 66 */ mailForm.setStartPage("1"); /* 55: */ } /* 56: */ } /* 57: */ else { /* 58: 69 */ mailForm.setStartPage(request.getParameter("spage")); /* 59: */ } /* 60: 71 */ pagingBean = new PagingBean(Integer.parseInt(mailForm.getStartPage())); /* 61: */ } /* 62: */ catch (Exception e) {} /* 63: 76 */ if ((option == SendMailAction$OPTIONS.SEND) && (!mailForm.getTestdId().equals("Select Test"))) /* 64: */ { /* 65: 77 */ String examId = mailForm.getTestdId().substring(0, mailForm.getTestdId().indexOf("-")); /* 66: 78 */ String testId = mailForm.getTestdId().substring(mailForm.getTestdId().indexOf("-") + 1, mailForm.getTestdId().length()); /* 67: 79 */ int[] userids = mailForm.getUserId(); /* 68: */ /* 69: */ /* 70: 82 */ CandidateImpl candImpl = new CandidateImpl(); /* 71: 83 */ ExamListDTO qpDTO = examDAO.getExamDetails(examId, testId); /* 72: */ /* 73: 85 */ EmailTemplateImplementor emailImpl = new EmailTemplateImplementor(); /* 74: */ /* 75: 87 */ EmailTemplateDTO emailTemplateDTO = emailImpl.getEmailTemplate("Scheduled Exam", companyid); /* 76: 88 */ String mailBody = ""; /* 77: 89 */ String LogoURL = request.getScheme() + "://" + request.getServerName(); /* 78: 90 */ int portNo = request.getServerPort(); /* 79: 91 */ //if (request.getServerName().equals("localhost")) { /* 80: 92 */ LogoURL = LogoURL + ":" + portNo + request.getContextPath(); /* 81: */ //} else { /* 82: 94 */ // LogoURL = LogoURL + request.getContextPath(); /* 83: */ //} /* 84: 96 */ LogoURL = LogoURL + "/uploads/logos/logo-blue.png"; /* 85: 97 */ String imageTag = "<a href='" + request.getScheme() + "://" + request.getServerName() + request.getContextPath() + "/'><img src=\"" + LogoURL + "\" alt=\"Internal Assessment Tool\" border=\"0\"></a>"; /* 86: 98 */ if (userids != null) { /* 87: 99 */ for (int id : userids) { /* 88: */ try /* 89: */ { /* 90:101 */ String UserMails = candImpl.getEmail(id); /* 91:102 */ String passwords = candImpl.getUserPassword(id); /* 92:103 */ mailBody = emailTemplateDTO.getMailcontent(); /* 93:104 */ mailBody = StringUtils.replace(mailBody, "$$MYLOGO$$", LogoURL); /* 94:105 */ mailBody = StringUtils.replace(mailBody, "$$EXAMENAME$$", qpDTO.getExamName() + " - " + qpDTO.getQuestionPaperName()); /* 95:106 */ mailBody = StringUtils.replace(mailBody, "$$URL$$", "<a href='" + hostPath + request.getContextPath() + "'>here</a>"); /* 96:107 */ mailBody = StringUtils.replace(mailBody, "$$STARTDATE$$", "" + qpDTO.getStartDate()); /* 97:108 */ mailBody = StringUtils.replace(mailBody, "$$ENDDATE$$", "" + qpDTO.getEndDate()); /*removed by Tools team starts*/ /* 98:109 */ /* mailBody = StringUtils.replace(mailBody, "$$USERNAME$$", UserMails); 99:110 mailBody = StringUtils.replace(mailBody, "$$PASSWORD$$", EncryptionManager.decryptBlowfish(passwords));*/ /* 100: */ /*removed by Tools team ends*/ /* 101:112 */ mailBody = StringUtils.replace(mailBody, "$$COMMENTS$$", "<pre style='white-space: pre-wrap; word-wrap: break-word; font-family: verdana;'>" + mailForm.getComments() + "</pre>"); /* 102:113 */ mailBody = emailTemplateDTO.getHeader() + mailBody + emailTemplateDTO.getFooter(); /* 103: */ /* 104:115 */ MailSend mailsend = new MailSend(); /* 105:116 */ if (mailsend.sendMail(emailTemplateDTO.getFromfield(), UserMails, emailTemplateDTO.getMailsubject(), mailBody, emailTemplateDTO.getType())) /* 106: */ { /* 107:118 */ System.out.println("Message send successfully"); /* 108: */ /* 109:120 */ examDAO.updateMailSendStatus(examId, testId, id); /* 110: */ } /* 111: */ } /* 112: */ catch (Exception e) {} /* 113: */ } /* 114: */ } /* 115:127 */ result = "schedule"; /* 116:128 */ mailForm.setOperation(null); /* 117:129 */ mailForm.setComments(""); /* 118: */ } /* 119:133 */ ArrayList<ExamListDTO> testList = examDAO.getExamList(companyid, "0", "0"); /* 120:134 */ request.setAttribute("testList", testList); /* 121:135 */ String examId = "0"; /* 122:136 */ String testId = "0"; /* 123:137 */ if (option == SendMailAction$OPTIONS.EDIT) /* 124: */ { /* 125:138 */ searchString = request.getParameter("sSearch") == null ? "" : request.getParameter("sSearch"); /* 126:139 */ examId = mailForm.getTestdId().substring(0, mailForm.getTestdId().indexOf("-")); /* 127:140 */ testId = mailForm.getTestdId().substring(mailForm.getTestdId().indexOf("-") + 1, mailForm.getTestdId().length()); /* 128:141 */ userList = examDAO.getSchduleTestUserList(pagingBean, examId, testId, -1, -1, searchString.trim()); /* 129: */ /* 130:143 */ request.setAttribute("userList", userList); /* 131:144 */ mailForm.setOperation("VIEW_MAIL"); /* 132: */ } /* 133:145 */ else if (option == SendMailAction$OPTIONS.VIEW_MAIL) /* 134: */ { /* 135:146 */ searchString = request.getParameter("sSearch") == null ? "" : request.getParameter("sSearch"); /* 136:147 */ if ((!StringUtils.isEmpty(request.getParameter("testId"))) && (request.getParameter("testId") != null)) /* 137: */ { /* 138:148 */ examId = request.getParameter("testId").substring(0, request.getParameter("testId").indexOf("-")); /* 139:149 */ testId = request.getParameter("testId").substring(request.getParameter("testId").indexOf("-") + 1, request.getParameter("testId").length()); /* 140: */ } /* 141:151 */ totalUserList = examDAO.getSchduleTestUserList(pagingBean, examId, testId, -1, -1, searchString.trim()); /* 142:152 */ userList = examDAO.getSchduleTestUserList(pagingBean, examId, testId, request.getParameter("iDisplayStart") == null ? 1 : Integer.parseInt(request.getParameter("iDisplayStart")), request.getParameter("iDisplayLength") == null ? 20 : Integer.parseInt(request.getParameter("iDisplayLength")), searchString.trim()); /* 143:153 */ response.setContentType("application/Json"); /* 144:155 */ if (totalUserList.size() != 0) /* 145: */ { /* 146:156 */ response.getWriter().print(getJsonResponse(request, userList, totalUserList.size())); /* 147:157 */ return null; /* 148: */ } /* 149: */ } /* 150:160 */ request.setAttribute("pagingBean", pagingBean); /* 151:161 */ if (option != null) { /* 152:162 */ request.setAttribute("SearchCriteriaTypes", option); /* 153: */ } else { /* 154:164 */ request.setAttribute("SearchCriteriaTypes", "LIST"); /* 155: */ } /* 156:166 */ return mapping.findForward(result); /* 157: */ } /* 158: */ /* 159: */ public String getJsonResponse(HttpServletRequest request, List<TestScheduleDTO> userList, int totalSize) /* 160: */ { /* 161:170 */ JsonObject jsonResponse = new JsonObject(); /* 162:171 */ JsonArray data = new JsonArray(); /* 163: */ try /* 164: */ { /* 165:173 */ jsonResponse.addProperty("sEcho", Integer.valueOf(request.getParameter("sEcho") == null ? 1 : Integer.parseInt(request.getParameter("sEcho")))); /* 166:174 */ jsonResponse.addProperty("iTotalRecords", Integer.valueOf(totalSize)); /* 167:175 */ jsonResponse.addProperty("iTotalDisplayRecords", Integer.valueOf(totalSize)); /* 168:176 */ jsonResponse.addProperty("iDisplayLength", Integer.valueOf(request.getParameter("iDisplayLength") == null ? 20 : Integer.parseInt(request.getParameter("iDisplayLength")))); /* 169:177 */ jsonResponse.addProperty("iDisplayStart", Integer.valueOf(request.getParameter("iDisplayStart") == null ? 1 : Integer.parseInt(request.getParameter("iDisplayStart")) + 1)); /* 170:178 */ Gson gson = new Gson(); /* 171:180 */ for (TestScheduleDTO testScheduleDTO : userList) /* 172: */ { /* 173:181 */ JsonArray row = new JsonArray(); /* 174:182 */ row.add(new JsonPrimitive(String.valueOf(testScheduleDTO.getUserId()))); /* 175:183 */ row.add(new JsonPrimitive(testScheduleDTO.getEmail())); /* 176:184 */ row.add(new JsonPrimitive(Integer.valueOf(testScheduleDTO.getMailSendStatus()))); /* 177:185 */ data.add(row); /* 178: */ } /* 179:187 */ jsonResponse.add("aaData", data); /* 180: */ } /* 181: */ catch (Exception e) /* 182: */ { /* 183:189 */ e.printStackTrace(); /* 184: */ } /* 185:191 */ return jsonResponse.toString(); /* 186: */ } /* 187: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.test.scheduletest.action.SendMailAction * JD-Core Version: 0.7.0.1 */
package com.fabio.dropbox.services.exception; public class ExistingUserException extends RuntimeException{ public ExistingUserException(String message) { super(message); } }
package com.aries.orion.model.po; import java.util.ArrayList; import java.util.List; public class CourseExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public CourseExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andTeacherNameIsNull() { addCriterion("teacher_name is null"); return (Criteria) this; } public Criteria andTeacherNameIsNotNull() { addCriterion("teacher_name is not null"); return (Criteria) this; } public Criteria andTeacherNameEqualTo(String value) { addCriterion("teacher_name =", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameNotEqualTo(String value) { addCriterion("teacher_name <>", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameGreaterThan(String value) { addCriterion("teacher_name >", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameGreaterThanOrEqualTo(String value) { addCriterion("teacher_name >=", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameLessThan(String value) { addCriterion("teacher_name <", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameLessThanOrEqualTo(String value) { addCriterion("teacher_name <=", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameLike(String value) { addCriterion("teacher_name like", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameNotLike(String value) { addCriterion("teacher_name not like", value, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameIn(List<String> values) { addCriterion("teacher_name in", values, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameNotIn(List<String> values) { addCriterion("teacher_name not in", values, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameBetween(String value1, String value2) { addCriterion("teacher_name between", value1, value2, "teacherName"); return (Criteria) this; } public Criteria andTeacherNameNotBetween(String value1, String value2) { addCriterion("teacher_name not between", value1, value2, "teacherName"); return (Criteria) this; } public Criteria andTeacherDescIsNull() { addCriterion("teacher_desc is null"); return (Criteria) this; } public Criteria andTeacherDescIsNotNull() { addCriterion("teacher_desc is not null"); return (Criteria) this; } public Criteria andTeacherDescEqualTo(String value) { addCriterion("teacher_desc =", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescNotEqualTo(String value) { addCriterion("teacher_desc <>", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescGreaterThan(String value) { addCriterion("teacher_desc >", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescGreaterThanOrEqualTo(String value) { addCriterion("teacher_desc >=", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescLessThan(String value) { addCriterion("teacher_desc <", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescLessThanOrEqualTo(String value) { addCriterion("teacher_desc <=", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescLike(String value) { addCriterion("teacher_desc like", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescNotLike(String value) { addCriterion("teacher_desc not like", value, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescIn(List<String> values) { addCriterion("teacher_desc in", values, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescNotIn(List<String> values) { addCriterion("teacher_desc not in", values, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescBetween(String value1, String value2) { addCriterion("teacher_desc between", value1, value2, "teacherDesc"); return (Criteria) this; } public Criteria andTeacherDescNotBetween(String value1, String value2) { addCriterion("teacher_desc not between", value1, value2, "teacherDesc"); return (Criteria) this; } public Criteria andCourseDescIsNull() { addCriterion("course_desc is null"); return (Criteria) this; } public Criteria andCourseDescIsNotNull() { addCriterion("course_desc is not null"); return (Criteria) this; } public Criteria andCourseDescEqualTo(String value) { addCriterion("course_desc =", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescNotEqualTo(String value) { addCriterion("course_desc <>", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescGreaterThan(String value) { addCriterion("course_desc >", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescGreaterThanOrEqualTo(String value) { addCriterion("course_desc >=", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescLessThan(String value) { addCriterion("course_desc <", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescLessThanOrEqualTo(String value) { addCriterion("course_desc <=", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescLike(String value) { addCriterion("course_desc like", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescNotLike(String value) { addCriterion("course_desc not like", value, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescIn(List<String> values) { addCriterion("course_desc in", values, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescNotIn(List<String> values) { addCriterion("course_desc not in", values, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescBetween(String value1, String value2) { addCriterion("course_desc between", value1, value2, "courseDesc"); return (Criteria) this; } public Criteria andCourseDescNotBetween(String value1, String value2) { addCriterion("course_desc not between", value1, value2, "courseDesc"); return (Criteria) this; } public Criteria andCourseNameIsNull() { addCriterion("course_name is null"); return (Criteria) this; } public Criteria andCourseNameIsNotNull() { addCriterion("course_name is not null"); return (Criteria) this; } public Criteria andCourseNameEqualTo(String value) { addCriterion("course_name =", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameNotEqualTo(String value) { addCriterion("course_name <>", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameGreaterThan(String value) { addCriterion("course_name >", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameGreaterThanOrEqualTo(String value) { addCriterion("course_name >=", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameLessThan(String value) { addCriterion("course_name <", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameLessThanOrEqualTo(String value) { addCriterion("course_name <=", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameLike(String value) { addCriterion("course_name like", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameNotLike(String value) { addCriterion("course_name not like", value, "courseName"); return (Criteria) this; } public Criteria andCourseNameIn(List<String> values) { addCriterion("course_name in", values, "courseName"); return (Criteria) this; } public Criteria andCourseNameNotIn(List<String> values) { addCriterion("course_name not in", values, "courseName"); return (Criteria) this; } public Criteria andCourseNameBetween(String value1, String value2) { addCriterion("course_name between", value1, value2, "courseName"); return (Criteria) this; } public Criteria andCourseNameNotBetween(String value1, String value2) { addCriterion("course_name not between", value1, value2, "courseName"); return (Criteria) this; } public Criteria andCourseIntroduceIsNull() { addCriterion("course_introduce is null"); return (Criteria) this; } public Criteria andCourseIntroduceIsNotNull() { addCriterion("course_introduce is not null"); return (Criteria) this; } public Criteria andCourseIntroduceEqualTo(String value) { addCriterion("course_introduce =", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceNotEqualTo(String value) { addCriterion("course_introduce <>", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceGreaterThan(String value) { addCriterion("course_introduce >", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceGreaterThanOrEqualTo(String value) { addCriterion("course_introduce >=", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceLessThan(String value) { addCriterion("course_introduce <", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceLessThanOrEqualTo(String value) { addCriterion("course_introduce <=", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceLike(String value) { addCriterion("course_introduce like", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceNotLike(String value) { addCriterion("course_introduce not like", value, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceIn(List<String> values) { addCriterion("course_introduce in", values, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceNotIn(List<String> values) { addCriterion("course_introduce not in", values, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceBetween(String value1, String value2) { addCriterion("course_introduce between", value1, value2, "courseIntroduce"); return (Criteria) this; } public Criteria andCourseIntroduceNotBetween(String value1, String value2) { addCriterion("course_introduce not between", value1, value2, "courseIntroduce"); return (Criteria) this; } public Criteria andBrightSpotIsNull() { addCriterion("bright_spot is null"); return (Criteria) this; } public Criteria andBrightSpotIsNotNull() { addCriterion("bright_spot is not null"); return (Criteria) this; } public Criteria andBrightSpotEqualTo(String value) { addCriterion("bright_spot =", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotNotEqualTo(String value) { addCriterion("bright_spot <>", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotGreaterThan(String value) { addCriterion("bright_spot >", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotGreaterThanOrEqualTo(String value) { addCriterion("bright_spot >=", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotLessThan(String value) { addCriterion("bright_spot <", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotLessThanOrEqualTo(String value) { addCriterion("bright_spot <=", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotLike(String value) { addCriterion("bright_spot like", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotNotLike(String value) { addCriterion("bright_spot not like", value, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotIn(List<String> values) { addCriterion("bright_spot in", values, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotNotIn(List<String> values) { addCriterion("bright_spot not in", values, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotBetween(String value1, String value2) { addCriterion("bright_spot between", value1, value2, "brightSpot"); return (Criteria) this; } public Criteria andBrightSpotNotBetween(String value1, String value2) { addCriterion("bright_spot not between", value1, value2, "brightSpot"); return (Criteria) this; } public Criteria andImageIdIsNull() { addCriterion("image_id is null"); return (Criteria) this; } public Criteria andImageIdIsNotNull() { addCriterion("image_id is not null"); return (Criteria) this; } public Criteria andImageIdEqualTo(Long value) { addCriterion("image_id =", value, "imageId"); return (Criteria) this; } public Criteria andImageIdNotEqualTo(Long value) { addCriterion("image_id <>", value, "imageId"); return (Criteria) this; } public Criteria andImageIdGreaterThan(Long value) { addCriterion("image_id >", value, "imageId"); return (Criteria) this; } public Criteria andImageIdGreaterThanOrEqualTo(Long value) { addCriterion("image_id >=", value, "imageId"); return (Criteria) this; } public Criteria andImageIdLessThan(Long value) { addCriterion("image_id <", value, "imageId"); return (Criteria) this; } public Criteria andImageIdLessThanOrEqualTo(Long value) { addCriterion("image_id <=", value, "imageId"); return (Criteria) this; } public Criteria andImageIdIn(List<Long> values) { addCriterion("image_id in", values, "imageId"); return (Criteria) this; } public Criteria andImageIdNotIn(List<Long> values) { addCriterion("image_id not in", values, "imageId"); return (Criteria) this; } public Criteria andImageIdBetween(Long value1, Long value2) { addCriterion("image_id between", value1, value2, "imageId"); return (Criteria) this; } public Criteria andImageIdNotBetween(Long value1, Long value2) { addCriterion("image_id not between", value1, value2, "imageId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.advance.academy.homework.bank.system.repository; public interface GetReference { public <T> T getReference(Class<T> tClass, Integer id); }
package com.ls.Test.packages.net.TCP1; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); while (true) { new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub synchronized (this) { Socket socket = null; try { socket = serverSocket.accept(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //输入流 DataInputStream dataInputStream = null; try { dataInputStream = new DataInputStream(socket.getInputStream()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String str = null; try { str = dataInputStream.readUTF(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("客户端收到了"+str); //输出流 DataOutputStream dataOutputStream = null; try { dataOutputStream = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { dataOutputStream.writeUTF(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("客户端转发了"+str); try { dataOutputStream.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } } }
package com.example.springStudy.transactional.service; import com.example.springStudy.transactional.dto.TOne; /** * t_one 表 service * * @author lijie * @date 2021/5/23 18:56 */ public interface TestService { /** * 根据 id 查询 * @author lijie * @date 2021/5/23 20:07 * @param id: * @return com.example.springStudy.transactional.dto.TOne */ TOne selectByPrimaryKey(Integer id); /** * 插入一条数据 * @author lijie * @date 2021/5/23 20:50 * @param entity: * @return int */ int insertOne(TOne entity); }
package modelo; public class Libro { //ATRIBUTOS private int diaAgreLibre; private int mesAgreLibre; private int anoAgreLibre; private String pais; private int cantidadPag; private String nombre; private String nombreDelAutor; private String regisISBN; private boolean editAnoActu; //CONSTRUCTOR public Libro(int dia, int mes, int ano, String elPais, int cant, String elNombre, String autor, String ISBN) { diaAgreLibre = dia; mesAgreLibre = mes; anoAgreLibre = ano; pais = elPais; cantidadPag = cant; nombre = elNombre; nombreDelAutor = autor; regisISBN = ISBN; editAnoActu = false; } public int darDia() { return diaAgreLibre; } public void modificarDia(int dia) { diaAgreLibre = dia; } public int darMes() { return mesAgreLibre; } public void modificarMes(int mes) { mesAgreLibre = mes; } public int darAno() { return anoAgreLibre; } public void modificarAno(int ano) { anoAgreLibre = ano; } public String darPais() { return pais; } public void modificarPais(String elPais) { pais = elPais; } public int darCantidadPag() { return cantidadPag; } public void modificarCantidadPag(int cant) { cantidadPag = cant; } public String darNombre() { return nombre; } public void modificarNombre(String elNombre) { nombre = elNombre; } public String darNombreDelAutor() { return nombreDelAutor; } public void modificarNombreDelAutor(String autor) { nombreDelAutor = autor; } public String darRegisISBN() { return regisISBN; } public void modificarRegisISBN(String ISBN) { regisISBN = ISBN; } public boolean darEditadoAnoActu() { return editAnoActu; } public void modificarEditado(boolean editado) { editAnoActu = false; } }
package com.solomon; import com.solomon.domain.Question; import com.solomon.repository.QuestionRepo; 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; /** * Created by xuehaipeng on 2017/7/31. */ @RunWith(SpringRunner.class) @SpringBootTest public class QuestionTests { @Autowired QuestionRepo questionRepo; @Test public void test1() { Question question = questionRepo.findOne(1L); System.out.println(question.getMenuId()); } }
/** * * ****************************************************************************** * MontiCAR Modeling Family, www.se-rwth.de * Copyright (c) 2017, Software Engineering Group at RWTH Aachen, * All rights reserved. * * This project is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this project. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* */ package de.monticore.lang.monticar.cnnarch.helper; import de.monticore.lang.math.math._symboltable.expression.*; import de.monticore.lang.monticar.cnnarch._symboltable.TupleExpressionSymbol; import de.monticore.lang.monticar.ranges._ast.ASTRange; import de.monticore.lang.monticar.types2._ast.ASTElementType; import de.monticore.symboltable.Scope; import de.monticore.symboltable.Symbol; import de.monticore.symboltable.resolving.ResolvingFilter; import java.util.*; import java.util.function.Function; public class Utils { public static List<MathExpressionSymbol> createSubExpressionList(MathExpressionSymbol expression){ List<MathExpressionSymbol> list = new LinkedList<>(); list.add(expression); //switch expression.class if (expression instanceof MathParenthesisExpressionSymbol){ MathParenthesisExpressionSymbol exp = (MathParenthesisExpressionSymbol) expression; list.addAll(createSubExpressionList(exp.getMathExpressionSymbol())); } else if (expression instanceof MathCompareExpressionSymbol){ MathCompareExpressionSymbol exp = (MathCompareExpressionSymbol) expression; list.addAll(createSubExpressionList(exp.getLeftExpression())); list.addAll(createSubExpressionList(exp.getRightExpression())); } else if (expression instanceof MathArithmeticExpressionSymbol){ MathArithmeticExpressionSymbol exp = (MathArithmeticExpressionSymbol) expression; list.addAll(createSubExpressionList(exp.getLeftExpression())); list.addAll(createSubExpressionList(exp.getRightExpression())); } else if (expression instanceof MathPreOperatorExpressionSymbol){ MathPreOperatorExpressionSymbol exp = (MathPreOperatorExpressionSymbol) expression; list.addAll(createSubExpressionList(exp.getMathExpressionSymbol())); } else if (expression instanceof TupleExpressionSymbol){ TupleExpressionSymbol tuple = (TupleExpressionSymbol) expression; for (MathExpressionSymbol exp : tuple.getExpressions()){ list.addAll(createSubExpressionList(exp)); } } else if (expression instanceof MathValueExpressionSymbol){ //do nothing } else { throw new IllegalArgumentException("Unknown expression type: " + expression.getClass().getSimpleName()); } return list; } public static String replace(String expression, Map<String, String> replacementMap){ String resolvedString = expression; for (String name : replacementMap.keySet()){ resolvedString = resolvedString.replaceAll(name, replacementMap.get(name)); } return resolvedString; } public static <T> String createTupleTextualRepresentation(List<T> list, Function<T,String> stringFunction){ StringBuilder builder = new StringBuilder(); builder.append("("); for (int i = 0; i< list.size(); i++){ builder.append(stringFunction.apply(list.get(i))); if (i != list.size()-1 || i==0){ builder.append(","); } } builder.append(")"); return builder.toString(); } public static MathExpressionSymbol copy(MathExpressionSymbol expression){ MathExpressionSymbol copy; //switch expression.class if (expression instanceof MathParenthesisExpressionSymbol){ MathParenthesisExpressionSymbol exp = (MathParenthesisExpressionSymbol) expression; copy = new MathParenthesisExpressionSymbol(copy(exp.getMathExpressionSymbol())); } else if (expression instanceof MathCompareExpressionSymbol){ MathCompareExpressionSymbol exp = (MathCompareExpressionSymbol) expression; MathCompareExpressionSymbol castedCopy = new MathCompareExpressionSymbol(); castedCopy.setCompareOperator(exp.getCompareOperator()); castedCopy.setLeftExpression(copy(exp.getLeftExpression())); castedCopy.setRightExpression(copy(exp.getRightExpression())); copy = castedCopy; } else if (expression instanceof MathArithmeticExpressionSymbol){ MathArithmeticExpressionSymbol exp = (MathArithmeticExpressionSymbol) expression; MathArithmeticExpressionSymbol castedCopy = new MathArithmeticExpressionSymbol(); castedCopy.setMathOperator(exp.getMathOperator()); castedCopy.setLeftExpression(copy(exp.getLeftExpression())); castedCopy.setRightExpression(copy(exp.getRightExpression())); copy = castedCopy; } else if (expression instanceof MathPreOperatorExpressionSymbol){ MathPreOperatorExpressionSymbol exp = (MathPreOperatorExpressionSymbol) expression; MathPreOperatorExpressionSymbol castedCopy = new MathPreOperatorExpressionSymbol(); castedCopy.setOperator(exp.getOperator()); castedCopy.setMathExpressionSymbol(copy(exp.getMathExpressionSymbol())); copy = castedCopy; } else if (expression instanceof TupleExpressionSymbol){ TupleExpressionSymbol exp = (TupleExpressionSymbol) expression; TupleExpressionSymbol castedCopy = new TupleExpressionSymbol(); List<MathExpressionSymbol> elementCopies = new ArrayList<>(); for (MathExpressionSymbol element : exp.getExpressions()){ elementCopies.add(copy(element)); } castedCopy.setExpressions(elementCopies); copy = castedCopy; } else if (expression instanceof MathNameExpressionSymbol){ MathNameExpressionSymbol exp = (MathNameExpressionSymbol) expression; copy = new MathNameExpressionSymbol(exp.getNameToResolveValue()); } else if (expression instanceof MathNumberExpressionSymbol){ MathNumberExpressionSymbol exp = (MathNumberExpressionSymbol) expression; copy = new MathNumberExpressionSymbol(exp.getValue().getRealNumber()); } else { throw new IllegalArgumentException("Unknown expression type: " + expression.getClass().getSimpleName()); } copy.setID(expression.getExpressionID()); if (expression.getAstNode().isPresent()){ copy.setAstNode(expression.getAstNode().get()); } return copy; } public static boolean equals(ASTElementType firstType, ASTElementType secondType){ if (firstType.isIsBoolean() ^ secondType.isIsBoolean() || firstType.isIsNatural() ^ secondType.isIsNatural() || firstType.isIsRational() ^ secondType.isIsRational() || firstType.isIsWholeNumberNumber() ^ secondType.isIsWholeNumberNumber() || firstType.isIsComplex() ^ secondType.isIsComplex()){ return false; } if (firstType.getRange().isPresent()){ if (!secondType.getRange().isPresent()){ return false; } } else { return !secondType.getRange().isPresent(); } return equals(firstType.getRange().get(), secondType.getRange().get()); } public static boolean equals(ASTRange firstRange, ASTRange secondRange){ if (firstRange.getStartInf().isPresent() ^ secondRange.getStartInf().isPresent() || firstRange.getEndInf().isPresent() ^ secondRange.getEndInf().isPresent()){ return false; } if (!firstRange.getStartInf().isPresent() && !firstRange.getStartValue().equals(secondRange.getStartValue())){ return false; } if (!firstRange.getEndInf().isPresent() && !firstRange.getEndValue().equals(secondRange.getEndValue())){ return false; } if (firstRange.getStep().isPresent() ^ secondRange.getStep().isPresent()){ return false; } if (firstRange.getStep().isPresent() && !firstRange.getStepValue().equals(secondRange.getStepValue())){ return false; } return true; } public static void recursiveSetResolvingFilters(Scope scope, Collection<ResolvingFilter<? extends Symbol>> resolvingFilters){ scope.getAsMutableScope().setResolvingFilters(resolvingFilters); for (Scope subScope : scope.getSubScopes()){ recursiveSetResolvingFilters(subScope, resolvingFilters); } } }
package main.fr.brice.quarto.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Bag { ArrayList<Token> tokens; public Bag(){ this.tokens = new ArrayList<Token>(); } public void addToken(List<Token> token){ if(token != null){ this.tokens.addAll(token); } } public Token getToken(int index){ return this.tokens != null && !this.tokens.isEmpty() ? this.tokens.get(index) : null; } public Token removeToken(int index){ return this.tokens.remove(index); } public ArrayList<Token> getTokens() { return tokens; } }
package com.chuxin.family.parse; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.chuxin.family.parse.been.CxPairInit; import com.chuxin.family.parse.been.CxTabloid; import com.chuxin.family.parse.been.CxTabloidCateConf; import com.chuxin.family.parse.been.data.CxPairInitData; import com.chuxin.family.parse.been.data.TabloidCateConfData; import com.chuxin.family.parse.been.data.TabloidCateConfObj; import com.chuxin.family.parse.been.data.TabloidData; import com.chuxin.family.parse.been.data.TabloidObj; import com.chuxin.family.utils.CxLog; public class TabloidParse { private final String TAG = "TabloidParse"; /** * 获取小报配置接口的网络应答解析 * @param obj * @return */ public CxTabloidCateConf parseCateConf(Object obj){ if (null == obj) { return null; } CxTabloidCateConf tabloidCateConf = new CxTabloidCateConf(); JSONObject jObj = (JSONObject)obj; int rc = -1; try { rc = jObj.getInt("rc"); } catch (Exception e2) { e2.printStackTrace(); } if (-1 == rc) { return null; } tabloidCateConf.setRc(rc); try { String msg = jObj.getString("msg"); int ts = jObj.getInt("ts"); tabloidCateConf.setMsg(msg); tabloidCateConf.setTs(ts); } catch (Exception e2) { e2.printStackTrace(); } if (0 != rc) { return tabloidCateConf; } //解析data字段 JSONArray tempArray = new JSONArray(); JSONObject dataObj = null; String version = "1"; int max_amount = 20; String fetch_resource_time = ""; String notification_time = "" ; try{ dataObj = (JSONObject) jObj.get("data"); tempArray = (JSONArray)dataObj.get("config"); version = dataObj.getString("version"); max_amount = dataObj.getInt("max_amount"); fetch_resource_time = dataObj.getString("fetch_resource_time"); notification_time = dataObj.getString("notification_time") ; }catch(Exception e){ CxLog.e(TAG, "解析json错误, jsonStr:" + obj.toString()); } TabloidCateConfData data = new TabloidCateConfData(); List<TabloidCateConfObj> config = new ArrayList<TabloidCateConfObj>(); int len = tempArray.length(); for(int i = 0; i < len; i++){ TabloidCateConfObj cateConfObj = new TabloidCateConfObj(); JSONObject tempElement = null; try { tempElement = (JSONObject)tempArray.get(i); } catch (Exception e1) { e1.printStackTrace(); } if (null == tempElement) { continue; } try { int category_id = tempElement.getInt("category_id"); cateConfObj.setCategory_id(category_id);; } catch (Exception e) { e.printStackTrace(); } try { String notification_week = tempElement.getString("notification_week"); cateConfObj.setNotification_week(notification_week);; } catch (Exception e) { e.printStackTrace(); } try { String img = tempElement.getString("img"); cateConfObj.setImg(img); } catch (Exception e) { e.printStackTrace(); } try { String title = tempElement.getString("title"); cateConfObj.setTitle(title); } catch (Exception e) { e.printStackTrace(); } try { String status = tempElement.getString("notification_status"); cateConfObj.setNotification_status(status); } catch (Exception e) { e.printStackTrace(); } config.add(cateConfObj); }//end for(i) data.setConfig(config); data.setFetch_resource_time(fetch_resource_time); data.setNotification_time(notification_time); data.setVersion(version); data.setMax_amount(max_amount); tabloidCateConf.setData(data); return tabloidCateConf; } public CxTabloid parseTabloid(Object obj){ if (null == obj) { return null; } CxTabloid tabloid = new CxTabloid(); JSONObject jObj = (JSONObject)obj; int rc = -1; try { rc = jObj.getInt("rc"); } catch (Exception e2) { e2.printStackTrace(); } if (-1 == rc) { return null; } tabloid.setRc(rc); try { String msg = jObj.getString("msg"); int ts = jObj.getInt("ts"); tabloid.setMsg(msg); tabloid.setTs(ts); } catch (Exception e2) { e2.printStackTrace(); } if (0 != rc) { return tabloid; } //解析data字段 JSONArray tempArray = new JSONArray(); JSONArray dataObjArr = null; List<TabloidData> dataList = new ArrayList<TabloidData>(); try{ dataObjArr = (JSONArray) jObj.get("data"); }catch(Exception e){ e.printStackTrace(); } CxLog.d(TAG, "dataObjArr.length:" + dataObjArr.length()); for(int i=0; i<dataObjArr.length(); i++){ TabloidData tabloidData = new TabloidData(); JSONObject cateDataObj; int category_id ; try { cateDataObj = (JSONObject)dataObjArr.get(i); category_id = cateDataObj.getInt("category_id"); tempArray = (JSONArray)cateDataObj.get("tabloids"); } catch (JSONException e) { CxLog.e(TAG,"json解析异常:" + e.toString()); continue; } CxLog.d(TAG, "tabloids.length:" + tempArray.length()); for(int j=0; j<tempArray.length();j++){ TabloidObj tObj = new TabloidObj(); String text = ""; int id = -1; try { JSONObject tempElement = (JSONObject)tempArray.get(j); text = tempElement.getString("text"); id = tempElement.getInt("id"); } catch (JSONException e) { CxLog.e(TAG, "json解析异常2:" + e.getMessage()); } tObj.setId(id); tObj.setText(text); tabloidData.getTabloids().add(tObj); } tabloidData.setCategory_id(category_id); dataList.add(tabloidData); } tabloid.setData(dataList); return tabloid; } }
package openopoly.control.business; import openopoly.Player; /** Classe que representa o banco como um Proprietario * * @author Lucas * @author Sergio */ public class Bank { private static Player bank; /** * O construtor tem a função de instanciar um Jogador de nome "bank" */ public Bank() { bank = new Player("bank", ""); bank.setIsBank(true); } public static Player getBank() { return bank; } }
import java.io.File; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.util.*; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import java.util.regex.Pattern; import org.xml.sax.helpers.DefaultHandler; import java.nio.charset.Charset; class values{ } public class GenerateStopwords { public static HashMap<String,Integer> tf=new HashMap<String,Integer>(); public static HashMap<String,Integer> idf=new HashMap<String,Integer>(); public static HashMap<String,Integer> mat=new HashMap<String,Integer>(); private Set<String> stopwords; public void GenerateStopwords(){ } public static void main(String[] args){ } public void Generatefromxml(String file) { try { File inputFile = new File(file); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); UserHandler2 userhandler = new UserHandler2(); userhandler.sample(tf, idf); saxParser.parse(inputFile, userhandler); Map<String,Integer> idf_sorted = sortByValue(idf); Map<String,Integer> tf_sorted = sortByValue(tf); for(Map.Entry m:idf.entrySet()){ Integer s1=(Integer) tf.get(m.getKey()); Integer s2 =(Integer) m.getValue(); Integer s3=s1*s2; mat.put((String)m.getKey(),s3); } Map<String,Integer> mat_sorted = sortByValue(mat); for(Map.Entry m:mat_sorted.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } catch (Exception e) { e.printStackTrace(); } } private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) { // 1. Convert Map to List of Map List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet()); // 2. Sort list with Collections.sort(), provide a custom Comparator // Try switch the o1 o2 position for a different order Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } public void generatefromfile(String file){ stopwords = new HashSet<>(); try{ FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8"))); String line; while ((line = br.readLine()) != null) { //System.out.println(line); stopwords.add(line); } br.close(); } catch( Exception e) { e.printStackTrace(); } } public boolean checkStopWord(StringBuilder str){ return (stopwords.contains(str)); } public boolean checkStopWord(String str){ return (stopwords.contains(str)); } public static <K, V> void printMap(Map<K, V> map) { for (Map.Entry<K, V> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } } } class UserHandler2 extends DefaultHandler { boolean isTitle = false; boolean isBody = false; boolean isRevision = false; boolean isId = false; Pattern ptn = Pattern.compile("(d+|[w]+)"); HashSet<String> set=new HashSet<String>(); HashMap<String,Integer> tf; HashMap<String,Integer> idf; int counter=1; public void sample(HashMap<String,Integer> tf,HashMap<String,Integer> idf){ this.tf=tf; this.idf=idf; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { counter++; if(counter==100) { // TODO: Whatever should happen when condition is reached return; } // System.out.println("Roll No : " + qName); if (qName.equalsIgnoreCase("revision")) { isRevision = true; } else if (qName.equalsIgnoreCase("title")) { isTitle = true; } else if (qName.equalsIgnoreCase("text")) { isBody = true; } else if (qName.equalsIgnoreCase("nickname")) { isRevision = true; } else if (qName.equalsIgnoreCase("id")) { // String rollNo = attributes.getValue("id"); // System.out.println("Roll No : " + rollNo); isId = true; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { System.out.println("End Element :" + qName); } } @Override public void characters(char ch[], int start, int length) throws SAXException { set=new HashSet<String>(); if (isTitle) { // System.out.println("Title: " // + new String(ch, start, length)); isTitle = false; } else if (isBody) { String s2 = new String(ch, start, length); s2=s2.toLowerCase(); System.out.println(s2); String s1 = s2.replaceAll("[-:()^[!|=,?._'{}@+\\[\\]]]", " "); String[] parts = s1.split("\\s+"); for(String p:parts){ set.add(p); if(tf.get(p)==null) { tf.put(p,1); } else { Integer r = tf.get(p)+1; tf.put(p,r); } System.out.println(p); } Iterator<String> itr=set.iterator(); System.out.println(set.toString()); while(itr.hasNext()){ String y = itr.next(); if(idf.get(y)==null) { idf.put(y,1); } else{ Integer r = tf.get(y)+1; idf.put(y,r); } // System.out.println(itr.next()); } isBody = false; } else if (isRevision) { // System.out.println("Revision: " + new String(ch, start, length)); isRevision = false; } else if (isId) { isId = false; } } }
import java.util.*; import java.io.*; class prime{ public static void main(String args[]){ int n,sum=0; Scanner sc= new Scanner(System.in); System.out.println("Enter size of array"); n=sc.nextInt(); int arr[]; arr= new int[n]; System.out.println("Enter elements"); int r,c=0; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); for(int j=1;j<n;j++){ r=arr[i]%j; if(r==0){ c++; } } if(c==2){ sum=sum+arr[i]; } } System.out.println("Sum is "+sum); } }
package com.mctoybox.toybox.exceptions; public class PlayerNotAllowedClassException extends Exception { private static final long serialVersionUID = 1L; public PlayerNotAllowedClassException() { super(); } public PlayerNotAllowedClassException(String message) { super(message); } public PlayerNotAllowedClassException(String message, Throwable cause) { super(message, cause); } public PlayerNotAllowedClassException(Throwable cause) { super(cause); } }
package com.xiruan.demand.demand.job; import com.xiruan.demand.entity.automation.ParamField; import com.xiruan.demand.repository.ParamFieldDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Component; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import java.util.List; /** * Created by dell on 2015/10/12. */ @Component @Transactional public class ParamFieldService { @Autowired private ParamFieldDao paramFieldDao; public Page<ParamField> getJobTemplate(int pageNumber, int pageSize) { PageRequest pageRequest = buildPageRequest(pageNumber, pageSize); return paramFieldDao.findAll(new Specification<ParamField>() { @Override public Predicate toPredicate(Root<ParamField> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { return null; } }, pageRequest); } private PageRequest buildPageRequest(int pageNumber, int pagzSize) { return new PageRequest(pageNumber - 1, pagzSize, new Sort(Sort.Direction.DESC, "id")); } public void saveParamField(ParamField paramField){ paramFieldDao.save(paramField); } public List<ParamField> findAll(){ return (List<ParamField>) paramFieldDao.findAll(); } }
package org.slf4j.event; import java.util.Objects; public class KeyValuePair { public final String key; public final Object value; public KeyValuePair(String key, Object value) { this.key = key; this.value = value; } @Override public String toString() { return String.valueOf(key) + "=\"" + String.valueOf(value) +"\""; } @Override public boolean equals(Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; KeyValuePair that = (KeyValuePair) o; return Objects.equals(key, that.key) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(key, value); } }
package org.usfirst.frc.team1155.robot; class Timer { private double startTime, previousTime, currentTime, differenceInTime; // Called During Auto-Init void setStartTime() { startTime = System.currentTimeMillis(); previousTime = startTime; System.out.println("Start Time " + startTime); } public double getStartTime() { return startTime; } private double getPreviousTime() { if (currentTime != 0.0) { previousTime = currentTime; return previousTime; } return previousTime; } private double getCurrentTime() { currentTime = System.currentTimeMillis(); return currentTime; } double getTimeDifference() { differenceInTime = -getPreviousTime() + getCurrentTime(); return differenceInTime; } }
package com.xactly.automation.GmailTest; import junit.framework.Test; import junit.framework.TestCase; import com.jayway.restassured.RestAssured; import com.jayway.restassured.response.Headers; import com.jayway.restassured.response.ResponseBody; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; /** * Unit test for simple App. */ public class Base { String bearer_Token = "ya29.Glv5BXTVCm7q-civBES_PUjuAaLRoU1jBDgBSVZtpCvlWbTkSXvHoftQxtgxZq1P_AhiHC__EjDGJ2-jTkdU2ShsxHLVKtAsINF6p4GyzWxawDtMQXPeVwUaap1x"; String gmail_BaseUrl = "https://www.googleapis.com/gmail/v1/users/accesssantu@gmail.com/" // Retrieve Scheduler History @SuppressWarnings("rawtypes") public ResponseBody getSchedulerHistory(String apiToken,String Scheduler_ID) { ResponseBody response = RestAssured.given() .contentType("application/json") .header("Authorization", createAuthHeader(apiToken)) .expect() .statusCode(200) .when() .get(gmail_BaseUrl+"/messages").getBody(); return response; } }
package com.example.responsimobile.view.fragment; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.responsimobile.R; import com.example.responsimobile.adapter.KasusAdapter; import com.example.responsimobile.model.ContentItemDataHarian; import com.example.responsimobile.viewmodel.DataHarianViewModel; import java.util.ArrayList; public class KasusFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER //menghubungkan ke layout activity main private RecyclerView recyclerView; private KasusAdapter kasusAdapter; private DataHarianViewModel dataHarianViewModel; //data yg akan ditampilkan adapter ke recycler public KasusFragment() { // Required empty public constructor } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); kasusAdapter = new KasusAdapter(getContext()); kasusAdapter.notifyDataSetChanged(); recyclerView = view.findViewById(R.id.rv_data); dataHarianViewModel = new ViewModelProvider(this).get(DataHarianViewModel.class); dataHarianViewModel.setItemDataHarian(); dataHarianViewModel.getResponseData().observe(getViewLifecycleOwner(), getResponseData); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(kasusAdapter); } private Observer<ArrayList<ContentItemDataHarian>> getResponseData = new Observer<ArrayList<ContentItemDataHarian>>() { @Override public void onChanged(ArrayList<ContentItemDataHarian> contentItemDataHarians) { if(dataHarianViewModel != null){ kasusAdapter.setData(contentItemDataHarians); } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_list, container, false); } }
package org.twak.gouraud; import static org.lwjgl.assimp.Assimp.AI_MATKEY_COLOR_AMBIENT; import static org.lwjgl.assimp.Assimp.AI_MATKEY_COLOR_DIFFUSE; import static org.lwjgl.assimp.Assimp.AI_MATKEY_COLOR_SPECULAR; import static org.lwjgl.assimp.Assimp.aiGetErrorString; import static org.lwjgl.assimp.Assimp.aiGetMaterialColor; import static org.lwjgl.assimp.Assimp.aiReleaseImport; import static org.lwjgl.assimp.Assimp.aiTextureType_NONE; import static org.lwjgl.opengl.ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB; import static org.lwjgl.opengl.ARBVertexBufferObject.GL_ELEMENT_ARRAY_BUFFER_ARB; import static org.lwjgl.opengl.ARBVertexBufferObject.GL_STATIC_DRAW_ARB; import static org.lwjgl.opengl.ARBVertexBufferObject.glBindBufferARB; import static org.lwjgl.opengl.ARBVertexBufferObject.glBufferDataARB; import static org.lwjgl.opengl.ARBVertexBufferObject.glGenBuffersARB; import static org.lwjgl.opengl.ARBVertexBufferObject.nglBufferDataARB; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import org.lwjgl.assimp.AIColor4D; import org.lwjgl.assimp.AIFace; import org.lwjgl.assimp.AIMaterial; import org.lwjgl.assimp.AIMesh; import org.lwjgl.assimp.AIScene; import org.lwjgl.assimp.AIVector3D; import org.lwjgl.system.MemoryUtil; class Model { public AIScene scene; public List<Model.Mesh> meshes; public List<Model.Material> materials; public Model(AIScene scene) { this.scene = scene; int meshCount = scene.mNumMeshes(); PointerBuffer meshesBuffer = scene.mMeshes(); meshes = new ArrayList<>(); for (int i = 0; i < meshCount; ++i) { meshes.add(new Mesh(AIMesh.create(meshesBuffer.get(i)))); } int materialCount = scene.mNumMaterials(); PointerBuffer materialsBuffer = scene.mMaterials(); materials = new ArrayList<>(); for (int i = 0; i < materialCount; ++i) { materials.add(new Material(AIMaterial.create(materialsBuffer.get(i)))); } } public void free() { aiReleaseImport(scene); scene = null; meshes = null; materials = null; } public static class Mesh { public AIMesh mesh; public int vertexArrayBuffer; public int normalArrayBuffer; public int colourArrayBuffer; public int elementArrayBuffer; public int elementCount; public Mesh(AIMesh mesh) { this.mesh = mesh; vertexArrayBuffer = glGenBuffersARB(); glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexArrayBuffer); AIVector3D.Buffer vertices = mesh.mVertices(); nglBufferDataARB(GL_ARRAY_BUFFER_ARB, AIVector3D.SIZEOF * vertices.remaining(), vertices.address(), GL_STATIC_DRAW_ARB); normalArrayBuffer = glGenBuffersARB(); glBindBufferARB(GL_ARRAY_BUFFER_ARB, normalArrayBuffer); AIVector3D.Buffer normals = mesh.mNormals(); nglBufferDataARB(GL_ARRAY_BUFFER_ARB, AIVector3D.SIZEOF * normals.remaining(), normals.address(), GL_STATIC_DRAW_ARB); colourArrayBuffer = glGenBuffersARB(); glBindBufferARB(GL_ARRAY_BUFFER_ARB, colourArrayBuffer); float[] colors = new float[vertices.remaining() * 3 * 4]; for (int i = 0; i < colors.length; i++) colors[i] = (float)Math.random(); FloatBuffer colorsBuffer = BufferUtils.createFloatBuffer(colors.length); colorsBuffer.put(colors); colorsBuffer.flip(); glBufferDataARB(GL_ARRAY_BUFFER_ARB, colorsBuffer, GL_STATIC_DRAW_ARB); // nglBufferDataARB(GL_ARRAY_BUFFER_ARB, AIVector3D.SIZEOF * 24, MemoryUtil.getAddress(fb), GL_STATIC_DRAW_ARB); // PointerBuffer colours = PointerBuffer.allocateDirect(capacity) mesh.mColors();//mNormals(); int faceCount = mesh.mNumFaces(); elementCount = faceCount * 3; IntBuffer elementArrayBufferData = BufferUtils.createIntBuffer(elementCount); AIFace.Buffer facesBuffer = mesh.mFaces(); for (int i = 0; i < faceCount; ++i) { AIFace face = facesBuffer.get(i); if (face.mNumIndices() != 3) { throw new IllegalStateException("AIFace.mNumIndices() != 3"); } elementArrayBufferData.put(face.mIndices()); } elementArrayBufferData.flip(); elementArrayBuffer = glGenBuffersARB(); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, elementArrayBuffer); glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, elementArrayBufferData, GL_STATIC_DRAW_ARB); } } public static class Material { public AIMaterial mMaterial; public AIColor4D mAmbientColor; public AIColor4D mDiffuseColor; public AIColor4D mSpecularColor; public Material(AIMaterial material) { mMaterial = material; mAmbientColor = AIColor4D.create(); if (aiGetMaterialColor(mMaterial, AI_MATKEY_COLOR_AMBIENT, aiTextureType_NONE, 0, mAmbientColor) != 0) { throw new IllegalStateException(aiGetErrorString()); } mDiffuseColor = AIColor4D.create(); if (aiGetMaterialColor(mMaterial, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_NONE, 0, mDiffuseColor) != 0) { throw new IllegalStateException(aiGetErrorString()); } mSpecularColor = AIColor4D.create(); if (aiGetMaterialColor(mMaterial, AI_MATKEY_COLOR_SPECULAR, aiTextureType_NONE, 0, mSpecularColor) != 0) { throw new IllegalStateException(aiGetErrorString()); } } } }
package swexpert; import java.util.Scanner; public class SWEA_1209_D3_Sum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 10; i++) { sb.append("#").append(i).append(" "); int N = sc.nextInt(); int[][] arr = new int[100][100]; for (int r = 0; r < 100; r++) { for (int c = 0; c < 100; c++) { arr[r][c] = sc.nextInt(); } } int max = Integer.MIN_VALUE; for (int r = 0; r < 100; r++) { int sumR =0; for (int c = 0; c < 100; c++) { sumR+=arr[r][c]; } max = Integer.max(max, sumR); } for (int c = 0; c < 100; c++) { int sumR =0; for (int r = 0; r < 100; r++) { sumR+=arr[r][c]; } max = Integer.max(max, sumR); } int sumCrossX =0; int sumCrossY =0; for (int j = 0; j < 100; j++) { sumCrossX += arr[j][j]; sumCrossY += arr[j][99-j]; } max = Integer.max(max, sumCrossX); max = Integer.max(max, sumCrossY); sb.append(max).append("\n"); } System.out.println(sb); } }
package View; import Server.Server; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.Duration; import ViewModel.MyViewModel; import java.io.*; import java.net.URL; import java.nio.file.FileSystems; import java.util.*; import static java.lang.System.exit; public class FatherController implements Initializable, Observer { @FXML protected CheckMenuItem muteAllButton; @FXML protected CheckMenuItem muteBackgroundButton; @FXML protected MenuBar menuBar; protected Stage stage; protected Scene scene; protected MyViewModel viewModel; protected static MediaPlayer mediaPlayer = null; protected String about; protected String help; // Setter for the about's window public void setAbout(String about) { this.about = about; } // Setter for the help's window public void setHelp(String help) { this.help = help; } @Override public void initialize(URL location, ResourceBundle resources) { } // Setter for the view model public void setViewModel(MyViewModel viewModel){ this.viewModel = viewModel; } // New game button pushed public void newGameButtonPushed (javafx.event.ActionEvent actionEvent) { { Parent game = null; FXMLLoader loader = new FXMLLoader(); try { loader.setLocation(getClass().getResource("GameView.fxml")); game = loader.load(); } catch (IOException e) { Server.LOG.debug("fxml loader exception"); } Scene gameScene = new Scene(game); GameViewController controller = loader.getController(); controller.setMuteButtons(muteAllButton.isSelected(), muteBackgroundButton.isSelected()); controller.setStage(stage); controller.setScene(gameScene); controller.setViewModel(viewModel); viewModel.addObserver(controller); controller.setAbout(about); controller.setHelp(help); stage.setOnCloseRequest(event -> { Alert alert = new Alert(Alert.AlertType.CONFIRMATION,"Do you wish to exit?"); alert.setHeaderText("Exit"); DialogPane dialogPane = alert.getDialogPane(); dialogPane.getStylesheets().add(getClass().getResource("myDialog.css").toExternalForm()); dialogPane.getStyleClass().add("myDialog"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ viewModel.close(); } else { event.consume(); } }); gameScene.setOnKeyPressed(event -> { viewModel.moveCharacter(event.getCode()); event.consume(); }); stage.setScene(gameScene); stage.show(); } } // Setter for the mute buttons protected void setMuteButtons(boolean muteAll, boolean muteBackground) { muteAllButton.setSelected(muteAll); muteBackgroundButton.setSelected(muteBackground); } // Setter for the stage public void setStage(Stage primaryStage){ stage = primaryStage; } // Setter for the scene public void setScene(Scene currScene){ scene = currScene; } // Showing the alert with a specific CSS style protected void showAlert(String alertMessage, String alertHeader) { Alert alert = new Alert(Alert.AlertType.INFORMATION); DialogPane dialogPane = alert.getDialogPane(); dialogPane.getStylesheets().add(getClass().getResource("myDialog.css").toExternalForm()); dialogPane.getStyleClass().add("myDialog"); alert.setHeaderText(alertHeader); alert.setContentText(alertMessage); alert.show(); } // About button pushed public void aboutButtonPushed(javafx.event.ActionEvent actionEvent) { showAlert(about, "About"); } // Help button pushed public void helpButtonPushed(ActionEvent actionEvent) { showAlert(help, "Help"); } // Getting the current path protected String getCurrentFixedPath() { String absoluteCurrentPath = FileSystems.getDefault().getPath(".").toAbsolutePath().toString(); absoluteCurrentPath = absoluteCurrentPath.substring(0, absoluteCurrentPath.length()-2); String fixedPath = ""; for (int i = 0; i < absoluteCurrentPath.length(); i++) { if (absoluteCurrentPath.charAt(i) == '\\') fixedPath = fixedPath + "/"; else fixedPath = fixedPath + absoluteCurrentPath.charAt(i); } return fixedPath; } // Initiating the music protected void initMusic() { if (mediaPlayer == null) { String path = getCurrentFixedPath(); File tmpFile = new File(path + "/resources/General/Opener.mp3"); path = tmpFile.toURI().toASCIIString(); Media file = new Media(path); mediaPlayer = new MediaPlayer(file); } } // Mute all button pushed public void muteAllButtonPushed(javafx.event.ActionEvent actionEvent) { if(muteAllButton.isSelected() || muteBackgroundButton.isSelected()){ mediaPlayer.stop(); } else{ mediaPlayer.setOnEndOfMedia(new Runnable() { public void run() { mediaPlayer.seek(Duration.ZERO); } }); mediaPlayer.play(); } } // Mute background music button pushed public void muteBackgroundButtonPushed(javafx.event.ActionEvent actionEvent) { if(muteAllButton.isSelected() || muteBackgroundButton.isSelected()){ mediaPlayer.stop(); } else{ mediaPlayer.setOnEndOfMedia(new Runnable() { public void run() { mediaPlayer.seek(Duration.ZERO); } }); mediaPlayer.play(); } } // Load button pushed public void loadButtonPushedMainMenu(javafx.event.ActionEvent actionEvent) { newGameButtonPushed(actionEvent); FileChooser fc = new FileChooser(); fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("maze files", "*.maze")); File f = fc.showOpenDialog(null); viewModel.loadGame(f); } // Properties button pushed public void PropertiesButtonPushed(javafx.event.ActionEvent actionEvent){ Properties prop = null; try { String current = getCurrentFixedPath(); InputStream input = new FileInputStream(current + "/resources/config.properties"); prop = new Properties(); prop.load(input); } catch (Exception e) { Server.LOG.debug("GetProperty Error, Class: GameViewController"); } if (prop != null) { String maxThreadsPool = prop.getProperty("maxPoolSize"); String generator = prop.getProperty("MazeGenerator"); String solver = prop.getProperty("SearchingAlgorithm"); String res = "Properties\n\n\n" + "maxPoolSize :\t\t" + maxThreadsPool +"\n\n" + "MazeGenerator :\t\t" + generator + "\n\n" + "SearchingAlgorithm :\t" + solver; showAlert(res, "Properties"); } } @Override public void update(Observable o, Object arg) { } // Exit button pushed public void exitButtonPushed(ActionEvent actionEvent){ Alert alert = new Alert(Alert.AlertType.CONFIRMATION,"Do you wish to exit?"); alert.setHeaderText("Exit"); DialogPane dialogPane = alert.getDialogPane(); dialogPane.getStylesheets().add(getClass().getResource("myDialog.css").toExternalForm()); dialogPane.getStyleClass().add("myDialog"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ viewModel.close(); exit(0); } else { actionEvent.consume(); } } }
import java.util.ArrayList; import java.util.LinkedList; public class PrintLinkListReversely { public static void main(String[] args) { PrintLinkListReversely printLinkListReversely = new PrintLinkListReversely(); ListNode node0 = new ListNode(0); ListNode node1 = node0.next = new ListNode(1); ListNode node2 = node1.next = new ListNode(2); ListNode node3 = node2.next = new ListNode(3); ListNode node4 = node3.next = new ListNode(4); ListNode node5 = node4.next = new ListNode(5); ListNode node6 = node5.next = new ListNode(6); System.out.println(printLinkListReversely.printListFromTailToHead(node0)); } public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if (listNode == null) { return new ArrayList<>(); } LinkedList<Integer> stack = new LinkedList<>(); while (listNode.next != null) { stack.addLast(listNode.val); listNode = listNode.next; } stack.addLast(listNode.val); ArrayList<Integer> result = new ArrayList<>(); while (stack.size() > 0) { result.add(stack.removeLast()); } return result; } }
/** * Audit specific code. */ package tech.jhipster.react.demo.config.audit;
package edu.frostburg.COSC310.TrippJohnathan; /** * Public interface for the Map abstract data type * @author Johnathan Tripp (╯°□°)╯︵ ┻━┻ */ public interface MapADT<K,V> { /** * Nested interface for an entry in the map * @param <K> the key of the entry * @param <V> the value of the entry */ public interface Entry<K,V>{ K getKey(); V getValue(); } /** * Method to obtain a hash value for a key * @param key a key to be hashed * @return the hash value for the given key */ int hashValue(K key); /** * Method to obtain the size of the map * @return the size of the map */ int size(); /** * Method to determine if a map is empty * @return whether or not the map is empty */ boolean isEmpty(); /** * Method to get a value from the map at the position specified by the given key * @param key the key to determine the position in the map * @return the value at the position specified by the key */ Object get(K key); /** * Method to put the specified value in the map at the position specified by the given key * @param key the key to determine the position in the map * @param value the value to be put in the map */ void put(K key, V value); /** * Method to remove a value from the map at the position specified by the key * @param key the key to determine the position in the map * @return the value removed from the map */ V remove(K key); /** * Method to return an iterable collection of the keys of the map * @return an iterable collection of keys */ Iterable<K> keySet(); /** * Method to return an iterable collection of the values of the map * @return an iterable collection of values */ Iterable<V> values(); /** * Method to return an iterable collection of the entries of the map * @return an iterable collection of map entries */ Iterable<Entry<K,V>> entrySet(); }
package foo.dbgroup.RDFstruct; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.RDFNode; import virtuoso.jena.driver.*; public class TestConnection { public static void main( String[] args ) { String url; if(args.length == 0) url = "jdbc:virtuoso://localhost:1111/"; else url = args[0]; /* STEP 1 */ VirtGraph set = new VirtGraph ("Wordnet3",url, "dba", "fagiolo"); // Model md = VirtModel.openDatabaseModel("CountryCodeEurostat", url, "dba", "fagiolo"); /* STEP 2 */ /* STEP 3 */ /* Select all data in virtuoso */ Query sparql = QueryFactory.create("SELECT (COUNT(DISTINCT ?o ) AS ?no) { ?s ?p ?o filter(!isLiteral(?o)) } "); /* STEP 4 */ VirtuosoQueryExecution vqe = VirtuosoQueryExecutionFactory.create (sparql, set); ResultSet results = vqe.execSelect(); while (results.hasNext()) { QuerySolution result = results.nextSolution(); // RDFNode graph = result.get("graph"); RDFNode s = result.get("?o"); RDFNode p = result.get("?no"); // RDFNode o = result.get("o"); System.out.println(s+" ---- "+p); // System.out.println(" { " + s + " " + p + " " + o + " . }"); } } }
package net.minecraftforge.common.capabilities; public class NBTBase {} // Dummies so the other classes can compile.
/* * Copyright 2014 Hippo B.V. (http://www.onehippo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onehippo.cms7.essentials.plugins.contentblocks; import java.text.MessageFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.cxf.rs.security.cors.CrossOriginResourceSharing; import org.onehippo.cms7.essentials.dashboard.ctx.PluginContext; import org.onehippo.cms7.essentials.dashboard.ctx.PluginContextFactory; import org.onehippo.cms7.essentials.dashboard.rest.BaseResource; import org.onehippo.cms7.essentials.dashboard.rest.KeyValueRestful; import org.onehippo.cms7.essentials.dashboard.rest.MessageRestful; import org.onehippo.cms7.essentials.dashboard.rest.RestfulList; import org.onehippo.cms7.essentials.dashboard.utils.EssentialConst; import org.onehippo.cms7.essentials.dashboard.utils.GlobalUtils; import org.onehippo.cms7.essentials.dashboard.utils.HippoNodeUtils; import org.onehippo.cms7.essentials.dashboard.rest.exc.RestException; import org.onehippo.cms7.essentials.plugins.contentblocks.model.RestList; import org.onehippo.cms7.essentials.plugins.contentblocks.model.contentblocks.AllDocumentMatcher; import org.onehippo.cms7.essentials.plugins.contentblocks.model.contentblocks.CBPayload; import org.onehippo.cms7.essentials.plugins.contentblocks.model.contentblocks.Compound; import org.onehippo.cms7.essentials.plugins.contentblocks.model.contentblocks.ContentBlockModel; import org.onehippo.cms7.essentials.plugins.contentblocks.model.contentblocks.DocumentType; import org.onehippo.cms7.essentials.plugins.contentblocks.model.contentblocks.HasProviderMatcher; import org.onehippo.cms7.essentials.plugins.contentblocks.utils.RestWorkflow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; @CrossOriginResourceSharing(allowAllOrigins = true) @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED}) @Path("contentblocks") public class ContentBlocksResource extends BaseResource { private static Logger log = LoggerFactory.getLogger(ContentBlocksResource.class); @GET @Path("/") public RestfulList<DocumentType> getControllers(@Context ServletContext servletContext) { final RestfulList<DocumentType> types = new RestList<>(); final Session session = GlobalUtils.createSession(); final PluginContext context = PluginContextFactory.getContext(); final String projectNamespacePrefix = context.getProjectNamespacePrefix(); String prefix = projectNamespacePrefix + ':'; try { final List<String> primaryTypes = HippoNodeUtils.getPrimaryTypes(session, new AllDocumentMatcher(), "new-document"); final Map<String, Compound> compoundMap = getCompoundMap(servletContext); for (String primaryType : primaryTypes) { final RestList<KeyValueRestful> keyValueRestfulRestfulList = new RestList<>(); final NodeIterator it = executeQuery(MessageFormat.format("{0}//element(*, frontend:plugin)[@cpItemsPath]", HippoNodeUtils.resolvePath(primaryType).substring(1)), session); while (it.hasNext()) { final String name = it.nextNode().getName(); String namespaceName = MessageFormat.format("{0}{1}", prefix, name); if (compoundMap.containsKey(namespaceName)) { final Compound compound = compoundMap.get(namespaceName); keyValueRestfulRestfulList.add(compound); } } types.add(new DocumentType(HippoNodeUtils.getDisplayValue(session, primaryType), primaryType, keyValueRestfulRestfulList)); } } catch (RepositoryException e) { log.error("Exception while trying to retrieve document types from repository {}", e); GlobalUtils.refreshSession(session, false); } finally { GlobalUtils.cleanupSession(session); } return types; } private NodeIterator executeQuery(String queryString, final Session session) throws RepositoryException { final QueryManager queryManager = session.getWorkspace().getQueryManager(); final Query query = queryManager.createQuery(queryString, EssentialConst.XPATH); final QueryResult execute = query.execute(); return execute.getNodes(); } private Map<String, Compound> getCompoundMap(final ServletContext servletContext) { final RestfulList<Compound> compounds = getCompounds(servletContext); Map<String, Compound> compoundMap = new HashMap<>(); for (Compound compound : compounds.getItems()) { compoundMap.put(compound.getValue(), compound); } return compoundMap; } @GET @Path("/compounds") public RestfulList<Compound> getCompounds(@Context ServletContext servletContext) { final RestfulList<Compound> types = new RestList<>(); final Session session = GlobalUtils.createSession(); try { final Set<String> primaryTypes = HippoNodeUtils.getCompounds(session, new HasProviderMatcher()); for (String primaryType : primaryTypes) { types.add(new Compound(HippoNodeUtils.getDisplayValue(session, primaryType), primaryType, HippoNodeUtils.resolvePath(primaryType))); } } catch (RepositoryException e) { log.error("Exception while trying to retrieve document types from repository {}", e); }finally{ GlobalUtils.cleanupSession(session); } //example if empty return types; } @PUT @Path("/compounds/create/{name}") public MessageRestful createCompound(@PathParam("name") String name, @Context ServletContext servletContext) { if (Strings.isNullOrEmpty(name)) { throw new RestException("Content block name was empty", Response.Status.NOT_ACCEPTABLE); } final Session session = GlobalUtils.createSession(); try { final PluginContext context = PluginContextFactory.getContext(); final RestWorkflow workflow = new RestWorkflow(session, context); workflow.addContentBlockCompound(name); return new MessageRestful("Successfully created compound with name: " + name); } finally { GlobalUtils.cleanupSession(session); } } @DELETE @Path("/compounds/delete/{name}") public MessageRestful deleteCompound(@PathParam("name") String name, @Context ServletContext servletContext) { final Session session = GlobalUtils.createSession(); try { final PluginContext context = PluginContextFactory.getContext(); final RestWorkflow workflow = new RestWorkflow(session, context); workflow.removeDocumentType(name); return new MessageRestful("Document type for name: " + name + " successfully deleted. You'll have to manually delete " + name + " entry from project CND file"); } finally { GlobalUtils.cleanupSession(session); } } //see org.hippoecm.hst.pagecomposer.jaxrs.services.ContainerComponentResource.updateContainer() @POST @Path("/compounds/contentblocks/create") public MessageRestful createContentBlocks(CBPayload body, @Context ServletContext servletContext) { final List<DocumentType> docTypes = body.getDocumentTypes().getItems(); final Session session = GlobalUtils.createSession(); try { final RestWorkflow workflow = new RestWorkflow(session, PluginContextFactory.getContext()); for (DocumentType documentType : docTypes) { final List<KeyValueRestful> providers = documentType.getProviders().getItems(); if (providers.isEmpty()) { log.debug("DocumentType {} had no providers", documentType.getKey()); // TODO: remove them.... continue; } for (KeyValueRestful item : providers) { ContentBlockModel model = new ContentBlockModel(item.getValue(), ContentBlockModel.Prefer.LEFT, ContentBlockModel.Type.LINKS, item.getKey(), documentType.getValue()); workflow.addContentBlockToType(model); } } return new MessageRestful("Successfully updated content blocks settings"); } finally { GlobalUtils.cleanupSession(session); } } }
package com.tatteam.popthecamera.actors; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor; /** * Created by dongc_000 on 9/24/2015. */ public class Camera extends Actor { private TextureRegion background; public Camera(TextureRegion background) { this.background = new TextureRegion(background); setBounds(getX(), getY(), background.getRegionWidth(), background.getRegionHeight()); } @Override public void draw(Batch batch, float parentAlpha) { Color color = getColor(); batch.setColor(color.r, color.g, color.b, color.a*parentAlpha); batch.draw(background, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation()); } }
package com.tencent.c.e.a.a; public final class k { public int vki = 0; public int vkj = 0; public int vkk = 0; public int vkl = 0; }
package com.hua.mvp.base.presenter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hua.mvp.base.BaseFragment; import com.hua.mvp.base.presenter.i.IPresenter; import com.hua.mvp.base.view.i.IView; import com.hua.mvp.utils.GenericHelper; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * Fragment作为Presenter的基类 */ public abstract class FragmentPresenterImpl<T extends IView> extends BaseFragment implements IPresenter<T> { protected T mView; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { create(savedInstanceState); if(containView == null) { try { mView = getViewClass().newInstance(); containView = mView.create(inflater, container); isPrepared = true; mView.bindPresenter(this); created(savedInstanceState); mView.bindEvent(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } ViewGroup parent = (ViewGroup) containView.getParent(); if(parent != null) { parent.removeView(parent); } return containView; } @Override public Class<T> getViewClass() { return GenericHelper.getViewClass(getClass()); } @Override public void create(Bundle saveInstance) { } @Override public void created(Bundle saveInstance) { init(); lazyLoad(); } }
package com.xiruan.demand.demand.service; import com.xiruan.demand.entity.monitor.SubCategory; import com.xiruan.demand.repository.SubCategoryDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.transaction.Transactional; import java.util.List; /** * Created by Chen.Ju on 2015/5/25. */ @Component @Transactional public class SubCategoryService { private SubCategoryDao subCategoryDao; public List<SubCategory> findByCategoryId(Long categoryId){ return subCategoryDao.findByCategoryId(categoryId); } public SubCategory findById(Long id){ return subCategoryDao.findOne(id); } @Autowired public void setSubCategoryDao(SubCategoryDao subCategoryDao) { this.subCategoryDao = subCategoryDao; } }
package ru.vlad805.mapssharedpoints; import ru.yandex.yandexmapkit.MapController; import ru.yandex.yandexmapkit.overlay.Overlay; import ru.yandex.yandexmapkit.utils.GeoPoint; import ru.yandex.yandexmapkit.utils.ScreenPoint; import android.content.Context; import android.content.Intent; public class MapOverlay extends Overlay { Context context; public MapOverlay(MapController controller, Context ctx) { super(controller); this.context = ctx; } public boolean onLongPress (float x, float y) { GeoPoint g = getMapController().getGeoPoint(new ScreenPoint(x, y)); Intent intent = new Intent(context, NewPointActivity.class); intent.putExtra(Const.LATITUDE, g.getLat()); intent.putExtra(Const.LONGITUDE, g.getLon()); context.startActivity(intent); return true; } @SuppressWarnings("NullableProblems") @Override public int compareTo ( Object another) { return 0; } }
class Main { public static void main(String[] args) { class MyDate { int day; int month; int year; MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } void increaseOneDay() { if(this.day == 30) { this.day = 0; this.month++; } else { this.day++; } } void increaseDate(int amount) { this.day += amount; if(this.day > 30) { int backup = this.day; this.month += (this.day / 30); this.day = backup % 30; } } void timeHandler() { if(month > 12) { int backup = this.month; this.year += (this.month / 12); this.month = backup % 12; } } void display() { String dayString; String monthString; if(this.day < 10) { dayString = "0" + Integer.toString(this.day); } else { dayString = Integer.toString(this.day); } if(this.month < 10) { monthString = "0" + Integer.toString(this.month); } else { monthString = Integer.toString(this.month); } System.out.println(dayString + "/" + monthString + "/" + this.year); } } MyDate date = new MyDate(12, 1, 2018); date.increaseOneDay(); date.display(); } }
package de.jmda.home.ui.vaadin; import javax.ejb.EJB; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import org.apache.log4j.Logger; import org.vaadin.virkki.cdiutils.application.UIContext.UIScoped; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.UI; import de.jmda.cbo.user.User; import de.jmda.common.ui.web.vaadin.service.DefaultSessionContext; import de.jmda.home.bl.usermgmt.UserManagementBean; /** * Main UI class */ @SuppressWarnings("serial") @UIScoped // virkii version //@CDIUI // vaadin version, not yet available //@Root // vaadin version, not yet available public class MainUI extends UI { private final static Logger LOGGER = Logger.getLogger(MainUI.class); @EJB private UserManagementBean userManagement; @Override protected void init(VaadinRequest request) { // default session context will put itself into the session context during // construction, no handle has to be stored here, session context data will // be available session wide through static access method new DefaultSessionContext(); DefaultSessionContext.get().setUserManagement(userManagement); initAdminUser(); initUI(); } private void initAdminUser() { LOGGER.debug(userManagement.allUsersAsString("users before initialisation")); User user = userManagement.findUserByUsername(UserManagementBean.ADMIN); if (user == null) { try { userManagement.createAdminRegistrationRequest(); } catch (AddressException e) { LOGGER.error("failure sending mail for admin registration", e); } catch (MessagingException e) { LOGGER.error("failure sending mail for admin registration", e); } } LOGGER.debug(userManagement.allUsersAsString("users after initialisation")); } private void initUI() { setWidth(1200, Unit.PIXELS); setHeight(100, Unit.PERCENTAGE); MainUIComponent content = new MainUIComponent(); content.setSizeFull(); setContent(content); } }
package util; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class EuclidianNode { private Float x; private Float y; public static int calcCostEdge (EuclidianNode a, EuclidianNode b){ float xd = a.getX() - b.getX(); float yd = a.getY() - b.getY(); int dij = (int) Math.round(Math.sqrt(xd*xd + yd*yd)); return dij; } }
package common; public enum OrderType { MARKET((byte)1), LIMIT((byte)2), STOP((byte)3), STOP_LIMIT((byte)4), HIDDEN_LIMIT((byte)5); private byte orderType; OrderType(byte orderType){ this.orderType = orderType; } public byte getOrderType(){ return this.orderType; } public static OrderType getOrderType(byte value){ switch (value) { case 1: return MARKET; case 2: return LIMIT; case 3: return STOP; case 4: return STOP_LIMIT; case 5: return HIDDEN_LIMIT; } return null; } }
package io.tjf.releasenotes; import java.io.IOException; import java.util.List; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; import io.tjf.releasenotes.generator.Generator; /** * {@link ApplicationRunner} that triggers the generation of the release notes * based on application arguments. * * @author Rubens dos Santos Filho */ @Component public class CommandProcessor implements ApplicationRunner { private final Generator generator; public CommandProcessor(Generator generator) { this.generator = generator; } @Override public void run(ApplicationArguments args) throws IOException { run(args.getNonOptionArgs()); } private void run(List<String> args) throws IOException { this.generator.generate(); } }
package cn.canlnac.onlinecourse.domain.interactor; import javax.inject.Inject; import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import cn.canlnac.onlinecourse.domain.repository.CatalogRepository; import rx.Observable; /** * 获取目录下的文档使用用例. */ public class GetDocumentsInCatalogUseCase extends UseCase { private final int catalogId; private final Integer start; private final Integer count; private final String sort; private final CatalogRepository catalogRepository; @Inject public GetDocumentsInCatalogUseCase( int catalogId, Integer start, Integer count, String sort, CatalogRepository catalogRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread ) { super(threadExecutor, postExecutionThread); this.catalogId = catalogId; this.start = start; this.count = count; this.sort = sort; this.catalogRepository = catalogRepository; } @Override protected Observable buildUseCaseObservable() { return this.catalogRepository.getDocumentsInCatalog(catalogId, start, count, sort); } }
package be.cytomine.ldap; /* * Copyright (c) 2009-2017. Authors: see NOTICE file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.DirContextOperations; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.ldap.userdetails.UserDetailsContextMapper; import org.springframework.util.Assert; import java.util.Collection; /** * Created by hoyoux on 09.12.14. */ public class LdapUlgMemberPersonContextMapper implements UserDetailsContextMapper { @Override public UserDetails mapUserFromContext(DirContextOperations dirContextOperations, String s, Collection<? extends GrantedAuthority> grantedAuthorities) { LdapUlgMemberPerson.Essence p = new LdapUlgMemberPerson.Essence(dirContextOperations); p.setUsername(s); p.setAuthorities(grantedAuthorities); return p.createUserDetails(); } public void mapUserToContext(UserDetails user, DirContextAdapter ctx) { Assert.isInstanceOf(LdapUlgMemberPerson.class, user, "UserDetails must be an LdapUlgMemberPerson instance"); LdapUlgMemberPerson p = (LdapUlgMemberPerson) user; p.populateContext(ctx); } }
package com.five_philosophers; class Sout { static void prnt(int nTime, String sWhat) { String[] sout = {"%20s\n", "%40s\n", "%60s\n", "%80s\n","%100s\n"}; System.out.printf(sout[nTime],sWhat); } }
package org.lvzr.fast.java.patten.behavior.visitor; public interface Visitor { public void visitAction(Subject sub); }
package com.rensimyl.www.mathics; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class Matgeo1 extends AppCompatActivity { Button backgeo1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_matgeo1); backgeo1 = findViewById(R.id.geo1_back); backgeo1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package ru.bm.eetp.exception.handler; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import ru.bm.eetp.dto.ErrorDetail; import ru.bm.eetp.exception.GWFaultError; import ru.bm.eetp.exception.SimpleError; @ControllerAdvice @RestController public class ControllerExceptionAdvice extends ResponseEntityExceptionHandler { @ExceptionHandler(GWFaultError.class) public ResponseEntity handleException(GWFaultError e, WebRequest request){ ErrorDetail errorDetail = new ErrorDetail(e.getprocessResult().getErrorCode(), e.getprocessResult().getErrorMessage() ); return new ResponseEntity(errorDetail, e.getprocessResult().getHttpCode()); } @ExceptionHandler(SimpleError.class) public ResponseEntity handleException(SimpleError e, WebRequest request) { return new ResponseEntity(e.getRequestResult().getresultBody(), e.getRequestResult().getresultCode()); } }
package practise; public class Child extends Abstract { @Override public void sum() { // TODO Auto-generated method stub } }
package shawn.designpattern.adapter; public interface Chargable { void charge(); }
package com.nsp.test.reflect.parent; public interface TestInterface<T> { }
package com.example.oop13072020; public class SinhVien { //Thuộc tính private String Ten; private int Tuoi; private String Diachi; // Định nghĩa constructer : phương thức khởi tạo public SinhVien(String Ten ,int tuoi,String DiaChi) { this.Ten = Ten; this.Tuoi = Tuoi; this.Diachi = DiaChi; } // trỏ chuột vào tên class nhấn alt + insert để gọi getter setter tự động public String getTen() { return Ten; } public void setTen(String ten) { Ten = ten; } public int getTuoi() { return Tuoi; } public void setTuoi(int tuoi) { Tuoi = tuoi; } public String getDiachi() { return Diachi; } public void setDiachi(String diachi) { Diachi = diachi; } // Phương thức //public void setTen(String ten) //{ //if(!ten.isEmpty()) //{ //this.Ten = ten; //} //} //public String getTen() //{ // return Ten; //} }
package com.udacity.georgebalasca.popularmoviesstage_2.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; /** * Created by george.balasca on 18/02/2018. */ public class NetUtils{ // params needed private static final String API_KEY_KEY = "api_key"; private static final String LANGUAGE_KEY = "language"; private static final String LANGUAGE_VAL = "en-US"; // https://api.themoviedb.org/3/movie/popular?api_key=****************&language=en-US&page=1 private static final String SCHEME = "https"; private static final String API_BASE_URL = "api.themoviedb.org"; private static final String API_VERSION = "3"; private static final String TYPE_MOVIE = "movie"; public static final String SORT_BY_POPULAR = "popular"; public static final String SORT_BY_TOP_RATED = "top_rated"; // https://image.tmdb.org/t/p/w185/kqjL17yufvn9OVLyXYpvtyrFfak.jpg private static final String IMAGES_BASE_URL = "image.tmdb.org"; private static final String PATH_T = "t"; private static final String PATH_P = "p"; private static final String MOVIE_POSTER_SIZE = "w185"; //"w185" // used to get particular movie data(along with movie's ID) private static final String EXTRAS_VIDEOS = "videos"; private static final String EXTRAS_REVIEWS = "reviews"; /** * Method to build URL for the movies list(with sorting). Chose to add to avoid confusion about params in the buildUrl(..) method. * @param api_key_value * @param sort_by * @return */ public static URL getMoviesListSortedUrl(String api_key_value, String sort_by) { return buildUrl(api_key_value, sort_by, null, 0, null); } /** * Method to build URL for the movies posters. Chose to add to avoid confusion about params in the buildUrl(..) method. * @param api_key_value * @param poster_path * @return */ public static URL getMoviePosterURL(String api_key_value, String poster_path) { return buildUrl(api_key_value, null, poster_path, 0, null); } /** * Method used to get the URL for getting a movie's videos * * @param api_key_value * @param movie_id * @return */ public static URL getMovieVideosURL(String api_key_value, int movie_id) { // https://api.themoviedb.org/3/movie/337167/videos?api_key=********&language=en-US&page=1 return buildUrl(api_key_value, null, null, movie_id, EXTRAS_VIDEOS); } /** * Method used to get the URL for getting a movie's comments * * @param api_key_value * @param movie_id * @return */ public static URL getMovieReviewsURL(String api_key_value, int movie_id) { // https://api.themoviedb.org/3/movie/337167/reviews?api_key=*******&language=en-US&page=1 return buildUrl(api_key_value, null, null, movie_id, EXTRAS_REVIEWS); } /** * Build my URL using URI Parse. Based on params received decide what URL should build! * * @param api_key_value * @param sort_by * @param poster_path * @param movie_id - if needed particular movie extras, the movie ID is needed * @param extras - particular movie extras (ex: videos, reviews) * @return */ private static URL buildUrl(String api_key_value, String sort_by, String poster_path, int movie_id, String extras) { Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME); // build URL for sorted movies list if(sort_by != null && poster_path == null){ builder.authority(API_BASE_URL) .appendPath(API_VERSION) .appendPath(TYPE_MOVIE) .appendPath(sort_by) .appendQueryParameter(API_KEY_KEY, api_key_value) .appendQueryParameter(LANGUAGE_KEY, LANGUAGE_VAL); // build URL for movie poster } else if(poster_path != null){ builder.authority(IMAGES_BASE_URL) .appendPath(PATH_T) .appendPath(PATH_P) .appendPath(MOVIE_POSTER_SIZE) .appendPath(poster_path); // build URL for extras (videos, comments) } else if (extras != null && movie_id != 0){ builder.authority(API_BASE_URL) .appendPath(API_VERSION) .appendPath(TYPE_MOVIE) .appendPath(String.valueOf(movie_id)) .appendPath(extras) .appendQueryParameter(API_KEY_KEY, api_key_value) .appendQueryParameter(LANGUAGE_KEY, LANGUAGE_VAL); } URL url = null; try { url = new URL(builder.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } /** * Call a httpUrl and return the response as a string * * @param url * @return * @throws IOException * */ public static String getResponseFromHttpUrl(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); if (hasInput) { return scanner.next(); } else { return null; } } finally { urlConnection.disconnect(); } } /** * Check if connection to internet is available * @return */ public static boolean isOnline(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm != null ? cm.getActiveNetworkInfo() : null; return netInfo != null && netInfo.isConnectedOrConnecting(); } /** * Returns the name of the file from a URL * @param url * @return */ public static String getFileNameFromURL(String url) { if (url == null) { return ""; } try { URL resource = new URL(url); String host = resource.getHost(); if (host.length() > 0 && url.endsWith(host)) { // handle ...example.com return ""; } } catch(MalformedURLException e) { return ""; } int startIndex = url.lastIndexOf('/') + 1; int length = url.length(); // find end index for ? int lastQMPos = url.lastIndexOf('?'); if (lastQMPos == -1) { lastQMPos = length; } // find end index for # int lastHashPos = url.lastIndexOf('#'); if (lastHashPos == -1) { lastHashPos = length; } // calculate the end index int endIndex = Math.min(lastQMPos, lastHashPos); return url.substring(startIndex, endIndex); } }
package org.gnunet.integration.internal.share; import java.util.concurrent.TimeUnit; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; public class Constantes { //Waiting time for message passing, actor are asynchronous, we must wait few time between tell message and Assert verification public final static long TEMPO = 100; // Waiting time during expectNoMsg() public final static FiniteDuration RESPONSE_DURATION_MAX = Duration.create(200, TimeUnit.MILLISECONDS); }
package com.semantyca.nb.core.dataengine.jpa.model.convertor.db.eclipselink; import com.semantyca.nb.core.dataengine.jpa.IAppEntity; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.sessions.Session; import java.sql.Types; public abstract class ELEntityConverter implements Converter { private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override public Object convertObjectValueToDataValue(Object objectValue, Session session) { if (objectValue != null) { return ((IAppEntity) objectValue).getId(); } return null; } public abstract Object convertDataValueToObjectValue(Object dataValue, Session session); @Override public boolean isMutable() { return true; } @Override public void initialize(DatabaseMapping mapping, Session session) { DatabaseField field = mapping.getField(); field.setSqlType(Types.OTHER); field.setTypeName("java.util.UUID"); field.setColumnDefinition("uuid"); } }
package com.myth.videofilter.filter.advance; import android.content.Context; import com.myth.videofilter.filter.base.OpenGlUtils; public class B612AdoreFilter extends B612BaseFilter { public B612AdoreFilter(Context context) { super(context); } @Override protected int getInputTexture() { return OpenGlUtils.loadTexture(mContext, "filter/adore_new.png"); } }
package boletin.pkg13; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Juan Borrajo Rodriguez Nº5937 */ public class Boletin13 { public static void main(String[] args) { ConversorTemperaturas a=new ConversorTemperaturas(); a.pedirTemperatura(); try { a.centigradosAFharenheit(); } catch (TemperaturaErradaExcepcion ex) { ex.printStackTrace(); } a.centígradosAReamur(); a.amosar(); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyForm extends JApplet implements ActionListener { String str="",str1="",str2=""; Object x[]; JLabel n,a,i,lbl; JTextField name; JTextArea addr; JList lst; JButton b1,b2; Container c; public void init() { JFrame jf=new JFrame(); c=jf.getContentPane(); c.setBackground(Color.yellow); c.setLayout(null); jf.setSize(500,400); jf.setTitle("Online Shopping Form"); jf.setVisible(true); Font f=new Font("Comic Sans MS",Font.BOLD,26); lbl=new JLabel(); lbl.setFont(f); lbl.setForeground(Color.red); lbl.setText("VIJAY SALES ONLINE SHOP"); lbl.setBounds(200,10,500,30); c.add(lbl); n=new JLabel("Name: ",JLabel.LEFT); name=new JTextField(30); n.setBounds(50,100,100,30); name.setBounds(200,100,200,30); c.add(n); c.add(name); a=new JLabel("Address: ",JLabel.LEFT); addr=new JTextArea(5,50); a.setBounds(50,150,100,30); addr.setBounds(200,150,200,100); c.add(a); c.add(addr); i=new JLabel("Select Items: ",JLabel.LEFT); String[] data={"TVs","Washing Machines","DVD Players","Refrigerators"}; lst=new JList(data); i.setBounds(50,270,100,30); lst.setBounds(200,270,200,100); c.add(i); c.add(lst); b1=new JButton("OK"); b2=new JButton("Cancel"); b1.setBounds(200,400,100,30); b1.setBounds(350,400,100,30); c.add(b1); c.add(b2); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { str=ae.getActionCommand(); if(str.equals("OK")) { str1=name.getText()+"\n"; str1+=addr.getText()+"\n"; x=lst.getSelectedValues(); for(int i=0;i<x.length;i++) str2+=(String)x[i]+"\n"; addr.setText(str1+str2); str1=""; str2=""; } else { name.setText(""); addr.setText(""); lst.clearSelection(); } } }
/* * Sonar Drools Plugin * Copyright (C) 2011 Jérémie Lagarde * dev@sonar.codehaus.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.sonar.plugins.drools.rules; import java.util.List; import org.sonar.api.profiles.ProfileDefinition; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleRepository; import org.sonar.api.utils.ValidationMessages; import org.sonar.plugins.drools.language.Drools; /** * Default Drools Profile. * It activates by default the MAJOR, CRITICAL and BLOCKER rules * * @author Jeremie Lagarde * @since 0.1 */ public class DefaultDroolsProfile extends ProfileDefinition { private RuleRepository repository; public DefaultDroolsProfile(DroolsRuleRepository ruleRepository) { this.repository = ruleRepository; } @Override public RulesProfile createProfile(ValidationMessages validation) { List<Rule> rules = repository.createRules(); RulesProfile rulesProfile = RulesProfile.create(DroolsRuleRepository.REPOSITORY_NAME, Drools.KEY); for (Rule rule : rules) { //if(RulePriority.MAJOR.equals(rule.getPriority()) || RulePriority.CRITICAL.equals(rule.getPriority()) || RulePriority.BLOCKER.equals(rule.getPriority() )) rulesProfile.activateRule(rule,null); } rulesProfile.setDefaultProfile(true); return rulesProfile; } }
package capstone.abang.com.Models; /** * Created by Pc-user on 23/02/2018. */ public class Services { private String serviceName; private String serviceStatus; private String serviceType; public Services() { } public Services(String serviceName, String serviceStatus, String serviceType) { this.serviceName = serviceName; this.serviceStatus = serviceStatus; this.serviceType = serviceType; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getServiceStatus() { return serviceStatus; } public void setServiceStatus(String serviceStatus) { this.serviceStatus = serviceStatus; } public String getServiceType() { return serviceType; } public void setServiceType(String serviceType) { this.serviceType = serviceType; } }
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.plugin.webview.model.ad; import com.tencent.mm.plugin.webview.model.d.b; import com.tencent.mm.plugin.webview.modeltools.e; class UploadMediaFileHelp$8 implements OnCancelListener { final /* synthetic */ String jHJ; final /* synthetic */ UploadMediaFileHelp$a jHK; final /* synthetic */ b jHL; UploadMediaFileHelp$8(b bVar, String str, UploadMediaFileHelp$a uploadMediaFileHelp$a) { this.jHL = bVar; this.jHJ = str; this.jHK = uploadMediaFileHelp$a; } public final void onCancel(DialogInterface dialogInterface) { e.bUW().a(this.jHL); e.bUW(); ad.rq(this.jHJ); this.jHK.b(false, "", ""); } }
/** * Copyright &copy; 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved. */ package com.beiyelin.commonsql.persistence.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 标识MyBatis的DAO,方便{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的扫描。 * @author Tony Wong * @version 2015-04-04 */ @Deprecated @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyBatisMapper { }
/* * Copyright (C), 2013-2015, 上海汽车集团股份有限公司 * FileName: NeedLoginParam.java * Author: baowenzhou * Date: 2016年03月10日 下午5:27:08 * Description: //模块目的、功能描述 * History: //修改记录 * <author> <time> <version> <desc> * 修改人姓名 修改时间 版本号 描述 */ package com.xjf.wemall.annotation; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * 必须登录说明声明<BR> * * 需校验的方法上添加此annotation,支持Ajax提交<BR> * 注意: * Ajax判断时,需指定回调页面; * <BR> * 必须登录渠道、忽略登录渠道都为空时,全渠道校验<BR> * 必须登录渠道有时,判断当前渠道是在此中,在则校验,不在则不校验<BR> * 必须登录渠道空时,忽略登录渠道有时,判断当前渠道是在此中,在则不校验,不在则校验<BR> * * @author baowenzhou */ @Target({PARAMETER}) @Retention(RUNTIME) public @interface NeedLoginParam { /** * 必须登录渠道<br> */ String[] checkParam() default {}; /** * 忽略登录渠道<br> */ String[] ignoreParam() default {}; }
package com.beiyelin.account.security; import com.beiyelin.account.service.AccountService; import com.beiyelin.common.utils.CollectionUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; import java.util.Arrays; /** * @Description: 权限处理拦截器 * @Author: newmann * @Date: Created in 9:47 2018-01-20 */ @Slf4j public class AccessPermissionInterceptor extends HandlerInterceptorAdapter { /** * todo 暂时通过account service来验证权限,为了提高效率,可以换到redis中去 * @Autowired 注入无效 * */ // @Autowired private AccountService accountService; // @Autowired private JwtTokenService jwtTokenService; public AccessPermissionInterceptor(AccountService accountService,JwtTokenService jwtTokenService){ this.accountService = accountService; this.jwtTokenService = jwtTokenService; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("处理 AccessPermission Interceptor"); boolean superResult = super.preHandle(request, response, handler); if (!superResult) return superResult; //如果其他的过程发生错误,就直接返回; // 将handler强转为HandlerMethod, 前面已经证实这个handler就是HandlerMethod HandlerMethod handlerMethod = (HandlerMethod) handler; // 从方法处理器中获取出要调用的方法 Method method = handlerMethod.getMethod(); // 获取出方法上的AccessPermission注解,可能有多个 AccessPermission[] accessPermissions = method.getAnnotationsByType(AccessPermission.class); if (CollectionUtils.arrayIsBlank(accessPermissions)) { // 如果注解为null, 说明不需要拦截, 直接放过 return true; } //todo 暂时这样没有取到对应的信息,就跳过 if(SecurityContextHolder.getContext().getAuthentication() == null) return true; if("anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString())) return true; // UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getDetails(); if (userDetails == null) return true; //验证权限,当前账户只要拥有其中一个权限,就算拥有对应的权限 String username = userDetails.getUsername(); boolean checkResult = Arrays.stream(accessPermissions).map( (item) -> { return accountService.checkPermissionByUsername(username,item.packageName(),item.moduleName(),item.action());} ).anyMatch((item) -> item.equals(true)); if(!checkResult){ log.warn("登录账户:%s 调用过程 %s 非法。",username,method.getName()); } return checkResult; } }
package com.sixmac.service; import com.sixmac.entity.Site; import com.sixmac.entity.Stadium; import com.sixmac.service.common.ICommonService; import java.util.List; /** * Created by Administrator on 2016/5/24 0024 下午 3:52. */ public interface SiteService extends ICommonService<Site> { public List<Site> findByStadiumId(Long stadiumId); //根据区域、类型筛选场地 public List<Site> page(Integer type); }
package br.usp.memoriavirtual.modelo.fachadas; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import br.usp.memoriavirtual.modelo.entidades.Autoria; import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Assunto; import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemPatrimonial; import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Descritor; import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.Titulo; import br.usp.memoriavirtual.modelo.fachadas.remoto.CadastrarBemPatrimonialRemote; import br.usp.memoriavirtual.modelo.fachadas.remoto.EditarBemPatrimonialRemote; @Stateless(mappedName = "CadastrarBemPatrimonial") public class CadastrarBemPatrimonial implements CadastrarBemPatrimonialRemote { @PersistenceContext(unitName = "memoriavirtual") private EntityManager entityManager; @EJB private EditarBemPatrimonialRemote editarBemPatrimonialEJB; @Override public BemPatrimonial cadastrarBemPatrimonial(BemPatrimonial bem) throws ModeloException { for (Assunto a : bem.getAssuntos()) { Assunto assunto = entityManager.find(Assunto.class, a.getAssunto()); if (assunto == null) { entityManager.persist(a); } } for (Descritor d : bem.getDescritores()) { Descritor descritor = entityManager.find(Descritor.class, d.getDescritor()); if (descritor == null) { entityManager.persist(d); } } try { entityManager.persist(bem); for (Titulo t : bem.getTitulos()) { t.setBempatrimonial(bem); } for (Autoria a : bem.getAutorias()) { a.setBemPatrimonial(bem); } } catch (Exception e) { e.printStackTrace(); throw new ModeloException(e); } return bem; } @Override public BemPatrimonial salvarBemPatrimonial(BemPatrimonial bem) throws ModeloException { return bem; } @Override public BemPatrimonial getBemPatrimonial(long id) throws ModeloException { try { return (BemPatrimonial) entityManager .find(BemPatrimonial.class, id); } catch (Exception e) { e.printStackTrace(); throw new ModeloException(e); } } }
package com.wsr.handler; import com.wsr.config.SecurityProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author :wangsr * @description: * @date :Created in 2021/8/28 0028 9:47 */ @Component public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Autowired private SecurityProperties securityProperties; private RequestCache requestCache = new HttpSessionRequestCache(); @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { logger.info("登录成功"); // 如果设置了loginSuccessUrl,总是跳到设置的地址上 // 如果没设置,则尝试跳转到登录之前访问的地址上,如果登录前访问地址为空,则跳到网站根路径上 if (!StringUtils.isEmpty(securityProperties.getLogin().getLoginSuccessUrl())) { requestCache.removeRequest(request, response); setAlwaysUseDefaultTargetUrl(true); setDefaultTargetUrl(securityProperties.getLogin().getLoginSuccessUrl()); } super.onAuthenticationSuccess(request, response, authentication); } }
package com.sojay.testfunction.card.card1; import android.annotation.TargetApi; import android.os.Build; import android.view.View; import androidx.viewpager.widget.ViewPager; public class CardTransformer implements ViewPager.PageTransformer { private int mOffset = 20; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void transformPage(View page, float position) { // viewpager item平移到叠加状态 // +mOffset 有叠加的效果 if (position >= 0) { page.setTranslationX(- (page.getWidth() + mOffset) * position); } // 控制除最上面的item外,其余item进行缩放 if (position != 0) { page.setPivotX(page.getWidth()); page.setPivotY(page.getHeight()); page.setScaleX(1 - (0.1f * position)); page.setScaleY(1 - (0.1f * position)); } // 控制最上面的item滑动透明渐变 if (position <= 0) { page.setAlpha(1 + (position * 0.7f)); page.setRotation(10 * position); } } }
package com.support.kafka; /** * @author zhangbingquan * @desc kafka的消息生产者 * @time 2019-10-20 17:33 */ public class KafkaProducer { }
package com.tencent.mm.plugin.game.model.a; import android.database.Cursor; import com.tencent.mm.ab.b; import com.tencent.mm.ab.l; import com.tencent.mm.compatible.util.f; import com.tencent.mm.plugin.downloader.model.FileDownloadTaskInfo; import com.tencent.mm.plugin.downloader.model.d; import com.tencent.mm.plugin.game.a.c; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.na; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.ao; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; import java.util.List; public final class g { /* renamed from: com.tencent.mm.plugin.game.model.a.g$2 */ class AnonymousClass2 implements com.tencent.mm.ab.v.a { final /* synthetic */ String bAj; AnonymousClass2(String str) { this.bAj = str; } public final int a(int i, int i2, String str, b bVar, l lVar) { if (i == 0 && i2 == 0) { na naVar = (na) bVar.dIE.dIL; if (naVar == null) { return 0; } x.i("MicroMsg.GameSilentDownloader", "op:%d", new Object[]{Integer.valueOf(naVar.op)}); switch (naVar.op) { case 1: ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().DH(this.bAj); if (naVar.rrf != null && naVar.rrf.rdc != null && !bi.oW(naVar.rrf.rdc.rcY)) { c DC = ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().DC(this.bAj); if (DC != null) { if (!naVar.rrf.rdc.rcY.equals(bi.oV(DC.field_downloadUrl))) { x.i("MicroMsg.GameSilentDownloader", "update downloadInfo. [oldDownloadUrl]:%s, [newDownloadUrl]:%s, [size]:%d, [md5]:%s", new Object[]{DC.field_downloadUrl, naVar.rrf.rdc.rcY, Long.valueOf(naVar.rrf.rdc.rcZ), naVar.rrf.rdc.rda}); if (bi.oW(DC.field_downloadUrl)) { FileDownloadTaskInfo yP = d.aCU().yP(naVar.rrf.rdc.rcY); if (!(yP == null || yP.id <= 0 || yP.status == 4)) { x.i("MicroMsg.GameSilentDownloader", "download task already exists"); e.C(this.bAj, 6, 0); ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().a(DC, new String[0]); g.this.fv(false); return 0; } } DC.field_downloadUrl = naVar.rrf.rdc.rcY; DC.field_size = naVar.rrf.rdc.rcZ; DC.field_md5 = naVar.rrf.rdc.rda; if (!bi.oW(naVar.rrf.rdc.jPg)) { DC.field_packageName = naVar.rrf.rdc.jPg; } ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().c(DC, new String[0]); } int i3 = naVar.rrf.rdc.jPZ; if (DC != null && !bi.oW(DC.field_downloadUrl)) { x.i("MicroMsg.GameSilentDownloader", "startDownload, appId:%s, url:%s, size:%d, md5:%s, packageName:%s, expireTime:%d, isFirst:%b, nextCheckTime:%d, isRunning:%b", new Object[]{DC.field_appId, DC.field_downloadUrl, Long.valueOf(DC.field_size), DC.field_md5, DC.field_packageName, Long.valueOf(DC.field_expireTime), Boolean.valueOf(DC.field_isFirst), Long.valueOf(DC.field_nextCheckTime), Boolean.valueOf(DC.field_isRunning)}); FileDownloadTaskInfo yP2 = d.aCU().yP(DC.field_downloadUrl); long j; if (yP2 != null && yP2.id > 0 && yP2.status == 2) { x.i("MicroMsg.GameSilentDownloader", "resume downloadTask"); j = yP2.id; d.aCU().ibV = true; d.aCU().co(j); break; } com.tencent.mm.plugin.downloader.model.e.a aVar = new com.tencent.mm.plugin.downloader.model.e.a(); aVar.yQ(DC.field_downloadUrl); aVar.setAppId(DC.field_appId); aVar.cx(DC.field_size); aVar.cQ(DC.field_packageName); aVar.yS(com.tencent.mm.pluginsdk.model.app.g.b(ad.getContext(), com.tencent.mm.pluginsdk.model.app.g.bl(DC.field_appId, true), null)); aVar.yT(DC.field_md5); aVar.ef(false); aVar.eg(false); aVar.ox(1); aVar.aDa(); d.aCU().ibV = true; j = i3 == 1 ? d.aCU().b(aVar.ick) : d.aCU().a(aVar.ick); x.i("MicroMsg.GameSilentDownload.GameDownloadHelper", "add downloadTask id:%d, downloaderType:%d", new Object[]{Long.valueOf(j), Integer.valueOf(i3)}); break; } x.e("MicroMsg.GameSilentDownloader", "downloadInfo is null"); break; } x.i("MicroMsg.GameSilentDownloader", "local SilentDownloadTask is deleted"); return 0; } x.e("MicroMsg.GameSilentDownloader", "downloadInfo is null"); h.mEJ.a(860, 20, 1, false); return 0; break; case 2: x.i("MicroMsg.GameSilentDownloader", "delay, nextInterval:%d", new Object[]{Long.valueOf(naVar.rre)}); ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().E(this.bAj, bi.VE() + naVar.rre); g.this.fv(false); break; case 3: e.C(this.bAj, 5, 0); g.cancelDownload(this.bAj); g.this.fv(false); break; default: h.mEJ.a(860, 19, 1, false); break; } return 0; } x.e("MicroMsg.GameSilentDownloader", "Check Error, errType:%d, errCode:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); h.mEJ.a(860, 18, 1, false); return 0; } } private static class a { private static g jOR = new g(); } /* synthetic */ g(byte b) { this(); } private g() { } public final void fv(boolean z) { while (true) { c cVar; f aSl = ((c) com.tencent.mm.kernel.g.l(c.class)).aSl(); Cursor rawQuery = aSl.rawQuery(String.format("select * from %s where %s=1 limit 1", new Object[]{"GameSilentDownload", "isRunning"}), new String[0]); c cVar2; if (rawQuery == null) { x.i("MicroMsg.GameSilentDownloadStorage", "first cursor is null"); cVar = null; } else if (rawQuery.moveToFirst()) { cVar2 = new c(); cVar2.d(rawQuery); rawQuery.close(); cVar = cVar2; } else { x.i("MicroMsg.GameSilentDownloadStorage", "no running task"); rawQuery.close(); rawQuery = aSl.rawQuery(String.format("select * from %s where %s < ? limit 1", new Object[]{"GameSilentDownload", "nextCheckTime"}), new String[]{String.valueOf(bi.VE())}); if (rawQuery == null) { x.i("MicroMsg.GameSilentDownloadStorage", "second cursor is null"); cVar = null; } else if (rawQuery.moveToFirst()) { cVar2 = new c(); cVar2.d(rawQuery); rawQuery.close(); cVar = cVar2; } else { rawQuery.close(); x.i("MicroMsg.GameSilentDownloadStorage", "no record"); cVar = null; } } if (cVar == null) { x.i("MicroMsg.GameSilentDownloader", "silentDownload witch can check is empty!"); return; } x.i("MicroMsg.GameSilentDownloader", "[appid:%s] in DB to check download", new Object[]{cVar.field_appId}); if (cVar.field_expireTime <= bi.VE()) { x.i("MicroMsg.GameSilentDownloader", "task expire time, appId:%s", new Object[]{cVar.field_appId}); e.DB(cVar.field_appId); cancelDownload(cVar.field_appId); z = false; } else if (ao.isWifi(ad.getContext())) { ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().DD(cVar.field_appId); com.tencent.mm.kernel.g.Ek(); if (com.tencent.mm.kernel.g.Ei().isSDCardAvailable()) { ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().DE(cVar.field_appId); if (cVar.field_size <= 0 || f.aM(cVar.field_size)) { ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().DF(cVar.field_appId); x.i("MicroMsg.GameSilentDownloader", "fromBattery:%b", new Object[]{Boolean.valueOf(z)}); if (z) { ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().DG(cVar.field_appId); } else { com.tencent.mm.plugin.game.model.a.a.a aUG = a.aUG(); x.i("MicroMsg.GameSilentDownloader", "battery isCharging:%b percent:%f", new Object[]{Boolean.valueOf(aUG.gCp), Float.valueOf(aUG.jOI)}); if (aUG.gCp || ((double) aUG.jOI) >= 0.2d) { ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().DG(cVar.field_appId); } else { x.i("MicroMsg.GameSilentDownloader", "battery is low"); return; } } com.tencent.mm.bu.a.post(new Runnable() { public final void run() { if (com.tencent.mm.pluginsdk.model.app.g.a(ad.getContext(), com.tencent.mm.pluginsdk.model.app.g.bk(cVar.field_appId, false))) { x.i("MicroMsg.GameSilentDownloader", "app is installed, appid = %s", new Object[]{cVar.field_appId}); e.C(cVar.field_appId, 4, 0); ah.A(new 1(this)); return; } ah.A(new 2(this)); } }); return; } x.i("MicroMsg.GameSilentDownloader", "sdcard dont have enough space"); return; } x.i("MicroMsg.GameSilentDownloader", "sdcard isnt available"); return; } else { x.i("MicroMsg.GameSilentDownloader", "NetType is not WIFI"); return; } } } public static void pauseDownload() { Cursor rawQuery = ((c) com.tencent.mm.kernel.g.l(c.class)).aSl().rawQuery(String.format("select * from %s", new Object[]{"GameSilentDownload"}), new String[0]); List list; if (rawQuery == null) { x.i("MicroMsg.GameSilentDownloadStorage", "cursor is null"); list = null; } else if (rawQuery.moveToFirst()) { list = new ArrayList(); do { c cVar = new c(); cVar.d(rawQuery); list.add(cVar); } while (rawQuery.moveToNext()); rawQuery.close(); x.i("MicroMsg.GameSilentDownloadStorage", "getDownloadInfoList size:%s", new Object[]{Integer.valueOf(list.size())}); } else { rawQuery.close(); x.i("MicroMsg.GameSilentDownloadStorage", "getDownloadInfoList no record"); list = null; } if (!bi.cX(list)) { for (c cVar2 : list) { if (cVar2 != null) { if (cVar2.field_expireTime <= bi.VE()) { x.i("MicroMsg.GameSilentDownloader", "pauseDownload, task expire time, appId:%s", new Object[]{cVar2.field_appId}); e.DB(cVar2.field_appId); cancelDownload(cVar2.field_appId); } else { FileDownloadTaskInfo yO = d.aCU().yO(cVar2.field_appId); if (yO != null && yO.id > 0 && yO.status == 1) { long j = yO.id; d.aCU().ibV = true; boolean cn = d.aCU().cn(j); x.i("MicroMsg.GameSilentDownloader", "pauseDownload, appid:%s, ret:%b", new Object[]{yO.appId, Boolean.valueOf(cn)}); } } } } } } static void cancelDownload(String str) { if (!bi.oW(str)) { c cVar = new c(); cVar.field_appId = str; x.i("MicroMsg.GameSilentDownloader", "remove SilentDownload DB, appid:%s, ret:%b", new Object[]{str, Boolean.valueOf(((c) com.tencent.mm.kernel.g.l(c.class)).aSl().a(cVar, new String[0]))}); if (((c) com.tencent.mm.kernel.g.l(c.class)).aSl().a(cVar, new String[0])) { FileDownloadTaskInfo yO = d.aCU().yO(str); if (yO != null && yO.id > 0) { d.aCU().cl(yO.id); x.i("MicroMsg.GameSilentDownloader", "remove download task, appid:%s", new Object[]{yO.appId}); } } } } }
package com.app.cosmetics.api.exception; import org.springframework.http.HttpStatus; public class ExpiredException extends MyException { public ExpiredException() { super(HttpStatus.UNAUTHORIZED, "Expired Exception"); } }
package br.com.nozinho.util.json; import java.io.Reader; import java.lang.reflect.Type; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * Classe Entidade com JSon methods * * @author RodrigoAndrade */ public class JsonUtil { public static String toJson(Object propriedade) { Gson gson = new GsonBuilder().create(); if (propriedade != null) { return gson.toJson(propriedade); } return null; } public static <T> T fromJson(String jsonString, Class<T> clazz) { Gson gson = new GsonBuilder().create(); if (jsonString != null) { return gson.fromJson(jsonString, clazz); } return null; } public static <T> List<T> fromListJson(String jsonString, Type listType) { Gson gson = new GsonBuilder().create(); if (jsonString != null) { List<T> list = gson.fromJson(jsonString, listType); return list; } return null; } public static <T> List<T> fromListJson(Reader jsonReader, Type listType) { Gson gson = new GsonBuilder().create(); if (jsonReader != null) { List<T> list = gson.fromJson(jsonReader, listType); return list; } return null; } }
package com.elkattanman.farmFxml.controllers.spending; import com.elkattanman.farmFxml.callback.CallBack; import com.elkattanman.farmFxml.domain.Capital; import com.elkattanman.farmFxml.domain.Spending; import com.elkattanman.farmFxml.repositories.CapitalRepository; import com.elkattanman.farmFxml.repositories.SpendingRepository; import com.elkattanman.farmFxml.util.AlertMaker; import com.elkattanman.farmFxml.util.AssistantUtil; import com.jfoenix.controls.JFXTextField; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.text.Text; import net.rgielen.fxweaver.core.FxControllerAndView; import net.rgielen.fxweaver.core.FxWeaver; import net.rgielen.fxweaver.core.FxmlView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.net.URL; import java.time.LocalDate; import java.util.ArrayList; import java.util.ResourceBundle; @Component @FxmlView("/FXML/spending/spending.fxml") public class SpendingController implements Initializable, CallBack<Boolean, Spending> { @Autowired private FxWeaver fxWeaver; @FXML private TableView<Spending> table; @FXML private TableColumn<Spending, Integer> idCol; @FXML private TableColumn<Spending, String> typeCol, nameCol; @FXML private TableColumn<Spending, LocalDate> dateCol; @FXML private TableColumn<Spending, Integer> numCol; @FXML private TableColumn<Spending, Double> priceCol; @FXML private JFXTextField searchTF; @FXML private Text infoTXT; private ObservableList<Spending> list = FXCollections.observableArrayList(); private final SpendingRepository spendingRepository; private final CapitalRepository capitalRepository; public SpendingController(SpendingRepository spendingRepository, CapitalRepository capitalRepository) { this.spendingRepository = spendingRepository; this.capitalRepository = capitalRepository; } private void initCol() { idCol.setCellValueFactory(new PropertyValueFactory<>("id")); typeCol.setCellValueFactory(new PropertyValueFactory<>("typeName")); dateCol.setCellValueFactory(new PropertyValueFactory<>("date")); nameCol.setCellValueFactory(new PropertyValueFactory<>("name")); priceCol.setCellValueFactory(new PropertyValueFactory<>("cost")); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { initCol(); list.setAll(spendingRepository.findAll()); table.setItems(list); MakeMyFilter(); double total=0.0; total = list.stream().mapToDouble(Spending::getCost).sum(); infoTXT.setText("العدد الكلى = "+ list.size() +" والتكلفه الكليه = "+ total); } private void MakeMyFilter(){ FilteredList<Spending> filteredData = new FilteredList<>(list, s -> true); searchTF.textProperty().addListener( (observable, oldValue, newValue) -> { filteredData.setPredicate(spending -> { if (newValue == null || newValue.isEmpty()) { return true; } String lowerCaseFilter = newValue.toLowerCase(); if (spending.getType().getName().toLowerCase().indexOf(lowerCaseFilter) != -1) { return true; } return false; }); double total=0.0; total = filteredData.stream().mapToDouble(Spending::getCost).sum(); infoTXT.setText("العدد الكلى = "+ filteredData.size() +" والتكلفه الكليه = "+ total); }); SortedList<Spending> sorted = new SortedList<>(filteredData) ; sorted.comparatorProperty().bind(table.comparatorProperty()); table.setItems(sorted); } @FXML void edit(ActionEvent event) { Spending selectedItem = table.getSelectionModel().getSelectedItem(); FxControllerAndView<SpendingAddController, Parent> load = fxWeaver.load(SpendingAddController.class); SpendingAddController controller = load.getController(); controller.setCallBack(this); controller.inflateUI(selectedItem); controller.setInEditMode(true); AssistantUtil.loadWindow(null, load.getView().get()); } @FXML void remove(ActionEvent event){ Spending selectedItem = table.getSelectionModel().getSelectedItem(); spendingRepository.delete(selectedItem); list.remove(selectedItem) ; Capital capital = capitalRepository.findById(1).get(); capital.setSpending(capital.getSpending()-selectedItem.getCost()); capital.setCurrentTotal(capital.getCurrentTotal()+selectedItem.getCost()); capitalRepository.save(capital); } @FXML void refresh(ActionEvent event){ list.setAll(spendingRepository.findAll()); } public void add(ActionEvent actionEvent) { FxControllerAndView<SpendingAddController, Parent> load = fxWeaver.load(SpendingAddController.class); SpendingAddController controller = load.getController(); controller.setCallBack(this); controller.inflateUI(new Spending()); controller.setInEditMode(false); AssistantUtil.loadWindow(null, load.getView().get()); } @Override public Boolean callBack(Spending obj) { Capital capital = capitalRepository.findById(1).get(); for (int i=0 ; i < list.size(); ++i) { Spending object= list.get(i); if (object.getId().equals(obj.getId())) { capital.setSpending(capital.getSpending()-object.getCost()+obj.getCost()); capital.setCurrentTotal(capital.getCurrentTotal()+object.getCost()-obj.getCost()); capitalRepository.save(capital); list.set(i, obj); return true; } } capital.setSpending(capital.getSpending()+obj.getCost()); capital.setCurrentTotal(capital.getCurrentTotal()-obj.getCost()); capitalRepository.save(capital); list.add(obj) ; return true; } }