text
stringlengths
10
2.72M
package com.shahinnazarov.gradle.models.k8s; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.shahinnazarov.gradle.models.enums.K8sPodTemplateSpecDnsPolicies; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonPropertyOrder( { "activeDeadlineSeconds", "affinity", "automountServiceAccountToken", "containers", "dnsConfig", "dnsPolicy", "enableServiceLinks", "hostAliases", "hostIPC", "hostNetwork", "hostPID", "hostname", "imagePullSecrets", "initContainers", "nodeName", "nodeSelector", "priority", "priorityClassName", "readinessGates", "restartPolicy", "runtimeClassName", "schedulerName", "securityContext", "serviceAccountName", "shareProcessNamespace", "subdomain", "terminationGracePeriodSeconds", "tolerations", "volumes", } ) public final class PodTemplateSpec<R extends DefaultK8sObject> extends AbstractK8sObject<R, PodTemplateSpec<R>> { public PodTemplateSpec(R result, ChangeListener<PodTemplateSpec<R>> listener) { super(result, listener); } @JsonProperty("activeDeadlineSeconds") private Integer activeDeadlineSeconds; @JsonProperty("affinity") private Affinity<PodTemplateSpec<R>> affinity; @JsonProperty("automountServiceAccountToken") private Boolean automountServiceAccountToken; @JsonProperty("containers") private List<Container<PodTemplateSpec<R>>> containers; @JsonProperty("dnsConfig") private DNSConfig<PodTemplateSpec<R>> dnsConfig; /** * 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS */ @JsonProperty("dnsPolicy") private String dnsPolicy; @JsonProperty("enableServiceLinks") private Boolean enableServiceLinks; @JsonProperty("hostAliases") private List<HostAlias<PodTemplateSpec<R>>> hostAliases; @JsonProperty("hostIPC") private Boolean hostIPC; @JsonProperty("hostNetwork") private Boolean hostNetwork; @JsonProperty("hostPID") private Boolean hostPID; @JsonProperty("hostname") private String hostname; @JsonProperty("imagePullSecrets") private List<ImagePullSecret<PodTemplateSpec<R>>> imagePullSecrets; @JsonProperty("initContainers") private List<Container<PodTemplateSpec<R>>> initContainers; @JsonProperty("nodeName") private String nodeName; @JsonProperty("nodeSelector") private Map<String, String> nodeSelector; @JsonProperty("priority") private Integer priority; @JsonProperty("priorityClassName") private String priorityClassName; @JsonProperty("readinessGates") private List<ReadinessGate<PodTemplateSpec<R>>> readinessGates; /** * Restart policy for all containers within the pod. One of Always, OnFailure, */ @JsonProperty("restartPolicy") private String restartPolicy; @JsonProperty("runtimeClassName") private String runtimeClassName; @JsonProperty("schedulerName") private String schedulerName; @JsonProperty("securityContext") private PodSecurityContext<PodTemplateSpec<R>> securityContext; @JsonProperty("serviceAccountName") private String serviceAccountName; @JsonProperty("shareProcessNamespace") private Boolean shareProcessNamespace; @JsonProperty("subdomain") private String subdomain; @JsonProperty("terminationGracePeriodSeconds") private Integer terminationGracePeriodSeconds; @JsonProperty("tolerations") private List<Toleration<PodTemplateSpec<R>>> tolerations; @JsonProperty("volumes") private List<PodVolume<PodTemplateSpec<R>>> volumes; public PodTemplateSpec<R> activeDeadlineSeconds(Integer activeDeadlineSeconds) { this.activeDeadlineSeconds = activeDeadlineSeconds; return this; } public Affinity<PodTemplateSpec<R>> affinity() { return new Affinity<>(this, this::affinity); } public PodTemplateSpec<R> affinity(Affinity<PodTemplateSpec<R>> affinity) { this.affinity = affinity; return this; } public PodTemplateSpec<R> automountServiceAccountToken(Boolean automountServiceAccountToken) { this.automountServiceAccountToken = automountServiceAccountToken; return this; } public PodTemplateSpec<R> addContainer(Container<PodTemplateSpec<R>> container) { if (this.containers == null) { this.containers = new ArrayList<>(); } this.containers.add(container); return this; } public Container<PodTemplateSpec<R>> addContainer() { return new Container<>(this, this::addContainer); } public DNSConfig<PodTemplateSpec<R>> dnsConfig() { return new DNSConfig<>(this, this::dnsConfig); } public PodTemplateSpec<R> dnsConfig(DNSConfig<PodTemplateSpec<R>> dnsConfig) { this.dnsConfig = dnsConfig; return this; } public PodTemplateSpec<R> dnsPolicy(String dnsPolicy) { this.dnsPolicy = dnsPolicy; return this; } public PodTemplateSpec<R> dnsPolicy(K8sPodTemplateSpecDnsPolicies dnsPolicy) { this.dnsPolicy = dnsPolicy.getType(); return this; } public PodTemplateSpec<R> enableServiceLinks(Boolean enableServiceLinks) { this.enableServiceLinks = enableServiceLinks; return this; } public PodTemplateSpec<R> addHostAlias(HostAlias<PodTemplateSpec<R>> hostAlias) { if (this.hostAliases == null) { this.hostAliases = new ArrayList<>(); } this.hostAliases.add(hostAlias); return this; } public HostAlias<PodTemplateSpec<R>> addHostAlias() { return new HostAlias<>(this, this::addHostAlias); } public PodTemplateSpec<R> hostIPC(Boolean hostIPC) { this.hostIPC = hostIPC; return this; } public PodTemplateSpec<R> hostNetwork(Boolean hostNetwork) { this.hostNetwork = hostNetwork; return this; } public PodTemplateSpec<R> hostPID(Boolean hostPID) { this.hostPID = hostPID; return this; } public PodTemplateSpec<R> hostname(String hostname) { this.hostname = hostname; return this; } public PodTemplateSpec<R> addImagePullSecret(ImagePullSecret<PodTemplateSpec<R>> imagePullSecret) { if (this.imagePullSecrets == null) { this.imagePullSecrets = new ArrayList<>(); } this.imagePullSecrets.add(imagePullSecret); return this; } public ImagePullSecret<PodTemplateSpec<R>> addImagePullSecret() { return new ImagePullSecret<>(this, this::addImagePullSecret); } public PodTemplateSpec<R> addInitContainer(Container<PodTemplateSpec<R>> initContainer) { if (this.initContainers == null) { this.initContainers = new ArrayList<>(); } this.initContainers.add(initContainer); return this; } public Container<PodTemplateSpec<R>> addInitContainer() { return new Container<>(this, this::addInitContainer); } public PodTemplateSpec<R> nodeName(String nodeName) { this.nodeName = nodeName; return this; } public PodTemplateSpec<R> addNodeSelector(String key, String value) { if (this.nodeSelector == null) { this.nodeSelector = new HashMap<>(); } this.nodeSelector.put(key, value); return this; } public PodTemplateSpec<R> nodeSelector(Map<String, String> nodeSelector) { this.nodeSelector = nodeSelector; return this; } public PodTemplateSpec<R> priority(Integer priority) { this.priority = priority; return this; } public PodTemplateSpec<R> priorityClassName(String priorityClassName) { this.priorityClassName = priorityClassName; return this; } public PodTemplateSpec<R> addReadinessGate(ReadinessGate<PodTemplateSpec<R>> readinessGate) { if (this.readinessGates == null) { this.readinessGates = new ArrayList<>(); } this.readinessGates.add(readinessGate); return this; } public ReadinessGate<PodTemplateSpec<R>> addReadinessGate() { return new ReadinessGate<>(this, this::addReadinessGate); } public PodTemplateSpec<R> restartPolicy(String restartPolicy) { this.restartPolicy = restartPolicy; return this; } public PodTemplateSpec<R> runtimeClassName(String runtimeClassName) { this.runtimeClassName = runtimeClassName; return this; } public PodTemplateSpec<R> schedulerName(String schedulerName) { this.schedulerName = schedulerName; return this; } public PodSecurityContext<PodTemplateSpec<R>> podSecurityContext() { return new PodSecurityContext<>(this, this::podSecurityContext); } public PodTemplateSpec<R> podSecurityContext(PodSecurityContext<PodTemplateSpec<R>> podSecurityContext) { this.securityContext = podSecurityContext; return this; } public PodTemplateSpec<R> serviceAccountName(String serviceAccountName) { this.serviceAccountName = serviceAccountName; return this; } public PodTemplateSpec<R> shareProcessNamespace(Boolean shareProcessNamespace) { this.shareProcessNamespace = shareProcessNamespace; return this; } public PodTemplateSpec<R> subdomain(String subdomain) { this.subdomain = subdomain; return this; } public PodTemplateSpec<R> terminationGracePeriodSeconds(Integer terminationGracePeriodSeconds) { this.terminationGracePeriodSeconds = terminationGracePeriodSeconds; return this; } public PodTemplateSpec<R> addToleration(Toleration<PodTemplateSpec<R>> toleration) { if (this.tolerations == null) { this.tolerations = new ArrayList<>(); } this.tolerations.add(toleration); return this; } public Toleration<PodTemplateSpec<R>> addToleration() { return new Toleration<>(this, this::addToleration); } public PodTemplateSpec<R> addVolume(PodVolume<PodTemplateSpec<R>> podVolume) { if (this.volumes == null) { this.volumes = new ArrayList<>(); } this.volumes.add(podVolume); return this; } public PodVolume<PodTemplateSpec<R>> addVolume() { return new PodVolume<>(this, this::addVolume); } public R buildPodTemplateSpec() { listener.apply(this); return result; } }
package dev.liambloom.softwareEngineering.chapter17.balance; import java.util.ArrayList; public class BinarySearchTree<E extends Comparable<E>> { private TreeNode<E> root = null; public static void main(final String[] args) { final BinarySearchTree<Integer> tree = new BinarySearchTree<>(); tree.addAll(50,40,60,30,70,105,20,80,35,5,10,90,100,110,65); System.out.println("Unbalanced"); System.out.println(tree); tree.balance(); System.out.println("Balanced"); System.out.println(tree); } public void add(final E e) { root = add(root, e); } private TreeNode<E> add(final TreeNode<E> node, final E e) { if (node == null) return new TreeNode<>(e); else if (node.data.compareTo(e) <= 0) node.right = add(node.right, e); else node.left = add(node.left, e); return node; } @SafeVarargs public final void addAll(final E... es) { for (final E e : es) add(e); } public void balance() { final ArrayList<TreeNode<E>> nodes = new ArrayList<>(); intoList(nodes, root); /*System.out.println(nodes.toString()); System.out.println(nodes.size());*/ root = addBalanced(nodes, 0, nodes.size()); } private void intoList(final ArrayList<TreeNode<E>> list, final TreeNode<E> node) { if (node != null) { intoList(list, node.left); list.add(node); intoList(list, node.right); } } private TreeNode<E> addBalanced(final ArrayList<TreeNode<E>> list, final int low, final int high) { if (low >= high) return null; final int middle = (high + low) / 2; final TreeNode<E> root = list.get(middle); root.left = addBalanced(list, low, middle); root.right = addBalanced(list, middle + 1, high); return root; } /*@Override public String toString() { StringBuilder builder = new StringBuilder(); toString(builder, root); return builder.toString(); } private void toString(StringBuilder builder, TreeNode<E> root) { if (root == null) builder.append("empty"); else { boolean isLeaf = root.left == null && root.right == null; if (!isLeaf) builder.append('('); builder.append(root.data); if (!isLeaf) { builder.append(", "); toString(builder, root.left); builder.append(", "); toString(builder, root.right); builder.append(')'); } } }*/ @Override public String toString() { if (root == null) return "[Empty Tree]"; final StringBuilder builder = new StringBuilder(); for (final String row : toString(root)) builder.append(row).append(System.lineSeparator()); return builder.toString(); } private String[] toString(TreeNode<E> node) { if (node == null) return null; String root = node.toString(); final String[] left = toString(node.left); final String[] right = toString(node.right); if (left == null && right == null) return new String[]{ node.toString() }; else if (left == null || right == null) { final String[] single = left == null ? right : left; assert sameLength(single): "Center strings were different lengths"; final int width = Math.max(single[0].length(), root.length()); final String[] r = new String[single.length + 2]; r[0] = center(root, width); // Maybe center(center(root, single[0].length()), width); r[1] = center(left == null ? "\u2572" : "\u2571", width); for (int i = 0; i < single.length; i++) r[i + 2] = center(single[i], width); /* for (String row : r) System.out.println(row);*/ return r; } else { assert sameLength(left): "Left strings were different lengths"; assert sameLength(right): "Right strings were different lengths"; final int subWidth = left[0].length() + right[0].length() + 1; final int width = Math.max(subWidth, root.length()); final String[] r = new String[Math.max(left.length, right.length) + 2]; r[0] = center(root, width); assert r[0].length() == width: "Incorrectly centered"; final String leftPad = " ".repeat((width - subWidth) / 2); final String rightPad = " ".repeat((width - subWidth + 1) / 2); /* if ((width - 1) / 2 - leftPad.length() - 1 < 0) { System.out.printf("leftPad: %d, width: %d, subWidth: %d%n", leftPad.length(), width, subWidth); } */ final StringBuilder r1 = new StringBuilder() .append(leftPad) .append(" ".repeat(Math.max((left[0].length() - 1) / 2, 0))) .append('\u250c') .append("\u2500".repeat(Math.max(left[0].length() / 2, 0))) .append('\u2500') .append("\u2500".repeat(Math.max((right[0].length() - 1) / 2, 0))) .append('\u2510') .append(" ".repeat(Math.max(right[0].length() / 2, 0))) .append(rightPad); r1.setCharAt((width - 1) / 2, '\u2534'); r[1] = r1.toString(); //assert r[1].charAt(width / 2) == '\u2534'; final String spaces = " ".repeat(left.length < right.length ? left[0].length() : right[0].length()); int i; for (i = 0; i < r.length - 2; i++) r[i + 2] = leftPad + (i >= left.length ? spaces : left[i]) + " " + (i >= right.length ? spaces : right[i]) + rightPad; /* for (String row : r) System.out.println(row); */ return r; } } private static String center(String s, int width) { return width > s.length() ? " ".repeat((width - s.length()) / 2) + s + " ".repeat((width - s.length() + 1) / 2) : s; } private static boolean sameLength(String[] a) { if (a.length < 2) return true; final int l = a[0].length(); for (String s : a) { if (s.length() != l) return false; } return true; } }
package com.estrok; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Map; public class GetStockPrices { public static void main(String[] args) { // 종료 년 String endYear = "2020"; // 종료 월 String endMonth = "01"; // 종료 일 String endDate = "30"; // String domain = Connection conn = null; PreparedStatement pstmt = null; Statement st = null; ResultSet rs = null; try { System.out.println("시작11"); Class.forName("com.mysql.cj.jdbc.Driver"); // mysql은 "jdbc:mysql://localhost/사용할db이름" 이다. String dbUrl = "jdbc:mysql://localhost/estrok?characterEncoding=UTF-8&serverTimezone=UTC"; // @param getConnection(url, userName, password); // @return Connection conn = DriverManager.getConnection(dbUrl, "root", "wjdekf$033"); conn.setAutoCommit(false); System.out.println("연결 성공"); // String sql = "select si.stock_code from stock_info si LEFT OUTER JOIN "+ // "(SELECT stock_code FROM stock_daily_price GROUP BY stock_code) d1 " + // "ON si.stock_code = d1.stock_code " + // "WHERE d1.stock_code IS NULL ORDER BY si.stock_code asc" ; String sql = "select stock_code from stock_info"; st = conn.createStatement(); rs = st.executeQuery(sql); int totalCodeCnt = 0; ArrayList<String> codeList = new ArrayList<String>(); while(rs.next()) { totalCodeCnt ++; codeList.add(rs.getString(1)); } rs.close(); System.out.println("total codes : " + totalCodeCnt); int codeCount = 0; // codeList = new ArrayList<>(); // codeList.add("005930"); for(String code : codeList) { codeCount ++; System.out.println("nowCode : " + codeCount + " // totalCodes : " + totalCodeCnt); HttpURLConnection httpConn = null; String urlParameters = ""; // 파라메타값 for(int page = 1;page<2;page++) { System.out.println("----------------------------------" + page); String targetURL = "http://vip.mk.co.kr/newSt/price/daily.php?p_page="+page+"&y1=2020&m1=12&d1=15&y2="+endYear+"&m2="+endMonth+"&d2="+endDate+"&stCode="+code; URL url = new URL(targetURL); httpConn = (HttpURLConnection) url.openConnection(); // 헤더 선언 httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpConn.setRequestProperty("Cookie", "cookievalue=" + ""); httpConn.setUseCaches(false); httpConn.setDoInput(true); httpConn.setDoOutput(true); PrintWriter pw = new PrintWriter(new OutputStreamWriter(httpConn.getOutputStream(), "utf-8")); pw.write(urlParameters); pw.flush(); pw.close(); // Get Response InputStream is = httpConn.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; String insertSql = "insert into stock_daily_price (stock_code, reg_dttm, price, volume) values (?,STR_TO_DATE(?, '%Y/%m/%d'),?,?) on duplicate key update volume = values(volume)"; pstmt = conn.prepareStatement(insertSql); Map<String, String> data = null; boolean dataArea1 = false; boolean dataArea2 = false; boolean dataArea3 = false; boolean dataArea4 = false; int effectLines = 0; String sCode = code; String sDate = ""; int sPrice = 0; int sVolume = 0; while ((line = rd.readLine()) != null) { if(dataArea1) { if(dataArea2) { if(dataArea3) { if(line.indexOf("</table>")>-1) { break; } if(dataArea4) { effectLines ++; line = line.trim(); if(effectLines==1) { sDate = line.substring(19, 27); } else if(effectLines==2) { line = line.replaceAll(",", ""); sPrice = Integer.parseInt(line.substring(4, line.indexOf("</td>"))); } else if(effectLines==8) { line = line.replaceAll(",", ""); sVolume = Integer.parseInt(line.substring(4, line.indexOf("</td>"))); pstmt.setString(1, sCode); pstmt.setString(2, sDate); pstmt.setInt(3, sPrice); pstmt.setInt(4, sVolume); pstmt.execute(); pstmt.clearParameters(); sDate = ""; sPrice = 0; sVolume = 0; effectLines = 0; dataArea4 = false; } } if(line.indexOf("<tr")>-1) { dataArea4 = true; } } if(line.indexOf("</thead>")>-1) { dataArea3 = true; } } if(line.indexOf("table")>-1 && line.indexOf("table_3")>-1) { dataArea2 = true; } } if (line.indexOf("dailyForm")>-1) { dataArea1=true; } } // System.out.println("code : " + codeCount + " // " + totalCodeCnt); // System.out.println("page : " + page + " per 3"); // System.out.println("=============================="); // httpConn.disconnect(); Thread.sleep(10); } conn.commit(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) { rs.close(); } if(pstmt!=null) { pstmt.close(); } if(conn!=null) { conn.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } }
package org.sayesaman.database.model; /** * Created by ameysami on 9/11/13. */ public class OrderItem { private String no; private String id; private Goods goods; private String qty; private String price; private String price_sum; public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getPrice_sum() { return price_sum; } public void setPrice_sum(String price_sum) { this.price_sum = price_sum; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Goods getGoods() { return goods; } public void setGoods(Goods goods) { this.goods = goods; } public String getQty() { return qty; } public void setQty(String qty) { this.qty = qty; } }
import java.util.Scanner; public class Assignment2 { public static void main(String[] args) { CustomerList cl = new CustomerList(); // instantiate a Customer List Customer c = null; boolean continueToPrompt = true; do { System.out.println("Please enter a selection between 1 to 62\r\n" +"" + "1. Add Customer\r\n" + "2. Delete Customer\r\n" + "3. View Customer List\r\n" + "4. Find Customer\r\n" + "5. Sort Customer List\r\n" + "6. Quit"); // display options Scanner input = new Scanner(System.in); // prompt and get user input String name; int option = -1; // Make sure the input is a valid int try { option = input.nextInt(); } catch (Exception e) { continue; } switch (option) { case 1: System.out.println("Please enter customer name: "); name = input.next(); if (cl.AddCustomer(name)) System.out.println(name + " is added."); else System.out.println(name + " is not added."); break; case 2: System.out.println("Please enter customer name: "); name = input.next(); boolean result = cl.DeleteCustomer(name); if(result) { System.out.println("Customer is found and removed successfully!"); } else { System.out.println("Customer is not found"); } break; case 3: System.out.println("List all the customers..."); cl.ViewCustomerList(); break; case 4: System.out.println("Please enter customer name: "); name = input.next(); c = cl.FindCustomer(name); if(c != null) { System.out.println("Customer is found!"); } else { System.out.println("Customer is not found"); } break; case 5: cl.SortCustomerList(); cl.ViewCustomerList(); break; case 6: System.out.println("Goodbye"); continueToPrompt = false; break; default: System.out.println("Please input only option 1 to 6."); break; } } while (continueToPrompt); } }
package polymorphishTest; public class Cat extends Animal { @Override public void makeSound() { System.out.println("moew"); } public void 前進() { System.out.println("GOGO"); } @Override public void breath() { } }
package kr.co.shop.batch.product.model.master.base; import lombok.Data; import java.io.Serializable; import kr.co.shop.common.bean.BaseBean; @Data public class BaseCmProductIcon extends BaseBean implements Serializable { /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 상품아이콘순번 */ private java.lang.Integer prdtIconSeq; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 사이트번호 */ private String siteNo; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 전시아이콘명 */ private String dispIconName; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 아이콘명 */ private String iconName; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 아이콘경로 */ private String iconPathText; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 아이콘URL */ private String iconUrl; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 대체텍스트 */ private String altrnText; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 적용우선순위 */ private java.lang.Short applyPrior; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 자동적용여부 */ private String autoApplyYn; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 내부관리정보 */ private String insdMgmtInfoText; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 사용여부 */ private String useYn; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 등록자번호 */ private String rgsterNo; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 등록일시 */ private java.sql.Timestamp rgstDtm; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 수정자번호 */ private String moderNo; /** * 이 필드는 Code Generator를 통하여 생성 되었습니다. * 설명 : 수정일시 */ private java.sql.Timestamp modDtm; }
package com.db.retail.rest.service; import javax.websocket.server.PathParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.db.retail.domain.GeoDetails; import com.db.retail.domain.Shop; import com.db.retail.exception.ErrorCodes; import com.db.retail.exception.RetailSystemException; import com.db.retail.service.IShopService; /** * Rest layer class having all the Rest API for Shop resource * @author ranveer * */ @RestController @RequestMapping("/shop") public class ShopRestService { @Autowired private IShopService storeService; /** * Rest API to add or replace shop * if shop is already present then it returns the old version of the same shop * @param shop * @return */ @RequestMapping(value="", method = RequestMethod.POST) @ResponseStatus( HttpStatus.CREATED) public Shop addOrReplaceShop(@RequestBody Shop shop) { return storeService.addOrReplaceShop(shop); } /** * Returns the details of nearest shop from the passed location(lat/long) * @param latitude * @param longitude * @return */ @RequestMapping(value="", method = RequestMethod.GET) @ResponseStatus( HttpStatus.OK) public Shop getNearByStore(@PathParam("latitude") String latitude, @PathParam("longitude") String longitude) { if(StringUtils.isEmpty(latitude) || StringUtils.isEmpty(longitude)) { throw new RetailSystemException(ErrorCodes.INSUFFICIENT_GEO_INFO); } GeoDetails geoDetails = new GeoDetails(Double.parseDouble(latitude), Double.parseDouble(longitude)); return storeService.getNearestShop(geoDetails); } }
package ru.job4j.chess; /** * Класс OccupiedPositionException реализует исключение "Позиция занята". * * @author Goureyev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-05-04 */ class OccupiedPositionException extends RuntimeException { /** * Конструктор. * @param position позиция на доске. */ OccupiedPositionException(String position) { super("Occupied position: " + position); } }
/** * */ package com.application.utils; import java.util.HashMap; import java.util.Map; import android.content.Context; import com.google.analytics.tracking.android.EasyTracker; import com.google.analytics.tracking.android.GoogleAnalytics; import com.google.analytics.tracking.android.Tracker; import com.mobcast.R; /** * @author Vikalp Patel(VikalpPatelCE) * */ /** * A collection of Google Analytics trackers. Fetch the tracker you need using * {@code AnalyticsTrackers.getInstance().get(...)} * <p/> * This code was generated by Android Studio but can be safely modified by hand * at this point. * <p/> * TODO: Call {@link #initialize(Context)} from an entry point in your app * before using this! */ public final class AnalyticsTrackersV3 { public enum Target { APP, // Add more trackers here if you need, and update the code in // #get(Target) below } private static AnalyticsTrackersV3 mInstance; public static synchronized void initialize(Context context) { if (mInstance != null) { throw new IllegalStateException( "Extra call to initialize analytics trackers"); } mInstance = new AnalyticsTrackersV3(context); } public static synchronized AnalyticsTrackersV3 getInstance() { if (mInstance == null) { throw new IllegalStateException( "Call initialize() before getInstance()"); } return mInstance; } private final Map<Target, Tracker> mTrackers = new HashMap<Target, Tracker>(); private final Context mContext; /** * Don't instantiate directly - use {@link #getInstance()} instead. */ private AnalyticsTrackersV3(Context context) { mContext = ApplicationLoader.getApplication().getApplicationContext(); } public synchronized Tracker get(Target target) { if (!mTrackers.containsKey(target)) { Tracker tracker; switch (target) { case APP: tracker = EasyTracker.getInstance(mContext); break; default: throw new IllegalArgumentException( "Unhandled analytics target " + target); } mTrackers.put(target, tracker); } return mTrackers.get(target); } }
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper; import FactoryImpl.MysqlFactory; import FactoryImpl.SqliteFactory; import IFactory.IDaoFactory; import model.Guitar; /** * Servlet implementation class AddGuitar */ @WebServlet("/AddGuitar") public class AddGuitar extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public AddGuitar() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); request.setCharacterEncoding("utf-8"); response.setContentType("utf-8"); //response.setCharacterEncoding("utf-8"); Double price=Double.parseDouble(request.getParameter("price")); String serialNumber=request.getParameter("serialNumber"); //String builder=request.getParameter("builder"); //String type=request.getParameter("type"); //String model=request.getParameter("model"); //String backwood=request.getParameter("backwood"); //String topwood=request.getParameter("topwood"); Guitar guitar=new Guitar(); guitar.setPrice(price); guitar.setSerialNumber(serialNumber); //guitar.setBuilder(builder); //guitar.setType(type); //guitar.setModel(model); //guitar.setBackwood(backwood); //guitar.setTopwood(topwood); //根据需要调换数据库 IDaoFactory iDaoFactory=new SqliteFactory(); try { boolean a=iDaoFactory.GetGuitarInstance().addGuitar(guitar); System.out.println(a); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /*PrintWriter out=response.getWriter(); out.println("success"); */ } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.jpeng.demo.add; import android.app.Dialog; import android.content.Intent; import android.support.design.widget.Snackbar; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.githang.statusbar.StatusBarCompat; import com.jpeng.demo.ActivityCollector; import com.jpeng.demo.CarmeraAndGall; import com.jpeng.demo.MyApplication; import com.jpeng.demo.R; import com.jpeng.demo.notes.Carmera; import java.util.Date; public class AddCarmera extends CarmeraAndGall implements View.OnClickListener { RelativeLayout toolbarLin; LinearLayout back; TextView title,time,labelText,address; ImageView label,addCarmear,save; RadioButton tourism,personal,life; Dialog dialog; int labelID=1; EditText moodText; private LocalBroadcastManager localBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_carmera); ActivityCollector.addActivity(this); localBroadcastManager=LocalBroadcastManager.getInstance(this); StatusBarCompat.setStatusBarColor(this, MyApplication.getPeople().getToolbarColor(), true); toolbarLin=(RelativeLayout)findViewById(R.id.toolbar_lin); toolbarLin.setBackgroundColor(MyApplication.getPeople().getToolbarColor()); title=(TextView)findViewById(R.id.title_tooolbar); title.setText("新建拍摄"); save=(ImageView)findViewById(R.id.save_toolbar); save.setImageResource(R.drawable.save_white); save.setOnClickListener(this); time=(TextView)findViewById(R.id.time_event); Date date = new Date(); time.setText(date.toLocaleString()); back=(LinearLayout) findViewById(R.id.back_toolbar); back.setOnClickListener(this); labelText=(TextView)findViewById(R.id.label_text); label=(ImageView)findViewById(R.id.label_event); label.setOnClickListener(this); addCarmear=(ImageView)findViewById(R.id.add_camera); addCarmear.setOnClickListener(this); moodText=(EditText)findViewById(R.id.mood_carmera); address=(TextView)findViewById(R.id.address_carmera); address.setText(MyApplication.getPeople().getAddress()); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.back_toolbar: finish(); ActivityCollector.removeActivity(this); break; case R.id.label_event: createLebelDialog(); break; case R.id.tourism_label: dialogRadio(1); break; case R.id.personal_label: dialogRadio(2); break; case R.id.life_label: dialogRadio(3); break; case R.id.add_camera: goCarmera(); break; case R.id.save_toolbar: saveCarmear(); Intent intent=new Intent("com.jpeng.demo.ADDSUCCESSCARMEAR"); localBroadcastManager.sendBroadcast(intent); Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show(); finish(); ActivityCollector.removeActivity(this); break; default:break; } } private void saveCarmear(){ Date date = new Date(); Carmera carmera=new Carmera(); carmera.setCreateTime(date.toLocaleString()); carmera.setLabelCarmera(labelText.getText().toString()); carmera.setPathCarmera(path); carmera.setMoodCarmera(moodText.getText().toString()); carmera.setAddressCarmera(MyApplication.getPeople().getAddress()); carmera.save(); } private void dialogRadio(int id){ labelID=id; label.setImageResource(R.drawable.icn_label_two); switch (id){ case 1:labelText.setText("旅游");break; case 2:labelText.setText("个人");break; case 3:labelText.setText("生活");break; default:break; } } @Override protected void onDestroy() { super.onDestroy(); ActivityCollector.removeActivity(this); } private void createLebelDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = LayoutInflater.from(this); View v = inflater.inflate(R.layout.label_event_layout, null); tourism=(RadioButton)v.findViewById(R.id.tourism_label); personal=(RadioButton)v.findViewById(R.id.personal_label); life=(RadioButton)v.findViewById(R.id.life_label); tourism.setOnClickListener(this); personal.setOnClickListener(this); life.setOnClickListener(this); dialog = builder.create(); dialog.show(); dialog.getWindow().setContentView(v); } @Override protected void onResume() { super.onResume(); Glide.with(this).load(path).placeholder(R.drawable.add_camera).into(addCarmear); } }
public class exam01_순차탐색 { public static void main(String[] args) { // sequential Search 순차 탐색 알고리즘 int[] array = {100, 23, 56, 7, 8, 11, 99, 32, 14, 56}; int find = 200 ; //찾고자 하는 수 int index = -1; // 찾고자 하는 수의 인덱스 for (int i = 0; i < array.length; i++) { if(find == array[i]) { index = i; break; } } if(index == -1) { System.out.println("찾는 수는 존재하지 않습니다."); }else { System.out.println(String.format("%d는 %d번째 인덱스에 존재합니다.", find, index)); } } }
package com.somoo.organizer; import com.somoo.organizer.persistence.hibernate.conf.HibernateUtils; import com.somoo.organizer.user.User; import com.somoo.organizer.user.role.Role; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import java.util.ArrayList; import java.util.List; public class DummyMain { public static void main(String[] args) { // createUser(); User userOfDb = readUser("admin", "root"); System.out.println(userOfDb); } private static User readUser(String login, String pw) { SessionFactory sessionFactory = HibernateUtils.getSessionFactory(); Session session = sessionFactory.getCurrentSession(); session.getTransaction().begin(); String hql = "FROM User U WHERE U.logIn ='" + login + "'"; Query query = session.createQuery(hql); List<User> userList = query.list(); session.close(); sessionFactory.close(); return userList.get(0); } private static void createUser() { SessionFactory sessionFactory = HibernateUtils.getSessionFactory(); Session session = sessionFactory.getCurrentSession(); session.getTransaction().begin(); User user = new User(); user.setId(1234); user.setAge(18); user.setFirstName("somoo"); user.setSecondName("boehm"); user.setLogIn("admin"); user.setPassWord("root"); ArrayList<Role> role = new ArrayList<>(); Role admin = new Role(); admin.setRole("adm"); admin.setId("111"); admin.setUser(user); Role userrole = new Role(); userrole.setRole("use"); userrole.setId("222"); userrole.setUser(user); role.add(admin); role.add(userrole); user.setRoles(role); session.save(user); for (Role r : user.getRoles()) { session.save(r); } session.getTransaction().commit(); session.close(); sessionFactory.close(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package me.yongshang.cbfm.test; import me.yongshang.cbfm.MultiDBitmapIndex; import org.junit.Test; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.ByteBuffer; import static org.junit.Assert.*; /** * Created by yongshangwu on 2016/11/8. */ public class MultiDBitmapIndexTest { // @Test public void testFunctionality3D(){ // --Table partsupp: // ----A: int // ----B: string // ----C: double MultiDBitmapIndex index = new MultiDBitmapIndex(0.1, 10, 3); byte[][] bytes = new byte[][]{ ByteBuffer.allocate(4).putInt(17).array(), "Test of Multi-Dimension".getBytes(), ByteBuffer.allocate(8).putDouble(77.7).array() }; index.insert(bytes); assertTrue(index.contains(bytes)); } @Test public void testMassively3D() throws IOException { int elementCount = 100000; byte[][][] bytes = new byte[elementCount][3][]; // --Table partsupp: // ----A: int // ----B: string // ----C: double MultiDBitmapIndex index = new MultiDBitmapIndex(0.1, elementCount, 3); FileReader reader = new FileReader("/Users/yongshangwu/Downloads/tpch_2_17_0/dbgen/partsupp.tbl"); BufferedReader br = new BufferedReader(reader); long insertTime = 0; for(int i = 0; i < elementCount; i ++){ String line = br.readLine(); String[] tokens = line.split("\\|"); bytes[i][0] = ByteBuffer.allocate(4).putInt(Integer.valueOf(tokens[2])).array(); bytes[i][1] = tokens[4].getBytes(); bytes[i][2] = ByteBuffer.allocate(8).putDouble(Double.valueOf(tokens[3])).array(); long start = System.currentTimeMillis(); index.insert(bytes[i]); insertTime += (System.currentTimeMillis()-start); } index.displayUsage(); long start = System.currentTimeMillis(); for (byte[][] element : bytes) { assertTrue(index.contains(element)); } // test non-member assertFalse(index.contains(new byte[][]{ ByteBuffer.allocate(4).putInt(-17).array(), "FUCK".getBytes(), ByteBuffer.allocate(8).putDouble(-77.7).array() })); System.out.println("[MDBitmapIdx]\tavg insert time: "+insertTime/(double)elementCount+" ms, avg query time: "+(System.currentTimeMillis()-start)/(double)elementCount+" ms"); } @Test public void testMassively1D() throws IOException { int elementCount = 100000; byte[][][] bytes = new byte[elementCount][1][]; // --Table partsupp: // ----A: int MultiDBitmapIndex index = new MultiDBitmapIndex(0.1, elementCount, 1); FileReader reader = new FileReader("/Users/yongshangwu/Downloads/tpch_2_17_0/dbgen/partsupp.tbl"); BufferedReader br = new BufferedReader(reader); long insertTime = 0; for(int i = 0; i < elementCount; i ++){ String line = br.readLine(); String[] tokens = line.split("\\|"); bytes[i][0] = ByteBuffer.allocate(4).putInt(Integer.valueOf(tokens[2])).array(); long start = System.currentTimeMillis(); index.insert(bytes[i]); insertTime += (System.currentTimeMillis()-start); } index.displayUsage(); long start = System.currentTimeMillis(); for (byte[][] element : bytes) { assertTrue(index.contains(element)); } // System.out.println("[MDBitmapIdx]\tavg insert time: "+insertTime/(double)elementCount+" ms, avg query time: "+(System.currentTimeMillis()-start)/(double)elementCount+" ms"); } @Test public void testMassively2D() throws IOException { int elementCount = 100000; byte[][][] bytes = new byte[elementCount][2][]; // --Table partsupp: // ----A: int // ----B: string MultiDBitmapIndex index = new MultiDBitmapIndex(0.1, elementCount, 2); FileReader reader = new FileReader("/Users/yongshangwu/Downloads/tpch_2_17_0/dbgen/partsupp.tbl"); BufferedReader br = new BufferedReader(reader); long insertTime = 0; for(int i = 0; i < elementCount; i ++){ String line = br.readLine(); String[] tokens = line.split("\\|"); bytes[i][0] = ByteBuffer.allocate(4).putInt(Integer.valueOf(tokens[2])).array(); bytes[i][1] = tokens[4].getBytes(); long start = System.currentTimeMillis(); index.insert(bytes[i]); insertTime += (System.currentTimeMillis()-start); } index.displayUsage(); long start = System.currentTimeMillis(); for (byte[][] element : bytes) { assertTrue(index.contains(element)); } // System.out.println("[MDBitmapIdx]\tavg insert time: "+insertTime/(double)elementCount+" ms, avg query time: "+(System.currentTimeMillis()-start)/(double)elementCount+" ms"); } // @Test public void testMassively4D() throws IOException { int elementCount = 50000; byte[][][] bytes = new byte[elementCount][4][]; // --Table partsupp: // ----A: int // ----B: string // ----C: double // ----D: int MultiDBitmapIndex index = new MultiDBitmapIndex(0.1, elementCount, 4); FileReader reader = new FileReader("/Users/yongshangwu/Downloads/tpch_2_17_0/dbgen/partsupp.tbl"); BufferedReader br = new BufferedReader(reader); long insertTime = 0; for(int i = 0; i < elementCount; i ++){ String line = br.readLine(); String[] tokens = line.split("\\|"); bytes[i][0] = ByteBuffer.allocate(4).putInt(Integer.valueOf(tokens[2])).array(); bytes[i][1] = tokens[4].getBytes(); bytes[i][2] = ByteBuffer.allocate(8).putDouble(Double.valueOf(tokens[3])).array(); bytes[i][3] = ByteBuffer.allocate(4).putInt(Integer.valueOf(tokens[1])).array(); long start = System.currentTimeMillis(); index.insert(bytes[i]); insertTime += (System.currentTimeMillis()-start); } index.displayUsage(); long start = System.currentTimeMillis(); for (byte[][] element : bytes) { assertTrue(index.contains(element)); } System.out.println("[MDBitmapIdx]\tavg insert time: "+insertTime/(double)elementCount+" ms, avg query time: "+(System.currentTimeMillis()-start)/(double)elementCount+" ms"); } }
package synch_demo; import java.util.Arrays; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * <br> * 〈〉 * * @author wensir * @create 2018/12/23 * @since 1.0.0 */ public class BanK { // 一家银行,有许多银行账户 private final double[] accounts; private Lock bankLock = new ReentrantLock(); /** * 初始化所有账户金额 * * @param n 数量 * @param initalBalance 账户初始化值 */ public BanK(int n, double initalBalance) { accounts = new double[n]; Arrays.fill(accounts, initalBalance); } /** * 将一个账户的钱转移到另外一个账户中 * * @param from 金额来源方 * @param to 金额获取方 * @param amount 要转移的钱数 */ public void transfer(int from, int to, double amount) { bankLock.lock(); //加锁保证安全 try { if (accounts[from] < amount) return; //当金额来源方资金不足时,结束线程 System.out.print(Thread.currentThread()); //打印线程 accounts[from] -= amount; //金额来源方减去相应的转移金额。 System.out.printf("%10.2f from %d to %d", amount, from, to); /* 该行代码非原子性操作指令可能如下: 1)将accounts[to]加载到寄存器 2)增加amount 3)将结果写回accounts[to] 假定第一个线程执行步骤1和2,然后它被剥夺了运行权。第2个线程被唤醒并修改了accounts数组中的同一项。然后第一个线程被唤醒并完成其第三步将第一个 线程前两步执行的结果写会了数组,这一动作擦去了第二个线程所做的更新,于是总金额不再正确。 */ accounts[to] += amount;//金额获取方加入相应的金额 //打印所有账户总金额 /* 可重入锁: 1.transfer方法调用了getTotalBalance方法,这也会封锁bankLock对象(该线程已经持有该锁,故默认获取到), 此时bankLock对象的持有计数器为2. 2.当getTotalBalance方法退出的时候,持有计数变回1。当transfer方法退出的时候,持有计数变为0。 3.线程释放锁。 */ System.out.printf(" Total Balance:%10.2f%n", getTotalBalance()); } catch (Exception e) { System.out.println(e.getMessage()); }finally { bankLock.unlock(); } } /** * 计算所有账户总金额之和 * * @return */ private double getTotalBalance() { double sum = 0; for (double a : accounts) { sum += a; } return sum; } public int size() { return accounts.length; } }
public class ReverseNumber { static void doResvers (int input) { int rem,res=0; int num=input; while(num>0) { rem=num%10; res=res*10+rem; num=num/10; } if (input==res) { System.out.println("Given number is palindrome"); } else System.out.println("Given number is not palindrome"); } public static void main (String[]args) { doResvers(122); } }
package com.github.dongchan.scheduler; import java.io.*; /** * @author DongChan * @date 2020/10/23 * @time 2:09 PM */ public interface Serializer { byte[] serialize(Object data); <T> T deserialize(Class<T> clazz, byte[] serializedData); Serializer DEFAULT_JAVA_SERIALIZER = new Serializer() { public byte[] serialize(Object data) { if (data == null) return null; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(data); return bos.toByteArray(); } catch (Exception e) { throw new RuntimeException("Failed to serialize object", e); } } public <T> T deserialize(Class<T> clazz, byte[] serializedData) { if (serializedData == null) return null; try (ByteArrayInputStream bis = new ByteArrayInputStream(serializedData); ObjectInput in = new ObjectInputStream(bis)) { return clazz.cast(in.readObject()); } catch (Exception e) { throw new RuntimeException("Failed to deserialize object", e); } } }; }
import java.util.*; public class ComparatorEight { public static void main(String[] args) { Employee emp1 = new Employee("Amardeep","Bhowmick",26,1000d,7044475857l); Employee emp2 = new Employee("Amardeep","Champa",29,1200d,7044475857l); List<Employee> empList1 = new ArrayList(Arrays.asList(emp2,emp1,null)); empList1.sort(Comparator.nullsFirst(Comparator.comparing(Employee::getFirstName))); empList1.forEach(System.out::println); List<Employee> empList2 = new ArrayList(Arrays.asList(emp2,emp1,null)); empList2.sort(Comparator.nullsLast(Comparator.comparing(Employee::getFirstName).thenComparing(Employee::getLastName))); empList2.forEach(System.out::println); List<Employee> empList3 = new ArrayList(Arrays.asList(emp2,emp1,null)); empList3.sort(Comparator.nullsLast(Comparator.comparing(Employee::getAge, (age1, age2) -> age2 > age1 ? -1: 1).thenComparing(Employee::getLastName))); empList3.forEach(System.out::println); empList3.stream().filter(Objects::nonNull).max(Comparator.comparing(Employee::getAge)).ifPresent(System.out::println); } } class Employee implements Comparable<String>{ private String firstName; private String lastName; private int age; private double salary; private long cellphone; public Employee(String firstName, String lastName, int age, double salary, long cellphone) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.salary = salary; this.cellphone = cellphone; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public long getCellphone() { return cellphone; } public void setCellphone(long cellphone) { this.cellphone = cellphone; } @Override public int compareTo(String firstName) { return this.firstName.compareTo(firstName); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public String toString() { return "Employee{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + ", salary=" + salary + ", cellphone=" + cellphone + '}'; } }
package effectivejava.item41; public interface CustomInterface { }
/* * Main.java */ package GUI; public class Main { /** Default Constructor */ public Main() { } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DigLibSEUI().setVisible(true); } }); } }
import javafx.application.Application; import javafx.scene.control.*; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.GridPane; import javafx.geometry.Pos; import javafx.geometry.Insets; import javafx.event.ActionEvent; public class CreatePassword extends Application { private Label prompt; private Label lblPassword; private Label lblConfirm; private PasswordField tfPassword; private PasswordField tfConfirm; private Button submit; //Overridden start method @Override public void start(Stage primaryStage) { //Set title of stage primaryStage.setTitle("Create Password"); //Create labels, password fields, and button prompt = new Label("Choose and Confirm a Password"); lblPassword = new Label("Password:"); lblConfirm = new Label("Confirm:"); tfPassword = new PasswordField(); tfConfirm = new PasswordField(); submit = new Button("Submit"); //Create rootNode GridPane rootNode = new GridPane(); //Set up rootNode createRootNode(rootNode); //Add controls to rootNode rootNode.add(prompt, 0, 0, 2, 1); rootNode.add(lblPassword, 0, 1); rootNode.add(tfPassword, 1, 1); rootNode.add(lblConfirm, 0, 2); rootNode.add(tfConfirm, 1, 2); rootNode.add(submit, 0, 4); //Submit button ActionEvent submit.setOnAction(e -> submitAction(e)); //Create Scene Scene primaryScene = new Scene(rootNode, 600, 500); //Add Scene to Stage primaryStage.setScene(primaryScene); //Show Stage primaryStage.show(); } public static void main(String[] args) { launch(args); } //createRootNode method sets up GridPane layout as root node public GridPane createRootNode(GridPane gridPane) { //Set padding of root node gridPane.setPadding(new Insets(10, 10, 10, 10)); //Set gaps between controls gridPane.setHgap(20); gridPane.setVgap(40); //Set alignment of controls gridPane.setAlignment(Pos.CENTER); return gridPane; } //Handle event when submit button is pushed public void submitAction(ActionEvent e) { //Check if PasswordFields are empty if(tfPassword.getText().isEmpty() || tfConfirm.getText().isEmpty()) { Alert alert = new Alert(Alert.AlertType.ERROR, "Field is Empty!"); alert.show(); } else { //If both PasswordFields match, password accepted if(tfPassword.getText().equals(tfConfirm.getText())) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Password Accepted!"); alert.show(); } else { Alert alert = new Alert(Alert.AlertType.ERROR, "Passwords Do Not Match!"); alert.show(); } } } }
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.user.export.core.internal.service.impl; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Map; public class UserInformationServiceImplTest { @Test public void testGetRetainedUserInformation() throws Exception { UserInformationServiceImpl userInformationService = new UserInformationServiceImpl(); userInformationService.setUserAttributeProvider(new MockUserInformationProvider()); Map<String, Object> retainedUserInformation = userInformationService.getRetainedUserInformation ("admin", "PRIMARY", -1234); Object basicUserInformation = retainedUserInformation.get("basic"); if (basicUserInformation instanceof Map) { Map basicUserInformationMap = (Map) basicUserInformation; if (basicUserInformationMap.size() != 3) { Assert.fail(); } } } }
package com.aim.project.pwp.heuristics; import java.util.Random; import com.aim.project.pwp.interfaces.ObjectiveFunctionInterface; import com.aim.project.pwp.interfaces.PWPSolutionInterface; import com.aim.project.pwp.interfaces.XOHeuristicInterface; public class OX implements XOHeuristicInterface { private final Random oRandom; private ObjectiveFunctionInterface oObjectiveFunction; public OX(Random oRandom) { this.oRandom = oRandom; } @Override public double apply(PWPSolutionInterface oSolution, double dDepthOfSearch, double dIntensityOfMutation) { } @Override public double apply(PWPSolutionInterface p1, PWPSolutionInterface p2, PWPSolutionInterface c, double depthOfSearch, double intensityOfMutation) { } @Override public boolean isCrossover() { return true; } @Override public boolean usesIntensityOfMutation() { return true; } @Override public boolean usesDepthOfSearch() { return false; } @Override public void setObjectiveFunction(ObjectiveFunctionInterface f) { this.oObjectiveFunction = f; } }
// // Voter_truthful.java: sample implementation for Voter // COS 445 HW1, Spring 2018 import java.util.List; import java.util.Arrays; import java.util.ArrayList; public class Voter_hop implements Voter { // Constants private double MEASURE_OF_BALANCE = 0.1; private double SWITCH_THRESH = 0.3; // IV private int P; private int N; private Candidate F; private List<Poll> polls; private int currPoll; private int no_of_honest_rounds; private Candidate lastRes; private class Poll { double fstRatio; double sndRatio; double thrRatio; private Poll(double fst, double snd, double thr) { fstRatio = fst; sndRatio = snd; thrRatio = thr; } public String toString() { return fstRatio + " - " + sndRatio + " - " + thrRatio + "\n"; } } public void setup(int N, int P, int v, Candidate F) { this.P = P; this.N = N; this.F = F; this.lastRes = F; polls = new ArrayList<Poll>(); currPoll = 0; int cap = P / 2; no_of_honest_rounds = (cap >= 3) ? cap : 3; } private Candidate getSndCand() { return (this.F == Candidate.A) ? Candidate.B : (this.F == Candidate.B ? Candidate.C : Candidate.A); } public Candidate getPoll() { Candidate res = null; if (P == 0) return F; else if (currPoll != P-1) { if (currPoll % 5 != 0) res = F; else res = this.getSndCand(); } else { Poll poll = polls.get(currPoll-1); double fst = poll.fstRatio; double snd = poll.sndRatio; double thr = poll.thrRatio; double max = Math.max(fst, Math.max(snd, thr)); if (fst == max) res = F; else res = this.getSndCand(); } currPoll++; lastRes = res; return res; } public void addResults(List<Candidate> results) { int countA = 0; int countB = 0; int countC = 0; for (Candidate c : results) { switch (c) { case A: countA++; break; case B: countB++; break; default: countC++; } } double total = results.size(); int topCount = (F == Candidate.A) ? countA : ((F == Candidate.B) ? countB : countC); int secCount = (F == Candidate.A) ? countB : ((F == Candidate.B) ? countC : countA); int thrCount = (F == Candidate.A) ? countC : ((F == Candidate.B) ? countA : countB); Poll p = new Poll( topCount / total, secCount / total, thrCount / total ); polls.add(p); } public Candidate getVote() { return lastRes; } }
String[] fileNaming(String[] names) { HashSet<String> kaka = new HashSet<String>(); for(int i = 0; i < names.length; i++) { if(kaka.add(names[i])) continue; else { for(int j = 1; j < 16; j++) { String bab = names[i] + '(' + j + ')'; if(kaka.add(bab)) { names[i] = bab; break; } } } } return names; }
package client; public class Message { Object origin; String topic; String payload; Message(Object origin, String topic, String payload){ this.origin=origin; this.topic=topic; this.payload=payload; } public String toString() { return "origin:"+origin+"\ntopic:"+topic+"\npayload:"+payload; } }
package pages; import org.junit.Assert; import org.openqa.selenium.By; import runnerclass.ObjectRepo; public class Loginpage extends ObjectRepo { public void loginpageAssertion() { Assert.assertEquals("Login | Tu clothing", driver.getTitle()); } public void username() { driver.findElement(By.cssSelector("#j_username")).sendKeys("testmail@gmail.com"); } public void password() { driver.findElement(By.cssSelector("#j_password")).sendKeys("test@123"); } public void loginbutton() { driver.findElement(By.cssSelector(".ln-c-button.ln-c-button--primary.tuButton.loginButtonMain.js-login-button")) .click(); } public void username(String name) { driver.findElement(By.cssSelector("#j_username")).sendKeys(name); } public void password(String pass) { driver.findElement(By.cssSelector("#j_password")).sendKeys(pass); } }
package com.lab2; import java.util.Scanner; public class demo3 { private static Scanner scanner; public static void main(String[] args) { thucHienTinhTong(); thucHienTinhTru(); } public static void thucHienTinhTong() { int a ,b; scanner = new Scanner(System.in); System.out.println("Nhap so a"); a = scanner.nextInt(); System.out.println("Nhap so b"); b = scanner.nextInt(); double c = a+b; System.out.println("Tong :"+c); } public static void thucHienTinhTru() { int a ,b; scanner = new Scanner(System.in); System.out.println("Nhap so a"); a = scanner.nextInt(); System.out.println("Nhap so b"); b = scanner.nextInt(); double c = a-b; System.out.println("Tong :"+c); } }
package aaa.assignment3; import java.util.*; import aaa.*; public class StateMulti implements State { private Agent me; private final Agent prey; private final List<Agent> predators; private HashMap<Agent, Coordinate> positions; private List<Coordinate> distances; public StateMulti(Agent me, Agent prey, List<Agent> predators) { this.me = me; this.prey = prey; this.predators = predators; positions = new HashMap<Agent, Coordinate>(); distances = new ArrayList<Coordinate>(); positions.put(prey, new Coordinate(5, 5)); switch (predators.size()) { case 4: positions.put(predators.get(3), new Coordinate(0, 10)); case 3: positions.put(predators.get(2), new Coordinate(10, 0)); case 2: positions.put(predators.get(1), new Coordinate(10, 10)); case 1: positions.put(predators.get(0), new Coordinate(0, 0)); } calculateDistances(); } @Override public Iterator<State> stateIterator() { // TODO Auto-generated method stub return null; } @Override public boolean isFinal() { return collisionPrey() || collisionPredators(); } @Override public int getX(Agent agent) { return positions.get(agent).x; } @Override public int getY(Agent agent) { return positions.get(agent).y; } @Override public void move(Agent agent) { float sum = 0; float random = (float) Math.random(); for (int action: AGENT_ACTIONS) { sum += agent.pi(this, action); if (sum >= random) { move(agent, action); break; } } } @Override public void move(Agent agent, int action) { float random = (float) Math.random(); if (agent.getType() != Agent.TYPE_PREY || random > 0.2f) // Prey tripping behaviour. { int newX, newY; if (action % 2 == 0) { newX = StateSimple.fixCoord(positions.get(agent).x + action / 2); newY = positions.get(agent).y; } else { newX = positions.get(agent).x; newY = StateSimple.fixCoord(positions.get(agent).y + action); } positions.put(agent, new Coordinate(newX, newY)); } calculateDistances(); } public void changeViewPoint(Agent me) { this.me = me; calculateDistances(); } public int getReward(Agent agent) { if (collisionPredators()) { if (agent.getType() == Agent.TYPE_PREDATOR) { return -10; } else // Agent.TYPE_PREY { return +10; } } else if (collisionPrey()) { if (agent.getType() == Agent.TYPE_PREDATOR) { return +10; } else // Agent.TYPE_PREY { return -10; } } else { return 0; } } private boolean collisionPredators() { for (int i = 0; i < predators.size(); i++) { for (int j = i + 1; j < predators.size(); j++) { Agent predatorA = predators.get(i); Agent predatorB = predators.get(j); if (getX(predatorA) == getX(predatorB) && getY(predatorA) == getY(predatorB)) { return true; } } } return false; } private boolean collisionPrey() { for (Agent predator: predators) { if (getX(predator) == getX(prey) && getY(predator) == getY(prey)) { return true; } } return false; } @SuppressWarnings("unchecked") private void calculateDistances() { // Initial calculation of distances: List<Coordinate> distances = new ArrayList<Coordinate>(); for (Agent predator: predators) { if (predator != me) { distances.add(calculateDistance(predator)); } } // Ordering of the predators by distance: Collections.sort(distances); // We finally add the prey: if (me.getType() == Agent.TYPE_PREDATOR) { distances.add(0, calculateDistance(prey)); } this.distances = distances; } private Coordinate calculateDistance(Agent agent) { int distX, distY; int innerX = positions.get(me).x - positions.get(agent).x; int outterX; if (innerX < 0) { outterX = innerX + ENVIRONMENT_SIZE; } else { outterX = innerX - ENVIRONMENT_SIZE; } if (Math.abs(innerX) < Math.abs(outterX)) { distX = innerX; } else { distX = outterX; } int innerY = positions.get(me).y - positions.get(agent).y; int outterY; if (innerY < 0) { outterY = innerY + ENVIRONMENT_SIZE; } else { outterY = innerY - ENVIRONMENT_SIZE; } if (Math.abs(innerY) < Math.abs(outterY)) { distY = innerY; } else { distY = outterY; } return new Coordinate(distX, distY); } @SuppressWarnings("unchecked") @Override public Object clone() { StateMulti clone = new StateMulti(me, prey, predators); clone.positions = (HashMap<Agent, Coordinate>) this.positions.clone(); clone.distances = new ArrayList<Coordinate>(); clone.calculateDistances(); return clone; } @Override public int hashCode() { final int[] primes = new int[] {19, 23, 29, 31}; final int prime = primes[distances.size() - 1]; int result = 1; for (Coordinate c: distances) { result = prime * result + c.x; result = prime * result + c.y; } return result; } @Override public boolean equals(Object obj) { StateMulti other = (StateMulti) obj; if (this.distances.size() == other.distances.size()) { for (int i = 0; i < distances.size(); i++) { if (!this.distances.get(i).equals(other.distances.get(i))) { return false; } } return true; } return false; } }
//package sublist; // //public class BinaryTree { // public String maxSubtree(){ // Info info = root.maxSubtree(); // return "" + info.where + info.maxSum; // } // class Info{ // int sum; // int maxSum; // char where; // public Info(int sum, int maxSum, char where){ // this.sum = sum; // this.maxSum = maxSum; // this.where = where; // } // } // public class BinaryNode{ // public Info maxSubtree(){ // if(this == NULL_NODE){ // return new Info(0,0, '$'); // } // Info leftInfo = left.maxSubtree(); // Info rightInfo = right.maxSubtree(); // int mySum = leftInfo.sum + rightInfo.sum + this.value; // // //Figure out which is largest: // //1. left subtree max sum: // if(leftInfo.maxSum >- rightInfo.maxSum && leftInfo.maxSum >= mySum){ // return new Info(mySum, leftInfo.maxSum, leftInfo.where); // // } // //2. current nodes sum largest: // if(mySum >= rightInfo.maxSum){ // return new Info(mySum, mySum, label); // } // //3. the right subtree's maxSum // return new Info(mySum, rightInfo.maxSum,rightInfo.where); // } // } // } // } //}
package com.globant.university; import java.util.ArrayList; import com.globant.university.Teacher; public class Lesson { private String name; private String classroom; private Teacher teacher; private ArrayList<Student> studentList; private static int amount=0; public Lesson(String name, String classroom, Teacher teacher, ArrayList<Student> studentList ) { this.name=name; this.classroom=classroom; this.teacher=teacher; this.studentList=studentList; amount++; } static int getAmount() { return amount; } public String toStringSubMenu() { return name; } public ArrayList<Student> getStudentList() { return studentList; } public String toStringObject() { return "Classroom: "+classroom+ "\nTeacher:" + teacher.toString()+"\nStudent List: " ; } public String getName() { return name; } public String searchStudent(long id, ArrayList<Teacher> teacherList) { return "x"; } public Teacher getTeacher() { return teacher; } }
package com.fedorov.example.rabbit.consumer.model; import lombok.Data; @Data public class Event { private Long id; private String number; private String text; private Long timeStamp; }
package Topic24Interface; public class Triangle implements Shape { private double a; private double h; public Triangle(double a, double h) { this.a = a; this.h = h; } @Override public double calculateArea() { return a * h / 2; } @Override public double calculatePerimeter() { return 3*a; } }
package cz.muni.fi.pa165.monsterslayers.sample_data; public interface SampleDataLoadingFacade { void loadData(); }
package com.sh.offer.linkedlist; /** * @Auther: bjshaohang * @Date: 2019/2/27 */ public class DeleteRepeat { public static void main(String[] args) { ListNode head = new ListNode(1); ListNode b = new ListNode(3); ListNode c = new ListNode(3); ListNode d = new ListNode(4); ListNode e = new ListNode(4); ListNode f = new ListNode(9); head.next = b; b.next = c; c.next = d; d.next = e; e.next = f; ListNode result = new DeleteRepeat().deleteDuplication_3(head); new MergeListNode().printLink(result); } public ListNode deleteDuplication_3(ListNode pHead) { if(pHead==null||pHead.next==null) return pHead; ListNode pPreNode=null; ListNode pNode=pHead; while(pNode!=null){ ListNode pNext=pNode.next; boolean needDelete=false; if(pNext!=null&&pNext.val==pNode.val) needDelete=true; if(!needDelete){ pPreNode=pNode; pNode=pNode.next; }else{ int value=pNode.val; ListNode pToBeDel=pNode; while(pToBeDel!=null&&pToBeDel.val==value){ pNext=pToBeDel.next; pToBeDel=pNext; } if(pPreNode==null) pHead=pNext; else pPreNode.next=pNext; pNode=pNext; } } return pHead; } }
package org.seforge.monitor.web; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.hyperic.hq.hqapi1.types.LastMetricData; import org.seforge.monitor.domain.Metric; import org.seforge.monitor.domain.ResourceGroup; import org.seforge.monitor.manager.MetricManager; import org.seforge.monitor.domain.ResourcePrototype; import org.seforge.monitor.extjs.JsonObjectResponse; import org.seforge.monitor.hqapi.HQProxy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import flexjson.JSONSerializer; import flexjson.transformer.DateTransformer; @RequestMapping("/generate_metrics") @Controller public class GenerateMetric { @Autowired private HQProxy proxy; @Autowired private MetricManager metricManager; //thd PathVariable id is the id of a resourcePrototype @RequestMapping(method = RequestMethod.POST) public ResponseEntity<String> generateMetrics(@RequestParam("groupId") Integer groupId, @RequestParam("resourcePrototypeId") Integer resourcePrototypeId, @RequestParam("metrics") String metricsJson) { HttpStatus returnStatus; JsonObjectResponse response = new JsonObjectResponse(); if( groupId == null){ returnStatus = HttpStatus.BAD_REQUEST; response.setMessage("No ResourcePrototype Id provided."); response.setSuccess(false); response.setTotal(0L); }else{ try { ResourceGroup group = ResourceGroup.findResourceGroup(groupId); ArrayList<Metric> metrics = new ArrayList<Metric>(Metric.fromJsonArrayToMetrics(metricsJson)); int len = metrics.size(); for (int i = 0; i < len; i ++) { ResourcePrototype rpt = metrics.get(i).getMetricTemplate().getResourcePrototype(); metrics.get(i).setResourceGroup(group); metrics.get(i).setResourcePrototype(rpt); } metricManager.saveAndUpdateMetrics(metrics); returnStatus = HttpStatus.OK; response.setMessage("All Metric Templates found"); response.setSuccess(true); response.setTotal(0L); response.setData(null); } catch (Exception e) { e.printStackTrace(); returnStatus = HttpStatus.INTERNAL_SERVER_ERROR; response.setMessage(e.getMessage()); response.setSuccess(false); response.setTotal(0L); } } return new ResponseEntity<String>(new JSONSerializer().exclude("*.class").transform(new DateTransformer("MM/dd/yy"), Date.class).serialize(response), returnStatus); } }
package iozip.transactions; import java.io.BufferedOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class TransactionFileManager { public void saveTransactions(Path file, List<Transaction> transactions) { if (file == null) { throw new IllegalArgumentException("File can't be null"); } if (transactions == null) { throw new IllegalArgumentException("Transactions can't be null"); } try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(file)))) { for (Transaction item : transactions) { zip.putNextEntry(new ZipEntry(String.valueOf(item.getId()))); zip.write(item.toString().getBytes()); } } catch (IOException e) { e.printStackTrace(); } } }
package cn.okay.page.officialwebsite.secondpage; import cn.okay.testbase.AbstractPage; import cn.okay.tools.WaitTool; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; /** * Created by yutz on 2018/2/5. *培训机构的机构详情页 */ public class TrainingInstitutionDetailPage extends AbstractPage { @FindBy(css="div[class='desc clearfix auto-h']") WebElement aboutUsElement; @FindBy(xpath = "html/body/div[1]/div[4]/div/div/ul/li[2]/img") WebElement showSchoolImg; public TrainingInstitutionDetailPage(WebDriver driver) { super(driver); WaitTool.waitFor(driver,WaitTool.DEFAULT_WAIT_4_ELEMENT,aboutUsElement); } public void clickSchoolImg(){ moveToElement(driver,showSchoolImg); pageWait(2000); click(showSchoolImg); pageWait(3000); } }
package com.jwebsite.vo; public class RoleRight { private Integer ID;//ID private Integer RoleID;//角色ID private String PurviewCode;//权限名称 private String PurviewValue;//权限值 public Integer getID() { return ID; } public void setID(Integer iD) { ID = iD; } public Integer getRoleID() { return RoleID; } public void setRoleID(Integer roleID) { RoleID = roleID; } public String getPurviewCode() { return PurviewCode; } public void setPurviewCode(String purviewCode) { PurviewCode = purviewCode; } public String getPurviewValue() { return PurviewValue; } public void setPurviewValue(String purviewValue) { PurviewValue = purviewValue; } }
import java.util.*; import java.text.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double payment = scanner.nextDouble(); scanner.close(); NumberFormat enusC = NumberFormat.getCurrencyInstance(Locale.US); NumberFormat zhcnC = NumberFormat.getCurrencyInstance(Locale.CHINA); NumberFormat frfrC = NumberFormat.getCurrencyInstance(Locale.FRANCE); NumberFormat eninC = NumberFormat.getCurrencyInstance( new Locale.Builder().setLanguage("en").setRegion("IN").build()); System.out.println("US: " + enusC.format(payment)); System.out.println("India: " + eninC.format(payment)); System.out.println("China: " + zhcnC.format(payment)); System.out.println("France: " + frfrC.format(payment)); } }
package com.mad.cityassignment; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button playButton, settingsButton; private Settings settings; private static final int REQUEST_CODE_SETTINGS = 0; private static final int REQUEST_CODE_PLAY = 101; private DatabaseInteraction db; private GameData gameData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); playButton = (Button) findViewById(R.id.playButton); settingsButton = (Button) findViewById(R.id.settingsButton); //settings = new Settings(); db = new DatabaseInteraction(this); settings = db.load(); gameData = db.gameLoad(); playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (settings != null) { if (gameData == null) { gameData = new GameData(settings.getMapHeight(), settings.getMapWidth(), settings.getInitialMoney()); } startActivityForResult(MapActivity.getIntent(MainActivity.this, settings, gameData), REQUEST_CODE_PLAY); } else { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Unable to Start!"); builder.setMessage("Please Configure Settings First!"); builder.setCancelable(true); builder.show(); } } }); settingsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(SettingsActivity.getIntent(MainActivity.this, settings), REQUEST_CODE_SETTINGS); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_SETTINGS){ settings = (Settings) data.getSerializableExtra("New_Settings"); db.add(settings); } else if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_PLAY){ gameData = (GameData) data.getSerializableExtra("Game_Data_Update"); db.addGameData(gameData); } else{ System.out.println("ERROR IN LOADING RESULTS"); } } }
package com.forfinance.dao; import com.forfinance.domain.Customer; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static org.junit.Assert.*; public class CustomerDAOTest extends AbstractIntegrationTestCase { @Autowired private CustomerDAO customerDAO; @Test public void testBaseMethods() { // test 'findAll' List<Customer> customers = customerDAO.findAll(); assertEquals(2, customers.size()); Customer source = new Customer(); source.setFirstName("Petr"); source.setLastName("Petrov"); source.setCode("12345678"); // test 'createCustomer' Customer created = customerDAO.create(source); Long createdId = created.getId(); assertNotNull(createdId); customers = customerDAO.findAll(); assertEquals(3, customers.size()); boolean found = false; for (Customer customer : customers) { if ("Petr".equals(customer.getFirstName()) && "Petrov".equals(customer.getLastName()) && "12345678".equals(customer.getCode())) { found = true; } } if (!found) { fail("Customer 'Petr' not found"); } // test 'update' Customer toUpdate = new Customer(); toUpdate.setId(createdId); toUpdate.setFirstName("Ivan"); toUpdate.setLastName("Ivanov"); toUpdate.setCode("987654321"); customerDAO.update(toUpdate); // test 'findById' Customer updated = customerDAO.findById(createdId); assertNotNull(updated); assertEquals("Ivan", updated.getFirstName()); assertEquals("Ivanov", updated.getLastName()); assertEquals("987654321", updated.getCode()); // test 'delete' customerDAO.delete(createdId); customers = customerDAO.findAll(); assertEquals(2, customers.size()); found = false; for (Customer customer : customers) { if ("Petr".equals(customer.getFirstName()) || "Ivan".equals(customer.getFirstName())) { found = true; } } if (found) { fail("Created customer wasn't deleted"); } } }
package com.stylefeng.guns.rest.order.serviceimpl; import com.alibaba.dubbo.config.annotation.Reference; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.cskaoyan.bean.order.OrderInfo; import com.cskaoyan.bean.order.OrderVo; import com.cskaoyan.bean.vo.StatusVo; import com.cskaoyan.bean.vo.Vo; import com.cskaoyan.service.CinemaFieldService; import com.cskaoyan.service.OrderService; import com.cskaoyan.service.UserService; import com.stylefeng.guns.core.util.UuidUtil; import com.stylefeng.guns.rest.order.bean.MoocOrderT; import com.stylefeng.guns.rest.order.dao.MoocOrderTMapper; import com.stylefeng.guns.rest.order.util.Ftputil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @Author: yyc * @Date: 2019/6/8 18:27 */ @Slf4j @Component @com.alibaba.dubbo.config.annotation.Service(interfaceClass = OrderService.class) public class DefaultOrderServiceImpl implements OrderService { @Autowired private MoocOrderTMapper moocOrderTMapper; @Autowired private Ftputil ftputil; @Reference(check = false) private CinemaFieldService cinemaFieldService; @Reference(check = false) private UserService userService; @Override public boolean isTrueSeats(Integer fieldId, String seats) { //获取seats真实地址 String seats_addrress = moocOrderTMapper.getAllSeatsByFieldId(fieldId); String seats_json = ftputil.getFileStrByAddr(seats_addrress); JSONObject jsonObject = JSONObject.parseObject(seats_json); String ids = jsonObject.get("ids").toString(); String[] idsArray = ids.split(","); String[] buy_seats = seats.split(","); //是否是全包括 List<String> validlist = Arrays.asList(idsArray); return validlist.containsAll(Arrays.asList(buy_seats)); } /** * 判断是否包含在已卖出订单中 * @param fieldId * @param seats * @return */ @Override public boolean isAllSeatsUnsold(Integer fieldId, String seats) { String allSoldSeatsStr = moocOrderTMapper.getSoldSeatsByFieldId(fieldId); if (allSoldSeatsStr==null){ allSoldSeatsStr=""; } String[] split = allSoldSeatsStr.split(","); String[] buy_seats = seats.split(","); return !Arrays.asList(split).containsAll(Arrays.asList(buy_seats)); } /** * 创建新订单 * @param fieldId * @param soldSeats * @param seatsName * @param username * @return */ @Override public OrderVo addOrder(Integer fieldId, String soldSeats, String seatsName, String username) { String uuid = UuidUtil.getUuid(); //影片信息 OrderInfo orderInfo = cinemaFieldService.getOrderInfoByFieldId(fieldId); String[] seatids = soldSeats.split(","); //总金额 double totalPrice = getTotalPrice(seatids.length, orderInfo.getPrice()); MoocOrderT moocOrderT = new MoocOrderT(); moocOrderT.setUuid(uuid); moocOrderT.setSeatsName(seatsName); moocOrderT.setSeatsIds(soldSeats); moocOrderT.setOrderUser(userService.getUserIdByUsername(username)); moocOrderT.setOrderPrice(totalPrice); moocOrderT.setFilmPrice(orderInfo.getPrice()+0.0); moocOrderT.setFilmId(orderInfo.getFilmId()); moocOrderT.setFieldId(fieldId); moocOrderT.setCinemaId(orderInfo.getCinemaId()); Integer insert = moocOrderTMapper.insert(moocOrderT); if (insert>0){ //返回查询结果 return moocOrderTMapper.getOrderDetailByOrderId(uuid); }else { log.error("订单插入失败"); return null; } } private double getTotalPrice(int sold,int price){ BigDecimal sold_deci= new BigDecimal(sold); BigDecimal film_price = new BigDecimal(price); BigDecimal result =sold_deci.multiply(film_price); //四舍五入 result.setScale(2, RoundingMode.HALF_UP); return result.doubleValue(); } @Override public List<OrderVo> getOrderByUsername(String username, Integer nowPage, Integer pageSize) { if (username==null || username.trim().length()==0){ log.error("用户订单信息获取失败,用户未传入"); return null; } int userId = userService.getUserIdByUsername(username); Page<OrderVo> page = new Page<>(nowPage,pageSize); List<OrderVo> orderDetailByUserId = moocOrderTMapper.getOrderDetailByUserId(userId,page); if (orderDetailByUserId==null || orderDetailByUserId.size()==0){ orderDetailByUserId = new ArrayList<>(); } return orderDetailByUserId; } @Override public String getSoldSeatsByFieldId(Integer fieldId) { if (fieldId==null){ log.error("查询已售座位错误,未传入任何场次信息"); return ""; } try { return moocOrderTMapper.getSoldSeatsByFieldId(fieldId); } catch (Exception e) { e.printStackTrace(); } return null; } @Override public Vo getPayInfo(String orderId) { return new StatusVo(999,"无法购买"); } }
package mdc.collab.nightreader.activities; /** * @author Jesse Frush */ import java.util.ArrayList; import mdc.collab.nightreader.R; import mdc.collab.nightreader.application.NightReader; import mdc.collab.nightreader.application.NightReader.SortingMode; import mdc.collab.nightreader.singleton.MediaState; import mdc.collab.nightreader.util.Audio; import mdc.collab.nightreader.util.AudioFileGroup; import mdc.collab.nightreader.util.AudioFileInfo; import mdc.collab.nightreader.util.AudioFileInfoAdapter; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnHoverListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.ListView; public class ListViewActivity extends Activity { private static final String TAG = "ListViewActivity"; private static NightReader application; private ListView listView; //the current list of items being displayed private static ArrayList<AudioFileInfo> list; //a state variable for the current sorting mode private static SortingMode mode = SortingMode.SONG; //controls what level of the list we are on. behaviors such as selecting items & the back button depend on this private boolean isMainMenu; @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_list_view ); application = (NightReader) getApplication(); listView = (ListView) findViewById( R.id.AudioListView ); listView.setClickable( true ); listView.setOnItemClickListener( new ItemClickListener() ); //set up the list if( list == null ) { list = application.getAllAudioFiles(); populateListView( list ); isMainMenu = true; } else { populateListView( list ); isMainMenu = false; } switch( mode ) { default: case SONG: sortByTitle( null ); break; case ALBUM: sortByAlbum( null ); break; case ARTIST: sortByArtist( null ); break; } } @Override public boolean onCreateOptionsMenu( Menu menu ) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate( R.menu.list_view, menu ); return true; } /** * override the behavior of the back button, to prevent from automatically exiting * the activity if we are browsing an artist, album, or other */ @Override public void onBackPressed() { //super.onBackPressed(); if( isMainMenu ) finish(); else { sortByTitle( null ); } } /** * the callback method for title sorting button */ public void sortByTitle( View view ) { isMainMenu = true; mode = SortingMode.SONG; list = application.getAllAudioFiles(); NightReader.sortAudioFiles( SortingMode.SONG, list ); populateListView( list ); } /** * the callback method for artist sorting button */ public void sortByArtist( View view ) { list = null; isMainMenu = true; mode = SortingMode.ARTIST; populateListView( application.getArtists() ); } /** * the callback method for album sorting button */ public void sortByAlbum( View view ) { list = null; isMainMenu = true; mode = SortingMode.ALBUM; populateListView( application.getAlbums() ); } /** * the callback method for genre sorting button */ public void sortByGenre( View view ) { //disabled, for now //populateListView( application.getAllAudioFiles() ); } /** * populates the list view with the titles of the given list of audio files */ private <E extends Audio> void populateListView( ArrayList<E> audio ) { AudioFileInfoAdapter arrayAdapter = new AudioFileInfoAdapter( application.getApplicationContext(), audio ); listView.setAdapter( arrayAdapter ); updateButtonIcons(); } /** * re-applies the proper icons to the buttons across the top */ private void updateButtonIcons() { int song = R.drawable.notes; int artist = R.drawable.microphone; int album = R.drawable.record; int genre = R.drawable.book; switch( mode ) { case SONG: song = R.drawable.notes_select; break; case ARTIST: artist = R.drawable.microphone_select; break; case ALBUM: album = R.drawable.record_select; break; case GENRE: genre = R.drawable.book_select; break; default: break; } ((Button) findViewById( R.id.SongTitleButton )).setBackgroundResource( song ); ((Button) findViewById( R.id.ArtistNameButton )).setBackgroundResource( artist ); ((Button) findViewById( R.id.AlbumNameButton )).setBackgroundResource( album ); //((Button) findViewById( R.id.GenreNameButton )).setBackgroundResource( genre ); } private class ItemClickListener implements OnItemClickListener { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { MediaState mediaState = MediaState.getInstance(); if( list != null ) { mediaState.playMedia( list, position ); ListViewActivity.this.finish(); } else //if( isMainMenu )//&& ( sort == Sorting.ALBUM || sort == Sorting.ARTIST ) ) { ArrayList<AudioFileGroup> grouping = ( mode == SortingMode.ALBUM ? application.getAlbums() : application.getArtists() ); list = grouping.get( position ).getItems(); NightReader.sortAudioFiles( SortingMode.SONG, list ); populateListView( list ); isMainMenu = false; } } } }
package com.social.server.controller; import com.social.server.entity.Sex; import com.social.server.http.ErrorCode; import com.social.server.http.Response; import com.social.server.http.model.UserDetailsModel; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit4.SpringRunner; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Date; @RunWith(SpringRunner.class) @WebMvcTest(ProfileController.class) public class ProfileControllerTest extends CommonControllerTest { private UserDetailsModel getUserDetailsModel() { UserDetailsModel detailsModel = new UserDetailsModel(); detailsModel.setId(ID); detailsModel.setName("test"); detailsModel.setSurname("test"); detailsModel.setSex(Sex.MALE); detailsModel.setPhone("+79531851461"); detailsModel.setCity("test"); detailsModel.setAbout("test"); detailsModel.setCountry("test"); detailsModel.setBirthday(LocalDateTime.of(2018, 4, 12, 18, 40, 0)); detailsModel.setBirthday(new Timestamp(new Date().getTime()).toLocalDateTime()); return detailsModel; } @Test public void incorrectBirthdaySaveProfile() throws Exception { UserDetailsModel model = getUserDetailsModel(); model.setBirthday(null); checkPostRequest("/api/v1/" + ID + "/profile", model, Response.error(ErrorCode.DETAILS_BIRTHDAY_INCORRECT)); } //@Test public void successSaveProfile() throws Exception { UserDetailsModel model = getUserDetailsModel(); checkPostRequest("/api/v1/" + ID + "/profile", model, Response.error(ErrorCode.DETAILS_BIRTHDAY_INCORRECT)); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package boletin1_1; import java.util.Scanner; /** * * @author slorenzorodriguez */ public class Boletin1_1 { /** * @param args the command line arguments */ public static void main(String[] args) { //area triangulo = (base*altura)/2 int base=4, altura= 3, area; area = base*altura/2; System.out.println("area = "+area); } }
package com.softwareengineeringapp.kamys.findmean; import android.content.ContentValues; import android.database.Cursor; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class DatabaseHelper extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name public static final String DATABASE_NAME = "Buildings.db"; // Amenities Table name private static final String TABLE_NAME = "Amenities"; // Table Columns names public static final String COL1 = "BUILDING_NAME"; public static final String COL2 = "HAND"; public static final String COL3 = "BATHROOMS"; public static final String COL4 = "ELEVATORS"; public static final String COL5 = "STUDY_AREA"; public static final String COL6 = "LONG"; public static final String COL7 = "LAT"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_AMENITIES_TABLE = "CREATE TABLE " + DATABASE_NAME + "(" + COL1 + " TEXT PRIMARY KEY," //Building Name + COL2 + " TEXT," //Handicap + COL3 + " TEXT," //Bathroom + COL4 + " TEXT," //Elevators + COL5 + " TEXT," //Study Area + COL6 + " TEXT," //Long + COL7 + " TEXT," //Lat + ")"; db.execSQL(CREATE_AMENITIES_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // Creating tables again onCreate(db); } // Adding new Building public void addBuilding(buildingObject building) { SQLiteDatabase db = this.getWritableDatabase(); //SCHEMA: buildingObject(String name, int hand, int bath, int elev, String longi, String lat) ContentValues values = new ContentValues(); values.put(COL1, building.BuildingName()); //Building Name values.put(COL2, building.getHand()); //HandiCap values.put(COL3, building.getBath()); //Bathroom values.put(COL4, building.getElev()); //Elevators values.put(COL5, building.getStudy()); //Study area values.put(COL6, building.getLong()); //Longitude values.put(COL7, building.getLat()); //Latitude // Inserting a new Row db.insert(TABLE_NAME, null, values); db.close(); // Closing database connection } }
package com.windtalker.database.preference; import android.content.Context; import com.windtalker.database.IDatabase; import com.windtalker.database.IDatabaseReference; /** * Created by jaapo on 26-10-2017. */ public class DatabaseLocalPreference implements IDatabase{ private String mDatabaseName; @Override public IDatabaseReference getReference(Context context) { return new DatabaseReferenceLocalPreference(context, mDatabaseName, mDatabaseName) { }; } @Override public void clear() { } }
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.jta; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import jakarta.transaction.UserTransaction; import org.springframework.util.Assert; /** * Adapter for a JTA UserTransaction handle, taking a JTA * {@link jakarta.transaction.TransactionManager} reference and creating * a JTA {@link jakarta.transaction.UserTransaction} handle for it. * * <p>The JTA UserTransaction interface is an exact subset of the JTA * TransactionManager interface. Unfortunately, it does not serve as * super-interface of TransactionManager, though, which requires an * adapter such as this class to be used when intending to talk to * a TransactionManager handle through the UserTransaction interface. * * <p>Used internally by Spring's {@link JtaTransactionManager} for certain * scenarios. Not intended for direct use in application code. * * @author Juergen Hoeller * @since 1.1.5 */ public class UserTransactionAdapter implements UserTransaction { private final TransactionManager transactionManager; /** * Create a new UserTransactionAdapter for the given TransactionManager. * @param transactionManager the JTA TransactionManager to wrap */ public UserTransactionAdapter(TransactionManager transactionManager) { Assert.notNull(transactionManager, "TransactionManager must not be null"); this.transactionManager = transactionManager; } /** * Return the JTA TransactionManager that this adapter delegates to. */ public final TransactionManager getTransactionManager() { return this.transactionManager; } @Override public void setTransactionTimeout(int timeout) throws SystemException { this.transactionManager.setTransactionTimeout(timeout); } @Override public void begin() throws NotSupportedException, SystemException { this.transactionManager.begin(); } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException { this.transactionManager.commit(); } @Override public void rollback() throws SecurityException, SystemException { this.transactionManager.rollback(); } @Override public void setRollbackOnly() throws SystemException { this.transactionManager.setRollbackOnly(); } @Override public int getStatus() throws SystemException { return this.transactionManager.getStatus(); } }
package com.homework.springhomework.loggers; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /*"you can just annotate the class with @Slf4j which will automatically generate a logger for the class without * having to declare a constant. The annotation supplies a static variable called log which provides the logger * utilities by default"*/ @Slf4j @Component public class StartLogger { @Autowired public void warnLevelDisplay() { log.warn("hello"); } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.validation; import org.junit.jupiter.api.Test; import org.springframework.beans.testfixture.beans.TestBean; import org.springframework.validation.DefaultMessageCodesResolver.Format; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultMessageCodesResolver}. * * @author Phillip Webb */ class DefaultMessageCodesResolverTests { private final DefaultMessageCodesResolver resolver = new DefaultMessageCodesResolver(); @Test void shouldResolveMessageCode() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); assertThat(codes).containsExactly("errorCode.objectName", "errorCode"); } @Test void shouldResolveFieldMessageCode() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); assertThat(codes).containsExactly( "errorCode.objectName.field", "errorCode.field", "errorCode.org.springframework.beans.testfixture.beans.TestBean", "errorCode"); } @Test void shouldResolveIndexedFieldMessageCode() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "a.b[3].c[5].d", TestBean.class); assertThat(codes).containsExactly( "errorCode.objectName.a.b[3].c[5].d", "errorCode.objectName.a.b[3].c.d", "errorCode.objectName.a.b.c.d", "errorCode.a.b[3].c[5].d", "errorCode.a.b[3].c.d", "errorCode.a.b.c.d", "errorCode.d", "errorCode.org.springframework.beans.testfixture.beans.TestBean", "errorCode"); } @Test void shouldResolveMessageCodeWithPrefix() throws Exception { resolver.setPrefix("prefix."); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); assertThat(codes).containsExactly("prefix.errorCode.objectName", "prefix.errorCode"); } @Test void shouldResolveFieldMessageCodeWithPrefix() throws Exception { resolver.setPrefix("prefix."); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); assertThat(codes).containsExactly( "prefix.errorCode.objectName.field", "prefix.errorCode.field", "prefix.errorCode.org.springframework.beans.testfixture.beans.TestBean", "prefix.errorCode"); } @Test void shouldSupportNullPrefix() throws Exception { resolver.setPrefix(null); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); assertThat(codes).containsExactly( "errorCode.objectName.field", "errorCode.field", "errorCode.org.springframework.beans.testfixture.beans.TestBean", "errorCode"); } @Test void shouldSupportMalformedIndexField() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field[", TestBean.class); assertThat(codes).containsExactly( "errorCode.objectName.field[", "errorCode.field[", "errorCode.org.springframework.beans.testfixture.beans.TestBean", "errorCode"); } @Test void shouldSupportNullFieldType() throws Exception { String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", null); assertThat(codes).containsExactly( "errorCode.objectName.field", "errorCode.field", "errorCode"); } @Test void shouldSupportPostfixFormat() throws Exception { resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); assertThat(codes).containsExactly("objectName.errorCode", "errorCode"); } @Test void shouldSupportFieldPostfixFormat() throws Exception { resolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName", "field", TestBean.class); assertThat(codes).containsExactly( "objectName.field.errorCode", "field.errorCode", "org.springframework.beans.testfixture.beans.TestBean.errorCode", "errorCode"); } @Test void shouldSupportCustomFormat() throws Exception { resolver.setMessageCodeFormatter((errorCode, objectName, field) -> DefaultMessageCodesResolver.Format.toDelimitedString("CUSTOM-" + errorCode, objectName, field)); String[] codes = resolver.resolveMessageCodes("errorCode", "objectName"); assertThat(codes).containsExactly("CUSTOM-errorCode.objectName", "CUSTOM-errorCode"); } }
package walke.base.tool; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; /** * Created by walke.Z on 2017/8/2. */ public class SetUtil { public static List<String> arrToList(String[] arr){ List<String> list=new ArrayList<>(); if (arr==null||arr.length==0) return list; for (String s : arr) { list.add(s); } return list; } public static void sort(List<Objects> list){ Collections.sort(list, new Comparator<Objects>() { /*  按票箱号排序             * int compare(Student o1, Student o2) 返回一个基本类型的整型,               * 返回负数表示:o1 小于o2,    返回0 表示:o1和o2相等,   返回正数表示:o1大于o2。               */ public int compare(Objects o1, Objects o2) { if (o1.hashCode() > o2.hashCode()) { return 1; } if (o1.hashCode() == o2.hashCode()) { return 0; } return -1; } } ); } }
package fudan.database.project.entity; public class ChiefNurse { private int chiefNurseId; private String name; private String password; private int areaId; public ChiefNurse() { // } public int getChiefNurseId() { return chiefNurseId; } public void setChiefNurseId(int chiefNurseId) { this.chiefNurseId = chiefNurseId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAreaId() { return areaId; } public void setAreaId(int areaId) { this.areaId = areaId; } }
import java.awt.*; import javax.swing.JPanel; /** * @author (ikbiel) * @version (23 March 2015) */ public class FractalTree extends JPanel { // how much smaller branches are private double diffOfSize = .75; // how small branches get private double minSize = 5.0; // angle between branches private double aAngle = Math.toRadians(60); //create panel private final int PANEL_WIDTH = 400; private final int PANEL_HEIGHT = 400; private int current; //current order /** * Default constructor for objects of class FractalTree */ public FractalTree(int currentOrder) { current = currentOrder; setBackground(Color.black); setPreferredSize (new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); } //Draws fractal recursively //if lines are too small, stop program! //Otherwise trunk is drawn, two new branches are computed - //each line segment is drawn as a fractal public void drawFractal(double angle, int x1, int y1, int x2, int y2, Graphics page) { //calculate length double length1 = Math.sqrt((Math.pow(x2-x1, 2))+(Math.pow(y2-y1, 2))); //new branch points int x3, y3; //right int x4, y4; //left //new angles double rightAngle, leftAngle; if(length1<minSize) { return; } else { //draw trunk page.drawLine(x1, y1, x2, y2); //calculate next length double length2 = length1 * diffOfSize; //calculate right branch rightAngle = angle + aAngle; x3 = x2 + (int)(length2*Math.sin(rightAngle)); y3 = y2 + (int)(length2*Math.cos(rightAngle)); //draw right line page.drawLine(x2, y2, x3, y3); //calculate left branch leftAngle = angle - aAngle; x4 = x2 - (int)(length2*Math.sin(leftAngle)); y4 = y2 - (int)(length2*Math.cos(leftAngle)); //draw left line page.drawLine(x2, y2, x4, y4); drawFractal(rightAngle+30, x2, y2, x3, y3, page); drawFractal(leftAngle-30, x2, y2, x4, y4, page); } } public void paintComponent(Graphics page) { super.paintComponent(page); page.setColor(Color.green); //trunk values int startX = 200, startY = 350; int endX = 200, endY = 260; drawFractal(Math.toRadians(90), startX, startY, endX, endY, page); } public void setOrder( int order ) { current = order; } public int getOrder() { return current; } }
package com.networks.ghosttears.fragments; import android.animation.Animator; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Transformation; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.networks.ghosttears.R; import com.networks.ghosttears.activities.Achievements; import com.networks.ghosttears.activities.Home; import com.networks.ghosttears.activities.LoadingScreen; import com.networks.ghosttears.activities.Shop; import com.networks.ghosttears.gameplay_package.GhostTears; import com.networks.ghosttears.gameplay_package.ManagingImages; import com.networks.ghosttears.gameplay_package.ManagingSoundService; import com.networks.ghosttears.user_profiles.GhosttearsUser; import com.networks.ghosttears.user_profiles.LevelAndExp; public class ToolbarFragment extends Fragment { ManagingImages managingImages = new ManagingImages(); private FirebaseAuth mAuth = FirebaseAuth.getInstance(); private FirebaseDatabase firebaseDatabase = GhostTears.firebaseDatabase; ManagingSoundService managingSoundService = new ManagingSoundService(); public ToolbarFragment(){ } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); //update ui accordingly if(GhosttearsUser.currentLevel==0) { updateToolbarDetails(currentUser); }else { setToolbarDetails(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ //Inflate layout for this fragment View view = inflater.inflate(R.layout.fragment_toolbar,container,false); RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.toolbar_background); managingImages.loadToolbarBackground(relativeLayout); ImageView profileImageView = (ImageView) view.findViewById(R.id.user_ghost_image); ImageView goldCoinsImageView = (ImageView) view.findViewById(R.id.gold_coins_imageview); Button addGoldCoinsButton = (Button) view.findViewById(R.id.add_gold_coins); managingImages.loadImageIntoImageview(R.drawable.gold_coins,goldCoinsImageView); managingImages.loadButtonBackground(addGoldCoinsButton,R.drawable.add_button_background); profileImageView.setOnTouchListener(onTouchListener()); profileImageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { managingSoundService.playButtonClickSound(view); Intent intent = new Intent(ToolbarFragment.this.getContext(), Achievements.class); startActivity(intent); //go to achievements } } ); addGoldCoinsButton.setOnTouchListener(onTouchListener()); addGoldCoinsButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { managingSoundService.playButtonClickSound(view); //go to shop or watch ads ((GhostTears) ToolbarFragment.this.getActivity().getApplication()).setShouldPlay(true); Intent shopIntent = new Intent(ToolbarFragment.this.getContext(), Shop.class); shopIntent.putExtra("fragmentToDisplay","getMoreCoinsFragment"); startActivity(shopIntent); } } ); return view; } private View.OnTouchListener onTouchListener(){ View.OnTouchListener onTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { managingImages.powerupsbuttontouched(view,motionEvent); return false; } }; return onTouchListener; } public void updateToolbarDetails(FirebaseUser currentUser){ if(currentUser!=null) { updateDisplayName(currentUser); updateLevelAndExp(currentUser); updateAmountOfCoins(currentUser); } } private void setToolbarDetails(){ TextView displayNameTextview = (TextView) getView().findViewById(R.id.user_display_name); TextView levelUpTextView = (TextView) getView().findViewById(R.id.level); ProgressBar experiencePointsProgress = (ProgressBar) getView().findViewById(R.id.experience_points); TextView amountOfCoinsTextview = (TextView) getView().findViewById(R.id.amount_Of_Coins); displayNameTextview.setText(GhosttearsUser.currentDisplayName); amountOfCoinsTextview.setText(""+GhosttearsUser.currentAmountOfCoins); ImageView levelImageView = (ImageView) getView().findViewById(R.id.user_ghost_image); LevelAndExp gtLevel = new LevelAndExp(); managingImages.loadImageIntoImageview(gtLevel.getLevelsGhostId(GhosttearsUser.currentLevel),levelImageView); String levelString =""+GhosttearsUser.currentLevel; Log.i("ToolbarFragmet",levelString); levelUpTextView.setText(levelString); experiencePointsProgress.setMax(gtLevel.getExpPointsMax(GhosttearsUser.currentLevel)); experiencePointsProgress.setProgress(GhosttearsUser.currentExperiencePoints); } private void updateDisplayName(FirebaseUser user){ DatabaseReference usersReference = firebaseDatabase.getReference().child("users").child(user.getUid()).child("displayName"); usersReference.keepSynced(true); usersReference.addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String displayName = dataSnapshot.getValue(String.class); GhosttearsUser.currentDisplayName = displayName; TextView displayNameTextview = (TextView) getView().findViewById(R.id.user_display_name); displayNameTextview.setText(displayName); } @Override public void onCancelled(DatabaseError databaseError) { } } ); } private void updateLevelAndExp(final FirebaseUser user){ DatabaseReference usersReference = firebaseDatabase.getReference().child("users").child(user.getUid()).child("level"); usersReference.keepSynced(true); usersReference.addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { final int level = dataSnapshot.getValue(Integer.class); //do level up check if(level-GhosttearsUser.currentLevel>0&&level-GhosttearsUser.currentLevel<5&&GhosttearsUser.currentLevel!=0){ final TextView levelUpTextView = (TextView) getView().findViewById(R.id.level_up_textview); levelUpTextView.setVisibility(View.VISIBLE); managingSoundService.playSound(ToolbarFragment.this.getContext(),R.raw.positionstagesound); YoYo.with(Techniques.RubberBand) .duration(1000) .repeat(2) .onEnd(new YoYo.AnimatorCallback() { @Override public void call(Animator animator) { levelUpTextView.setVisibility(View.INVISIBLE); } }) .playOn(levelUpTextView); } GhosttearsUser.currentLevel = level; TextView levelTextview = (TextView) getView().findViewById(R.id.level); String levelString = ""+level; levelTextview.setText(levelString); ImageView levelImageView = (ImageView) getView().findViewById(R.id.user_ghost_image); LevelAndExp gtLevel = new LevelAndExp(); managingImages.loadImageIntoImageview(gtLevel.getLevelsGhostId(level),levelImageView); DatabaseReference usersReference = firebaseDatabase.getReference().child("users").child(user.getUid()).child("experiencePoints"); usersReference.keepSynced(true); usersReference.addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { int experiencePoints = dataSnapshot.getValue(Integer.class); GhosttearsUser.currentExperiencePoints = experiencePoints; ProgressBar experiencePointsProgress = (ProgressBar) getView().findViewById(R.id.experience_points); LevelAndExp gtLevel = new LevelAndExp(); experiencePointsProgress.setMax(gtLevel.getExpPointsMax(level)); ProgressBarAnimation animation = new ProgressBarAnimation(experiencePointsProgress, experiencePointsProgress.getProgress(),experiencePoints); animation.setDuration(1000); experiencePointsProgress.startAnimation(animation); } @Override public void onCancelled(DatabaseError databaseError) { } } ); } @Override public void onCancelled(DatabaseError databaseError) { } } ); } private void updateAmountOfCoins(FirebaseUser user){ DatabaseReference usersReference = firebaseDatabase.getReference().child("users").child(user.getUid()).child("amountOfCoins"); usersReference.keepSynced(true); usersReference.addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { int amountOfCoins = dataSnapshot.getValue(Integer.class); GhosttearsUser.currentAmountOfCoins = amountOfCoins; TextView amountOfCoinsTextview = (TextView) getView().findViewById(R.id.amount_Of_Coins); String amtString = ""+amountOfCoins; amountOfCoinsTextview.setText(amtString); } @Override public void onCancelled(DatabaseError databaseError) { } } ); } private class ProgressBarAnimation extends Animation { private ProgressBar progressBar; private float from; private float to; public ProgressBarAnimation(ProgressBar progressBar, float from, float to) { super(); this.progressBar = progressBar; this.from = from; this.to = to; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); float value = from + (to - from) * interpolatedTime; progressBar.setProgress((int) value); } } }
package com.meehoo.biz.core.basic.concurrency.task; import lombok.Getter; import java.util.concurrent.atomic.AtomicInteger; /** * @author zc * @date 2020-12-31 */ //@Setter @Getter public class TaskResult { private AtomicInteger successQty; private AtomicInteger failedQty; public TaskResult() { this.successQty = new AtomicInteger(); this.failedQty = new AtomicInteger(); } public void success(){ successQty.incrementAndGet(); } public void fail(){ failedQty.incrementAndGet(); } public String getDescription(){ return "成功"+successQty.get()+"个;失败"+failedQty.get()+"个"; } }
package egovframework.adm.fin.service.impl; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.interceptor.TransactionAspectSupport; import com.ziaan.library.CalcUtil; import com.ziaan.library.SQLString; import egovframework.adm.fin.dao.FinishManageDAO; import egovframework.adm.fin.service.FinishManageService; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; import org.apache.log4j.Logger; @Service("finishManageService") public class FinishManageServiceImpl extends EgovAbstractServiceImpl implements FinishManageService{ @Resource(name="finishManageDAO") private FinishManageDAO finishManageDAO; private Logger logger = Logger.getLogger(this.getClass()); public List selectFinishCourseList(Map<String, Object> commandMap) throws Exception{ List list = finishManageDAO.selectFinishCourseList(commandMap); List result = new ArrayList(); if( list != null && list.size() > 0 ){ String Bcourse = ""; String Bcourseseq = ""; for(int i=0; i<list.size(); i++){ Map inputMap = (Map)list.get(i); if( Integer.valueOf(inputMap.get("studentcnt").toString()) > 0 ){ inputMap.put("ses_search_gyear", commandMap.get("ses_search_gyear")); inputMap.put("ses_search_grseq", commandMap.get("ses_search_grseq")); Map tmp = new HashMap(); if( inputMap.get("course") != null && !inputMap.get("course").toString().equals("000000") && !(Bcourse.equals((String)inputMap.get("course")) && Bcourseseq.equals((inputMap.get("courseseq")))) ){ tmp = finishManageDAO.selectPackage(inputMap); tmp.put("isnewcourse", "Y"); }else{ tmp.put("rowspan", 0); tmp.put("cnt", 0); tmp.put("isnewcourse", "N"); } Bcourse = (String)inputMap.get("course"); Bcourseseq = (String)inputMap.get("courseseq"); inputMap.putAll(tmp); result.add(inputMap); } } } return result; } public List selectFinishStudentList(Map<String, Object> commandMap) throws Exception{ if( commandMap.get("p_isclosed").toString().equals("Y") && commandMap.get("p_mgubun").toString().equals("0") ){ commandMap.put("selectTable", "A"); }else{ commandMap.put("selectTable", "B"); } List result = new ArrayList(); List tmp = new ArrayList(); if( commandMap.get("p_isonoff").toString().equals("RC") ){ List list = finishManageDAO.selectFinishStudentList(commandMap); if( list != null && list.size() > 0 ){ for( int i=0; i<list.size(); i++ ){ List list2 = new ArrayList(); List list3 = new ArrayList(); Map map = (Map)list.get(i); tmp = finishManageDAO.selectBookList(map); if( tmp != null && tmp.size() > 0 ){ for(int j=0; j<tmp.size(); j++){ Map m = (Map)tmp.get(j); list2.add(m); } map.put("bookexam_result", list2); } result.add(map); } } }else{ result = finishManageDAO.selectExamList(commandMap); } return result; } public Map SelectSubjseqInfoDbox(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.SelectSubjseqInfoDbox(commandMap); } public List ScoreCntList(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.ScoreCntList(commandMap); } public int getCntBookMonth(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.getCntBookMonth(commandMap); } public int graduatedUpdate(Map<String, Object> commandMap) throws Exception{ int isOk = 1; try{ String sserno = ""; if( commandMap.get("p_isgraduated").toString().equals("Y") ){ Object tmp = finishManageDAO.getCompleteSerno(commandMap); if( tmp != null && !tmp.toString().equals("") ){ sserno = (String)tmp; }else{ sserno = finishManageDAO.getMaxCompleteCode(commandMap); } } commandMap.put("p_sserno", sserno); finishManageDAO.graduatedUpdate(commandMap); if( commandMap.get("p_isgraduated").toString().equals("Y") ){ finishManageDAO.updateStudentSerno(commandMap); } finishManageDAO.updateStudentIsgraduated(commandMap); }catch(Exception ex){ isOk = 0; TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); ex.printStackTrace(); } return isOk; } /** * 수료처리 취소 */ public int subjectCompleteCancel(Map<String, Object> commandMap) throws Exception{ int isOk = 1; try{ //수료정보 삭제 finishManageDAO.deleteStoldTable(commandMap); // 수료 필드 수정 - isclosed = 'Y' commandMap.put("p_isclosed", "N"); finishManageDAO.setCloseColumn(commandMap); // 외주과목 최종확인 N commandMap.put("p_iscpflag", "N"); finishManageDAO.updateIsCpflag(commandMap); commandMap.put("p_isgraduated", "N"); finishManageDAO.updateStudentIsgraduated(commandMap); /** * tz_strout * 강 제약 조건 (해당기수) 등록자 삭제 처리안됨 * afbean.deleteSubjseqStrOut(connMgr, v_subj, v_year, v_subjseq); * FinishBean.java * 2693 Line */ }catch(Exception ex){ isOk = 0; ex.printStackTrace(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } return isOk; } public int updateOutSubjReject(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.updateOutSubjReject(commandMap); } /** * 수료처리 */ public String completeUpdate(Map<String, Object> commandMap) throws Exception{ String resultMsg = "수료처리가 완료되었습니다."; try{ //기간이 지난 수강신청 제약조건 삭제 finishManageDAO.deleteStroutProc(commandMap); finishManageDAO.deleteStroutYear(commandMap); String process = (String)commandMap.get("p_process"); if(process.equals("subjectComplete")){ // 수료처리 완료여부, 학습중 검토 Map subjInfo = finishManageDAO.SelectSubjseqInfoDbox(commandMap); logger.info("subjInfo : " + subjInfo); if( subjInfo.get("isclosed") != null && subjInfo.get("isclosed").equals("Y") ){ TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return "이미 수료처리 되었습니다."; }else if( Integer.valueOf(subjInfo.get("today").toString()) < Integer.valueOf(subjInfo.get("edustart").toString().substring(0, 8))){ TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return "학습시작후 가능합니다."; } //수료정보 삭제 finishManageDAO.deleteStoldTable(commandMap); // 미채점 리포트 갯수 확인 -->온라인 과제로 대체 함 2010.05.20 int v_remainReportcnt = finishManageDAO.chkRemainReport(commandMap); if ( v_remainReportcnt > 0 ) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); return "학습자의 리포트 중 " + String.valueOf(v_remainReportcnt) + " 개가 미채점되었습니다."; } commandMap.put("p_whtest", subjInfo.get("whtest")); commandMap.put("p_wftest", subjInfo.get("wftest")); commandMap.put("p_wmtest", subjInfo.get("wmtest")); commandMap.put("p_wreport", subjInfo.get("wreport")); commandMap.put("p_wetc1", subjInfo.get("wetc1")); commandMap.put("p_wetc2", subjInfo.get("wetc2")); //수료대상자 리스트 List student = finishManageDAO.selectCompleteStudent(commandMap); //수료조건삭제 finishManageDAO.deleteUsergraduated(commandMap); //수료조건 확인 String[] userGraduated = isgraduatedCheck(commandMap, student, subjInfo); commandMap.put("userGraduated", userGraduated); // 컨텐츠타입이 'L'인것은 위탁과정이므로 재산정 필요없음 // 2012.03.21 컨텐츠타입에는 L코드없음. 다른 버전의 프로세스인듯 // 'L'일경우 student 테이블의 graduated만 업데이트함. if( !subjInfo.get("contenttype").toString().equals("L") ){ finishManageDAO.updateCompleteStudent(commandMap); } //수료정보 등록 finishManageDAO.insertStoldTable(commandMap); //수강생 수료증번호 발급 finishManageDAO.updateStudentSernoAll(commandMap); /** * tz_strout * 수강신청 제약정보등록 처리안됨 * afbean.insertSubjseqStrOut(connMgr, box, v_userid, data.getName(), subjseqdata.getEduend().substring(0, 8), v_year, v_subj, v_subjseq ); * FinishBean.java * 2158 Line */ // 수료 필드 수정 - isclosed = 'Y' commandMap.put("p_isclosed", "Y"); finishManageDAO.setCloseColumn(commandMap); } }catch(Exception ex){ resultMsg = "실패하였습니다."; TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); ex.printStackTrace(); } return resultMsg; } public int subjectCompleteRerating(Map<String, Object> commandMap) throws Exception{ int isOk = 1; try{ // 수료처리 완료여부, 학습중 검토 Map subjInfo = finishManageDAO.SelectSubjseqInfoDbox(commandMap); logger.info(" subjInfo : " + subjInfo); if( subjInfo.get("isclosed") != null && subjInfo.get("isclosed").equals("Y") ){ return -1; //이미 수료처리 되었습니다. }else if( Integer.valueOf(subjInfo.get("today").toString()) < Integer.valueOf(subjInfo.get("edustart").toString().substring(0, 8))){ return -2; //학습시작후 가능합니다. } commandMap.put("p_whtest", subjInfo.get("whtest")); commandMap.put("p_wftest", subjInfo.get("wftest")); //가중치(%) 온라인시험 commandMap.put("p_wmtest", subjInfo.get("wmtest")); //가중치(%) 출석시험 commandMap.put("p_wreport", subjInfo.get("wreport")); //가중치(%) 온라인과제 commandMap.put("p_wetc1", subjInfo.get("wetc1")); //수료기준 참여도(출석일) commandMap.put("p_wetc2", subjInfo.get("wetc2")); //가중치 참여도(출석일) //수료대상자 리스트 List student = finishManageDAO.selectCompleteStudent(commandMap); //수료조건삭제 finishManageDAO.deleteUsergraduated(commandMap); //수료조건 확인 String[] userGraduated = isgraduatedCheck(commandMap, student, subjInfo); commandMap.put("userGraduated", userGraduated); // 컨텐츠타입이 'L'인것은 위탁과정이므로 재산정 필요없음 // 2012.03.21 컨텐츠타입에는 L코드없음. 다른 버전의 프로세스인듯 // 'L'일경우 student 테이블의 graduated만 업데이트함. if( !subjInfo.get("contenttype").toString().equals("L") ){ finishManageDAO.updateCompleteStudent(commandMap); } finishManageDAO.updateRecalcudate(commandMap); }catch(Exception ex){ isOk = -99; TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); ex.printStackTrace(); } return isOk; } public List suRoyJeungPrintList(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.suRoyJeungPrintList(commandMap); } public int subjectComplete3(Map<String, Object> commandMap) throws Exception{ int isOk = 1; String pattern = "######.##"; DecimalFormat dformat = new DecimalFormat(pattern); try{ //Editlink set finishManageDAO.updateStudentEditlink(commandMap); Vector verscore = new Vector(); Vector vervar = new Vector(); Vector verscore2 = new Vector(); Vector vervar2 = new Vector(); Vector verrslt = new Vector(); Vector verrsltcnt = new Vector(); //80점~90점까지 조견표 List list = finishManageDAO.selectScoreVarList(commandMap); System.out.println("list.size() ---------> "+list.size()); if( list != null ){ for( int i=0; i<list.size(); i++ ){ Map m = (Map)list.get(i); verscore2.add(m.get("score")); vervar2.add(m.get("var")); System.out.println("verscore2 score ---------> "+m.get("score")); System.out.println("vervar2 var ---------> "+m.get("var")); } } //tz_crt_var List list2 = finishManageDAO.selectCrtVarList(commandMap); if( list2 != null ){ for( int i=0; i<list2.size(); i++ ){ Map m = (Map)list2.get(i); verrslt.add(m.get("verrslt")); verrsltcnt.add(m.get("cnt")); System.out.println("verrslt verrslt ---------> "+m.get("verrslt")); //null System.out.println("verrsltcnt cnt ---------> "+m.get("cnt")); } } //tz_student 60이상 int mem_cnt = finishManageDAO.selectStudentTotalCnt(commandMap); System.out.println("mem_cnt ---------> "+mem_cnt); //tz_crt_var int vcnt = finishManageDAO.selectVarSumCnt(commandMap); System.out.println("vcnt ---------> "+vcnt); int getTotRecCnt =mem_cnt; int get1stCnt = vcnt; int gap_num = 0; float max_num = 0.0F; float min_num = 0.0F; System.out.println("verscore2.size() ---------> "+verscore2.size()); float rate[] = new float[verscore2.size()]; int rnd[] = new int[verscore2.size()]; //80점~90점까지 조견표 for(int i = 0; i < verscore2.size(); i++){ rate[i] = Float.parseFloat(vervar2.elementAt(i).toString()); //조견표 점수의 값 //(조견표값*(tz_student 60이상인원/100))+0.5 rnd[i] = (int)((double)((Float.parseFloat(vervar2.elementAt(i).toString()) * (float)getTotRecCnt) / 100F) + 0.5D); System.out.println("rate[i] "+ i +" ---------> "+rate[i]); System.out.println("rnd[i] "+ i +" ---------> "+rnd[i]); } if(rnd[10] == 0) rnd[10] = 1; get1stCnt = 0; for(int i = 0; i < 11; i++){ get1stCnt += rnd[i] * 2; System.out.println("for get1stCnt ---------> "+get1stCnt); } System.out.println("get1stCnt ---------> "+get1stCnt); System.out.println("get1stCnt ---------> "+get1stCnt); get1stCnt -= rnd[10]; System.out.println("get1stCnt 2222 ---------> "+get1stCnt); System.out.println("getTotRecCnt ---------> "+getTotRecCnt); int lst[] = new int[11]; int snd[] = new int[11]; if(get1stCnt == getTotRecCnt){ for(int i = 0; i < 11; i++){ lst[i] = rnd[i]; System.out.println("rnd[i] ---------> "+rnd[i]); } } else{ snd = new int[11]; System.out.println("getTotRecCnt ---------> "+getTotRecCnt); System.out.println("get1stCnt ---------> "+get1stCnt); if((getTotRecCnt - get1stCnt) % 2 != 0){ System.out.println("snd[10] ---------> "+snd[10]); snd[10] = snd[10] + 1; System.out.println("snd[10] 222---------> "+snd[10]); get1stCnt++; System.out.println("get1stCnt 222---------> "+get1stCnt); } float gap[] = new float[11]; for(int i = 0; i < 10; i++){ System.out.println("(float)rnd[i] "+ i +" ---------> "+(float)rnd[i]); System.out.println("rate[i] "+ i +" ---------> "+rate[i]); System.out.println("(float)getTotRecCnt) "+ i +" ---------> "+(float)getTotRecCnt); gap[i] = (float)rnd[i] - (rate[i] * (float)getTotRecCnt) / 100F; System.out.println("gap[i] ---------> "+gap[i]); } System.out.println("get1stCnt ---------> "+get1stCnt); System.out.println("getTotRecCnt ---------> "+getTotRecCnt); if(get1stCnt - getTotRecCnt > 0) for(; get1stCnt - getTotRecCnt > 0; get1stCnt -= 2){ gap_num = 9; max_num = 0.0F; for(int i = 9; i >= 0; i--) if((gap[i] > max_num) & (snd[i] == 0)){ max_num = gap[i]; gap_num = i; System.out.println("max_num "+i+" ---------> "+max_num); System.out.println("gap_num "+i+" ---------> "+gap_num); } snd[gap_num] = -1; } else for(; get1stCnt - getTotRecCnt < 0; get1stCnt += 2){ gap_num = 9; min_num = 0.0F; for(int i = 9; i >= 0; i--) if((gap[i] < min_num) & (snd[i] == 0)){ min_num = gap[i]; gap_num = i; System.out.println("max_num "+i+" ---------> "+min_num); System.out.println("gap_num "+i+" ---------> "+gap_num); } snd[gap_num] = 1; } } lst = new int[11]; for(int i = 0; i < 11; i++){ lst[i] = rnd[i] + snd[i]; System.out.println("rnd[i] ---------> "+rnd[i]); System.out.println("snd[i] ---------> "+snd[i]); } finishManageDAO.deleteLank(commandMap); int lank = 1; for(int i = 0; i <= 10; i++){ for(int j = 1; j < lst[i]; j++){ commandMap.put("lst", lst[i]); commandMap.put("score", 100 - i); finishManageDAO.setNum(commandMap); System.out.println("lst 100 i :"+ i +" j :"+ j +"---------> "+commandMap.get("lst")); System.out.println("score 100 i :"+ i +" j :"+ j +" ---------> "+commandMap.get("score")); } for(int j = 0; j < lst[i]; j++){ commandMap.put("lank", lank++); commandMap.put("score", 100 - i); finishManageDAO.setLank(commandMap); System.out.println("lank 100 i :"+ i +" j :"+ j +"---------> "+commandMap.get("lank")); System.out.println("score 100 i :"+ i +" j :"+ j +" ---------> "+commandMap.get("score")); } } for(int i = 9; i >= 0; i--){ for(int j = 1; j <= lst[i]; j++){ commandMap.put("lst", lst[i]); commandMap.put("score", 80 + i); finishManageDAO.setNum(commandMap); System.out.println("lst 80 i :"+ i +" j :"+ j +"---------> "+commandMap.get("lst")); System.out.println("lst 80 i :"+ i +" j :"+ j +"---------> "+commandMap.get("lst")); } for(int j = 1; j <= lst[i]; j++){ commandMap.put("lank", lank++); commandMap.put("score", 80 + i); finishManageDAO.setLank(commandMap); System.out.println("lank 80 i :"+ i +" j :"+ j +" ---------> "+commandMap.get("lank")); System.out.println("score 80 i :"+ i +" j :"+ j +"---------> "+commandMap.get("score")); } } // TZ_CRT_LOG_TBL 테이블 ( 연수성적 분포 조건표 테이블)을 읽어온다. list = finishManageDAO.selectScoreList(commandMap); if( list != null ){ for(int i=0; i<list.size(); i++){ Map m = (Map)list.get(i); verscore.add(m.get("score")); vervar.add(m.get("var")); System.out.println("verscore "+ i +" ---------> "+m.get("score")); System.out.println("vervar "+ i +" ---------> "+m.get("var")); } } int ch_cnt = finishManageDAO.selectCrtVarCount(commandMap); System.out.println("ch_cnt ---------> "+ch_cnt); if( ch_cnt > 0 ){ finishManageDAO.deleteCrtVar(commandMap); } System.out.println(" verscore.size() ---------> "+ verscore.size()); double d1 =0; double d2 =0; double d3 =0; // 1.2번의 데이터를 가지고 와서 TZ_CRT_VAR 조정표 테이블에 insert 한다. for(int i =0; i < verscore.size(); i++){ d1 = Double.parseDouble(vervar.elementAt(i).toString()); System.out.println(" d1 ---------> "+ d1); d2 = Double.parseDouble(vervar.elementAt(i).toString()); System.out.println(" d2 ---------> "+ d2); d3 = Double.parseDouble(dformat.format(d2)); System.out.println(" d3 ---------> "+ d3); System.out.println(" score ---------> "+ verscore.elementAt(i).toString()); System.out.println(" var ---------> "+ vervar.elementAt(i).toString()); System.out.println(" mem_cnt ---------> "+ mem_cnt); Map input = new HashMap(); input.put("p_subj", commandMap.get("p_subj")); input.put("p_year", commandMap.get("p_year")); input.put("p_subjseq", commandMap.get("p_subjseq")); input.put("score", verscore.elementAt(i).toString()); input.put("var", vervar.elementAt(i).toString()); input.put("ratio", Math.round(mem_cnt* d3)/100); input.put("prv_num", Math.round(mem_cnt* d1)/100); input.put("rslt", Math.abs( Math.round(mem_cnt* d3)/100- Math.round(mem_cnt* d1)/100 ) ); finishManageDAO.insertCrtVar(input); System.out.println(" ratio ---------> "+ input.get("ratio")); System.out.println(" prv_num ---------> "+ input.get("prv_num")); System.out.println(" rslt ---------> "+ input.get("rslt")); } //저장된 lank를 가지고 tz_student의 link와 edit_score에 업뎃한다. finishManageDAO.updateStudentEditscore(commandMap); }catch(Exception ex){ isOk = 0; TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); ex.printStackTrace(); } return isOk; } // 수료조건 확인 public String[] isgraduatedCheck(Map commandMap, List list, Map subjInfo) throws Exception{ String[] result = new String[list.size()]; if( list != null && list.size() > 0 ){ for(int i=0; i<list.size(); i++){ Map data = (Map)list.get(i); String v_notgraducd = ""; String isgraduated = ""; double score = returnDouble(data.get("score")); //학습창 학습 진도율 변수.. double compJindo = returnDouble(subjInfo.get("ratewbt")); //수료진도율 if(compJindo < 50.0) { compJindo = 90.0; } else if(compJindo > 99.0) { compJindo = 100.0; } // if(subjInfo.get("upperclass") != null && subjInfo.get("upperclass").equals("PAR")) //학부모연수이면 진도율 50%이다.. // { // compJindo = 50.0; // } // if( score > 100){ score = 100; } // 총점 체크 if ( score < returnDouble(subjInfo.get("gradscore")) ) { v_notgraducd += "06,"; // 06 = 성적미달 - 총점점수 체크 } // 진도율 90 %이하 tz_subj.ratewbt ============================================================== if ( returnDouble(data.get("tstep")) < compJindo ) { v_notgraducd += "10,"; // 10 = 진도율미달 } // wetc2 참여도(학습진도율) if ( returnDouble(data.get("wetc2")) > 0 ) { if( ((subjInfo.get("isonoff").toString().equals("ON") || subjInfo.get("isonoff").toString().equals("RC")) && returnDouble(subjInfo.get("wetc1")) > returnDouble(data.get("avetc2")) && returnDouble(data.get("avetc2"))!=0 ) // (진도율*참여도(학습진도율))/100 = round(etc2 * wetc2, 2)/100 || (subjInfo.get("isonoff").toString().equals("OFF") && returnDouble(subjInfo.get("wetc1")) > returnDouble(data.get("etc2")) ) //출석점수 ){ v_notgraducd += "20,"; } } // 2008.12.13 수정 // 평가 제출여부(05) commandMap.put("pp_userid", data.get("userid")); if ("N".equals( (String)data.get("examFlag") )) { //v_notgraducd += "05,"; // 05 = 평가 미제출 } //출석시험 if ( returnDouble(data.get("mtest")) < returnDouble(subjInfo.get("gradexam")) ) { //v_notgraducd += "07,"; // 07 = 평가점수미달 } if ( returnDouble(data.get("htest")) < returnDouble(subjInfo.get("gradhtest")) ) { //v_notgraducd += "07,"; // 07 = 평가점수미달 } //온라인시험 if ( returnDouble(data.get("ftest")) < returnDouble(subjInfo.get("gradftest")) ) { //v_notgraducd += "07,"; // 07 = 평가점수미달 } //온라인과제 if ( returnDouble(data.get("report")) < returnDouble(subjInfo.get("gradreport")) ) { //v_notgraducd += "08,"; // 08 = 리포트점수미달 } //참여도(출석점수) // if ( returnDouble(data.get("etc2")) == 0 ) { // v_notgraducd += "13,"; // 13 = 출석점수미달 // } /* // 2008.12.13 수정 // 이러닝과정 - 수료기준(접속횟수, 학습시간)에 부합하는지 확인 if (subjseqdata.getIsonoff().equals("ON")) { // 학습횟수(09) if ( "N".equals(getStudyCountYn(connMgr, p_subj, p_year, p_subjseq, p_userid, subjseqdata))) { v_notgraducd += "09,"; // 09 = 학습횟수미달 } // 접속시간(12) if ( "N".equals(getStudyTimeYn(connMgr, p_subj, p_year, p_subjseq, p_userid, subjseqdata))) { v_notgraducd += "12,"; // 12 = 접속시간미달 } } */ if ( !v_notgraducd.equals("") ) { v_notgraducd = v_notgraducd.substring(0,v_notgraducd.length()-1); } //log.info(" ++++++++++++++++ " + score + " / " + returnDouble(subjInfo.get("gradscore")) + " || " + returnDouble(data.get("tstep")) + " / " + returnDouble(subjInfo.get("gradstep")) + " || " + v_notgraducd.length()); //System.out.println(" gradexam ---> "+returnDouble(subjInfo.get("gradexam"))); //System.out.println(" mstep ---> "+returnDouble(data.get("mstep"))); //System.out.println(" avmtest ---> "+returnDouble(data.get("avmtest"))); //System.out.println(" avetc2 ---> "+returnDouble(data.get("avetc2"))); // if ( score >= returnDouble(subjInfo.get("gradscore")) //총점 && returnDouble(data.get("tstep")) >= returnDouble(subjInfo.get("gradstep")) //진도율 && v_notgraducd.length() == 0 && ( ((subjInfo.get("isonoff").toString().equals("ON") || subjInfo.get("isonoff").toString().equals("RC")) && returnDouble(subjInfo.get("gradexam")) <= returnDouble(data.get("avmtest"))) // && data.getGradexamcnt() > 0 // 수료기준 - 출석시험 <= 가중치적용 출석시험 //기존mstep || subjInfo.get("isonoff").toString().equals("OFF") ) && ( ( ((subjInfo.get("isonoff").toString().equals("ON") || subjInfo.get("isonoff").toString().equals("RC")) && returnDouble(subjInfo.get("gradftest")) <= returnDouble(data.get("avftest")) ) //&& data.getGradftestcnt() > 0 //수료기준 - 온라인시험 <= examtype= 'E' 온라인평가 시험점수 //기존ftest || (subjInfo.get("isonoff").toString().equals("OFF") && returnDouble(subjInfo.get("gradftest")) <= returnDouble(data.get("ftest")) ) //&& data.getFtest() > 0 ) ) && ( ( ((subjInfo.get("isonoff").toString().equals("ON") || subjInfo.get("isonoff").toString().equals("RC")) && returnDouble(subjInfo.get("gradreport")) <= returnDouble(data.get("avreport")) ) //&& data.getGradreportcnt()> 0 // 수료기준 - 온라인과제 <= 과제점수 //기존report || (subjInfo.get("isonoff").toString().equals("OFF") && returnDouble(subjInfo.get("gradreport")) <= returnDouble(data.get("report")) ) //&& data.getReport() > 0 ) ) ) { // 전체 조건에 맞으면 수료 isgraduated = "Y"; } else { isgraduated = "N"; //미수료 시 U로 한다. } // 기타 조건으로 미수료 if ( (isgraduated).equals("")) { isgraduated = "N"; } result[i] = data.get("userid")+"!_"+v_notgraducd+"!_"+isgraduated; //수료정보 insert commandMap.put("notgraducd", v_notgraducd); commandMap.put("isgraduated", isgraduated); commandMap.put("usergraduated", result[i]); finishManageDAO.insertUsergraduated(commandMap); } } return result; } public double returnDouble(Object obj){ double ddb = 0.00; try{ ddb = Double.parseDouble(obj.toString()); } catch (Exception e) { return ddb; } return ddb; } /** * 개인별 수료리스트 - 모바일용 * @return * @exception Exception */ public List selectMblUserSuryuList(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.selectMblUserSuryuList(commandMap); } /** * 이수관리 > 과거이수내역리스트 * @return * @exception Exception */ public List selectfinishOldList(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.selectfinishOldList(commandMap); } /** * 이수관리 > 과거이수내역리스트 전체개수 * @return * @exception Exception */ public int selectfinishOldListTotCnt(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.selectfinishOldListTotCnt(commandMap); } /** * 나의학습방 > 나의 교육이력 > 과거이수내역리스트(사용자) * @return * @exception Exception */ public List selectUserFinishOldList(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.selectUserFinishOldList(commandMap); } /** * 이수관리 > 과거이수내역 보기 * @return * @exception Exception */ public Map selectFinishOldView(Map<String, Object> commandMap) throws Exception{ return finishManageDAO.selectFinishOldView(commandMap); } /** * 이수관리 > 과거이수내역 삭제 * @return * @exception Exception */ public int deleteFinishOld(Map<String, Object> commandMap) throws Exception{ int cnt = 0; try{ cnt = finishManageDAO.deleteFinishOld(commandMap); } catch (Exception e) { return 0; } return cnt; } /** * 이수관리 > 과거이수내역 등록 * @return * @exception Exception */ public void insertFinishOld(Map<String, Object> commandMap) throws Exception{ finishManageDAO.insertFinishOld(commandMap); } /** * 이수관리 > 과거이수내역 수정 * @return * @exception Exception */ public int updateFinishOld(Map<String, Object> commandMap) throws Exception{ int cnt = 0; try{ cnt = finishManageDAO.updateFinishOld(commandMap); } catch (Exception e) { return 0; } return cnt; } /** * 이수관리 엑셀출력 */ public List finishStudentExcelList(Map<String, Object> commandMap) throws Exception { return finishManageDAO.finishStudentExcelList(commandMap); } //수료증 출력여부 public int suroyprintYnUpdate(Map<String, Object> commandMap) throws Exception{ int isOk = 1; try{ finishManageDAO.suroyprintYnUpdate(commandMap); }catch(Exception ex){ isOk = 0; TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); ex.printStackTrace(); } return isOk; } }
package dk.webbies.tscreate.paser.AST; import com.google.javascript.jscomp.parsing.parser.util.SourceRange; import dk.webbies.tscreate.paser.ExpressionVisitor; /** * Created by Erik Krogh Kristensen on 01-09-2015. */ public abstract class Expression extends AstNode { Expression(SourceRange location) { super(location); } public abstract <T> T accept(ExpressionVisitor<T> visitor); }
package com.ua.dekhtiarenko.webapp.db.entity; /** * User entity. * Created by Dekhtiarenko-Daniil on 25.02.2021. */ public class User { private int id; private String email; private String name; private String surname; private boolean librarian; private boolean admin; private boolean blocked; private String password; public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public boolean getLibrarian() { return librarian; } public void setLibrarian(boolean librarian) { this.librarian = librarian; } public boolean getAdmin() { return admin; } public void setAdmin(boolean admin) { this.admin = admin; } public boolean getBlocked() { return blocked; } public void setBlocked(boolean blocked) { this.blocked = blocked; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", email='" + email + '\'' + ", name='" + name + '\'' + ", surname='" + surname + '\'' + ", librarian=" + librarian + ", admin=" + admin + ", blocked=" + blocked + ", password='" + password + '\'' + '}'; } }
package br.com.murilokakazu.ec7.ftt.cefsa.domain.specifications; import br.com.murilokakazu.ec7.ftt.cefsa.domain.model.Account; import br.com.murilokakazu.ec7.ftt.cefsa.domain.model.Account_; import org.springframework.data.jpa.domain.Specification; import java.util.ArrayList; import java.util.List; import static br.com.murilokakazu.ec7.ftt.cefsa.domain.specifications.SpecificationsHelper.*; public class AccountSpecifications { public static Specification<Account> matching(Account prototype) { List<Specification<Account>> specifications = new ArrayList<>(); if (prototype.getId() != null) { specifications.add(isFieldEqual(Account_.ID, prototype.getId())); } if (prototype.getName() != null) { specifications.add(isFieldEqual(Account_.NAME, prototype.getName())); } if (prototype.getEmail() != null) { specifications.add(isFieldEqual(Account_.EMAIL, prototype.getEmail())); } return satisfyingAll(specifications); } public static Specification<Account> matching(String query) { return fieldContains(Account_.NAME, query); } }
package pl.basistam.soa.parkingSpaceSensor.client; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebServiceClient(name = "ParkingSensorsService", targetNamespace = "http://webService.main.soa.basistam.pl", wsdlLocation = "file:/home/marcin/Documents/soa/Project/MainSystem/src/main/java/pl/basistam/soa/main/webService/ParkingSensorsService.wsdl") public class ParkingSensorsService_Service extends Service { private final static URL PARKINGSENSORSSERVICE_WSDL_LOCATION; private final static WebServiceException PARKINGSENSORSSERVICE_EXCEPTION; private final static QName PARKINGSENSORSSERVICE_QNAME = new QName("http://webService.main.soa.basistam.pl", "ParkingSensorsService"); static { URL url = null; WebServiceException e = null; try { url = new URL("file:/home/marcin/Documents/soa/Project/MainSystem/src/main/java/pl/basistam/soa/main/webService/ParkingSensorsService.wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } PARKINGSENSORSSERVICE_WSDL_LOCATION = url; PARKINGSENSORSSERVICE_EXCEPTION = e; } public ParkingSensorsService_Service() { super(__getWsdlLocation(), PARKINGSENSORSSERVICE_QNAME); } public ParkingSensorsService_Service(WebServiceFeature... features) { super(__getWsdlLocation(), PARKINGSENSORSSERVICE_QNAME, features); } public ParkingSensorsService_Service(URL wsdlLocation) { super(wsdlLocation, PARKINGSENSORSSERVICE_QNAME); } public ParkingSensorsService_Service(URL wsdlLocation, WebServiceFeature... features) { super(wsdlLocation, PARKINGSENSORSSERVICE_QNAME, features); } public ParkingSensorsService_Service(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public ParkingSensorsService_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { super(wsdlLocation, serviceName, features); } /** * * @return * returns ParkingSensorsService */ @WebEndpoint(name = "ParkingSensorsService") public ParkingSensorsService getParkingSensorsService() { return super.getPort(new QName("http://webService.main.soa.basistam.pl", "ParkingSensorsService"), ParkingSensorsService.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns ParkingSensorsService */ @WebEndpoint(name = "ParkingSensorsService") public ParkingSensorsService getParkingSensorsService(WebServiceFeature... features) { return super.getPort(new QName("http://webService.main.soa.basistam.pl", "ParkingSensorsService"), ParkingSensorsService.class, features); } private static URL __getWsdlLocation() { if (PARKINGSENSORSSERVICE_EXCEPTION!= null) { throw PARKINGSENSORSSERVICE_EXCEPTION; } return PARKINGSENSORSSERVICE_WSDL_LOCATION; } }
package com.tibco.as.util.file; import java.io.File; import org.junit.Assert; import org.junit.Test; public class TestFileUtils { private final static File FILE = new File( "/var/folders/tc/p_m_vk0d4yq3rdh3xw6qhf4w0000gq/T/com.tibco.as.util.Utils16978879243791375571414646018657/space1.csv"); @Test public void testGetBaseName() { Assert.assertEquals("report.sdfsdf", FileUtils.getBaseName("report.sdfsdf.xls")); Assert.assertEquals("space1", FileUtils.getBaseName(FILE)); } @Test public void testGetExtension() { Assert.assertEquals("csv", FileUtils.getExtension(FILE)); } }
//time: O(c) c: totel content of words //space:O(1) class Solution { public boolean isAlienSorted(String[] words, String order) { int[] index = new int[26]; for(int i = 0; i < order.length(); i++){ index[order.charAt(i) - 'a'] = i; } for(int i = 0; i < words.length - 1; i++){ int len = Math.min(words[i].length(), words[i+1].length()); for(int j = 0; j < len; j++){ if(words[i].charAt(j) != words[i+1].charAt(j)){ if(index[words[i].charAt(j) - 'a'] > index[words[i+1].charAt(j) - 'a']) return false; else len = -1; } } if(len != -1 && words[i].length() > words[i+1].length()) return false; } return true; } }
/** * Lab2 - simple object oriented program in java * * @author Muhammad Faizan Ali(100518916) * @version 1.0 */ public class Song { // variables required by the class private String artist; private String title; private int duration; public static String collectionName; // common for all instances of instances of the song class //constructor requires the value for artist title and duration when u make instance of this class public Song(String artist, String title, int duration){ this.artist = artist; this.title = title; this.duration = duration; } /** * @return the artist */ public String getArtist() { return artist; } /** * @param artist the artist to set */ public void setArtist(String artist) { this.artist = artist; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the duration */ public int getDuration() { return duration; } /** * @param duration the duration to set */ public void setDuration(int duration) { this.duration = duration; } public static void main(String [] args){ Song sed = new Song("The Ramones", "I Wanna be Sedated", 148); Song one = new Song("Draft Punk", "One More Time", 322); sed.collectionName = "Randy's Collection"; System.out.println("Collection: " + one.collectionName); printSong(sed); printSong(one); } public static void printSong(Song song){ int min = song.getDuration()/60; int sec = song.getDuration()%60; System.out.printf("%s (%s) ­ %d:%d\n", song.getTitle(), song.getArtist(), min, sec); } }
package com.example.logsys.controller; import com.example.logsys.entity.Log; import com.example.logsys.entity.LogVo; import com.example.logsys.service.LogService; import com.example.logsys.util.DownloadFileUtil; import com.example.logsys.util.GetServerRealPathUnit; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; @Slf4j @RestController @RequestMapping("/file") public class FileController extends BaseController{ // /** 文件存放路径 */ // @Value("${file.path}") // private String path; @Autowired private LogService logService; /** * 下载模板 * @return 返回excel模板 */ // @RequestMapping(value = "/download", method = RequestMethod.POST, produces ="application/json;charset=UTF-8") // @ResponseBody // public Object download(@RequestBody LogVo logVo ){ // ResponseEntity<InputStreamResource> response = null; // try { // if (logVo != null){ // String filePath = GetServerRealPathUnit.getPath("upload"); // String fileName = logVo.getFileName(); // response = DownloadFileUtil.download(filePath,fileName,"log"); // }else { // log.error("没有可供下载的文件!"); // } // // } catch (Exception e) { // log.error("下载失败"); // } //// String fileName = logVo.getFileName(); //// String filePath = GetServerRealPathUnit.getPath("upload"); //// // 获取文件全路径 //// File file = new File(filePath + fileName); //// // 判断是否存在磁盘中 //// if (file.exists()) { //// // 设置强制下载不打开 //// response.setContentType("application/force-download"); //// // 设置文件名 //// response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); //// byte[] buffer = new byte[1024]; //// FileInputStream fis = null; //// BufferedInputStream bis = null; //// try { //// fis = new FileInputStream(file); //// bis = new BufferedInputStream(fis); //// OutputStream os = response.getOutputStream(); //// int i = bis.read(buffer); //// while (i != -1) { //// os.write(buffer, 0, i); //// i = bis.read(buffer); //// } //// return this.outPutData("下载成功"); //// } catch (Exception e) { //// e.printStackTrace(); //// } finally { //// if (bis != null) { //// try { //// bis.close(); //// } catch (IOException e) { //// e.printStackTrace(); //// } //// } //// if (fis != null) { //// try { //// fis.close(); //// } catch (IOException e) { //// e.printStackTrace(); //// } //// } //// } //// } else { //// return this.outPutErr("数据库查询存在,本地磁盘不存在文件"); //// } //// //// // return response; // } @Transactional(readOnly = false,rollbackFor = Exception.class) @RequestMapping(value = "/download", method = RequestMethod.POST, produces ="application/json;charset=UTF-8") @ResponseBody public ResponseEntity<byte[]> serveFile(@RequestBody LogVo logVo) { String fileName = logVo.getFileName(); if(StringUtils.isEmpty(fileName)){ log.info("************文件不存在**************"); } String filePath = GetServerRealPathUnit.getPath("upload"); File file = new File(filePath + fileName); HttpHeaders headers = new HttpHeaders();// 设置一个head headers.setContentDispositionFormData("attachment", fileName);// 文件的属性,也就是文件叫什么吧 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);// 内容是字节流 try { return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);// 开始下载 } catch (IOException e) { e.printStackTrace(); } return null; } /** * 单文件上传 * @return */ @PostMapping("/upload") public String upload(@RequestParam(value="file",required=false) MultipartFile file , HttpServletRequest request){ log.info("************************开始上传文件****************************"); String imei = request.getParameter("imei"); log.info("******imei:"+ imei); if (StringUtils.isEmpty(imei)){ return this.outPutErr("参数有误,imei不能为空!"); } String exceptionName = request.getParameter("exceptionName"); log.info("******exceptionName:"+ exceptionName); if (StringUtils.isEmpty(exceptionName)){ return this.outPutErr("参数有误,异常名称不能为空!"); } String happenTime = request.getParameter("happenTime"); log.info("******happenTime:"+ happenTime); if (StringUtils.isEmpty(happenTime)){ return this.outPutErr("参数有误,异常发生时间不能为空!"); } if (file == null) { return this.outPutErr("上传失败,上传的文件不能为空!"); } // 判断文件是否为空 if (file.isEmpty()) { return this.outPutErr("文件为空"); } // 判断文件是否为空文件 if (file.getSize() <= 0) { return this.outPutErr("文件大小为空,上传失败"); } String fileName = file.getOriginalFilename(); String suffixName = fileName.substring(fileName.lastIndexOf(".")); String newFileName = UUID.randomUUID().toString() + suffixName; String filePath= uploadFile(file,newFileName); log.info("******文件路径:"+ filePath); // 保存文件路径 Log localLog = logService.getOne(exceptionName,happenTime); if(localLog !=null){ localLog.setFileName(newFileName); localLog.setFilePath(filePath); int b = logService.update(localLog); if(b==1){ log.info("******日志更新成功******"); }else { log.info("******日志更新失败******"); } } log.info("************************上传文件成功****************************"); return this.outPutData("上传文件成功!"); } }
package com.seven.contract.manage.service.impl; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.seven.contract.manage.common.PageResult; import com.seven.contract.manage.dao.MemberDao; import com.seven.contract.manage.model.Member; import com.seven.contract.manage.service.MemberService; import com.seven.contract.manage.utils.ca.CaUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; @Service @Transactional(rollbackFor = Exception.class) public class MemberServiceImpl implements MemberService { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private MemberDao memberDao; @Override public void addMember(Member member, String privateKeyPwd) throws Exception { //计算公私钥和CA认证 Map<String, String> caMap = CaUtil.createKeys(privateKeyPwd, member); String privateKey = caMap.get("privateKey"); String publicKey = caMap.get("publicKey"); String caCert = caMap.get("caCert"); member.setPrivateKeysFileUrl(privateKey); member.setPublicKeys(publicKey); member.setCaCert(caCert); memberDao.insert(member); } @Override public void updateMember(Member member){ memberDao.update(member); } @Override public void deleteById(long id) { memberDao.deleteById(id); } @Override public Member selectOneById(long id) { Member member = memberDao.selectOne(id); return member; } @Override public PageResult<Member> getListByPage(Map<String, Object> params, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<Member> dataList = memberDao.selectList(params); Page page=(Page) dataList; PageResult pageResult=new PageResult(); pageResult.setRecords(page.getTotal()); pageResult.setRows(dataList); pageResult.setPage(page.getPageNum()); pageResult.setTotal(page.getPages()); return pageResult; } @Override public Member selectOneByPhone(String phone) { return memberDao.selectOneByPhone(phone); } @Override public Member selectOneByPublicKeys(String publicKeys) { return memberDao.selectOneByPublicKeys(publicKeys); } }
import java.util.*; public class DS19L101 { public static int solve_grid(String[][] grid,int x , int y, int row, int column) { int a = 0; int b = 0; if (x < row - 1 && y < column ) { if (grid[x][y].equals("x")) {a = 1 + solve_grid(grid , x+1 , y, row, column);} else {a = solve_grid(grid , x+1 , y,row, column); } } if (y < column - 1 && x < row) { if (grid[x][y].equals("x")) {b = 1 + solve_grid(grid , x , y + 1, row, column);} else {b = solve_grid(grid , x , y + 1,row, column); } } if (a > b) {return a;} else {return b;} } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a = Integer.parseInt(scan.nextLine()); String[][] array = new String[a][a]; for (int i= 0; i < a; i++) { array[i] = scan.nextLine().split(""); } int j = solve_grid(array, 0, 0, a , a); if (array[a - 1][a - 1].equals("x")) {j += 1;} System.out.println(j); } }
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.resource; import java.util.List; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.Resource; import org.springframework.lang.Nullable; /** * Base class for {@link org.springframework.web.servlet.resource.ResourceResolver} * implementations. Provides consistent logging. * * @author Rossen Stoyanchev * @since 4.1 */ public abstract class AbstractResourceResolver implements ResourceResolver { protected final Log logger = LogFactory.getLog(getClass()); @Override @Nullable public Resource resolveResource(@Nullable HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) { return resolveResourceInternal(request, requestPath, locations, chain); } @Override @Nullable public String resolveUrlPath(String resourceUrlPath, List<? extends Resource> locations, ResourceResolverChain chain) { return resolveUrlPathInternal(resourceUrlPath, locations, chain); } @Nullable protected abstract Resource resolveResourceInternal(@Nullable HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain); @Nullable protected abstract String resolveUrlPathInternal(String resourceUrlPath, List<? extends Resource> locations, ResourceResolverChain chain); }
package processor; import bean.ClientJSON; public class ShareProcessor { public void process(ClientJSON cJSON){ System.out.println("shareprocessor"); } }
open module modmain { // allow reflective access, currently used in the example_jerry-mouse requires modb; // requires ALL-UNNAMED; // this does not compile, hence we need to set --add-reads modmain=ALL-UNNAMED in both compile and run scripts! }
public class ex1A { public static void main(String[] args) { String courseTitle = "Java Reskilling"; int nbrDays = 20; double pricePerDay = 195.99; boolean priorKnowledgeRequired = false; System.out.println("Course title: " +courseTitle+ "\nNumber of days: " +nbrDays+ "\nPrice per day: " +pricePerDay+ "\nPrior knowledge requested : " +priorKnowledgeRequired); } }
package org.point85.domain; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.text.DecimalFormatSymbols; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Base64; import java.util.Calendar; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime; import org.eclipse.paho.client.mqttv3.MqttException; import org.jinterop.dcom.common.JIException; import org.openscada.opc.dcom.common.FILETIME; import org.point85.domain.i18n.DomainLocalizer; public final class DomainUtils { // ISO 8601 datetime format, yyyy-mm-ddThh:mm:ss.nnnnnn+|-hh:mm public static final String OFFSET_DATE_TIME_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"; // ISO 8601 datetime format, yyyy-mm-ddThh:mm:ss.nnn public static final String LOCAL_DATE_TIME_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS"; // ISO 8601 date format, yyyy-mm-dd public static final String LOCAL_DATE_8601 = "yyyy-MM-dd"; // ISO 8601 datetime UTC format, yyyy-mm-ddThh:mm:ss.nnnZ public static final String UTC_DATE_TIME_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // pattern for OffsetDateTime display public static final String OFFSET_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS ZZZZZ"; // SSL key and truststore folder public static final String SECURITY_DIR = "config/security/"; private DomainUtils() { throw new IllegalStateException("Utility class"); } public static String getVersionInfo() { return DomainLocalizer.instance().getLangString("version") + " 3.9.1, " + LocalDate.of(2022, 12, 24).format(DateTimeFormatter.ISO_DATE); } // format a Duration public static String formatDuration(Duration duration) { if (duration == null) { return ""; } else { // remove the "PT" prefix long seconds = duration.getSeconds(); if (duration.getNano() > 500000000l) { seconds += 1; } Duration rounded = Duration.ofSeconds(seconds); return rounded.toString().substring(2); } } public static String[] parseDomainAndUser(String user) { String[] info = new String[2]; if (user == null) { return info; } String delimeters = "[/" + "\\Q\\\\E" + "]+"; String[] tokens = user.split(delimeters); info[0] = "localhost"; info[1] = user; if (tokens.length == 2) { info[0] = tokens[0]; info[1] = tokens[1]; } return info; } public static String offsetDateTimeToString(OffsetDateTime odt, String pattern) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); return (odt != null) ? odt.format(dtf) : null; } public static OffsetDateTime offsetDateTimeFromString(String iso8601, String pattern) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); return (iso8601 != null) ? OffsetDateTime.parse(iso8601.trim(), dtf) : null; } public static String localDateTimeToString(LocalDateTime ldt, String pattern) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); return (ldt != null) ? ldt.format(dtf) : null; } public static LocalDateTime localDateTimeFromString(String iso8601, String pattern) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); return (iso8601 != null) ? LocalDateTime.parse(iso8601.trim(), dtf) : null; } public static String localDateToString(LocalDate ld, String pattern) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); return (ld != null) ? ld.format(dtf) : null; } public static LocalDate localDateFromString(String iso8601, String pattern) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); return (iso8601 != null) ? LocalDate.parse(iso8601.trim(), dtf) : null; } // create a UTC OffsetDateTime from the DateTime public static OffsetDateTime utcTimeFromDateTime(DateTime dateTime) { long epochMillis = dateTime.getJavaTime(); Instant instant = Instant.ofEpochMilli(epochMillis); return OffsetDateTime.ofInstant(instant, ZoneId.of("Z")); } // create a local OffsetDateTime from the DateTime public static OffsetDateTime localTimeFromDateTime(DateTime dateTime) { long epochMillis = dateTime.getJavaTime(); Instant instant = Instant.ofEpochMilli(epochMillis); return OffsetDateTime.ofInstant(instant, ZoneId.systemDefault()); } public static OffsetDateTime fromLocalDateTime(LocalDateTime ldt) { OffsetDateTime odt = null; if (ldt != null) { ZoneOffset offset = OffsetDateTime.now().getOffset(); odt = OffsetDateTime.of(ldt, offset); } return odt; } // removed formatting from decimal string public static String removeThousandsSeparator(String formattedString) { if (formattedString == null) { return null; } DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); StringBuilder sb = new StringBuilder(); sb.append(decimalFormatSymbols.getGroupingSeparator()); String separator = sb.toString(); String[] thousands = formattedString.split(separator); sb = new StringBuilder(); for (String thousand : thousands) { sb.append(thousand); } return sb.toString(); } public static OffsetDateTime fromFiletime(FILETIME filetime) { Calendar cal = filetime.asCalendar(); Instant instant = Instant.ofEpochMilli(cal.getTime().getTime()); return OffsetDateTime.ofInstant(instant, cal.getTimeZone().toZoneId()); } // encode the string in base64 public static String encode(String toEncode) { String encoded = null; if (toEncode != null) { byte[] bytes = toEncode.getBytes(StandardCharsets.UTF_8); encoded = Base64.getEncoder().withoutPadding().encodeToString(bytes); } return encoded; } // decode a base64 encoded string public static String decode(String toDecode) { String decoded = null; if (toDecode != null) { byte[] bytes = toDecode.getBytes(StandardCharsets.UTF_8); byte[] decodedBytes = Base64.getDecoder().decode(bytes); decoded = new String(decodedBytes); } return decoded; } public static String formatException(Exception e) { StringBuilder sb = new StringBuilder(); sb.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage() != null ? e.getMessage() : ""); if (e.getCause() != null) { sb.append("\n\tCause: ").append(e.getCause()); } if (e instanceof MqttException) { MqttException me = (MqttException) e; sb.append("\n\tReason: ").append(me.getReasonCode()); } else if (e instanceof JIException) { JIException jie = (JIException) e; sb.append("\n\tCode: ").append(jie.getErrorCode()); } return sb.toString(); } public static String getJVMInfo() { return System.getProperty("java.version") + ", " + System.getProperty("java.vm.name") + ", " + System.getProperty("java.runtime.version"); } public static int getJVMVersion() { int version = 8; String[] tokens = System.getProperty("java.version").split("."); if (!tokens[0].equals("1")) { version = Integer.parseInt(tokens[0]); } return version; } public static void gzip(String content, String fileName) throws Exception { try (FileOutputStream outputStream = new FileOutputStream(fileName); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) { byte[] data = content.getBytes(); gzipOutputStream.write(data); } } public static String gunzip(byte[] data) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayInputStream bis = new ByteArrayInputStream(data); GZIPInputStream in = new GZIPInputStream(bis); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) >= 0) { bos.write(buffer, 0, len); } in.close(); bos.close(); return new String(bos.toByteArray()); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.config; import java.util.ArrayList; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatException; /** * Integration tests for advice invocation order for advice configured via the * AOP namespace. * * @author Sam Brannen * @since 5.2.7 * @see org.springframework.aop.framework.autoproxy.AspectJAutoProxyAdviceOrderIntegrationTests */ class AopNamespaceHandlerAdviceOrderIntegrationTests { @Nested @SpringJUnitConfig(locations = "AopNamespaceHandlerAdviceOrderIntegrationTests-afterFirst.xml") @DirtiesContext class AfterAdviceFirstTests { @Test void afterAdviceIsInvokedFirst(@Autowired Echo echo, @Autowired InvocationTrackingAspect aspect) throws Exception { assertThat(aspect.invocations).isEmpty(); assertThat(echo.echo(42)).isEqualTo(42); assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after", "after returning"); aspect.invocations.clear(); assertThatException().isThrownBy(() -> echo.echo(new Exception())); assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after", "after throwing"); } } @Nested @SpringJUnitConfig(locations = "AopNamespaceHandlerAdviceOrderIntegrationTests-afterLast.xml") @DirtiesContext class AfterAdviceLastTests { @Test void afterAdviceIsInvokedLast(@Autowired Echo echo, @Autowired InvocationTrackingAspect aspect) throws Exception { assertThat(aspect.invocations).isEmpty(); assertThat(echo.echo(42)).isEqualTo(42); assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after returning", "after"); aspect.invocations.clear(); assertThatException().isThrownBy(() -> echo.echo(new Exception())); assertThat(aspect.invocations).containsExactly("around - start", "before", "around - end", "after throwing", "after"); } } static class Echo { Object echo(Object obj) throws Exception { if (obj instanceof Exception) { throw (Exception) obj; } return obj; } } static class InvocationTrackingAspect { List<String> invocations = new ArrayList<>(); Object around(ProceedingJoinPoint joinPoint) throws Throwable { invocations.add("around - start"); try { return joinPoint.proceed(); } finally { invocations.add("around - end"); } } void before() { invocations.add("before"); } void afterReturning() { invocations.add("after returning"); } void afterThrowing() { invocations.add("after throwing"); } void after() { invocations.add("after"); } } }
package com.unisports.entities; public class EmailAttachment { private byte[] content; private String contentName; public void setContent(byte[] content){ this.content = content; } public byte[] getContent(){ return this.content; } public void setContentName(String name){ this.contentName = name; } public String getContentName(){ return this.contentName; } }
/** * Copyright (c) 2004-2021 All Rights Reserved. */ package com.adomy.mirpc.core.remoting.network; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.adomy.mirpc.core.remoting.invoker.MiRpcInvokerFactory; import com.adomy.mirpc.core.remoting.network.request.MiRpcRequest; import com.adomy.mirpc.core.serialize.MiRpcSerializer; /** * RPC客户端 * * @author adomyzhao * @version $Id: MiRpcClient.java, v 0.1 2021年03月23日 9:34 AM adomyzhao Exp $ */ public abstract class MiRpcClient { /** * 日志 */ protected static final Logger LOGGER = LoggerFactory.getLogger(MiRpcClient.class); /** * 初始化处理 * * @param address * @param serializer * @param factory */ public abstract void init(String address, final MiRpcSerializer serializer, final MiRpcInvokerFactory factory) throws Exception; /** * 关闭处理 */ public abstract void close(); /** * 判断客户端是否有效 * * @return */ public abstract boolean isValid(); /** * 发送处理 * * @param request * @throws Exception */ public abstract void send(MiRpcRequest request) throws Exception; }
package com.company; public interface School { Student adminStudent(Student student)throws ClassFullException; Double chargeFees(Student student); }
package com.vipvideo.ui.adpter; import android.view.View; import android.widget.TextView; import com.lixh.base.adapter.VBaseHolder; import com.vipvideo.R; import com.vipvideo.bean.VideoInfoBean; import java.util.List; import butterknife.Bind; /** * Created by Moushao on 2017/8/30. */ public class VideoTopShareHolder extends VBaseHolder<VideoInfoBean> { @Bind(R.id.tv_video_urls) TextView videoInfos; public VideoTopShareHolder(View itemView) { super (itemView); } @Override public void setData(int ps, VideoInfoBean data) { super.setData (ps, data); List<VideoInfoBean.SitesBean> sitesBeans = mData.getSites ( ); videoInfos.setText (sitesBeans.get (0).getSite_name ( )); } public void init() { videoInfos.setOnClickListener ((View v) -> { if (mListener != null) { mListener.onItemClick (v, 0, mData); } }); } }
public class ThrowScreen extends TargetScreen { @Override protected String getVerb() { return "throw"; } @Override protected boolean isAcceptable(Creature creature) { if (player.canSee(creature.x, creature.y) && !isPlayer(creature)) { return true; } return false; } @Override protected Screen use(Creature creature) { player.throwObject(creature); return null; } public ThrowScreen(Creature player, World world) { super(player, world); } @Override public void update() { } }
package com.yidatec.weixin.security; import java.util.ArrayList; import java.util.Collection; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; import com.yidatec.weixin.dao.security.SecurityDao; import com.yidatec.weixin.entity.PlatformUserEntity; import com.yidatec.weixin.util.Encrypt; /** *该类的主要作用是为Spring Security提供丄1�7个经过用户认证后的UserDetails〄1�7 *该UserDetails包括用户名�1�7�密码�1�7�是否可用�1�7�是否过期等信息〄1�7 */ @Service public class CustomUserDetailsService implements UserDetailsService { private static final Logger log = LogManager.getLogger(CustomUserDetailsService.class); @Autowired private SecurityDao securityDao; @Override public UserDetails loadUserByUsername(String username) { Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); // 根据用户名取得一个SysUsers对象,以获取该用户的其他信息〄1�7 PlatformUserEntity user = null; try { // 得到用户的权附1�7 auths = securityDao.loadUserAuthoritiesByName(username); user = securityDao.loadUserByAccount(username); if (user == null) return new PlatformUserEntity(); // 加密的时候用用户名做了salt,这里要移附1�7 user.setPassword(Encrypt.decryptPwdWithSalt(user.getPassword(), user.getAccount())); } catch (Exception e) { log.error(e.getMessage(), e); return null; } return new PlatformUserEntity(user.getId(), user.getUser_id(), user.getAccount(), user.getPassword(), user.getName(), user.getMail(), user.getMobile_phone(), user.getIssys(), user.getEnabled(), user.getBusy(), user.getType(), user.getCreate_user(), user.getCreate_date(), user.getModify_user(), user.getModify_date(), user.getRoles(), auths, user.isAccountNonExpired(), user.isAccountNonLocked(), user.isCredentialsNonExpired(), user.getWeichat_type() ,user.getSex() ); } public SecurityDao getSecurityDao() { return securityDao; } public void setSecurityDao(SecurityDao securityDao) { this.securityDao = securityDao; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* URL http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=332&sca=50&sfl=wr_hit&stx=1053&sop=and */ public class Main1053_피보나치 { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = 0; while ( (n = Integer.parseInt(br.readLine().trim())) != -1) { // 조건문에 선언 대입 사용 익히기!! if (n == 0) { System.out.println(0); continue; } //memo = new int[n+1]; //System.out.println(fivonacci1(n)); System.out.println(fivonacci2(n)[0][1]); } } // 메모하기 방법 static int[] memo = null; public static int fivonacci1(int n) { if (n == 1 || n == 2) return 1; if (memo[n] != 0) return memo[n]; return memo[n] = fivonacci1(n-2) + fivonacci1(n-1); } static int[][] unit = { {1, 1}, {1, 0} }; private static int[][] multiple(int[][] a, int[][] b) { int[][] temp = new int[2][2]; temp[0][0] = (a[0][0]*b[0][0] + a[0][1]*b[1][0]) % 10000; temp[0][1] = (a[0][0]*b[0][1] + a[0][1]*b[1][1]) % 10000; temp[1][0] = (a[1][0]*b[0][0] + a[1][1]*b[1][0]) % 10000; temp[1][1] = (a[1][0]*b[0][1] + a[1][1]*b[1][1]) % 10000; return temp; } public static int[][] fivonacci2(int n) { if (n == 1) return unit; int[][] temp = fivonacci2(n/2); temp = multiple(temp, temp); if (n % 2 == 1) temp = multiple(temp, unit); return temp; } }
/* * Copyright 2020 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.forge.folderctxmenus.common; import org.hippoecm.repository.api.Workflow; import org.hippoecm.repository.api.WorkflowException; import java.util.Locale; /** * Advanced folder workflow which provides the option to copy or move folders. */ public interface ExtendedFolderWorkflow extends Workflow { /** * Copy a folder to into another folder. * @param locale the locale of the folder * @param sourceFolderId the UUID of the source folder * @param destParentFolderId the UUID of the destination folder into which the folder is copied * @param destFolderNodeName the node name of the new folder * @param destFolderDisplayName the display name of the new folder * @throws WorkflowException when an exception occurs while copying */ void copyFolder(final Locale locale, final String sourceFolderId, final String destParentFolderId, final String destFolderNodeName, final String destFolderDisplayName) throws WorkflowException; /** * Move a folder to another folder. * @param locale the locale of the folder * @param sourceFolderId the UUID of the source folder * @param destParentFolderId the UUID of the destination folder into which the folder is copied * @param destFolderNodeName the node name of the new folder * @param destFolderDisplayName the display name of the new folder * @throws WorkflowException when an exception occurs while copying */ void moveFolder(final Locale locale, final String sourceFolderId, final String destParentFolderId, final String destFolderNodeName, final String destFolderDisplayName) throws WorkflowException; }
package owner.aopbeans; import org.springframework.stereotype.Component; @Component public class AopTest { public void method(){ System.out.printf("AopTest method......Running"); } }
import java.util.Properties; import com.troila.redis.JedisInterface; import com.troila.redis.factory.JedisFactory; import com.troila.redis.utils.ConfigureUtils; //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(locations = {"classpath:spring-core.xml"}) public class RedisTest{ // @Autowired // private JedisInterface redisUtils; // // @Test // public void testRedis() throws Exception{ // redisUtils.set("test","test"); // System.out.println(redisUtils.get("test")); // } public static void main(String[] args) { new ConfigureUtils().init(); JedisInterface redisUtils = JedisFactory.getJedis(ConfigureUtils.getConfigs()); redisUtils.set("test","limltest"); System.out.println(redisUtils.get("test")); } }
/* Tipos primitivos -> * (boolean , char , short int ou long , float ou double.) * double variavel = 100.2; * float variavel = 100.2f; * char variavel = 'a'; * String e uma classe e nao um tipo primitivo. * (&& and) (|| or) * Operadores Unarios: ++(+1) --(-1) -(negativo) !(not) * Operador Condicional (ternario): a = x ? b : c; boolean x = true or false. * Casting -> * int teste1 = 10; * int teste2 = 5; * float result = (float) teste1/teste2; */ import java.util.Scanner; public class Tools1 { //Modificador public permite acessar a classe em outra classe. public static void main(String[] args){ // Metodo main eh executado junto com o programa. int var1 = 10; float var2 = 10.0f; // private String variavel = "1234"; //Modificador private so permite acessar a variavel dentro da classe System.out.println("Estruturas de controle"); // Metodo da API Java para imprimir. if (var1 >= var2) { // instrucao 1 System.out.println("v1 maior v2"); } else if (var1 <= var2) { // caso instrucao 1 falhe System.out.println("v1 menor v2"); } else { // caso todas falhem System.out.println("NADA"); } switch (var1) { case 10: // Caso a var1 tiver valor 10 System.out.println("var1 eh 10"); break; // Precisa utilizar break em cada case. case 20: System.out.println("var1 eh 20"); break; default: // Caso nenhum case esteja definido System.out.println("default"); } // //Tipo de retorno: VOID (nao necessita retorno) // public void metodo(String teste) { // System.out.println("Metodo "+teste); // } /* Garbage Collector elimina objetos da memoria quando * nao sao mais referenciados. */ /* Modificadores: * public - (classe, atributos e metodos) * protected - (atributos e metodos para mesmo pacote) * private - (atributos e metodos para mesma classe) * static - (atributos e metodos para mesmo pacote) * final * native * transient * synchronized */ System.out.println("Modulo 4"); /* Variavel primitiva guarda seu valor * Variavel de objeto guarda um endereco para ele. */ String x = "teste"; String y = "Teste"; boolean resultado; resultado = x.equals(y); // Retorna true ou false da igualdade System.out.println(resultado); resultado = x.equalsIgnoreCase(y); // Ignora maiusculas System.out.println(resultado); String texto = "vamos achar as palavras"; int comeco = texto.indexOf("achar"); // Mostra o comeco da palavra System.out.println(comeco); String pegarParte = texto.substring(0,4); // pega uma string do indice System.out.println(pegarParte); // 0 ate o 3. char letter = texto.charAt(1); // pega uma letra no indice System.out.println(letter); ///////////////////////////////////////// Scanner input = new Scanner(System.in); ///////////////////////////////////////// System.out.println("Digite um nome: "); String palavra = input.nextLine(); System.out.print("Digite a idade: "); int numero = input.nextInt(); System.out.println(palavra+" "+numero); int tamanho = palavra.length(); System.out.println("tamanho "+tamanho); } }
package com.daydvr.store.bean; import android.graphics.drawable.Drawable; /** * @author LoSyc * @version Created on 2017/12/31. 0:37 */ public class GameBean { private String name; private String summary; private String type; private Drawable icon; private String url; private String packageName; private int version; private long size; private int rating; private int id; private int loadedPage; private int lastPage; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Drawable getIcon() { return icon; } public void setIcon(Drawable icon) { this.icon = icon; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getLoadedPage() { return loadedPage; } public void setLoadedPage(int loadedPage) { this.loadedPage = loadedPage; } public int getLastPage() { return lastPage; } public void setLastPage(int lastPage) { this.lastPage = lastPage; } }
package com.example.pawansiwakoti.vicroadslicensetest.activities; import android.content.Intent; import android.databinding.DataBindingUtil; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import com.example.pawansiwakoti.vicroadslicensetest.R; import com.example.pawansiwakoti.vicroadslicensetest.activities.MainActivity; import com.example.pawansiwakoti.vicroadslicensetest.activities.SplashScreen; import com.example.pawansiwakoti.vicroadslicensetest.databinding.ActivityResultBinding; public class Result extends AppCompatActivity implements View.OnClickListener{ public static final String ARG_TOTAL = "arg_total"; public static final String ARG_CORRECT = "arg_correct"; public static final String ARG_SKIP = "arg_skip"; public static final double PASS_PERCENTAGE = 50; private ActivityResultBinding binding; private int total; private int correct; private int skip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_result); binding = DataBindingUtil.setContentView(this, R.layout.activity_result); setupActionbar(); Intent intent = getIntent(); if (intent != null) { total = intent.getIntExtra(ARG_TOTAL,0); correct = intent.getIntExtra(ARG_CORRECT,0); skip = intent.getIntExtra(ARG_SKIP,0); calculateAndDisplayingResult(); } binding.buttonGoHome.setOnClickListener(this); binding.buttonTryAgain.setOnClickListener(this); } private void calculateAndDisplayingResult() { double acquiredPercentage = total == 0?0: (correct/total)*100; changeUIFor(acquiredPercentage>PASS_PERCENTAGE); } private void changeUIFor(boolean pass){ int color = getResources().getColor(pass ? R.color.colorPrimary: R.color.colorPrimary); Drawable drawable = ContextCompat.getDrawable(this, pass?R.drawable.ic_success : R.drawable.ic_exclamation); drawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(drawable,color); binding.imageResult.setImageDrawable(drawable); binding.textFeedback.setText(pass ? "Nice!": "Opps!"); binding.textPoints.setText(String.format("%id/%id, correct, total")); binding.textPoints.setTextColor(color); binding.textFeedback.setTextColor(color); } private void setupActionbar(){ ActionBar actionBar = getSupportActionBar(); if (actionBar == null) return; actionBar.setTitle("Result"); } @Override public void onClick(View v){ Intent intent = null; switch (v.getId()) { case R.id.button_go_home: intent = new Intent(this, SplashScreen.class); break; case R.id.button_try_again: intent = new Intent(this, MainActivity.class); break; } startActivity(intent); finish(); } }
package com.interestcalc; import java.io.FileOutputStream; import java.io.IOException; //import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class InterestCalculator { public static SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy"); public static long amountSanctioned; public static long initialTenure; public static long emi; public static int emiDay; public static long totalDisbursedAmount; public static long calculateEmi(long principal, double roi, long tenureMonthsRemaining) { double monthlyRoiFract=(roi/12)/100; double emi=(principal*monthlyRoiFract*Math.pow(1+monthlyRoiFract,tenureMonthsRemaining))/(Math.pow(1+monthlyRoiFract,tenureMonthsRemaining)-1); return Math.round(emi); } public static double calculateDailyInterest(long outstandingBalance, double roi) { double dailyRoiFract=(roi/365)/100; double interest=outstandingBalance*dailyRoiFract; return interest; } public static String getNextDate(String inputDate) { Date entryDate=null; try { entryDate=sdf.parse(inputDate); entryDate=new Date(entryDate.getTime() + (24*60*60*1000)); return sdf.format(entryDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public static String getPreviousDate(String inputDate) { Date entryDate=null; try { entryDate=sdf.parse(inputDate); entryDate=new Date(entryDate.getTime() - (24*60*60*1000)); return sdf.format(entryDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public static String getNextInstallmentDate(String inputDate) { String[] dateParts=inputDate.split("/"); int nextDay=emiDay; int nextMonth=new Integer(dateParts[1]) + 1; int nextYear=new Integer(dateParts[2]); if(nextMonth==13) { nextMonth=1; nextYear++; } try { return sdf.format(sdf.parse(nextDay + "/" + nextMonth + "/" + nextYear)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static String getPreviousInstallmentDate(String inputDate) { String[] dateParts=inputDate.split("/"); int previousDay=emiDay; int previousMonth=new Integer(dateParts[1]) - 1; int previousYear=new Integer(dateParts[2]); if(previousMonth==0) { previousMonth=12; previousYear--; } try { return sdf.format(sdf.parse(previousDay + "/" + previousMonth + "/" + previousYear)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static long calculatePeriodInterest(String startDate, String endDate) { long outstandingBalance=getNextTransaction(startDate).openingPrincipal; double totalInterest=0; while(startDate.equals(endDate)==false) { if(Transactions.getTransaction(startDate)!=null) { outstandingBalance=getNextTransaction(startDate).openingPrincipal; if(getNextTransaction(startDate).transactionType.equals("PartPayment")) { totalInterest=0; } } totalInterest=totalInterest + calculateDailyInterest(outstandingBalance, ROITrend.getRate(startDate)); startDate=getNextDate(startDate); } return Math.round(totalInterest); } public static Transaction getPreviousTransaction(String transactionDate) { String previousInstallmentStartDate=getPreviousInstallmentDate(transactionDate); //int previousTransactionIndex=Transactions.transactions.indexOf(Transactions.getTransaction(transactionDate))-1; transactionDate=getPreviousDate(transactionDate); while(transactionDate.equals(previousInstallmentStartDate)==false) { if(Transactions.getTransaction(transactionDate)!=null) { return Transactions.getTransaction(transactionDate); } transactionDate=getPreviousDate(transactionDate); } return Transactions.getTransaction(transactionDate); } public static Transaction getNextTransaction(String transactionDate) { int nextTransactionIndex=Transactions.transactions.indexOf(Transactions.getTransaction(transactionDate))+1; return Transactions.transactions.get(nextTransactionIndex); } public static Transaction getPreviousInstallmentTransaction(String transactionDate) { return Transactions.getTransaction(getPreviousInstallmentDate(transactionDate)); } public static void correctCurrentTransaction(String transactionDate) { Transaction previousTransaction=getPreviousTransaction(transactionDate); if(previousTransaction!=null) { Transaction currentTransaction=Transactions.getTransaction(transactionDate); currentTransaction.openingPrincipal=previousTransaction.closingPrincipal; if(currentTransaction.transactionType.equals("PartDisbursement")) { currentTransaction.principalComponent=0; currentTransaction.interestComponent=0; currentTransaction.closingPrincipal=currentTransaction.openingPrincipal+currentTransaction.amount; totalDisbursedAmount=totalDisbursedAmount+currentTransaction.amount; } else { Transaction previousInstallmentTransaction=previousTransaction; if(getPreviousInstallmentTransaction(transactionDate)!=null) { previousInstallmentTransaction=getPreviousInstallmentTransaction(transactionDate); } if(currentTransaction.transactionType.equals("PartPayment")) { currentTransaction.interestComponent=calculatePeriodInterest(previousInstallmentTransaction.transactionDateStr,transactionDate); currentTransaction.principalComponent=currentTransaction.amount-currentTransaction.interestComponent; currentTransaction.closingPrincipal=currentTransaction.openingPrincipal-currentTransaction.principalComponent; if(currentTransaction.closingPrincipal<0) { currentTransaction.closingPrincipal=0; } } else if(currentTransaction.transactionType.equals("PreEMI")) { currentTransaction.interestComponent=calculatePeriodInterest(previousInstallmentTransaction.transactionDateStr,transactionDate); currentTransaction.principalComponent=0; currentTransaction.amount=currentTransaction.interestComponent; currentTransaction.closingPrincipal=currentTransaction.openingPrincipal-currentTransaction.principalComponent; } else if(currentTransaction.transactionType.equals("PreEMIInterestCorrection")) { currentTransaction.principalComponent=0; currentTransaction.amount=currentTransaction.interestComponent; currentTransaction.closingPrincipal=currentTransaction.openingPrincipal; } else if(currentTransaction.transactionType.equals("EMI")) { currentTransaction.amount=emi; currentTransaction.interestComponent=calculatePeriodInterest(previousInstallmentTransaction.transactionDateStr,transactionDate); currentTransaction.principalComponent=emi-currentTransaction.interestComponent; currentTransaction.closingPrincipal=currentTransaction.openingPrincipal-currentTransaction.principalComponent; if(currentTransaction.closingPrincipal<0) { currentTransaction.closingPrincipal=0; currentTransaction.principalComponent=currentTransaction.openingPrincipal; currentTransaction.amount=currentTransaction.principalComponent+currentTransaction.interestComponent; } } else if(currentTransaction.transactionType.equals("EMIInterestCorrection")) { currentTransaction.amount=emi; currentTransaction.principalComponent=emi-currentTransaction.interestComponent; currentTransaction.closingPrincipal=currentTransaction.openingPrincipal-currentTransaction.principalComponent; if(currentTransaction.closingPrincipal<0) { currentTransaction.closingPrincipal=0; currentTransaction.principalComponent=currentTransaction.openingPrincipal; currentTransaction.amount=currentTransaction.principalComponent+currentTransaction.interestComponent; } } } System.out.println(currentTransaction.getDate() + "\t" + currentTransaction.transactionType + "\t" + currentTransaction.openingPrincipal + "\t" + currentTransaction.amount + "\t" + currentTransaction.principalComponent + "\t" + currentTransaction.interestComponent + "\t" + currentTransaction.roi + "\t" + currentTransaction.closingPrincipal); } //below will always be first disbursement transaction else { Transaction currentTransaction=Transactions.getTransaction(transactionDate); currentTransaction.closingPrincipal=currentTransaction.amount; } } public static void generateNextInstallmentTransaction(String transactionDate) { String nextInstallmentDate=getNextInstallmentDate(transactionDate); Transaction transaction; transaction=new Transaction(getNextInstallmentDate(transactionDate), 0, ""); if(Transactions.getTransaction(nextInstallmentDate)==null) { Transaction previousTransaction=getPreviousTransaction(transaction.transactionDateStr); if(previousTransaction!=null) { if(previousTransaction.transactionType.equals("PartDisbursement")||previousTransaction.transactionType.equals("PartPayment")) { if(previousTransaction.transactionType.equals("PartDisbursement")) { if((totalDisbursedAmount + previousTransaction.amount)==amountSanctioned) { Transactions.addEmi(transaction); return; } } Transactions.addPreEmi(transaction); return; } } Transactions.addEmi(transaction); } } public static void generateSchedule() { int currentTransactionIndex=0; Transaction currentTransaction=null; do{ currentTransaction=Transactions.transactions.get(currentTransactionIndex); correctCurrentTransaction(currentTransaction.transactionDateStr); if(currentTransaction.closingPrincipal>0) { String currentTransactionDate=currentTransaction.getDate(); generateNextInstallmentTransaction(currentTransactionDate); } currentTransactionIndex++; } while(currentTransaction.closingPrincipal!=0); } public static void main(String[] args) { amountSanctioned=23456; initialTenure=110; emiDay=5; ROITrend.addEntry("14/02/2011", 6); Transactions.addPartDisbursement("12/10/2012", 23432); emi=calculateEmi(amountSanctioned,ROITrend.roi.get(0).rate,initialTenure); ROITrend.addEntry("15/04/2013", 2); Transactions.addPreEMIInterestCorrection("10/12/2012", 484); Transactions.addEMIInterestCorrection("10/04/2013", 568); generateSchedule(); long totalPrincipal=0; long totalInterest=0; long totalAmount=0; for(Transaction transaction:Transactions.transactions) { totalPrincipal=totalPrincipal + transaction.principalComponent; totalInterest=totalInterest + transaction.interestComponent; } totalAmount=totalPrincipal + totalInterest; XSSFWorkbook workbook=new XSSFWorkbook(); XSSFSheet sheet=workbook.createSheet("schedule"); XSSFRow row=sheet.createRow(0); XSSFCell cell=row.createCell(0); cell.setCellValue("Date"); cell=row.createCell(1); cell.setCellValue("TransactionType"); cell=row.createCell(2); cell.setCellValue("OpeningPrincipal"); cell=row.createCell(3); cell.setCellValue("Amount"); cell=row.createCell(4); cell.setCellValue("Principal"); cell=row.createCell(5); cell.setCellValue("Interest"); cell=row.createCell(6); cell.setCellValue("ROI"); cell=row.createCell(7); cell.setCellValue("ClosingPrincipal"); int rowIndex=1; for(Transaction trans:Transactions.transactions) { int colIndex=0; row=sheet.createRow(rowIndex); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.getDate()); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.transactionType); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.openingPrincipal); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.amount); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.principalComponent); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.interestComponent); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.roi); cell=row.createCell(colIndex); colIndex++; cell.setCellValue(trans.closingPrincipal); /* System.out.println(trans.getDate() + "\t" + trans.transactionType + "\t" + trans.openingPrincipal + "\t" + trans.amount + "\t" + trans.principalComponent + "\t" + trans.interestComponent + "\t" + trans.roi + "\t" + trans.closingPrincipal); */ rowIndex++; } row=sheet.createRow(rowIndex); cell=row.createCell(1); cell.setCellValue("Total"); cell=row.createCell(3); cell.setCellValue(totalAmount); cell=row.createCell(4); cell.setCellValue(totalPrincipal); cell=row.createCell(5); cell.setCellValue(totalInterest); FileOutputStream outPutStream = null; try { outPutStream = new FileOutputStream("target/Schedule.xlsx"); workbook.write(outPutStream); } catch (IOException e) { e.printStackTrace(); } finally { if (outPutStream != null) { try { outPutStream.flush(); outPutStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package loecraftpack.common.items; import java.util.ArrayList; import java.util.List; import loecraftpack.LoECraftPack; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.Icon; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemBits extends Item { public static final String[] names = {"1 Bit", "5 Bits", "10 Bits", "25 Bits", "100 Bits"}; public static final String[] iconNames = new String[names.length]; public static final int num = names.length-1; @SideOnly(Side.CLIENT) private Icon[] icons; public ItemBits(int par1) { super(par1); this.setHasSubtypes(true); this.setMaxDamage(0); this.setCreativeTab(LoECraftPack.LoECraftTabItem); this.setUnlocalizedName("itemBits"); for(int i = 0; i < iconNames.length; i++) iconNames[i] = names[i].replace(" ", "").toLowerCase(); } @Override @SideOnly(Side.CLIENT) public Icon getIconFromDamage(int index) { return this.icons[MathHelper.clamp_int(index, 0, num)]; } @Override public String getUnlocalizedName(ItemStack iconNamestack) { return super.getUnlocalizedName() + "." + iconNames[MathHelper.clamp_int(iconNamestack.getItemDamage(), 0, num)]; } @Override public void getSubItems(int id, CreativeTabs tab, List list) { for (int j = 0; j < num+1; ++j) { list.add(new ItemStack(id, 1, j)); } } @Override @SideOnly(Side.CLIENT) public void registerIcons(IconRegister iconRegister) { icons = new Icon[iconNames.length]; for (int i = 0; i < iconNames.length; i++) { icons[i] = iconRegister.registerIcon("loecraftpack:bits/" + iconNames[i]); itemIcon = icons[i]; } } private static ItemStack[] GetItemstack(int amount) { ArrayList<ItemStack> bits = new ArrayList<ItemStack>(); int count = (int)(amount / 100); if (count > 0) { bits.add(new ItemStack(LoECraftPack.bits, count, 4)); amount -= count * 100; } count = (int)(amount / 25); if (count > 0) { bits.add(new ItemStack(LoECraftPack.bits, count, 3)); amount -= count * 25; } count = (int)(amount / 10); if (count > 0) { bits.add(new ItemStack(LoECraftPack.bits, count, 2)); amount -= count * 10; } count = (int)(amount / 5); if (count > 0) { bits.add(new ItemStack(LoECraftPack.bits, count, 1)); amount -= count * 5; } if (amount > 0) bits.add(new ItemStack(LoECraftPack.bits, amount, 0)); return bits.toArray(new ItemStack[0]); } public static void DropBits(int amount, Entity entity) { for(ItemStack item : ItemBits.GetItemstack(amount)) entity.entityDropItem(item, 0); } public static void DropBits(int amount, World world, Vec3 pos) { for(ItemStack item : ItemBits.GetItemstack(amount)) world.spawnEntityInWorld(new EntityItem(world, pos.xCoord, pos.yCoord, pos.zCoord, item)); } }
package ca.oneroof.oneroof.ui; import androidx.test.core.app.ActivityScenario; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Random; import ca.oneroof.oneroof.R; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static ca.oneroof.oneroof.TestUtils.createHouseInviteOther; import static ca.oneroof.oneroof.TestUtils.loginAs; @RunWith(AndroidJUnit4.class) public class InviteTests { // To run this test, run the backend with AUTH_DISABLED=1. @Test public void inviteTest() { // Make a random user for this test. User1 with invite User2. Random random = new Random(); String user1 = "User1" + random.nextInt(); String user2 = "User2" + random.nextInt(); // Do the invite. createHouseInviteOther("Test house", user1, user2); // Check that the invite worked. ActivityScenario<MainActivity> scenario = loginAs(user2); onView(withId(R.id.action_profile)) .perform(click()); onView(withId(R.id.house_name)) .check(matches(withText("Test house"))); scenario.close(); } }
package com.rednovo.ace.ui.activity.my; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.rednovo.ace.R; import com.rednovo.ace.common.UpdateAttacher; import com.rednovo.ace.data.UserInfoUtils; import com.rednovo.ace.ui.activity.LoginActivity; import com.rednovo.ace.ui.activity.RegistActivity; import com.rednovo.ace.view.dialog.SimpleDialog; import com.rednovo.ace.view.dialog.SimpleDialog.OnSimpleDialogBtnClickListener; import com.rednovo.libs.common.CacheUtils; import com.rednovo.libs.common.ShowUtils; import com.rednovo.libs.common.Utils; import com.rednovo.libs.net.fresco.FrescoEngine; import com.rednovo.libs.ui.base.BaseActivity; /** * 设置 * Created by Dk on 16/2/25. */ public class SettingActivity extends BaseActivity implements View.OnClickListener, OnSimpleDialogBtnClickListener { private TextView tvCache; private SimpleDialog logoutDialog; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); setContentView(R.layout.layout_setting); tvCache = (TextView) findViewById(R.id.tv_setting_cache); ((TextView) findViewById(R.id.tv_title)).setText(R.string.setting); findViewById(R.id.back_btn).setOnClickListener(this); findViewById(R.id.rl_setting_account_manager).setOnClickListener(this); findViewById(R.id.rl_setting_clean_cache).setOnClickListener(this); findViewById(R.id.rl_setting_suggestion_feedback).setOnClickListener(this); findViewById(R.id.rl_setting_update_version).setOnClickListener(this); findViewById(R.id.rl_setting_about).setOnClickListener(this); findViewById(R.id.rl_setting_logout).setOnClickListener(this); if(!UserInfoUtils.isAlreadyLogin()){ findViewById(R.id.rl_setting_account_manager).setVisibility(View.GONE); findViewById(R.id.rl_setting_logout).setVisibility(View.GONE); } tvCache.setText(Utils.getImageCacheSize(this)+""); if(UserInfoUtils.isAlreadyLogin() && UserInfoUtils.getUserInfo() != null){ if(UserInfoUtils.getUserInfo().getChannel() == null || UserInfoUtils.getUserInfo().getChannel().equals("1") || UserInfoUtils.getUserInfo().getChannel().equals("2") || UserInfoUtils.getUserInfo().getChannel().equals("5")){ findViewById(R.id.rl_setting_account_manager).setVisibility(View.GONE); } } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.rl_setting_account_manager: startActivity(new Intent(SettingActivity.this, AccountManagerActivity.class)); break; case R.id.rl_setting_clean_cache: ShowUtils.showProgressDialog(this, R.string.cache_cleaning); Utils.cleanCache(this); ShowUtils.dismissProgressDialog(); ShowUtils.showToast(R.string.clean_cache_success); tvCache.setText("0.0M"); break; case R.id.rl_setting_suggestion_feedback: startActivity(new Intent(SettingActivity.this, SuggestionFeedbackActivity.class)); break; case R.id.rl_setting_update_version: UpdateAttacher updateAttacher = new UpdateAttacher(this); if (updateAttacher.checkUpdateVer()) { updateAttacher.showUpdateDialog(); }else{ ShowUtils.showToast(R.string.not_find_new_version); } break; case R.id.rl_setting_about: startActivity(new Intent(SettingActivity.this, AboutActivity.class)); break; case R.id.rl_setting_logout: logoutDialog = new SimpleDialog(this, this, R.string.is_quit, R.string.text_cancel, R.string.quit); logoutDialog.show(); break; case R.id.back_btn: finish(); break; default: break; } } @Override public void onSimpleDialogLeftBtnClick() { } @Override public void onSimpleDialogRightBtnClick() { ShowUtils.showToast(R.string.logout_success); UserInfoUtils.logout(); finish(); } }
package com.leon.meepo.tinyioc.xml; import com.leon.meepo.tinyioc.AbstractBeanDefinitionReader; import com.leon.meepo.tinyioc.BeanDefinition; import com.leon.meepo.tinyioc.BeanReference; import com.leon.meepo.tinyioc.PropertyValue; import com.leon.meepo.tinyioc.PropertyValues; import com.leon.meepo.tinyioc.io.ResourceLoader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; /** * Created by songlin01 on 17/7/21. */ public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader { public XmlBeanDefinitionReader(ResourceLoader resourceLoader) { super(resourceLoader); } public void loadBeanDefinitions(String location) throws Exception { InputStream inputStream = getResourceLoader().getResource(location).getInputStream(); doLoadBeanDefinitions(inputStream); } public void doLoadBeanDefinitions(InputStream inputStream) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); registerBeanDefinitions(document); inputStream.close(); } public void registerBeanDefinitions(Document document) { Element root = document.getDocumentElement(); parseBeanDefinitions(root); } public void parseBeanDefinitions(Element root) { NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; processBeanDefinitions(element); } } } public void processBeanDefinitions(Element element) { String name = element.getAttribute("name"); String className = element.getAttribute("class"); BeanDefinition beanDefinition = new BeanDefinition(); beanDefinition.setPropertyValues(new PropertyValues()); processProperty(element, beanDefinition); beanDefinition.setBeanClassName(className); getRegistry().put(name, beanDefinition); } private void processProperty(Element element, BeanDefinition beanDefinition) { NodeList nodeList = element.getElementsByTagName("property"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element elementProperty = (Element) node; String name = elementProperty.getAttribute("name"); String value = elementProperty.getAttribute("value"); if (value != null && value.length() > 0) { beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue(name, value)); } else { String ref = elementProperty.getAttribute("ref"); BeanReference beanReference = new BeanReference(ref); beanDefinition.getPropertyValues().addPropertyValue(new PropertyValue(name, beanReference)); } } } } }
package com.gxtc.huchuan.bean; import java.util.List; /** * Describe: * Created by ALing on 2017/5/21 . */ public class InComeAllCountBean { /** * chatMoney : 0.01 * groupMoney : 10.0 * rewardMoney : 0 * totalMoney : 10.01 * tradeMoney : 0 * userStreams : [{"balance":"0.01","createTime":"1494387773000","orderId":"CI20170503193150161943","streamMoney":"0.01","title":"收费课程流水","type":"1"},{"balance":"10.00","createTime":"1494347400000","orderId":"123456","streamMoney":"10.00","title":"收费圈子流水","type":"3"}] */ private String chatMoney; private String groupMoney; private String rewardMoney; private String totalMoney; private String tradeMoney; private String distributionMoney; private List<UserStreamsBean> userStreams; public String getDistributionMoney() { return distributionMoney; } public void setDistributionMoney(String distributionMoney) { this.distributionMoney = distributionMoney; } public String getChatMoney() { return chatMoney;} public void setChatMoney(String chatMoney) { this.chatMoney = chatMoney;} public String getGroupMoney() { return groupMoney;} public void setGroupMoney(String groupMoney) { this.groupMoney = groupMoney;} public String getRewardMoney() { return rewardMoney;} public void setRewardMoney(String rewardMoney) { this.rewardMoney = rewardMoney;} public String getTotalMoney() { return totalMoney;} public void setTotalMoney(String totalMoney) { this.totalMoney = totalMoney;} public String getTradeMoney() { return tradeMoney;} public void setTradeMoney(String tradeMoney) { this.tradeMoney = tradeMoney;} public List<UserStreamsBean> getUserStreams() { return userStreams;} public void setUserStreams(List<UserStreamsBean> userStreams) { this.userStreams = userStreams;} public static class UserStreamsBean { /** * balance : 0.01 * createTime : 1494387773000 * orderId : CI20170503193150161943 * streamMoney : 0.01 * title : 收费课程流水 * type : 1 */ private String balance; private String createTime; private String orderId; private String streamMoney; private String title; private String type; public String getBalance() { return balance;} public void setBalance(String balance) { this.balance = balance;} public String getCreateTime() { return createTime;} public void setCreateTime(String createTime) { this.createTime = createTime;} public String getOrderId() { return orderId;} public void setOrderId(String orderId) { this.orderId = orderId;} public String getStreamMoney() { return streamMoney;} public void setStreamMoney(String streamMoney) { this.streamMoney = streamMoney;} public String getTitle() { return title;} public void setTitle(String title) { this.title = title;} public String getType() { return type;} public void setType(String type) { this.type = type;} } }
package com.test; import com.test.base.Solution; /** * 桶概念的使用 * @author YLine * * 2018年11月13日 下午8:05:34 */ public class SolutionA implements Solution { @Override public int firstMissingPositive(int[] nums) { // 入口校验 if (null == nums || nums.length == 0) { return 1; } // 遍历n,记录标记量 boolean[] signArray = new boolean[nums.length]; for (int i : nums) { if (i <= nums.length && i > 0) { signArray[i - 1] = true; } } // 遍历n是否存在标记量 for (int i = 0; i < signArray.length; i++) { if (!signArray[i]) { return i + 1; } } return signArray.length + 1; } }
package pages; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.Select; public class ManageReservesPage extends BasePage { private By addNewBankACBtnLocator = By.id("AccountAddNew"); private By accountTypeLocator = By.xpath("//select[@id='AccountType']"); private By defaultACChkBoxLocator = By.id("CLM_SC_013_DefaultAccount_10a"); private By bankACNumberTxtBoxLocator = By.id("CLM_SC_013_BankAccNo_10a"); private By routingNumberTxtBoxLocator = By.id("CLM_SC_013_SortCode_10a"); private By validateBtnLocator = By.id("accountValidate_10a"); private By saveBankACBtnLocator = By.id("accountSave_10a"); private String claimantLossRecordLocatorString = "//tr[(td[@id='CLAIMANT'] = '<claimant>') and (td[@id='RESERVETYPE'] = '<reserveType>')][1]"; private By reserveAmountTxtBoxLocator = By.id("CLM_SC_BO_0101_NewOS_50a"); private By reserveCancelBtnLocator = By.id("CLM_SC_BO_0101_Cancel"); private By reserveUpdateBtnLocator = By.id("CLM_SC_BO_0101_Update"); private By reserveConfirmBtnLocator = By.id("CLM_SC_BO_0101_Confirm"); public void clickAddNewBankACButton() { writeStepToTestNGReport("Click Add New Bank AC button"); driver.get().findElement(addNewBankACBtnLocator).click(); } public void selectBankACType(String accountType) { writeStepToTestNGReport("Select bank AC type"); new Select(driver.get().findElement(accountTypeLocator)).selectByVisibleText(accountType); } public void selectDefaultAC(String defaultAC) { writeStepToTestNGReport("Select Default AC check box"); defaultAC = defaultAC.trim().toUpperCase(); boolean isSelected = driver.get().findElement(defaultACChkBoxLocator).isSelected(); if (defaultAC.equals("YES")) { if (!isSelected) driver.get().findElement(defaultACChkBoxLocator).click(); } else { if (isSelected) driver.get().findElement(defaultACChkBoxLocator).click(); } } public void enterBankACNumber(String bankACNumber) { writeStepToTestNGReport("Enter bank account number"); driver.get().findElement(bankACNumberTxtBoxLocator).sendKeys(bankACNumber); } public void enterRoutingNumber(String routingNumber) { writeStepToTestNGReport("Enter routing number"); driver.get().findElement(routingNumberTxtBoxLocator).click(); driver.get().findElement(routingNumberTxtBoxLocator).sendKeys(routingNumber); } public void clickValidateBtn() { writeStepToTestNGReport("Click Validate button"); driver.get().findElement(validateBtnLocator).click(); progressSync(); } public void clickSaveBankACBtn() { writeStepToTestNGReport("Click Save Bank AC button"); driver.get().findElement(saveBankACBtnLocator).click(); progressSync(); } public void selectClaimantLossRecord(String policyHolderName, String reserveType) { writeStepToTestNGReport("Select claimant loss record"); driver.get().findElement(By.xpath((claimantLossRecordLocatorString.replace("<claimant>", policyHolderName)).replace("<reserveType>", reserveType))).click(); } public String enterAndGetReserveAmount(String reserveAmount) { String rtnReserveAmt = reserveAmount; String reserveAmtFromApp = driver.get().findElement(reserveAmountTxtBoxLocator).getAttribute("value"); Float reserveAmtFromAppFloat = Float.parseFloat(reserveAmtFromApp); Float reserveAmtForInput = Float.parseFloat(reserveAmount); if (reserveAmtFromAppFloat >= reserveAmtForInput){ rtnReserveAmt = Float.toString(reserveAmtFromAppFloat); driver.get().findElement(reserveConfirmBtnLocator).click(); } else { driver.get().findElement(reserveAmountTxtBoxLocator).sendKeys(reserveAmount); driver.get().findElement(reserveUpdateBtnLocator).click(); progressSync(); } return rtnReserveAmt; } }
package com.test; import java.io.IOException; import com.android.uiautomator.core.UiObjectNotFoundException; import com.android.uiautomator.testrunner.UiAutomatorTestCase; public class Helper { private UiAutomatorTestCase testcase; public Helper(UiAutomatorTestCase testcase) { this.testcase = testcase; } public void findAppWithName(String name, String packagename) throws UiObjectNotFoundException { try { Runtime.getRuntime().exec("am start -n " + packagename); testcase.sleep(1000); } catch (IOException e) { e.printStackTrace(); } for (int i = 0; i < 5; i++) { testcase.sleep(1000); if (testcase.getUiDevice().getCurrentPackageName().contains(packagename)) { return; } } return; } public void closeApp() { testcase.getUiDevice().pressBack(); testcase.getUiDevice().pressBack(); } }
package object; /** * 测试继承 * Object所有类的父类 */ public class TestExtends { public static void main(String[] args) { Student student = new Student("高晓青", 11, "计算机"); System.out.println("姓名 = " + student.name); System.out.println(student instanceof Student); //true System.out.println(student instanceof Person); //true System.out.println(student instanceof Object); //true } } class Person{ String name; int height; public void rest(){ System.out.println("休息一会儿"); } } class Student extends Person{ String major; public void study(){ System.out.println("休息一会儿"); } public Student(String name, int height, String major){ this.name = name; this.height = height; this.major = major; } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.log.pattern; import java.util.LinkedList; import java.util.List; /** * 样式格式配置解析类 * * @author 小流氓[176543888@qq.com] * @since 3.4.3 */ class PatternParser { /** * 格式定义的转义字符:% */ private static final char ESCAPE_CHAR = '%'; /** * 计算长度所用进制 */ private static final int DECIMAL = 10; /** * 解析临时用的SB */ private final StringBuilder tempSb = new StringBuilder(32); /** * 格式配置模板 */ private final String pattern; private final int patternLength; /** * 读指针 */ private int readIndex = 0; private PatternParser(String pattern) { this.pattern = pattern; this.patternLength = pattern.length(); } static List<PatternFormatter> parseFormatterList(String pattern) { return new PatternParser(pattern).parseFormatterList(); } List<PatternFormatter> parseFormatterList() { final List<PatternFormatter> formatterList = new LinkedList<>(); // 原样输出的起始位置 int literalIndex = 0; while (readIndex < patternLength) { char c = pattern.charAt(readIndex++); if (c == ESCAPE_CHAR) { // 发现%之前的格式先按固定输出提取 this.finalizeLiteralPatternConverter(formatterList, literalIndex); // % + 格式修饰符 + 识别编码 + {编码的参数} FormattingInfo formattingInfo = this.extractFormattingInfo(); String converterId = this.extractConverterId(); String options = this.extractOptions(); formatterList.add(FormatterFactory.create(converterId, formattingInfo, options)); // 重置下标 literalIndex = readIndex; } } // 最到后结束也要尝试按固定输出提取一下 this.finalizeLiteralPatternConverter(formatterList, literalIndex); return formatterList; } private void finalizeLiteralPatternConverter(List<PatternFormatter> converterList, int literalIndex) { if (readIndex - 1 > literalIndex) { char[] array = new char[readIndex - 1 - literalIndex]; pattern.getChars(literalIndex, readIndex - 1, array, 0); converterList.add(new LiteralPatternFormatter(array)); } } private String extractOptions() { tempSb.setLength(0); if (readIndex < patternLength && pattern.charAt(readIndex) == '{') { readIndex++; while (readIndex < patternLength) { char c = pattern.charAt(readIndex++); if (c == '}') { break; } tempSb.append(c); } } return tempSb.toString(); } /** * 提取转换器 */ private String extractConverterId() { tempSb.setLength(0); while (readIndex < patternLength) { char c = pattern.charAt(readIndex); if (Character.isUnicodeIdentifierPart(c)) { tempSb.append(c); this.readIndex++; } else { break; } } return tempSb.toString(); } /** * 提取格式化信息 * * @return 格式化信息 */ private FormattingInfo extractFormattingInfo() { // 最小长度 int minLength = 0; // 左对齐 boolean leftAlign = false; // %date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread][%file:%line] - %msg%n while (readIndex < patternLength) { char c = pattern.charAt(readIndex); // 使用左对齐 if (c == '-') { this.readIndex++; leftAlign = true; } // 最小长度 else if (c >= '0' && c <= '9') { this.readIndex++; minLength = minLength * DECIMAL + c - '0'; } // 配置结束,跳出循环 else { break; } } // 构建一个FormattingInfo,如果都是默认值,那就使用默认的 return FormattingInfo.getOrDefault(leftAlign, minLength); } }
package com.example.yx_lib_zxing.scanlogin.android; /** * Created by sdj on 2017/11/21. */ public class ScanConstants { //二维码弱光标识 public static boolean isWeakLight = false; public static final String KEY_DECODE_1D = "preferences_decode_1D"; public static final String KEY_DECODE_QR = "preferences_decode_QR"; public static final String KEY_DECODE_DATA_MATRIX = "preferences_decode_Data_Matrix"; public static final String KEY_CUSTOM_PRODUCT_SEARCH = "preferences_custom_product_search"; public static final String KEY_REVERSE_IMAGE = "preferences_reverse_image"; public static final String KEY_PLAY_BEEP = "preferences_play_beep"; public static final String KEY_VIBRATE = "preferences_vibrate"; public static final String KEY_FRONT_LIGHT = "preferences_front_light"; }
package com.harshitJaiswal.CareerBootCampEnteranceTest; /* * * Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, In how many ways can we make the change? The order of coins doesn’t matter. Input Format First line of input contain two space separated integers N and M. Second line of input contains M space separated integers - value of coins. Constraints 1<=N<=250 1<=m<=50 1 <= Si <= 50 Output Format Output a single integer denoting the number of ways to make the given change using given coin denominations. Sample Input 10 4 2 5 3 6 Sample Output 5 * * */ public class Main3 { }