blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
841da968dd58428840599527b7341e622512d422
c2388237306567a933b8a4133cda73633844e95e
/implementaciones/ColaPrioridadUno.java
9f77db163b316886cf3b66f80fd9447007337aba
[]
no_license
PabloLefort/uade-programming-II
0f233d436005f535bb1c933f722b75d2c3fe72a3
a3c3a80b219b1b764280fbbd8c45dc427072fd40
refs/heads/master
2020-03-30T06:32:54.881796
2018-10-09T02:59:47
2018-10-09T02:59:47
150,869,468
0
0
null
null
null
null
UTF-8
Java
false
false
906
java
public class ColaPrioridad implements ColaPrioridadTDA { int[] valores; int[] prioridades; int cantidad; public void InicializarCola(){ valores = new int[100]; prioridades = new int[100]; cantidad = 0; } public void Acolar(int x, int prioridad){ int i = this.cantidad; for (; i > 0 && this.prioridades[i] >= prioridad; i--) { this.valores[i] = this.valores[i-1]; this.prioridades[i] = this.prioridades[i-1]; } this.valores[i] = x; this.prioridades[i] = prioridad; this.cantidad++; } public void Desacolar(){ this.valores[this.cantidad-1] = null; this.prioridades[this.cantidad-1] = null; this.cantidad--; } public int Primero(){ return this.valores[this.cantidad-1]; } public int Prioridad(){ return this.prioridades[this.cantidad-1]; } public boolean ColaVacia(){ return (this.cantidad == 0) } }
5b5995f7213813fe33edf0527ae1a400b732160e
a6f37e9c63b011074755f941c32cf8ee242828cb
/src/main/java/tree/MathExpTreeMaker.java
4ae044fe1bdd29faf35fe2373652d071d06a5c76
[]
no_license
VafaTarighi/DataStructure
af6fdab22defc82ea3e94582801172e68489a1dc
68377462f1f0c33ff18f576181aaf80a8cb2dde4
refs/heads/master
2023-02-22T13:29:54.472371
2021-01-19T20:30:21
2021-01-19T20:30:21
315,920,157
2
0
null
null
null
null
UTF-8
Java
false
false
10,965
java
package tree; import calculator.Calculator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MathExpTreeMaker extends Calculator { public static class ExpressionTree { static class Node { private Object value; private Node parent; private Node left; private Node right; public Node(Object value) { this.value = value; } public Object getValue() { return value; } public Node getParent() { return parent; } public Node getLeft() { return left; } public Node getRight() { return right; } public boolean hasLeft() { return left != null; } public boolean hasRight() { return right != null; } public void setParent(Node parent) { this.parent = parent; } public void setLeft(Node left) { this.left = left; } public void setRight(Node right) { this.right = right; } } private final Node root; public ExpressionTree(Node root) { this.root = root; } public Node getRoot() { return root; } public String getPreorder() { Stack<Node> stack = new Stack<>(); stack.add(root); StringBuilder preorder = new StringBuilder(); preorder.append("[ "); while (!stack.isEmpty()) { Node p = stack.pop(); preorder.append('(').append(p.getValue()).append(')'); preorder.append(" => "); if (p.hasRight()) stack.push(p.getRight()); if (p.hasLeft()) stack.push(p.getLeft()); } preorder.delete(preorder.length()-4, preorder.length()); preorder.append(" ]"); return preorder.toString(); } public String getPostorder() { Stack<Node> stack1 = new Stack<>(); Stack<Node> stack2 = new Stack<>(); stack1.push(root); StringBuilder postorder = new StringBuilder(); postorder.append("[ "); while (!stack1.isEmpty()) { Node p = stack1.pop(); stack2.push(p); if (p.hasLeft()) stack1.push(p.getLeft()); if (p.hasRight()) stack1.push(p.getRight()); } while (!stack2.isEmpty()) { postorder.append('(').append(stack2.pop().getValue()).append(')'); postorder.append(" => "); } postorder.delete(postorder.length()-4, postorder.length()); postorder.append(" ]"); return postorder.toString(); } public String getInorder() { Stack<Node> stack = new Stack<>(); StringBuilder inorder = new StringBuilder(); inorder.append("[ "); Node current = root; while (!stack.isEmpty() || current != null) { while (current != null) { stack.push(current); current = current.getLeft(); } if (!stack.isEmpty()) { Node popped = stack.pop(); inorder.append('(').append(popped.getValue()).append(')'); inorder.append(" => "); current = popped.getRight(); } } inorder.delete(inorder.length()-4, inorder.length()); inorder.append(" ]"); return inorder.toString(); } public static Node createBound(Object parent, Object right, Object left) { Node p, l, r; if (parent instanceof Node) p = (Node) parent; else p = new Node(parent); if (left instanceof Node) l = (Node) left; else l = new Node(left); if (right instanceof Node) r = (Node) right; else r = new Node(right); p.setLeft(l); p.setRight(r); l.setParent(p); r.setParent(p); return p; } } public static void main(String[] args) throws IOException { System.out.println("-_-__Mathematical Expression Tree__-_-"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(".\n.\nto enter polish notation add [-p] flag to start of you input." + "\nto exit enter: exit" + "\n.\nSupported operators: + - * / ^ ( )" + "\n--------------------"); String input; List<Object> postfixList = null; List<String> polishlist = null; ExpressionTree et; while (true) { System.out.print(">>> "); input = reader.readLine(); if (input.equals("exit")) break; if (input.matches("^-p.+")) { polishlist = getPolishNotationList(input); if (!validatePolishNotation(polishlist)) { System.out.println("Invalid Input!"); continue; } et = createTreeWithPolish(polishlist); } else { input = input.replaceAll(" ", ""); if (!validateExpression(input)) { System.out.println("Invalid Input!"); continue; } postfixList = shuntingYard(input); et = createTreeWithPostfix(postfixList); } System.out.println("Pre-Order Traversal:"); System.out.println(et.getPreorder()); System.out.println("Post-Order Traversal:"); System.out.println(et.getPostorder()); System.out.println("In-Order Traversal:"); System.out.println(et.getInorder()); } } private static ExpressionTree createTreeWithPostfix(List<Object> postfixList) { Stack<Object> stack = new Stack<>(); while (!postfixList.isEmpty()) { stack.push(postfixList.remove(0)); if (stack.peek() instanceof String) { stack.push(ExpressionTree.createBound(stack.pop(), stack.pop(), stack.pop())); } } return new ExpressionTree((ExpressionTree.Node) stack.pop()); } private static List<String> getPolishNotationList(String input) { List<String> list = new LinkedList<>(); input = input.replaceAll("-p", "").trim(); String[] arr = input.split("\\s"); for (String s : arr) { if (s.length() != 0) list.add(s); } return list; } private static boolean validatePolishNotation(List<String> list) { int container = 0; String item; for (int i = list.size() - 1; i >= 0; i--) { item = list.get(i); if (!item.matches("\\d+|[+\\-*/^]")) return false; if (item.matches("\\d+")) container++; else container--; if (container < 1) return false; } return true; } private static ExpressionTree createTreeWithPolish(List<String> prefixList) { ExpressionTree et = new ExpressionTree(new ExpressionTree.Node(prefixList.remove(0))); ExpressionTree.Node current = et.getRoot(); ExpressionTree.Node left; ExpressionTree.Node right; while (!prefixList.isEmpty()) { if (current.getValue().toString().matches("\\d+")) { current = current.getParent(); } if(!current.hasLeft()) { left = new ExpressionTree.Node(prefixList.remove(0)); current.setLeft(left); left.setParent(current); current = current.getLeft(); } else if (!current.hasRight()) { right = new ExpressionTree.Node(prefixList.remove(0)); current.setRight(right); right.setParent(current); current = current.getRight(); } else { current = current.getParent(); } } return et; } private static final HashMap<String, Integer>oprPrecedence = new HashMap<>(); static { // add and subtract oprPrecedence.put("+", 1); oprPrecedence.put("-", 1); // multiply and divide oprPrecedence.put("×", 2); oprPrecedence.put("*", 2); oprPrecedence.put("÷", 2); oprPrecedence.put("/", 2); // power oprPrecedence.put("^", 3); } protected static List<Object> shuntingYard(String input) { Queue<String> items = new LinkedList<>(); Stack<String> operators = new Stack<>(); LinkedList<Object> output = new LinkedList<>(); input = "(" + input + ")"; // input = input.replaceAll("-\\(", "-1*("); Matcher ext = Pattern.compile("\\d+|\\D").matcher(input); while (ext.find()) { items.add(ext.group()); } boolean negative = false; while (!items.isEmpty()) { String element = items.poll(); if (element.matches("\\D")) { // if element is a operator if (element.equals("(")) { operators.push(element); if (items.peek().equals("-")) { negative = true; items.poll(); } } else if (element.equals(")")) { while (!operators.peek().equals("(")) { output.add(operators.pop()); } operators.pop(); } else if (operators.isEmpty() || operators.peek().equals("(") || element.equals("^") || oprPrecedence.get(element) > oprPrecedence.get(operators.peek())) { operators.push(element); } else { while (!operators.isEmpty() && !operators.peek().equals("(") && oprPrecedence.get(element) <= oprPrecedence.get(operators.peek())) { output.add(operators.pop()); } operators.push(element); } } else { // if element is a number if (negative) { output.add(new BigInteger("-" + element)); negative = false; } else output.add(new BigInteger(element)); } } return output; } }
c4d293efc690abe4eabdaf75d19bea5c5b28433f
f82f8ddbba4f6e8f8d2a7d1339966398913968bb
/Lecher/형남/java31/st1swing/frmAlert.java
c16b83c71b116e1d2a4241d24cf937cbd8ecc094
[]
no_license
gunee7/workspace
66dd0e0151f1f1e3d316c38976fadded6da70398
c962907b6e0859062fc05078e9c9f43e6b62dcff
refs/heads/master
2021-05-07T15:14:04.814560
2018-02-20T09:07:17
2018-02-20T09:07:17
114,836,940
0
1
null
null
null
null
UTF-8
Java
false
false
1,785
java
package java31.st1swing; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class frmAlert extends JFrame { private JPanel contentPane; private JTextField textField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { frmAlert frame = new frmAlert(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public frmAlert() { setTitle("알림창 띄우기"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.setBounds(41, 40, 240, 21); contentPane.add(textField); textField.setColumns(10); JButton btnClick = new JButton("click"); btnClick.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, textField.getText()); } }); btnClick.setBounds(325, 39, 97, 23); contentPane.add(btnClick); } }
52f288dfc7a7d1402b6cb51b394e821af782fea2
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/JetBrains--intellij-community/26828018ddfe307bc785b66ef8602ffad16d3604/after/PyConvertModuleToPackageAction.java
81fdd990b42cc86d3a9b2b9ad619cdcc911fdcc9
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
2,759
java
package com.jetbrains.python.refactoring.convert; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.refactoring.RefactoringActionHandler; import com.jetbrains.python.PyNames; import com.jetbrains.python.psi.PyFile; import com.jetbrains.python.psi.PyUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; /** * @author Mikhail Golubev */ public class PyConvertModuleToPackageAction extends PyBaseConvertRefactoringAction { public static final String ID = "py.refactoring.convert.module.to.package"; private static final Logger LOG = Logger.getInstance(PyConvertModuleToPackageAction.class); @Override protected boolean isEnabledOnElements(@NotNull PsiElement[] elements) { if (elements.length == 1) { return elements[0] instanceof PyFile && !PyUtil.isPackage((PyFile)elements[0]); } return false; } @Nullable @Override protected RefactoringActionHandler getHandler(@NotNull DataContext dataContext) { return new RefactoringActionHandler() { @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) { createPackageFromModule((PyFile)file); } @Override public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) { createPackageFromModule(((PyFile)elements[0])); } }; } @VisibleForTesting public void createPackageFromModule(@NotNull final PyFile file) { final VirtualFile vFile = file.getVirtualFile(); final VirtualFile parentDir = vFile.getParent(); final String newPackageName = vFile.getNameWithoutExtension(); final VirtualFile existing = parentDir.findChild(newPackageName); if (existing != null) { showFileExistsErrorMessage(existing, ID, file.getProject()); return; } WriteCommandAction.runWriteCommandAction(file.getProject(), new Runnable() { public void run() { try { final VirtualFile packageDir = parentDir.createChildDirectory(PyConvertModuleToPackageAction.this, newPackageName); vFile.move(PyConvertModuleToPackageAction.this, packageDir); vFile.rename(PyConvertModuleToPackageAction.this, PyNames.INIT_DOT_PY); } catch (IOException e) { LOG.error(e); } } }); } }
3dd7f2184d9a18c790709ebfc76f223a3b4faa75
22769f92bfcee4afa631e39b7ad5e6c5b95eeab5
/src/test/java/com/dBank/tests/RegistrationFirstTest.java
14d1fbf63079e43f8c96f53b7da42e57ffd21657
[]
no_license
anjukumaris/automation_Dbank
a945b4e42e3a4515addc80ad4dd643f875a56425
e5a53317604275eb466501d66039439ac0656b24
refs/heads/main
2023-02-25T09:09:14.567725
2021-01-30T07:08:42
2021-01-30T07:08:42
334,349,871
0
0
null
null
null
null
UTF-8
Java
false
false
724
java
package com.dBank.tests; import com.dBank.library.BaseClass; import com.dBank.pages.Registration_FirstPage; import com.dBank.pages.SignUpPage; import org.testng.annotations.Test; public class RegistrationFirstTest extends BaseClass { // public LoginTest(WebDriver driver) { // super(driver); // } @Test(priority = 0) public void signUpTest(){ SignUpPage page=new SignUpPage(driver); page.registration(); } @Test(priority = 1) public void registrationTest(){ SignUpPage page=new SignUpPage(driver); page.registration(); Registration_FirstPage registration=new Registration_FirstPage(driver); registration.registraion_hardCord(); } }
57e2ca97706ec0b1ac4fddc456afa5b3d89a4367
2fe968e7d50a7e7691ab371bb67c76ac7aec7916
/src/main/java/org/tikv/operation/KVErrorHandler.java
5e4a6566b38618124986024448477773c50cdb60
[ "Apache-2.0" ]
permissive
KenyonZ/tidb-client-java
fa1510088a90644033dca224dbeb75b62a6390ce
1d62d71ed3a9a8907c21bc072e10c9c733a39348
refs/heads/master
2023-06-08T08:16:45.941263
2018-11-28T12:35:56
2018-11-28T12:35:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,586
java
/* * * Copyright 2017 PingCAP, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and * limitations under the License. * */ package org.tikv.operation; import com.google.protobuf.ByteString; import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.util.function.Function; import org.apache.log4j.Logger; import org.tikv.codec.KeyUtils; import org.tikv.event.CacheInvalidateEvent; import org.tikv.exception.GrpcException; import org.tikv.kvproto.Errorpb; import org.tikv.region.RegionErrorReceiver; import org.tikv.region.RegionManager; import org.tikv.region.TiRegion; import org.tikv.util.BackOffFunction; import org.tikv.util.BackOffer; // TODO: consider refactor to Builder mode public class KVErrorHandler<RespT> implements ErrorHandler<RespT> { private static final Logger logger = Logger.getLogger(KVErrorHandler.class); private static final int NO_LEADER_STORE_ID = 0; // if there's currently no leader of a store, store id is set to 0 private final Function<RespT, Errorpb.Error> getRegionError; private final Function<CacheInvalidateEvent, Void> cacheInvalidateCallBack; private final RegionManager regionManager; private final RegionErrorReceiver recv; private final TiRegion ctxRegion; public KVErrorHandler( RegionManager regionManager, RegionErrorReceiver recv, TiRegion ctxRegion, Function<RespT, Errorpb.Error> getRegionError) { this.ctxRegion = ctxRegion; this.recv = recv; this.regionManager = regionManager; this.getRegionError = getRegionError; this.cacheInvalidateCallBack = regionManager != null && regionManager.getSession() != null ? regionManager.getSession().getCacheInvalidateCallback() : null; } private Errorpb.Error getRegionError(RespT resp) { if (getRegionError != null) { return getRegionError.apply(resp); } return null; } private void invalidateRegionStoreCache(TiRegion ctxRegion) { regionManager.invalidateRegion(ctxRegion.getId()); regionManager.invalidateStore(ctxRegion.getLeader().getStoreId()); notifyRegionStoreCacheInvalidate( ctxRegion.getId(), ctxRegion.getLeader().getStoreId(), CacheInvalidateEvent.CacheType.REGION_STORE); } /** Used for notifying Spark driver to invalidate cache from Spark workers. */ private void notifyRegionStoreCacheInvalidate( long regionId, long storeId, CacheInvalidateEvent.CacheType type) { if (cacheInvalidateCallBack != null) { cacheInvalidateCallBack.apply(new CacheInvalidateEvent(regionId, storeId, true, true, type)); logger.info( "Accumulating cache invalidation info to driver:regionId=" + regionId + ",storeId=" + storeId + ",type=" + type.name()); } else { logger.warn( "Failed to send notification back to driver since CacheInvalidateCallBack is null in executor node."); } } private void notifyRegionCacheInvalidate(long regionId) { if (cacheInvalidateCallBack != null) { cacheInvalidateCallBack.apply( new CacheInvalidateEvent( regionId, 0, true, false, CacheInvalidateEvent.CacheType.REGION_STORE)); logger.info( "Accumulating cache invalidation info to driver:regionId=" + regionId + ",type=" + CacheInvalidateEvent.CacheType.REGION_STORE.name()); } else { logger.warn( "Failed to send notification back to driver since CacheInvalidateCallBack is null in executor node."); } } private void notifyStoreCacheInvalidate(long storeId) { if (cacheInvalidateCallBack != null) { cacheInvalidateCallBack.apply( new CacheInvalidateEvent( 0, storeId, false, true, CacheInvalidateEvent.CacheType.REGION_STORE)); } else { logger.warn( "Failed to send notification back to driver since CacheInvalidateCallBack is null in executor node."); } } // Referenced from TiDB // store/tikv/region_request.go - onRegionError @Override public boolean handleResponseError(BackOffer backOffer, RespT resp) { if (resp == null) { String msg = String.format("Request Failed with unknown reason for region region [%s]", ctxRegion); logger.warn(msg); return handleRequestError(backOffer, new GrpcException(msg)); } // Region error handling logic Errorpb.Error error = getRegionError(resp); if (error != null) { if (error.hasNotLeader()) { // this error is reported from raftstore: // peer of current request is not leader, the following might be its causes: // 1. cache is outdated, region has changed its leader, can be solved by re-fetching from PD // 2. leader of current region is missing, need to wait and then fetch region info from PD long newStoreId = error.getNotLeader().getLeader().getStoreId(); boolean retry = true; // update Leader here logger.warn( String.format( "NotLeader Error with region id %d and store id %d, new store id %d", ctxRegion.getId(), ctxRegion.getLeader().getStoreId(), newStoreId)); BackOffFunction.BackOffFuncType backOffFuncType; // if there's current no leader, we do not trigger update pd cache logic // since issuing store = NO_LEADER_STORE_ID requests to pd will definitely fail. if (newStoreId != NO_LEADER_STORE_ID) { if (!this.regionManager.updateLeader(ctxRegion.getId(), newStoreId) || !recv.onNotLeader(this.regionManager.getStoreById(newStoreId))) { // If update leader fails, we need to fetch new region info from pd, // and re-split key range for new region. Setting retry to false will // stop retry and enter handleCopResponse logic, which would use RegionMiss // backOff strategy to wait, fetch new region and re-split key range. // onNotLeader is only needed when updateLeader succeeds, thus switch // to a new store address. retry = false; } notifyRegionStoreCacheInvalidate( ctxRegion.getId(), newStoreId, CacheInvalidateEvent.CacheType.LEADER); backOffFuncType = BackOffFunction.BackOffFuncType.BoUpdateLeader; } else { logger.info( String.format( "Received zero store id, from region %d try next time", ctxRegion.getId())); backOffFuncType = BackOffFunction.BackOffFuncType.BoRegionMiss; } backOffer.doBackOff(backOffFuncType, new GrpcException(error.toString())); return retry; } else if (error.hasStoreNotMatch()) { // this error is reported from raftstore: // store_id requested at the moment is inconsistent with that expected // Solution:re-fetch from PD long storeId = ctxRegion.getLeader().getStoreId(); logger.warn( String.format( "Store Not Match happened with region id %d, store id %d", ctxRegion.getId(), storeId)); this.regionManager.invalidateStore(storeId); recv.onStoreNotMatch(this.regionManager.getStoreById(storeId)); notifyStoreCacheInvalidate(storeId); return true; } else if (error.hasStaleEpoch()) { // this error is reported from raftstore: // region has outdated version,please try later. logger.warn(String.format("Stale Epoch encountered for region [%s]", ctxRegion)); this.regionManager.onRegionStale(ctxRegion.getId()); notifyRegionCacheInvalidate(ctxRegion.getId()); return false; } else if (error.hasServerIsBusy()) { // this error is reported from kv: // will occur when write pressure is high. Please try later. logger.warn( String.format( "Server is busy for region [%s], reason: %s", ctxRegion, error.getServerIsBusy().getReason())); backOffer.doBackOff( BackOffFunction.BackOffFuncType.BoServerBusy, new StatusRuntimeException( Status.fromCode(Status.Code.UNAVAILABLE).withDescription(error.toString()))); return true; } else if (error.hasStaleCommand()) { // this error is reported from raftstore: // command outdated, please try later logger.warn(String.format("Stale command for region [%s]", ctxRegion)); return true; } else if (error.hasRaftEntryTooLarge()) { logger.warn(String.format("Raft too large for region [%s]", ctxRegion)); throw new StatusRuntimeException( Status.fromCode(Status.Code.UNAVAILABLE).withDescription(error.toString())); } else if (error.hasKeyNotInRegion()) { // this error is reported from raftstore: // key requested is not in current region // should not happen here. ByteString invalidKey = error.getKeyNotInRegion().getKey(); logger.error( String.format( "Key not in region [%s] for key [%s], this error should not happen here.", ctxRegion, KeyUtils.formatBytes(invalidKey))); throw new StatusRuntimeException(Status.UNKNOWN.withDescription(error.toString())); } logger.warn(String.format("Unknown error for region [%s]", ctxRegion)); // For other errors, we only drop cache here. // Upper level may split this task. invalidateRegionStoreCache(ctxRegion); } return false; } @Override public boolean handleRequestError(BackOffer backOffer, Exception e) { regionManager.onRequestFail(ctxRegion.getId(), ctxRegion.getLeader().getStoreId()); notifyRegionStoreCacheInvalidate( ctxRegion.getId(), ctxRegion.getLeader().getStoreId(), CacheInvalidateEvent.CacheType.REQ_FAILED); backOffer.doBackOff( BackOffFunction.BackOffFuncType.BoTiKVRPC, new GrpcException( "send tikv request error: " + e.getMessage() + ", try next peer later", e)); return true; } }
6c91bb1f5440dafac2aa7cb400af86c504423058
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-14263-34-16-FEMO-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/internal/template/InternalTemplateManager_ESTest_scaffolding.java
996e5116f5bc4f66bc15f396ec920b0b528a7d2f
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
459
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Sun Apr 05 03:06:24 UTC 2020 */ package com.xpn.xwiki.internal.template; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; @EvoSuiteClassExclude public class InternalTemplateManager_ESTest_scaffolding { // Empty scaffolding for empty test suite }
1ac086404fafc2e3bcd005a8e39d7b0c0450f14c
bca3acebfec4345036f495867a7599c7793ddaa1
/level4_subtract.java
aedb3537e7818f91f73903a790e4d54833b24e26
[]
no_license
SharedMocha/JavaI-Interview-Questions-Answers-from-interviewbit.com
f0e99f0ee92ebecf81094254c6be758a4065585b
fc3b864b4d7a7ba34cd6a0c2659b57ae5b9bad2d
refs/heads/master
2021-06-19T12:49:26.585125
2017-07-19T18:21:30
2017-07-19T18:21:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,572
java
/** Given a singly linked list, modify the value of first half nodes such that : 1st node’s new value = the last node’s value - first node’s current value 2nd node’s new value = the second last node’s value - 2nd node’s current value, and so on … NOTE : * If the length L of linked list is odd, then the first half implies at first floor(L/2) nodes. So, if L = 5, the first half refers to first 2 nodes. * If the length L of linked list is even, then the first half implies at first L/2 nodes. So, if L = 4, the first half refers to first 2 nodes. Example : Given linked list 1 -> 2 -> 3 -> 4 -> 5, You should return 4 -> 2 -> 3 -> 4 -> 5 as for first node, 5 - 1 = 4 for second node, 4 - 2 = 2 Try to solve the problem using constant extra space. **/ class ListNode { public int val; public ListNode next; ListNode(int x) { val = x; next = null; } } public class Solution { public ListNode subtract(ListNode a) { ListNode current = a; int length = 0; //get length while(current.next != null){ length++; current = current.next; } length += 1; int half = length/2; for(int i=0,j=length-1; i<half; i++,j-- ){ current.val=nthElement(a,j).val-current.val; current = current.next; } return a; } /* Helper function*/ public ListNode nthElement(ListNode head, int n){ ListNode nth = head; for(int i=0; i<n; i++){ nth = nth.next; } return nth; } }
d67731d872ede80ccbe00f83cfeb167adb31d799
16bd4e214cccbb931d32d610490214aee017b5eb
/training/trainingcore/src/com/sri/pal/training/core/assessment/ValueIssue.java
0b54a6cb5e7e3ed0db321c807133c18e65f60e02
[ "Apache-2.0" ]
permissive
SRI-SAVE/ESE
df081e0f974fc37c1054f0a6d552d3fbf69fe300
e06ec5cd47d69ee6da10e0c7544787a53189a024
refs/heads/master
2021-01-10T15:31:33.086493
2016-07-26T17:05:01
2016-07-26T17:05:01
54,749,142
0
0
null
null
null
null
UTF-8
Java
false
false
1,263
java
/* * Copyright 2016 SRI International * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sri.pal.training.core.assessment; import javax.xml.bind.annotation.XmlTransient; import com.sri.pal.training.core.basemodels.ValueIssueBase; import com.sri.pal.training.core.exercise.ValueConstraint; public class ValueIssue extends ValueIssueBase { @XmlTransient private final ValueConstraint constraint; @Deprecated public ValueIssue() { constraint = null; } public ValueIssue(ValueConstraint constraint, ArgumentLocation loc) { super(); this.constraint = constraint; this.setLocation(loc); } public ValueConstraint getConstraint() { return constraint; } }
d236a7dfe4d6bb1342edb1852eebce9e03b5aacd
a1631fb61ced7ce300a5185346ebf1201ff72e35
/SCM_Water_frontDesk/src/main/java/util/RandomUtil.java
4f5055ce19247b9c1ff9797bd5063e3e447f2013
[]
no_license
tiancai1111/SCM_Water
54465e7cd63f3c51921b7845474c77f164ba709a
bde2c9399c5b3fd3cdf86a05538a4e0f5aa90405
refs/heads/master
2020-04-13T21:58:28.026537
2019-01-18T11:11:28
2019-01-18T11:11:28
163,261,588
0
0
null
null
null
null
UTF-8
Java
false
false
261
java
package util; /** * 随机数类 */ public class RandomUtil { /** * 返回前时间戳作为随机数 13位 * @return */ public static String getRandomNum() { String str=String.valueOf(System.currentTimeMillis()); return str; } }
e5b422730d83c98681a353253b8737cc08247913
9412cd1fc2ae3151f8516b7c141787a45da1cde6
/pp-workspace/webadmin/src/main/java/com/pengpeng/admin/stargame/manager/impl/PlayerSaleActionModelManagerImpl.java
5e9b1b3c679a357a56ef4fd65d911537e9c3485b
[]
no_license
imjamespond/java-recipe
2322d98d8db657fcd7e4784f706b66c10bee8d8b
6b8b0a6b46326dde0006d7544ffa8cc1ae647a0b
refs/heads/master
2021-08-28T18:22:43.811299
2016-09-27T06:41:00
2016-09-27T06:41:00
68,710,592
0
1
null
null
null
null
UTF-8
Java
false
false
4,094
java
package com.pengpeng.admin.stargame.manager.impl; import org.springframework.beans.factory.annotation.Qualifier; import java.io.Serializable; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Repository; import org.apache.commons.logging.Log; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.apache.commons.lang.builder.ToStringBuilder; import com.pengpeng.admin.stargame.dao.IPlayerSaleActionModelDao; import com.pengpeng.admin.stargame.manager.IPlayerSaleActionModelManager; import com.pengpeng.admin.stargame.model.PlayerSaleActionModel; import com.tongyi.exception.BeanAreadyException; import com.tongyi.exception.NotFoundBeanException; import java.util.Map; import java.util.HashMap; import com.tongyi.action.Page; import com.pengpeng.stargame.exception.GameException; import com.pengpeng.stargame.rpc.PlayerRpcRemote; import com.pengpeng.stargame.vo.role.PlayerVO; /** * managerImpl.vm * @author fangyaoxia */ @Repository(value = "playerSaleActionModelManager") public class PlayerSaleActionModelManagerImpl implements IPlayerSaleActionModelManager{ private static final Log log = LogFactory.getLog(PlayerSaleActionModelManagerImpl.class); @Autowired @Qualifier(value="playerSaleActionModelDao") private IPlayerSaleActionModelDao playerSaleActionModelDao; @Autowired private PlayerRpcRemote playerRpcRemote; @Override public PlayerSaleActionModel findById(Serializable id) throws NotFoundBeanException{ return playerSaleActionModelDao.findById(id); } public PlayerSaleActionModel createBean(PlayerSaleActionModel playerSaleActionModel) throws BeanAreadyException{ if (log.isDebugEnabled()){ log.debug("createBean:"+playerSaleActionModel); } playerSaleActionModelDao.createBean(playerSaleActionModel); return playerSaleActionModel; } @Override public void updateBean(PlayerSaleActionModel playerSaleActionModel) throws NotFoundBeanException{ if (log.isDebugEnabled()){ log.debug("updateBean:"+playerSaleActionModel); } playerSaleActionModelDao.updateBean(playerSaleActionModel); } @Override public void removeBean(Serializable id) throws NotFoundBeanException{ if (log.isDebugEnabled()){ log.debug("removeBean:"+id); } playerSaleActionModelDao.removeBean(id); } @Override public void removeBean(PlayerSaleActionModel playerSaleActionModel) throws NotFoundBeanException{ if (log.isDebugEnabled()){ log.debug("removeBean:"+playerSaleActionModel); } playerSaleActionModelDao.removeBean(playerSaleActionModel); } @Override public Page<PlayerSaleActionModel> findPages(Map<String,Object> params,int pageNo,int pageSize){ if (log.isDebugEnabled()){ log.debug("findPage[pageNo="+pageNo+",pageSize="+pageSize+";params="+ToStringBuilder.reflectionToString(params)+"]"); } if (pageNo<=0||pageSize<=0) throw new IllegalArgumentException("param.zero"); int start = (pageNo-1)*pageSize; Map<String,Object> map = new HashMap<String,Object>(params); map.remove("_"); String query = "from PlayerSaleActionModel a where id>0"; if(params.containsKey("uid")){ query+=" and a.uid=:uid"; } if(params.containsKey("dateBegin")&&params.containsKey("dateEnd")){ query+=" and a.date between :dateBegin and :dateEnd"; } Page<PlayerSaleActionModel> page = new Page<PlayerSaleActionModel>() ; List<PlayerSaleActionModel> list = playerSaleActionModelDao.findPages(query,map,start,pageSize); for (PlayerSaleActionModel pm : list) { com.pengpeng.stargame.rpc.Session session = new com.pengpeng.stargame.rpc.Session(pm.getPid(), ""); try { PlayerVO pv = playerRpcRemote.getPlayerInfo(session, pm.getPid()); pm.name = pv.getNickName(); } catch (GameException e) { e.printStackTrace(); } } page.setTotal(playerSaleActionModelDao.count("select count(*) "+query,map)); page.setRows(list); page.setPage(pageNo); return page; } }
6d61013ec7e2e13aa1e80b89eecc0b5eadc4bde2
4b0a833e9d32eb0b2c2a28c90040454c8bb7bd8f
/platforms/android/src/com/plugin/gcm/GCMIntentService.java
9a46aa4a64f4a218b33cbffed9912ef1c12563e1
[]
no_license
hollyschinsky/PushNotificationSample30
de1adbb4d995b776693980a745fb8d6ff1decd71
438d03f0ffdcc7da4aed8e09cce4011d4430f471
refs/heads/master
2020-04-27T00:11:20.043102
2013-09-22T20:40:10
2013-09-22T20:40:10
13,020,540
8
27
null
2015-01-29T22:20:08
2013-09-22T20:35:45
JavaScript
UTF-8
Java
false
false
4,633
java
package com.plugin.gcm; import java.util.List; import com.google.android.gcm.GCMBaseIntentService; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.util.Log; @SuppressLint("NewApi") public class GCMIntentService extends GCMBaseIntentService { public static final int NOTIFICATION_ID = 237; private static final String TAG = "GCMIntentService"; public GCMIntentService() { super("GCMIntentService"); } @Override public void onRegistered(Context context, String regId) { Log.v(TAG, "onRegistered: "+ regId); JSONObject json; try { json = new JSONObject().put("event", "registered"); json.put("regid", regId); Log.v(TAG, "onRegistered: " + json.toString()); // Send this JSON data to the JavaScript application above EVENT should be set to the msg type // In this case this is the registration ID PushPlugin.sendJavascript( json ); } catch( JSONException e) { // No message to the user is sent, JSON failed Log.e(TAG, "onRegistered: JSON exception"); } } @Override public void onUnregistered(Context context, String regId) { Log.d(TAG, "onUnregistered - regId: " + regId); } @Override protected void onMessage(Context context, Intent intent) { Log.d(TAG, "onMessage - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); if (extras != null) { boolean foreground = this.isInForeground(); extras.putBoolean("foreground", foreground); if (foreground) PushPlugin.sendExtras(extras); else createNotification(context, extras); } } public void createNotification(Context context, Bundle extras) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(this); Intent notificationIntent = new Intent(this, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(context.getApplicationInfo().icon) .setWhen(System.currentTimeMillis()) .setContentTitle(appName) .setTicker(appName) .setContentIntent(contentIntent); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } mNotificationManager.notify((String) appName, NOTIFICATION_ID, mBuilder.build()); tryPlayRingtone(); } private void tryPlayRingtone() { try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } catch (Exception e) { Log.e(TAG, "failed to play notification ringtone"); } } public static void cancelNotification(Context context) { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.cancel((String)getAppName(context), NOTIFICATION_ID); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String)appName; } public boolean isInForeground() { ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> services = activityManager .getRunningTasks(Integer.MAX_VALUE); if (services.get(0).topActivity.getPackageName().toString().equalsIgnoreCase(getApplicationContext().getPackageName().toString())) return true; return false; } @Override public void onError(Context context, String errorId) { Log.e(TAG, "onError - errorId: " + errorId); } }
00dd0eaad20547183dff773694ff28674c92bf4a
7571a87a644bd5a0256fb9cd6b2c9657a6d358cb
/src/main/java/com/rover/domain/EnvironmentDomain.java
637ac4f9ca2c0f6d0f418ee9ca45d6c8d1444bb9
[]
no_license
muthumkp13/RoverServices
a82aab3c44f455d15ba101658e394416fb2861b2
86515909a29a762190c42b7de97edffe1881d4c2
refs/heads/main
2023-06-22T13:45:18.752301
2021-07-29T07:11:16
2021-07-29T07:11:16
321,244,982
0
0
null
2021-07-29T07:11:17
2020-12-14T05:38:15
Java
UTF-8
Java
false
false
552
java
package com.rover.domain; import java.util.List; import com.rover.model.Environment; import com.rover.model.TerrainType; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) public class EnvironmentDomain { long temperature; long humidity; boolean solarFlare; boolean storm; List<List<TerrainType>> areaMap; public Environment toModel() { return new Environment().setAreaMap(areaMap).setHumidity(humidity) .setSolarFlare(solarFlare).setStorm(storm).setTemperature(temperature); } }
d91c36f04d697e72bc6770f270e928e170f15d11
3341ab3a9e719d182305fd362f6fbb8ca1caba91
/app/src/test/java/com/yilang/lemon/yilang/ExampleUnitTest.java
ba74c31f1bbc33bae77ddae07e2c0a797685b928
[]
no_license
Lemonqsj/YiLang
2cff817e905b5e7324d88920a6fcace949258f8d
b94e2877aec224c6ccb97b8ab5013e7f7c8e0463
refs/heads/master
2021-01-25T06:55:55.159557
2017-06-07T11:55:09
2017-06-07T11:55:09
93,626,420
0
0
null
null
null
null
UTF-8
Java
false
false
401
java
package com.yilang.lemon.yilang; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
4951aa0d0646248ce655f708f1eeb859bcef2cc4
e8146efc6a9e5095316aac2760125ba600886c8d
/app/src/main/java/com/brightkidmont/brilla/my_bright_brain/visual/colors/black/Black3.java
bcaaa74ef0798a4e28f95e5ab9fc1945df833846
[]
no_license
alijawdat/Brilla-pre
8cfb84f12abee03f0ed0d17e4ef87e73927bf638
85c5c1958cdd2822a394cbbd2d56b316151fe53e
refs/heads/master
2020-06-30T16:57:35.249991
2018-03-28T05:56:21
2018-03-28T05:56:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,912
java
package com.brightkidmont.brilla.my_bright_brain.visual.colors.black; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.brightkidmont.brilla.R; import com.squareup.picasso.Picasso; import static com.brightkidmont.brilla.my_bright_brain.visual.colors.black.BlackActivity.correct; import static com.brightkidmont.brilla.my_bright_brain.visual.colors.black.BlackActivity.q; import static com.brightkidmont.brilla.my_bright_brain.visual.colors.black.BlackActivity.wrong; public class Black3 extends Fragment implements View.OnClickListener { private ImageView crow1; private ImageView crow2; private ImageView black_right; private ImageView red_wrong; private ImageView blue_wrong; public Black3(){ } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.black3, container, false); TextView flash_header = (TextView) view.findViewById(R.id.flash_header); flash_header.setText("Color the crow with black color"); RelativeLayout flash_question = (RelativeLayout) view.findViewById(R.id.flash_question); flash_question.setBackgroundColor(getResources().getColor(R.color.f_black)); crow1 = (ImageView) view.findViewById(R.id.crow1); crow2 = (ImageView) view.findViewById(R.id.crow2); ImageView blackc = (ImageView) view.findViewById(R.id.blackc); ImageView redc = (ImageView) view.findViewById(R.id.redc); ImageView bluec = (ImageView) view.findViewById(R.id.bluec); black_right = (ImageView) view.findViewById(R.id.black_right); red_wrong = (ImageView) view.findViewById(R.id.red_wrong); blue_wrong = (ImageView) view.findViewById(R.id.blue_wrong); ImageView speaker = (ImageView) view.findViewById(R.id.speaker); String image1, image2; image1 = "https://firebasestorage.googleapis.com/v0/b/brilla-47f1f.appspot.com/o/Colors%2FBlack%2Fcrow1.png?alt=media&token=b6005247-cecc-48d6-ba6b-be7b503e41d9"; image2 = "https://firebasestorage.googleapis.com/v0/b/brilla-47f1f.appspot.com/o/Colors%2FBlack%2Fcrow2.png?alt=media&token=4bb2a16f-7172-45c4-9ab5-52b25d19f972"; Picasso.with(getContext()).load(image1).error(R.drawable.bright_kid_bg).into(crow1); Picasso.with(getContext()).load(image2).error(R.drawable.bright_kid_bg).into(crow2); crow2.setVisibility(View.GONE); black_right.setVisibility(View.GONE); red_wrong.setVisibility(View.GONE); blue_wrong.setVisibility(View.GONE); blackc.setOnClickListener(this); redc.setOnClickListener(this); bluec.setOnClickListener(this); speaker.setOnClickListener(this); return view; } public void transition_anim(){ Animation fade_out = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out); crow2.setVisibility(View.VISIBLE); crow2.startAnimation(fade_out); Animation fade_in = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in); crow1.startAnimation(fade_in); } public void hideView(){ Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { black_right.setVisibility(View.GONE); red_wrong.setVisibility(View.GONE); blue_wrong.setVisibility(View.GONE); } },1000); } @Override public void onClick(View v) { int id = v.getId(); if(!q.isPlaying() && !wrong.isPlaying()) { switch (id) { case R.id.blackc: correct.start(); black_right.setVisibility(View.VISIBLE); hideView(); transition_anim(); break; case R.id.redc: wrong.start(); red_wrong.setVisibility(View.VISIBLE); hideView(); break; case R.id.bluec: wrong.start(); blue_wrong.setVisibility(View.VISIBLE); hideView(); break; case R.id.speaker: q.start(); break; } } } }
7425918f596e7aa06d111b7a33406df5e4375304
eb5008a7b2076d039bdc7a742a4d14f8f82af612
/member/member/src/main/java/com/aristotle/member/service/MemberService.java
450437cb58ca5263223a90563e2f3143f463004b
[]
no_license
ModernAristotle/aristotle
49a57530c7b61a80bc3d72ef754f560dd5fb3f84
0e68dd81af123bdc20ddf00dab860b1969d384bf
refs/heads/master
2020-04-04T04:13:26.780390
2017-05-21T07:17:09
2017-05-21T07:17:09
35,366,339
0
3
null
2016-08-03T17:40:01
2015-05-10T10:19:25
Java
UTF-8
Java
false
false
415
java
package com.aristotle.member.service; import com.aristotle.core.exception.AppException; import com.aristotle.core.persistance.User; public interface MemberService { public User login(String userName, String password) throws AppException; public User register(String userName, String password, String passwordConfirm, String email, String countryCode, String mobileNumber, boolean nri) throws AppException; }
2db69d795ddc5f0568923a0f409d67dd22fc62c7
eff9a71fdec8f23f241602d0009d1217eb991b39
/src/main/java/com/vinculomedico/sinergis/api/config/LoggingConfiguration.java
616d59b2632aa1fa131de5dc7f47f27cd88f0932
[]
no_license
gpalli/jhipstermicroservice
fd7f19dddcf3ea213ab2465b0b175ab7ff78da22
d28681a90844d90ec1ceeea4ecba8f47a6089aa3
refs/heads/master
2021-01-15T17:15:26.985917
2017-08-08T22:50:10
2017-08-08T22:50:10
99,742,705
0
0
null
null
null
null
UTF-8
Java
false
false
4,489
java
package com.vinculomedico.sinergis.api.config; import io.github.jhipster.config.JHipsterProperties; import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggerContextListener; import ch.qos.logback.core.spi.ContextAwareBase; import net.logstash.logback.appender.LogstashSocketAppender; import net.logstash.logback.stacktrace.ShortenedThrowableConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class LoggingConfiguration { private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class); private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); private final String appName; private final String serverPort; private final String instanceId; private final JHipsterProperties jHipsterProperties; public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, @Value("${eureka.instance.instanceId}") String instanceId, JHipsterProperties jHipsterProperties) { this.appName = appName; this.serverPort = serverPort; this.instanceId = instanceId; this.jHipsterProperties = jHipsterProperties; if (jHipsterProperties.getLogging().getLogstash().isEnabled()) { addLogstashAppender(context); // Add context listener LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener(); loggerContextListener.setContext(context); context.addListener(loggerContextListener); } } public void addLogstashAppender(LoggerContext context) { log.info("Initializing Logstash logging"); LogstashSocketAppender logstashAppender = new LogstashSocketAppender(); logstashAppender.setName("LOGSTASH"); logstashAppender.setContext(context); String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"," + "\"instance_id\":\"" + instanceId + "\"}"; // Set the Logstash appender config from JHipster properties logstashAppender.setSyslogHost(jHipsterProperties.getLogging().getLogstash().getHost()); logstashAppender.setPort(jHipsterProperties.getLogging().getLogstash().getPort()); logstashAppender.setCustomFields(customFields); // Limit the maximum length of the forwarded stacktrace so that it won't exceed the 8KB UDP limit of logstash ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setMaxLength(7500); throwableConverter.setRootCauseFirst(true); logstashAppender.setThrowableConverter(throwableConverter); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName("ASYNC_LOGSTASH"); asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger("ROOT").addAppender(asyncLogstashAppender); } /** * Logback configuration is achieved by configuration file and API. * When configuration file change is detected, the configuration is reset. * This listener ensures that the programmatic configuration is also re-applied after reset. */ class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener { @Override public boolean isResetResistant() { return true; } @Override public void onStart(LoggerContext context) { addLogstashAppender(context); } @Override public void onReset(LoggerContext context) { addLogstashAppender(context); } @Override public void onStop(LoggerContext context) { // Nothing to do. } @Override public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) { // Nothing to do. } } }
16063482ebef1cf25d9636d68bb53444aaf12b6c
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/7/7_b570104118b6354efadbdd09267ae82568fac5ef/AtmosphereResponse/7_b570104118b6354efadbdd09267ae82568fac5ef_AtmosphereResponse_t.java
78f24dd2a505e554b873c4653e32a2ef8246a48d
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
37,936
java
/* * Copyright 2013 Jeanfrancois Arcand * * 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.atmosphere.cpr; import org.atmosphere.websocket.WebSocket; import org.atmosphere.util.ServletProxyFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM; import static org.atmosphere.cpr.ApplicationConfig.RECYCLE_ATMOSPHERE_REQUEST_RESPONSE; /** * An Atmosphere's response representation. An AtmosphereResponse can be used to construct bi-directional asynchronous * application. If the underlying transport is a WebSocket or if its associated {@link AtmosphereResource} has been * suspended, this object can be used to write message back tp the client at any moment. * <br/> * This object can delegates the write operation to {@link AsyncIOWriter}. */ public class AtmosphereResponse extends HttpServletResponseWrapper { private final static Logger logger = LoggerFactory.getLogger(AtmosphereResponse.class); private final List<Cookie> cookies = new ArrayList<Cookie>(); private final Map<String, String> headers; private AsyncIOWriter asyncIOWriter; private int status = 200; private String statusMessage = "OK"; private String charSet = "UTF-8"; private long contentLength = -1; private String contentType = "text/html"; private boolean isCommited = false; private Locale locale; private boolean headerHandled = false; private AtmosphereRequest atmosphereRequest; private static final HttpServletResponse dsr = (HttpServletResponse) Proxy.newProxyInstance(AtmosphereResponse.class.getClassLoader(), new Class[]{HttpServletResponse.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return ServletProxyFactory.getDefault().proxy(proxy, method, args); } }); private final AtomicBoolean writeStatusAndHeader = new AtomicBoolean(false); private boolean delegateToNativeResponse; private boolean destroyable; private HttpServletResponse response; private boolean forceAsyncIOWriter = false; public AtmosphereResponse(AsyncIOWriter asyncIOWriter, AtmosphereRequest atmosphereRequest, boolean destroyable) { super(dsr); response = dsr; this.asyncIOWriter = asyncIOWriter; this.atmosphereRequest = atmosphereRequest; this.writeStatusAndHeader.set(false); this.headers = new HashMap<String, String>(); this.delegateToNativeResponse = asyncIOWriter == null; this.destroyable = destroyable; } public AtmosphereResponse(HttpServletResponse r, AsyncIOWriter asyncIOWriter, AtmosphereRequest atmosphereRequest, boolean destroyable) { super(r); response = r; this.asyncIOWriter = asyncIOWriter; this.atmosphereRequest = atmosphereRequest; this.writeStatusAndHeader.set(false); this.headers = new HashMap<String, String>(); this.delegateToNativeResponse = asyncIOWriter == null; this.destroyable = destroyable; } private AtmosphereResponse(Builder b) { super(b.atmosphereResponse); response = b.atmosphereResponse; this.asyncIOWriter = b.asyncIOWriter; this.atmosphereRequest = b.atmosphereRequest; this.status = b.status; this.statusMessage = b.statusMessage; this.writeStatusAndHeader.set(b.writeStatusAndHeader.get()); this.headers = b.headers; this.delegateToNativeResponse = asyncIOWriter == null; this.destroyable = b.destroyable; } public final static class Builder { private AsyncIOWriter asyncIOWriter; private int status = 200; private String statusMessage = "OK"; private AtmosphereRequest atmosphereRequest; private HttpServletResponse atmosphereResponse = dsr; private AtomicBoolean writeStatusAndHeader = new AtomicBoolean(true); private final Map<String, String> headers = new HashMap<String, String>(); private boolean destroyable = true; public Builder() { } public Builder destroyable(boolean isRecyclable) { this.destroyable = isRecyclable; return this; } public Builder asyncIOWriter(AsyncIOWriter asyncIOWriter) { this.asyncIOWriter = asyncIOWriter; return this; } public Builder status(int status) { this.status = status; return this; } public Builder statusMessage(String statusMessage) { this.statusMessage = statusMessage; return this; } public Builder request(AtmosphereRequest atmosphereRequest) { this.atmosphereRequest = atmosphereRequest; return this; } public AtmosphereResponse build() { return new AtmosphereResponse(this); } public Builder header(String name, String value) { headers.put(name, value); return this; } public Builder writeHeader(boolean writeStatusAndHeader) { this.writeStatusAndHeader.set(writeStatusAndHeader); return this; } public Builder response(HttpServletResponse res) { this.atmosphereResponse = res; return this; } } private HttpServletResponse _r() { return HttpServletResponse.class.cast(response); } public void destroy() { destroy(destroyable); } public void destroy(boolean force) { if (!force) return; cookies.clear(); headers.clear(); atmosphereRequest = null; asyncIOWriter = null; } /** * {@inheritDoc} */ @Override public void addCookie(Cookie cookie) { if (delegateToNativeResponse) { _r().addCookie(cookie); } else { cookies.add(cookie); } } /** * {@inheritDoc} */ @Override public boolean containsHeader(String name) { return !delegateToNativeResponse ? (headers.get(name) == null ? false : true) : _r().containsHeader(name); } /** * {@inheritDoc} */ @Override public String encodeURL(String url) { return response.encodeURL(url); } /** * {@inheritDoc} */ @Override public String encodeRedirectURL(String url) { return response.encodeRedirectURL(url); } /** * {@inheritDoc} */ @Override public String encodeUrl(String url) { return response.encodeURL(url); } /** * {@inheritDoc} */ @Override public String encodeRedirectUrl(String url) { return response.encodeRedirectURL(url); } public AtmosphereResponse delegateToNativeResponse(boolean delegateToNativeResponse) { this.delegateToNativeResponse = delegateToNativeResponse; return this; } /** * {@inheritDoc} */ @Override public void sendError(int sc, String msg) throws IOException { if (forceAsyncIOWriter || !delegateToNativeResponse) { setStatus(sc, msg); // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; asyncIOWriter.writeError(this, sc, msg); forceAsyncIOWriter = b; } else { if (!_r().isCommitted()) { _r().sendError(sc, msg); } else { logger.warn("Committed error code {} {}", sc, msg); } } } /** * {@inheritDoc} */ @Override public void sendError(int sc) throws IOException { if (forceAsyncIOWriter || !delegateToNativeResponse) { setStatus(sc); // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; asyncIOWriter.writeError(this, sc, ""); forceAsyncIOWriter = b; } else { if (!_r().isCommitted()) { _r().sendError(sc); } else { logger.warn("Committed error code {}", sc); } } } /** * {@inheritDoc} */ @Override public void sendRedirect(String location) throws IOException { if (forceAsyncIOWriter || !delegateToNativeResponse) { // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; asyncIOWriter.redirect(this, location); forceAsyncIOWriter = b; } else { _r().sendRedirect(location); } } /** * {@inheritDoc} */ @Override public void setDateHeader(String name, long date) { if (!delegateToNativeResponse) { headers.put(name, String.valueOf(date)); } else { _r().setDateHeader(name, date); } } /** * {@inheritDoc} */ @Override public void addDateHeader(String name, long date) { if (!delegateToNativeResponse) { headers.put(name, String.valueOf(date)); } else { _r().setDateHeader(name, date); } } /** * {@inheritDoc} */ @Override public void setHeader(String name, String value) { headers.put(name, value); if (delegateToNativeResponse) { _r().setHeader(name, value); } } /** * {@inheritDoc} */ @Override public void addHeader(String name, String value) { headers.put(name, value); if (delegateToNativeResponse) { _r().addHeader(name, value); } } /** * {@inheritDoc} */ @Override public void setIntHeader(String name, int value) { setHeader(name, String.valueOf(value)); } /** * {@inheritDoc} */ @Override public void addIntHeader(String name, int value) { setHeader(name, String.valueOf(value)); } /** * {@inheritDoc} */ @Override public void setStatus(int status) { if (!delegateToNativeResponse) { this.status = status; } else { _r().setStatus(status); } } /** * {@inheritDoc} */ @Override public void setStatus(int status, String statusMessage) { if (!delegateToNativeResponse) { this.statusMessage = statusMessage; this.status = status; } else { _r().setStatus(status, statusMessage); } } /** * {@inheritDoc} */ @Override public int getStatus() { return status; } public ServletResponse getResponse() { if (Proxy.class.isAssignableFrom(response.getClass())) { return this; } else { return super.getResponse(); } } public String getStatusMessage() { return statusMessage; } public Map<String, String> headers() { if (!headerHandled) { for (Cookie c : cookies) { headers.put("Set-Cookie", c.toString()); } headerHandled = false; } return headers; } /** * {@inheritDoc} */ @Override public String getHeader(String name) { if (name.equalsIgnoreCase("content-type")) { String s = headers.get("Content-Type"); return s == null ? contentType : s; } return headers.get(name); } /** * {@inheritDoc} */ @Override public Collection<String> getHeaders(String name) { ArrayList<String> s = new ArrayList<String>(); String h; if (name.equalsIgnoreCase("content-type")) { h = headers.get("Content-Type"); } else { h = headers.get(name); } s.add(h); return Collections.unmodifiableList(s); } /** * {@inheritDoc} */ @Override public Collection<String> getHeaderNames() { return Collections.unmodifiableSet(headers.keySet()); } /** * {@inheritDoc} */ @Override public void setCharacterEncoding(String charSet) { if (!delegateToNativeResponse) { this.charSet = charSet; } else { _r().setCharacterEncoding(charSet); } } /** * {@inheritDoc} */ @Override public void flushBuffer() throws IOException { try { response.flushBuffer(); } catch (IOException ex) { handleException(ex); throw ex; } } /** * {@inheritDoc} */ @Override public int getBufferSize() { return response.getBufferSize(); } /** * {@inheritDoc} */ @Override public String getCharacterEncoding() { if (!delegateToNativeResponse) { return charSet; } else { return _r().getCharacterEncoding() == null ? charSet : _r().getCharacterEncoding(); } } /** * Can this object be destroyed. Default is true. */ public boolean isDestroyable() { return destroyable; } public AtmosphereResponse destroyable(boolean destroyable) { this.destroyable = destroyable; return this; } /** * {@inheritDoc} */ @Override public ServletOutputStream getOutputStream() throws IOException { if (forceAsyncIOWriter || !delegateToNativeResponse) { return new ServletOutputStream() { @Override public void write(int i) throws java.io.IOException { if (asyncIOWriter == null) return; writeStatusAndHeaders(); // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; try { asyncIOWriter.write(AtmosphereResponse.this, new byte[]{(byte) i}); } catch (IOException e) { handleException(e); throw e; } finally { forceAsyncIOWriter = b; } } @Override public void write(byte[] bytes) throws java.io.IOException { if (asyncIOWriter == null) return; writeStatusAndHeaders(); // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; try { asyncIOWriter.write(AtmosphereResponse.this, bytes); } catch (IOException e) { handleException(e); throw e; } finally { forceAsyncIOWriter = b; } } @Override public void write(byte[] bytes, int start, int offset) throws java.io.IOException { if (asyncIOWriter == null) return; writeStatusAndHeaders(); // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; try { asyncIOWriter.write(AtmosphereResponse.this, bytes, start, offset); } catch (IOException e) { handleException(e); throw e; } finally { forceAsyncIOWriter = b; } } @Override public void flush() throws IOException { if (asyncIOWriter == null) return; writeStatusAndHeaders(); // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; try { asyncIOWriter.flush(AtmosphereResponse.this); } catch (IOException e) { handleException(e); throw e; } finally { forceAsyncIOWriter = b; } } @Override public void close() throws java.io.IOException { if (asyncIOWriter == null) return; // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; try { asyncIOWriter.close(AtmosphereResponse.this); } catch (IOException e) { handleException(e); throw e; } finally { forceAsyncIOWriter = b; } } }; } else { return _r().getOutputStream() != null ? _r().getOutputStream() : new ServletOutputStream() { @Override public void write(int b) throws IOException { } }; } } private void writeStatusAndHeaders() throws java.io.IOException { if (writeStatusAndHeader.getAndSet(false) && !forceAsyncIOWriter) { asyncIOWriter.write(this, constructStatusAndHeaders()); } } private String constructStatusAndHeaders() { StringBuffer b = new StringBuffer("HTTP/1.1") .append(" ") .append(status) .append(" ") .append(statusMessage) .append("\n"); b.append("Content-Type").append(":").append(headers.get("Content-Type") == null ? contentType : headers.get("Content-Type")).append("\n"); if (contentLength != -1) { b.append("Content-Length").append(":").append(contentLength).append("\n"); } for (String s : headers().keySet()) { if (!s.equalsIgnoreCase("Content-Type")) { b.append(s).append(":").append(headers.get(s)).append("\n"); } } b.deleteCharAt(b.length() - 1); b.append("\r\n\r\n"); return b.toString(); } /** * {@inheritDoc} */ @Override public PrintWriter getWriter() throws IOException { if (forceAsyncIOWriter || !delegateToNativeResponse) { return new PrintWriter(getOutputStream()) { @Override public void write(char[] chars, int offset, int lenght) { if (asyncIOWriter == null) return; // Prevent StackOverflow boolean b = forceAsyncIOWriter; try { writeStatusAndHeaders(); forceAsyncIOWriter = false; asyncIOWriter.write(AtmosphereResponse.this, new String(chars, offset, lenght)); } catch (IOException e) { handleException(e); throw new RuntimeException(e); } finally { forceAsyncIOWriter = b; } } @Override public void write(char[] chars) { if (asyncIOWriter == null) return; boolean b = forceAsyncIOWriter; try { writeStatusAndHeaders(); // Prevent StackOverflow forceAsyncIOWriter = false; asyncIOWriter.write(AtmosphereResponse.this, new String(chars)); } catch (IOException e) { handleException(e); throw new RuntimeException(e); } finally { forceAsyncIOWriter = b; } } @Override public void write(String s, int offset, int lenght) { if (asyncIOWriter == null) return; boolean b = forceAsyncIOWriter; try { writeStatusAndHeaders(); // Prevent StackOverflow forceAsyncIOWriter = false; asyncIOWriter.write(AtmosphereResponse.this, new String(s.substring(offset, lenght))); } catch (IOException e) { handleException(e); throw new RuntimeException(e); } finally { forceAsyncIOWriter = b; } } @Override public void write(String s) { if (asyncIOWriter == null) return; boolean b = forceAsyncIOWriter; try { writeStatusAndHeaders(); // Prevent StackOverflow forceAsyncIOWriter = false; asyncIOWriter.write(AtmosphereResponse.this, s); } catch (IOException e) { handleException(e); throw new RuntimeException(e); } finally { forceAsyncIOWriter = b; } } @Override public void flush() { if (asyncIOWriter == null) return; boolean b = forceAsyncIOWriter; try { writeStatusAndHeaders(); // Prevent StackOverflow forceAsyncIOWriter = false; asyncIOWriter.flush(AtmosphereResponse.this); } catch (IOException e) { handleException(e); } finally { forceAsyncIOWriter = b; } } @Override public void close() { if (asyncIOWriter == null) return; // Prevent StackOverflow boolean b = forceAsyncIOWriter; forceAsyncIOWriter = false; try { asyncIOWriter.close(AtmosphereResponse.this); } catch (IOException e) { handleException(e); } finally { forceAsyncIOWriter = b; } } }; } else { return _r().getWriter() != null ? _r().getWriter() : new PrintWriter(new StringWriter()); } } /** * {@inheritDoc} */ @Override public void setContentLength(int len) { headers.put("Content-Length", String.valueOf(len)); if (!delegateToNativeResponse) { contentLength = len; } else { _r().setContentLength(len); } } /** * {@inheritDoc} */ @Override public void setContentType(String contentType) { headers.put("Content-Type", String.valueOf(contentType)); if (!delegateToNativeResponse) { this.contentType = contentType; } else { _r().setContentType(contentType); } } /** * {@inheritDoc} */ @Override public String getContentType() { return getHeader("Content-type"); } /** * {@inheritDoc} */ @Override public boolean isCommitted() { if (!delegateToNativeResponse) { return isCommited; } else { return _r().isCommitted(); } } @Override public void reset() { response.reset(); } @Override public void resetBuffer() { response.resetBuffer(); } @Override public void setBufferSize(int size) { response.setBufferSize(size); } /** * {@inheritDoc} */ @Override public void setLocale(Locale locale) { if (!delegateToNativeResponse) { this.locale = locale; } else { _r().setLocale(locale); } } /** * {@inheritDoc} */ @Override public Locale getLocale() { if (!delegateToNativeResponse) { return locale; } else { return _r().getLocale(); } } /** * Return the underlying {@link AsyncIOWriter} */ public AsyncIOWriter getAsyncIOWriter() { return asyncIOWriter; } /** * Set an implementation of {@link AsyncIOWriter} that will be invoked every time a write operation is ready to be * processed. * * @param asyncIOWriter of {@link AsyncIOWriter} * @return this */ public AtmosphereResponse asyncIOWriter(AsyncIOWriter asyncIOWriter) { this.asyncIOWriter = asyncIOWriter; forceAsyncIOWriter = true; return this; } /** * Return the associated {@link AtmosphereRequest} * * @return the associated {@link AtmosphereRequest} */ public AtmosphereRequest request() { return atmosphereRequest; } /** * Set the associated {@link AtmosphereRequest} * * @param atmosphereRequest a {@link AtmosphereRequest} * @return this */ public AtmosphereResponse request(AtmosphereRequest atmosphereRequest) { this.atmosphereRequest = atmosphereRequest; return this; } /** * Close the associated {@link AsyncIOWriter} * * @throws IOException */ public void close() throws IOException { if (asyncIOWriter != null) { asyncIOWriter.close(this); } } /** * Close the associated {@link PrintWriter} or {@link java.io.OutputStream} */ public void closeStreamOrWriter() { if (resource() != null && resource().transport() != AtmosphereResource.TRANSPORT.WEBSOCKET) { try { boolean isUsingStream = (Boolean) request().getAttribute(PROPERTY_USE_STREAM); if (isUsingStream) { try { getOutputStream().close(); } catch (java.lang.IllegalStateException ex) { logger.trace("", ex); } } else { getWriter().close(); } } catch (IOException e) { logger.trace("", e); } } } /** * Write the String by either using the {@link PrintWriter} or {@link java.io.OutputStream}. The decision is * based on the request attribute {@link ApplicationConfig#PROPERTY_USE_STREAM} * * @param data the String to write */ public AtmosphereResponse write(String data) { return write(data, false); } private void handleException(Exception ex) { AtmosphereResource r = resource(); if (r != null) { AtmosphereResourceImpl.class.cast(r).notifyListeners( new AtmosphereResourceEventImpl(AtmosphereResourceImpl.class.cast(r), true, false)); } logger.trace("", ex); } /** * Write the String by either using the {@link PrintWriter} or {@link java.io.OutputStream}. The decision is * based on the request attribute {@link ApplicationConfig#PROPERTY_USE_STREAM} If writeUsingOriginalResponse if set to true, * execute the write without invoking the defined {@link AsyncIOWriter} * * @param data the String to write * @param writeUsingOriginalResponse if true, execute the write without invoking the {@link AsyncIOWriter} */ public AtmosphereResponse write(String data, boolean writeUsingOriginalResponse) { if (Proxy.class.isAssignableFrom(response.getClass())) { writeUsingOriginalResponse = false; } boolean isUsingStream = (Boolean) request().getAttribute(PROPERTY_USE_STREAM); try { if (isUsingStream) { try { OutputStream o = writeUsingOriginalResponse ? _r().getOutputStream() : getOutputStream(); o.write(data.getBytes(getCharacterEncoding())); } catch (java.lang.IllegalStateException ex) { logger.trace("", ex); } } else { PrintWriter w = writeUsingOriginalResponse ? _r().getWriter() : getWriter(); w.write(data); } } catch (Exception ex) { handleException(ex); } return this; } /** * Write the bytes by either using the {@link PrintWriter} or {@link java.io.OutputStream}. The decision is * based on the request attribute {@link ApplicationConfig#PROPERTY_USE_STREAM} * * @param data the bytes to write */ public AtmosphereResponse write(byte[] data) { return write(data, false); } /** * Write the String by either using the {@link PrintWriter} or {@link java.io.OutputStream}. The decision is * based on the request attribute {@link ApplicationConfig#PROPERTY_USE_STREAM} If writeUsingOriginalResponse if set to true, * execute the write without invoking the defined {@link AsyncIOWriter} * * @param data the bytes to write * @param writeUsingOriginalResponse if true, execute the write without invoking the {@link AsyncIOWriter} */ public AtmosphereResponse write(byte[] data, boolean writeUsingOriginalResponse) { if (Proxy.class.isAssignableFrom(response.getClass())) { writeUsingOriginalResponse = false; } boolean isUsingStream = (Boolean) request().getAttribute(PROPERTY_USE_STREAM); try { if (isUsingStream) { try { OutputStream o = writeUsingOriginalResponse ? _r().getOutputStream() : getOutputStream(); o.write(data); } catch (java.lang.IllegalStateException ex) { } } else { PrintWriter w = writeUsingOriginalResponse ? _r().getWriter() : getWriter(); w.write(new String(data, getCharacterEncoding())); } } catch (Exception ex) { handleException(ex); } return this; } /** * Write the bytes by either using the {@link PrintWriter} or {@link java.io.OutputStream}. The decision is * based on the request attribute {@link ApplicationConfig#PROPERTY_USE_STREAM} * * @param data the bytes to write * @param offset the first byte position to write * @param length the data length */ public AtmosphereResponse write(byte[] data, int offset, int length) { return write(data, offset, length, false); } /** * Write the String by either using the {@link PrintWriter} or {@link java.io.OutputStream}. The decision is * based on the request attribute {@link ApplicationConfig#PROPERTY_USE_STREAM} If writeUsingOriginalResponse if set to true, * execute the write without invoking the defined {@link AsyncIOWriter} * * @param data the bytes to write * @param offset the first byte position to write * @param length the data length * @param writeUsingOriginalResponse if true, execute the write without invoking the {@link AsyncIOWriter} */ public AtmosphereResponse write(byte[] data, int offset, int length, boolean writeUsingOriginalResponse) { if (Proxy.class.isAssignableFrom(response.getClass())) { writeUsingOriginalResponse = false; } boolean isUsingStream = (Boolean) request().getAttribute(PROPERTY_USE_STREAM); try { if (isUsingStream) { try { OutputStream o = writeUsingOriginalResponse ? _r().getOutputStream() : getOutputStream(); o.write(data, offset, length); } catch (java.lang.IllegalStateException ex) { } } else { PrintWriter w = writeUsingOriginalResponse ? _r().getWriter() : getWriter(); w.write(new String(data, offset, length, getCharacterEncoding())); } } catch (Exception ex) { handleException(ex); } return this; } /** * The {@link AtmosphereResource} associated with this request. If the request hasn't been suspended, this * method will return null. * * @return an {@link AtmosphereResource}, or null. */ public AtmosphereResource resource() { if (atmosphereRequest != null) { return (AtmosphereResource) atmosphereRequest.getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE); } else { return null; } } public void setResponse(ServletResponse response) { super.setResponse(response); if (HttpServletResponse.class.isAssignableFrom(response.getClass())) { this.response = HttpServletResponse.class.cast(response); } } /** * Create an instance not associated with any response parent. * * @return */ public final static AtmosphereResponse newInstance() { return new Builder().build(); } /** * Create a new instance to use with WebSocket. * * @return */ public final static AtmosphereResponse newInstance(AtmosphereConfig config, AtmosphereRequest request, WebSocket webSocket) { boolean destroyable; String s = config.getInitParameter(RECYCLE_ATMOSPHERE_REQUEST_RESPONSE); if (s != null && Boolean.valueOf(s)) { destroyable = true; } else { destroyable = false; } return new AtmosphereResponse(webSocket, request, destroyable); } /** * Wrap an {@link HttpServletResponse} * * @param response {@link HttpServletResponse} * @return an {@link AtmosphereResponse} */ public final static AtmosphereResponse wrap(HttpServletResponse response) { return new Builder().response(response).build(); } @Override public String toString() { return "AtmosphereResponse{" + "cookies=" + cookies + ", headers=" + headers + ", asyncIOWriter=" + asyncIOWriter + ", status=" + status + ", statusMessage='" + statusMessage + '\'' + ", charSet='" + charSet + '\'' + ", contentLength=" + contentLength + ", contentType='" + contentType + '\'' + ", isCommited=" + isCommited + ", locale=" + locale + ", headerHandled=" + headerHandled + ", atmosphereRequest=" + atmosphereRequest + ", writeStatusAndHeader=" + writeStatusAndHeader + ", delegateToNativeResponse=" + delegateToNativeResponse + ", destroyable=" + destroyable + ", response=" + response + '}'; } }
a61b85b5256edc3e3ff77212d078e696f7bfd41a
6fcbc86f5538954529bec5b550661b2531396a9c
/src/main/java/com/tests/helpers/ui/Fill.java
d5be8141122ac70738fe4487598a2739d9534193
[]
no_license
hemantjanrao/codingRound
31233a36ea4f5e3217fa079ed66d5ff971d882c9
2aa8ce8cff9ac94cc60f55691d2f54dd221e3d9e
refs/heads/master
2021-08-08T13:33:54.474087
2017-11-10T12:22:59
2017-11-10T12:22:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
447
java
package com.tests.helpers.ui; import org.openqa.selenium.WebElement; public class Fill { private Page page; WebElement element; public Fill(Page page, WebElement element) { this.page = page; this.element = element; } public Page with(String value) { element.clear(); element.sendKeys(value); //element.sendKeys(Keys.TAB); return page; } }
0aa1d654ab417c27690da480234a857bc7938fc9
f79dffd995910a4459dfada727f633d10dbacd2f
/src/main/java/com/yyt/wuziqi/ChessTest.java
210ab14e88276372edc4369f055a28cf43257872
[]
no_license
964849768qq/wuziqiAI
70c5f2fe783a4864ea4f41b1be225c25b268f16c
106f2fa82d555005799e49d1b27dfbbd513de1a8
refs/heads/main
2023-01-08T11:45:09.156529
2020-11-15T09:22:10
2020-11-15T09:22:10
312,993,128
2
0
null
null
null
null
UTF-8
Java
false
false
331
java
package com.yyt.wuziqi; public class ChessTest { public void test(int[][] board){ for (int i=0;i<15;i++){ for (int j=0;j<15;j++){ if(board[i][j]!=0){ System.out.println("(i,j):"+i+","+j+" "+board[i][j]); } } } } }
83d2954a8163ba81a9cd47fa93616cbf1fab0851
3f243991d3176769c1ab236f77ba82375873aca2
/app/src/main/java/br/com/simplepass/cadevanmotorista/ui/PathEvaluator.java
b3a032a353469ba4653edbdb6c58378bcd840002
[]
no_license
leandroBorgesFerreira/CadeVanMotorista
bcadca3d13dffb9fcf429a89553723399321d4fb
f294d5c8e2d475640d574868a84aab0b98fd7b5f
refs/heads/master
2021-01-12T16:03:14.075962
2017-10-27T12:12:15
2017-10-27T12:12:15
71,927,124
1
0
null
null
null
null
UTF-8
Java
false
false
2,165
java
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.simplepass.cadevanmotorista.ui; import android.animation.TypeEvaluator; /** * This evaluator interpolates between two PathPoint values given the value t, the * proportion traveled between those points. The value of the interpolation depends * on the operation specified by the endValue (the operation for the interval between * PathPoints is always specified by the end point of that interval). */ public class PathEvaluator implements TypeEvaluator<PathPoint> { @Override public PathPoint evaluate(float t, PathPoint startValue, PathPoint endValue) { float x, y; if (endValue.mOperation == PathPoint.CURVE) { float oneMinusT = 1 - t; x = oneMinusT * oneMinusT * oneMinusT * startValue.mX + 3 * oneMinusT * oneMinusT * t * endValue.mControl0X + 3 * oneMinusT * t * t * endValue.mControl1X + t * t * t * endValue.mX; y = oneMinusT * oneMinusT * oneMinusT * startValue.mY + 3 * oneMinusT * oneMinusT * t * endValue.mControl0Y + 3 * oneMinusT * t * t * endValue.mControl1Y + t * t * t * endValue.mY; } else if (endValue.mOperation == PathPoint.LINE) { x = startValue.mX + t * (endValue.mX - startValue.mX); y = startValue.mY + t * (endValue.mY - startValue.mY); } else { x = endValue.mX; y = endValue.mY; } return PathPoint.moveTo(x, y); } }
8fcfdfd1a7bcdc0a49bcdcdfb7195dcb4cd47bfe
4c4610a4fffe6a3a0488b57a3333bb420187a215
/app/src/main/java/com/rishavyaduvanshi/online_insurance_app/activity_login.java
8b153246417a4e222708de59d9f5abb297f8b830
[]
no_license
RishavYaduvanshi/Online-Insurance-App
6451f6077ea16133351652c097948b9229f11bd9
d46c6f2d89c46b1aeb60988fbc18e4cb10b5ed96
refs/heads/main
2023-08-14T00:47:21.204717
2021-09-13T12:07:01
2021-09-13T12:07:01
332,671,849
0
0
null
null
null
null
UTF-8
Java
false
false
4,848
java
package com.rishavyaduvanshi.online_insurance_app; //login page import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; public class activity_login extends AppCompatActivity { TextInputEditText username ,password; TextInputLayout pass1; private int count = 0; public static final String keepUser ="name"; public static final String keepPass ="pass"; public static final String MyPREFERENCES = "MyPrefs"; SharedPreferences sharedpreferences; Button btnlogin,createAccount,adminLogin; DatabaseHelper myDb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); myDb = new DatabaseHelper(this); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); username = findViewById(R.id.userlog); password =findViewById(R.id.passlog); btnlogin = findViewById(R.id.login); createAccount = findViewById(R.id.createbtn); pass1 = findViewById(R.id.pass); adminLogin = findViewById(R.id.adminbtn); autoLogin(sharedpreferences.getString(keepUser,""),sharedpreferences.getString(keepPass,"")); check(); createAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } }); adminLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(count==3){ Toast.makeText(getApplicationContext(),"You Are Now Developer",Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(), adminlogin.class); startActivity(intent); count = 0; } count++; } }); } public void check(){ btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = username.getText().toString(); String pass = password.getText().toString(); if (name.equals("")||pass.equals(""))//repass.equals("") Toast.makeText(activity_login.this,"Enter All details correctly",Toast.LENGTH_LONG).show(); else { if (pass!=null) {//pass.equals(repass) boolean checkUser = myDb.checkUserPass(name, pass); if (checkUser == false) { Toast.makeText(activity_login.this, "User Does Not Exist", Toast.LENGTH_LONG).show(); pass1.setError("User Does Not Exist"); } else{ Toast.makeText(activity_login.this, "Login Successful", Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(keepUser, name); editor.putString(keepPass, pass); editor.apply(); Intent intent = new Intent(getApplicationContext(),home.class); intent.putExtra("USER",name); intent.putExtra("PASSWORD",pass); username.setText(null); password.setText(null); startActivity(intent); } } } } }); } public void autoLogin(String name,String pass){ String user= sharedpreferences.getString(keepUser,""); if(user.equals("")){ Toast.makeText(getApplicationContext(),"No logged In User",Toast.LENGTH_LONG).show(); } else { Intent intent = new Intent(getApplicationContext(), home.class); intent.putExtra("USER",name); intent.putExtra("PASSWORD",pass); startActivity(intent); } } } //db = new DatabaseHelper(this);
c2df0ecdc5b51373162b73a9c9acb3f49f87b791
506f208747b6d40bf7584d2bf837775dbe4f0468
/src/main/java/com/huazhao/mapper/UserMapper.java
1ccf29498e88e75efb3252228f6f9171454fb19a
[]
no_license
huazhao666/lucky-draw
e819c696657112112b39d9f9ffbd5ab966679b7d
c5b8acc7181f09b362c52d1908bfc40a0926011a
refs/heads/master
2023-03-06T22:53:37.071949
2021-02-19T02:34:25
2021-02-19T02:34:25
340,237,681
0
0
null
null
null
null
UTF-8
Java
false
false
251
java
package com.huazhao.mapper; import com.huazhao.base.BaseMapper; import com.huazhao.model.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper extends BaseMapper<User> { User selectByUsername(String username); }
27daebef8e29934d9659083b80169ffe2a364889
eb9f655206c43c12b497c667ba56a0d358b6bc3a
/plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/KotlinIdeaBundle.java
aeaf0d62c2ae21bcd8bbd5cee22e06c72a9e8dcf
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JetBrains/intellij-community
2ed226e200ecc17c037dcddd4a006de56cd43941
05dbd4575d01a213f3f4d69aa4968473f2536142
refs/heads/master
2023-09-03T17:06:37.560889
2023-09-03T11:51:00
2023-09-03T12:12:27
2,489,216
16,288
6,635
Apache-2.0
2023-09-12T07:41:58
2011-09-30T13:33:05
null
UTF-8
Java
false
false
1,029
java
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea; import com.intellij.DynamicBundle; import org.jetbrains.annotations.*; import java.util.function.Supplier; public final class KotlinIdeaBundle { private static final @NonNls String BUNDLE_FQN = "messages.KotlinIdeaBundle"; private static final DynamicBundle BUNDLE = new DynamicBundle(KotlinIdeaBundle.class, BUNDLE_FQN); private KotlinIdeaBundle() { } public static @Nls @NotNull String message( @PropertyKey(resourceBundle = BUNDLE_FQN) @NotNull String key, @Nullable Object @NotNull ... params ) { return BUNDLE.getMessage(key, params); } public static @NotNull Supplier<@NotNull String> messagePointer( @PropertyKey(resourceBundle = BUNDLE_FQN) @NotNull String key, @Nullable Object @NotNull ... params ) { return BUNDLE.getLazyMessage(key, params); } }
847d2cf4411c49e5c903d61c5139a3f39beff875
35e5081f308b3c5e402bb99387b34861bede4b44
/Factorial.java
9d39252c86f6ddbc971af45bdd9cbdf864ba6f49
[]
no_license
niharika95/Java-Programs
f428c12e4e07aec2f07dcb5b82d20b9e0ae7dd4e
dcfac52c5dc94368016848915518cc5c3cac5a46
refs/heads/master
2020-07-22T11:27:39.389036
2017-02-25T09:12:08
2017-02-25T09:12:08
73,814,898
0
0
null
null
null
null
UTF-8
Java
false
false
541
java
// Factorial of a number package codingbat; import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a number: "); int num = sc.nextInt(); int fac = 1; if(num == 1){ System.out.println("1"); } for(int i = 1; i <= num; i++){ fac = fac * i; } System.out.println("\nThe factorial of " + num + " is " + fac); } }
7b84ce581194dd05396f1267452b7a0ce1db2a40
d8398d50f044d43b72d3d09acd3e94da5111f2ae
/spring-boot-demo/src/main/java/com/myke/springboot/demo/config/TaskSchedulerConfig.java
cfac50bb59418b9fb5ce62d194fa46144573455d
[]
no_license
zhangjianbinJAVA/spring-boot-zhang
d54aa588fefc5fb3a6ee3844477f1cf755e35d61
3972af29e8c9ab9576a3e0edc047fa8faa9ca8b8
refs/heads/master
2021-05-09T20:55:17.912902
2018-11-12T09:59:14
2018-11-12T09:59:56
118,711,912
0
0
null
null
null
null
UTF-8
Java
false
false
424
java
package com.myke.springboot.demo.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; /** * user: zhangjianbin <br/> * date: 2018/1/30 13:03 */ @Configuration @EnableScheduling // 开启对计划任务的支持 @ComponentScan("com.myke") public class TaskSchedulerConfig { }
d4a96ff5d0c6b4f7b89b98b0376a0bd383335955
4d627fe5508fbffb2df7f8d18176a73ec04d033d
/app/src/main/java/com/archstud/architecturestudyapp/model/DataObjectDiffUtilCallbackImpl.java
a7685ff1ac69b0dc469f617218611304c71ba292
[]
no_license
Oleksandr49/MVPStudyApp
efef5e685ce353ad46575fd44d7d1d8a8b8c3c4b
f2d516c71f67cf6b824609794679360073b42a6e
refs/heads/master
2023-03-22T12:48:55.045821
2021-03-18T08:10:35
2021-03-18T08:10:35
346,119,691
0
0
null
null
null
null
UTF-8
Java
false
false
1,366
java
package com.archstud.architecturestudyapp.model; import androidx.recyclerview.widget.DiffUtil; import com.archstud.architecturestudyapp.model.domainModels.DataObject; import java.util.List; public class DataObjectDiffUtilCallbackImpl extends DiffUtil.Callback { private final List<DataObject> oldList; private final List<DataObject> newList; public DataObjectDiffUtilCallbackImpl(List<DataObject> oldList, List<DataObject> newList){ this.newList = newList; this.oldList = oldList; } @Override public int getOldListSize() { return oldList.size(); } @Override public int getNewListSize() { return newList.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { DataObject oldItem = oldList.get(oldItemPosition); DataObject newItem = newList.get(newItemPosition); return oldItem.getId().equals(newItem.getId()); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { DataObject oldItem = oldList.get(oldItemPosition); DataObject newItem = newList.get(newItemPosition); return (oldItem.getName().equals(newItem.getName()) && oldItem.getDetails().equals(newItem.getDetails()) && (oldItem.getId().equals(newItem.getId()))); } }
9779eb3735a286dc7994804c54062f3a76414a0f
0386dd72896464326174b50eb6743a02d1a87c3f
/sandbox/core20/src/main/java/org/apache/myfaces/custom/effect/EffectToggleClientBehaviorRenderer.java
73f3eb6c160a761ffeeb8804d33590df0f553242
[]
no_license
bschuette/tomahawk
f6922930bbb54e6914325fce11764eeeff63ef07
8e300e4adbadeb7221df00c3bb2e71ead86b656f
refs/heads/master
2023-01-04T06:06:33.733606
2020-11-05T20:33:48
2020-11-05T20:33:48
310,410,746
0
0
null
null
null
null
UTF-8
Java
false
false
3,744
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.custom.effect; import javax.faces.FacesException; import javax.faces.application.ResourceDependencies; import javax.faces.application.ResourceDependency; import javax.faces.component.UIComponent; import javax.faces.component.behavior.ClientBehavior; import javax.faces.component.behavior.ClientBehaviorContext; import javax.faces.render.ClientBehaviorRenderer; import org.apache.myfaces.buildtools.maven2.plugin.builder.annotation.JSFClientBehaviorRenderer; @JSFClientBehaviorRenderer( renderKitId = "HTML_BASIC", type = "org.apache.myfaces.custom.effect.EffectToggleBehavior") @ResourceDependencies({ @ResourceDependency(library="oam.custom.prototype", name="prototype.js"), @ResourceDependency(library="oam.custom.prototype", name="effects.js") }) public class EffectToggleClientBehaviorRenderer extends ClientBehaviorRenderer { /** * Effect.Fade('id_of_element', { duration: 3.0 }); */ @Override public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) { AbstractEffectToggleClientBehavior effectBehavior = (AbstractEffectToggleClientBehavior) behavior; UIComponent target = ( effectBehavior.getForId() != null ) ? behaviorContext.getComponent().findComponent(effectBehavior.getForId()) : behaviorContext.getComponent(); if (target == null) { throw new FacesException("Cannot find component set with forId: "+effectBehavior.getForId()); } String clientId = target.getClientId(); StringBuilder sb = new StringBuilder(); sb.append("new Effect.toggle('"); sb.append(clientId); sb.append('\''); sb.append(','); sb.append('\''); sb.append(effectBehavior.getMode()); sb.append('\''); if (EffectUtils.isAnyPropertySet( effectBehavior.getDelay(), effectBehavior.getDuration(), EffectUtils.isAnyJsEffectCallbackTargetPropertySet(effectBehavior) )) { sb.append(",{"); boolean addComma = false; addComma = EffectUtils.addProperty(sb, "delay", effectBehavior.getDelay(), addComma); addComma = EffectUtils.addProperty(sb, "duration", effectBehavior.getDuration(), addComma); //Javascript callbacks addComma = EffectUtils.addJSCallbacks(sb, effectBehavior, addComma); sb.append('}'); } sb.append(')'); if (effectBehavior.getAppendJs() != null && effectBehavior.getAppendJs().length() > 0) { sb.append(';'); sb.append(effectBehavior.getAppendJs()); } return sb.toString(); } }
1fe9c0e7805bed344f08948f6da92837a59757f2
3c459042e52ddbc75b39a6d79587412927b787be
/PillEatNow/app/src/main/java/com/example/pilleatnow/CalendarPage.java
e083df32caa4ee95aa09cc06154d4cea9a8ec6c0
[]
no_license
Hanju18/PillEatNow
65eb2733e1fe0747a0e69710647b18dd2824ba45
559db9310995adcac11e5f791676e39b89434608
refs/heads/master
2022-12-08T17:56:14.964727
2020-09-04T01:18:59
2020-09-04T01:18:59
269,339,149
0
1
null
2020-07-15T11:59:42
2020-06-04T11:16:23
null
UTF-8
Java
false
false
7,271
java
package com.example.pilleatnow; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.prolificinteractive.materialcalendarview.CalendarDay; import com.prolificinteractive.materialcalendarview.CalendarMode; import com.prolificinteractive.materialcalendarview.MaterialCalendarView; import com.prolificinteractive.materialcalendarview.OnDateSelectedListener; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.concurrent.Executors; public class CalendarPage extends AppCompatActivity { private ImageView menu_main, menu_calendar, menu_pill, menu_setting; private TextView pillX; private final OneDayDecorator oneDayDecorator=new OneDayDecorator(); private SelectedDecorator selectedDecorator; MaterialCalendarView materialCalendarView; UserData userData=(UserData)getApplication(); List<CalendarDay> result = new ArrayList<>(); List<Integer> index=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.page_calendar); Log.d("CalendarPage", "OnCreate"); userData=(UserData)getApplication(); materialCalendarView=findViewById(R.id.calendarView); materialCalendarView.state().edit() .setFirstDayOfWeek(Calendar.SUNDAY) .setMinimumDate(CalendarDay.from(2017, 0, 1)) .setMaximumDate(CalendarDay.from(2030, 11, 31)) .setCalendarDisplayMode(CalendarMode.MONTHS) .commit(); materialCalendarView.addDecorators( new SundayDecorator(), new SaturdayDecorator(), oneDayDecorator); List<PillData> pill=userData.pillData; Calendar calendar=Calendar.getInstance(); int addition=0; for(int i=0;i<pill.size();i++) { int stock=pill.get(i).getPill_stock(); int dosage=pill.get(i).getPill_dosage(); addition=stock/dosage; calendar.add(Calendar.DATE, addition); Log.d("Calendar", String.valueOf(addition)); CalendarDay day=CalendarDay.from(calendar); result.add(day); index.add(i); } new ApiSimulator(result).executeOnExecutor(Executors.newSingleThreadExecutor()); pillX=findViewById(R.id.pillX); List<CalendarDay> todays=new ArrayList<>(); Calendar c= Calendar.getInstance(); todays.add(CalendarDay.from(c)); selectedDecorator=new SelectedDecorator(Color.RED, todays,CalendarPage.this); materialCalendarView.clearSelection(); materialCalendarView.addDecorator(selectedDecorator); materialCalendarView.setOnDateChangedListener(new OnDateSelectedListener() { @Override public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) { materialCalendarView.removeDecorator(selectedDecorator); pillX.setText(""); List<PillData> pills=userData.pillData; for(int i=0;i<result.size();i++) { if(result.get(i).equals(date)) { pillX.setText(pills.get(i).getPill_name()+"가 떨어지는 날입니다.\n필요하다면 추가로 구매해주세요."); } } materialCalendarView.clearSelection(); List<CalendarDay> dates=new ArrayList<>(); dates.add(date); selectedDecorator=new SelectedDecorator(Color.RED, dates,CalendarPage.this); materialCalendarView.addDecorator(selectedDecorator); } }); menu_main=findViewById(R.id.menu_main); menu_main.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("CalendarPage", "Menu_MainClicked"); Intent intent = new Intent(CalendarPage.this, MainPage.class); startActivity(intent); } }); menu_calendar=findViewById(R.id.menu_calendar); menu_calendar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("CalendarPage", "Menu_CalendarClicked"); Intent intent = new Intent(CalendarPage.this, CalendarPage.class); startActivity(intent); } }); menu_pill=findViewById(R.id.menu_pill); menu_pill.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("CalendarPage", "Menu_PillClicked"); Intent intent = new Intent(CalendarPage.this, PillPage.class); startActivity(intent); } }); menu_setting=findViewById(R.id.menu_setting); menu_setting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("CalendarPage", "Menu_SettingClicked"); Intent intent = new Intent(CalendarPage.this, SettingPage.class); startActivity(intent); } }); } private class ApiSimulator extends AsyncTask<Void, Void, List<CalendarDay>> { List<CalendarDay> Time_Result; ApiSimulator(List<CalendarDay> Time_Result){ this.Time_Result = Time_Result; } @Override protected List<CalendarDay> doInBackground(@NonNull Void... voids) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return Time_Result; } @Override protected void onPostExecute(@NonNull List<CalendarDay> calendarDays) { super.onPostExecute(calendarDays); if (isFinishing()) { return; } materialCalendarView.addDecorator(new EventDecorator(Color.RED, calendarDays,CalendarPage.this)); } } @Override public void onBackPressed() { AlertDialog.Builder alert= new AlertDialog.Builder(this); alert.setMessage("정말로 종료하시겠습니까?"); alert.setPositiveButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alert.setNegativeButton("종료", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finishAffinity(); } }); alert.setTitle("PillEatNow 종료"); AlertDialog alert1=alert.create(); alert1.show(); } }
a502061c1c160418abfa2ee490871420ba60c43c
5c27db2047bd39b7dc0b614564a0a026549587ff
/Services/transparencia/src/main/java/br/com/mobibike/transparencia/main/exceptions/HttpStatusCode.java
edc73985550ec90cbe2c093452ba41f15948f2f3
[]
no_license
roberson-miguel/mobi-bike
1411e0b5b7d0a43b9141d9523ad0f0df7646a834
b5d2fd17dfe066ce581149f4506da391f77191a4
refs/heads/master
2020-03-23T05:17:13.316491
2018-06-24T00:27:53
2018-06-24T00:27:53
141,135,010
0
0
null
null
null
null
UTF-8
Java
false
false
613
java
package br.com.mobibike.transparencia.main.exceptions; public abstract class HttpStatusCode { private HttpStatusCode() { throw new IllegalStateException("Utility class"); } public static final int VALIDACAO_CAMPOS = 422; public static final int RECURSO_NAO_ENCONTRADO = 404; public static final int NAO_AUTORIZADO = 401; public static final int NAO_AUTENTICADO = 403; public static final int ERRO_INTERNO_SERVIDOR = 500; public static final int CONTRATO_VIOLADO = 400; public static final int SEM_RETORNO = 204; public static final int CADASTRADO = 201; public static final int SUCESSO = 200; }
3f7b6de9b1f0d6d36b54a6cde6dd338b56b89311
cf7704d9ef0a34aff366adbbe382597473ab509d
/src/net/sourceforge/plantuml/graphic/TextBlockMarged.java
1e1102d3d9010763a4785bb7bc39e308bd897fad
[]
no_license
maheeka/plantuml-esb
0fa14b60af513c9dedc22627996240eaf3802c5a
07c7c7d78bae29d9c718a43229996c068386fccd
refs/heads/master
2021-01-10T07:49:10.043639
2016-02-23T17:36:33
2016-02-23T17:36:33
52,347,881
0
4
null
null
null
null
UTF-8
Java
false
false
2,563
java
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * Original Author: Arnaud Roques * * Revision $Revision: 6577 $ * */ package net.sourceforge.plantuml.graphic; import java.awt.geom.Dimension2D; import java.awt.geom.Rectangle2D; import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UTranslate; class TextBlockMarged extends AbstractTextBlock implements TextBlock { private final TextBlock textBlock; private final double x1; private final double x2; private final double y1; private final double y2; public TextBlockMarged(TextBlock textBlock, double x1, double x2, double y1, double y2) { this.textBlock = textBlock; this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } public Dimension2D calculateDimension(StringBounder stringBounder) { final Dimension2D dim = textBlock.calculateDimension(stringBounder); return Dimension2DDouble.delta(dim, x1 + x2, y1 + y2); } public void drawU(UGraphic ug) { final UTranslate translate = new UTranslate(x1, y1); textBlock.drawU(ug.apply(translate)); } @Override public Rectangle2D getInnerPosition(String member, StringBounder stringBounder) { final Rectangle2D parent = textBlock.getInnerPosition(member, stringBounder); if (parent == null) { return null; } final UTranslate translate = new UTranslate(x1, y1); return translate.apply(parent); } }
a66538449e57aa274152464f2f377cfe1763473e
c8b94af863892bb8871a12166d7b2c24fe1588f0
/GreatSmallGiv.java
5e2a4e065fcabe07d4af0f1c011986b1b345d1d3
[ "MIT" ]
permissive
flick-23/JAVA-Programs
57e6658a7b6d7ef66ac03879a642ba11b91cac2b
5c7f082809ef63b41f372f9ba18565075a8f0c0f
refs/heads/master
2021-10-10T17:50:55.501817
2021-10-05T17:43:30
2021-10-05T17:43:30
216,357,681
1
1
MIT
2021-10-05T17:43:31
2019-10-20T12:23:22
Java
UTF-8
Java
false
false
697
java
/* Program to read a floating number and print a small number not less the number & given number & largest number not greater than the number */ import java.io.*; import java.lang.*; class GreatSmallGiv { public static void main(String []args) throws IOException { BufferedReader venki=new BufferedReader(new InputStreamReader(System.in)); float n; System.out.println("\nEnter a Floating number :"); n=Float.parseFloat(venki.readLine()); System.out.println("\nSmaller number not greater than the entered number :" + Math.ceil(n)); System.out.println("\nGiven number : "+n); System.out.println("\nGreater number not greater than the entered number :" + Math.floor(n)); } }
1e29680a5b1bdc74ea288c987844153b4df3d617
9a20f24f89f7b47725a55066d72c808d2a05ce68
/src/khanhnoi/com/server/Server.java
5d9949f4055bce55f693d7870269545686f2abde
[]
no_license
khanhnoi/xem-tu-vi-java
693abec150041fc98889669aa7a2bed9e3b2cd06
da16a24b67a83ad1515ff2d1b64f8d5007627794
refs/heads/master
2023-02-22T18:15:41.479626
2021-01-25T22:48:54
2021-01-25T22:48:54
327,388,199
0
0
null
null
null
null
UTF-8
Java
false
false
10,252
java
package khanhnoi.com.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Vector; import tuoi.Tuoi; public class Server { static int resetServerOld = 0; static int resetServerNew = 0; static int nhan = 0; private final String className = "com.mysql.jdbc.Driver"; Connection connection = null; private final String url = "jdbc:mysql://localhost:3306/tuvitest"; String user = "root"; String pass = "123456"; String table = "tuoi"; // cac luong vao ra ObjectInputStream ois; ObjectOutputStream oos; ServerSocket serversocket; OutputStream os; InputStream is; Socket socket; // // 1 Ket noi toi co so du lieu public void connect() { try { Class.forName(className); try { connection = DriverManager.getConnection(url, user, pass); System.out.println("Connect success - ket noi co su lieu"); } catch (SQLException e) { System.out.println("-Loi ket noi - Fail connect" + e); } } catch (ClassNotFoundException e) { System.out.println("Class not found" + e); } } // 2 Get data Tuoi - Hien thi dw lieu len bang public ResultSet getData01() { ResultSet rs = null; Statement stt; try { stt = connection.createStatement(); rs = stt.executeQuery("select * from tuoi "); } catch (SQLException e) { System.out.println("Select error" + e.toString()); } return rs; } // thuc hien truy van du lieu - man public List<Tuoi> getData02() { List<Tuoi> arr = new ArrayList<Tuoi>(); ResultSet rss = this.getData01(); // lay data Tuoi System.out.println("+ Bat dau truy van du lieu - mang du lieu"); try { while (rss.next()) { Tuoi tuoi = new Tuoi(); tuoi.setId(rss.getString("ID")); tuoi.setTuoi(rss.getString("Tuoi")); tuoi.setNoiDung(rss.getString("NoiDung")); tuoi.setTT(rss.getInt("TT")); arr.add(tuoi); } } catch (SQLException e) { e.printStackTrace(); } return arr; } // server mo cong va chap nhan ket noi tu client public void connectPort() { ArrayList<Socket> clientSockets = new ArrayList<>(); try { ServerSocket serverSocket = new ServerSocket(2222); // port same as client InetAddress inetAddress = InetAddress.getLocalHost(); // System.out.println("Server opened at: " + inetAddress.getHostAddress()); // System.out.println("Server ready..."); while (true) // this keeps the server listening { final Socket socket = serverSocket.accept(); // this accepts incomming connections clientSockets.add(socket); // adds current connection to an arraylist System.out.println("Connection from " + socket.getInetAddress()); System.out.println("Client " + clientSockets.size() + " Connected to server...."); Thread t = new Thread(new Runnable() // Thread handles messages sent by client that just connected { @Override public void run() { try { while (socket.isConnected()) { // System.out.println("socket.isConnected()"); // BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // String fromClient = br.readLine(); List<Tuoi> arr = new ArrayList<Tuoi>(); oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); os = socket.getOutputStream(); is = socket.getInputStream(); // System.out.println("1"); oos.writeObject(arr); // System.out.println("2"); if (arr != null) { // use message from client while (true) { // System.out.println("3"); // lien tuc check xem client gui yeu cau j ko va thuc hien no ktra(); System.out.println("+ Check xong"); arr = getData02(); oos.writeObject(arr); } } else // connection might have been reset by client { socket.close(); clientSockets.remove(socket); } } } catch (SocketException e) { System.out.println("Disconnection from " + socket.getInetAddress()); } catch (IOException e) { } } }); t.start(); } // Socket socket = serverSocket.accept(); // // System.out.println("Client Connected to server...."); // oos = new ObjectOutputStream(socket.getOutputStream()); // ois = new ObjectInputStream(socket.getInputStream()); // os = socket.getOutputStream(); // is = socket.getInputStream(); } catch (IOException e) { System.out.println("Loi o server: connectPort - IOException " + e); System.out.println("Reset Server "); // resetServerNew += 1; } } // server truyen du lieu cho client public void connectClient() { List<Tuoi> arr = new ArrayList<Tuoi>(); System.out.println("+ Bat dau ket noi vs Client"); // truy van database = lay dc mang data arr = this.getData02(); System.out.println(arr != null ? "- Du Lieu (Arr) co" : "-Du Lieu trong"); // server mo cong va chap nhan ket noi tu client this.connectPort(); System.out.println("Het - Cho nay ko chay dau"); } // 0. Ktra public void ktra() { try { // System.out.println("4"); // ma nhan dc int nhan = 0; // System.out.println("+ Dang doi Check Yeu cau ben client:"); nhan = is.read(); // Danhba db = (Danhba) ois.readObject(); if (nhan == 1) { System.out.println("-> Client yeu cau Them"); this.them(); } else if (nhan == 2) { System.out.println("-> Client yeu cau Xoa"); this.xoa(); } else if (nhan == 3) { System.out.println("-> Client yeu cau Update"); this.capNhat(); } else if (nhan == 4) { System.out.println("-> Client yeu cau Xem All"); this.xemAll(); } else if (nhan == 5) { System.out.println("-> Client yeu cau Xem"); this.xemAll(); } if (nhan != 0) { // System.out.println("+ Dang doi Check Yeu cau ben client:"); System.out.println("+ Nhan duoc la : " + nhan); // System.out.println("+ Check xong"); } // db.show(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Loi o server: KtraNhan " + e); e.printStackTrace(); } } // 1. Them doi tuong // server chen du lieu server toi database public void them() { try { // thong tin client nhap gui cho sever dung de xu ly Tuoi db = (Tuoi) ois.readObject(); db.show(); // lenh sql them String sql = "insert into tuoi value('" + db.getId() + "','" + db.getTuoi() + "','" + db.getNoiDung() + "','" + db.getTT() + "')"; System.out.println(sql); Statement stt; try { stt = connection.createStatement(); System.out.println(sql); stt.executeUpdate(sql); } catch (SQLException e) { System.out.println("fail" + e); } } catch (ClassNotFoundException e) { System.out.println("Loi them01: " + e); } catch (IOException e) { System.out.println("Loi them01: " + e); } } // 2. Xoa doi tuong // server xoa 1 ban ghi tren database public void xoa() { try { Tuoi db = (Tuoi) ois.readObject(); db.show(); String sql = "delete from tuoi where id = '" + db.getId() + "'"; Statement stt; try { stt = connection.createStatement(); System.out.println(sql); stt.executeUpdate(sql); } catch (SQLException e) { System.out.println("fail" + e); } } catch (ClassNotFoundException e) { System.out.println("Loi xoa01: " + e); } catch (IOException e) { System.out.println("Loi xoa02: " + e); } } // 3. Update - server cap nhat dua lieu toi database. public void capNhat() { try { Tuoi db = (Tuoi) ois.readObject(); db.show(); String sql = "update tuoi set Tuoi = '" + db.getTuoi() + "', NoiDung = '" + db.getNoiDung() + "', TT='" + db.getTT() + "' where id ='" + db.getId() + "'"; Statement stt; try { stt = connection.createStatement(); System.out.println(sql); stt.executeUpdate(sql); } catch (SQLException e) { System.out.println("fail" + e); } } catch (ClassNotFoundException e) { System.out.println("Loi update01: " + e); } catch (IOException e) { System.out.println("Loi update02: " + e); } } public void xemAll() { // try { // Tuoi db = (Tuoi) ois.readObject(); // db.show(); // lenh sql them // String sql = "select * from tuoi "; // System.out.println(sql); Statement stt; try { stt = connection.createStatement(); // System.out.println(sql); // stt.executeUpdate(sql); // rs = stt.executeQuery("select * from tuoi "); } catch (SQLException e) { System.out.println("fail" + e); } // } catch (ClassNotFoundException e) { // System.out.println("Loi them01: " + e); // } catch (IOException e) { // System.out.println("Loi them01: " + e); // } } // public void timKiem() { // try { // Tuoi db = (Tuoi) ois.readObject(); // db.show(); // // //lenh sql them // String sql = "insert into tuoi value('" + db.getId() + "','" + db.getTuoi() + "','" + db.getNoiDung() // + "','" + db.getTT() + "')"; // System.out.println(sql); // Statement stt; // try { // // stt = connection.createStatement(); // System.out.println(sql); // stt.executeUpdate(sql); // } catch (SQLException e) { // System.out.println("fail" + e); // } // } catch (ClassNotFoundException e) { // System.out.println("Loi them01: " + e); // } catch (IOException e) { // System.out.println("Loi them01: " + e); // } // } public static void main(String[] args) { while (true) { Server sv = new Server(); // ket noi co so du lieu sv.connect(); // Vector<Danhba> arr01 = sv.getData02(); System.out.println("----------Server da chay----------"); // ket noi vs Client sv.connectClient(); // sv.them(); if (resetServerNew > resetServerOld) { resetServerNew = 0; continue; } break; } } }
5aca4b8ab35c2cdc380ca57b9f923b96db0ce871
bb366cb444664834987f4b8439dc8ddac795f42e
/ysy-point/src/main/java/com/yunsunyun/point/controller/PtSmsController.java
b836186f18f7911aac64abf942d051a1f87d9c03
[]
no_license
yunsunyunGit/admin
b454151dc7f7e7726dad375c5f923f37ed771f57
6a9d7e84214db94f1ccd001f4e620f4e17a04af7
refs/heads/master
2020-03-21T02:58:45.630934
2018-06-20T12:52:18
2018-06-20T12:52:18
138,009,061
0
0
null
null
null
null
UTF-8
Java
false
false
4,601
java
package com.yunsunyun.point.controller; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.yunsunyun.point.po.PtSms; import com.yunsunyun.point.service.IPtSmsService; import com.yunsunyun.xsimple.api.common.DataTable; import com.google.common.base.Strings; import com.kingnode.diva.web.Servlets; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletRequest; import java.text.SimpleDateFormat; import java.util.Map; /** * <p> * 前端控制器 * </p> * * @author * @since 2018-03-30 */ @Controller @RequestMapping("/sms/list") public class PtSmsController { @Autowired private IPtSmsService iPtSmsService; private static Logger logger = LoggerFactory.getLogger(PtSmsController.class); @RequiresPermissions("sms-list") @RequestMapping(method = RequestMethod.GET) public String smsList(){ return "sms/smsList"; } @RequiresPermissions("sms-list") @RequestMapping(value = "/list",method = RequestMethod.POST) @ResponseBody public DataTable<PtSms> getPtSmsList(DataTable<PtSms> dt, ServletRequest request){ try { Page<PtSms> page = new Page<>(); page.setCurrent(dt.pageNo()+1); page.setSize(dt.getiDisplayLength()); Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_"); EntityWrapper<PtSms> wrapper = new EntityWrapper<>(); if (searchParams != null && searchParams.size() != 0) { if (searchParams.containsKey("LIKE_content") && !Strings.isNullOrEmpty(searchParams.get("LIKE_content").toString().trim())) { wrapper.like("content",searchParams.get("LIKE_content").toString().trim()); } if (searchParams.containsKey("LIKE_senderId") && !Strings.isNullOrEmpty(searchParams.get("LIKE_senderId").toString().trim())) { wrapper.like("sender_Id",searchParams.get("LIKE_senderId").toString().trim()); } if (searchParams.containsKey("LIKE_senderName") && !Strings.isNullOrEmpty(searchParams.get("LIKE_senderName").toString().trim())) { wrapper.like("sender_Name",searchParams.get("LIKE_senderName").toString().trim()); } if (searchParams.containsKey("LIKE_receiverId") && !Strings.isNullOrEmpty(searchParams.get("LIKE_receiverId").toString().trim())) { wrapper.like("receiver_Id",searchParams.get("LIKE_receiverId").toString().trim()); } if (searchParams.containsKey("LIKE_receiverName") && !Strings.isNullOrEmpty(searchParams.get("LIKE_receiverName").toString().trim())) { wrapper.like("receiver_Name",searchParams.get("LIKE_receiverName").toString().trim()); } if (searchParams.containsKey("LIKE_sendTime") && !Strings.isNullOrEmpty(searchParams.get("LIKE_sendTime").toString().trim())) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); wrapper.like("send_time",dateFormat.parse(searchParams.get("LIKE_sendTime").toString().trim()).getTime()+""); } if (searchParams.containsKey("LIKE_receiveTime") && !Strings.isNullOrEmpty(searchParams.get("LIKE_receiveTime").toString().trim())) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); wrapper.like("receive_time",dateFormat.parse(searchParams.get("LIKE_receiveTime").toString().trim()).getTime()+""); } if (searchParams.containsKey("EQ_readStatus") && !Strings.isNullOrEmpty(searchParams.get("EQ_readStatus").toString().trim())) { wrapper.eq("read_status",searchParams.get("EQ_readStatus").toString().trim()); } } page = iPtSmsService.selectPage(page,wrapper); dt.setiTotalDisplayRecords(page.getTotal()); dt.setAaData(page.getRecords()); }catch (Exception e){ logger.error("删除模板错误信息:{}", e); } return dt; } }
953386e5ac668dcdbd8ed8504bfc83fc8ea894c6
1305baafc401bb367036cb61b50409047c530254
/security/src/main/java/com/zp/security/authentication/sms/SmsCodeAuthenticationToken.java
92b500881ed0d8a0f21ab2dc4f6b42c1489fa585
[]
no_license
zp253908058/fcs
fe9f4bb0272fb4cda219e5a0c50534ade374fafc
b9cfbf3b03ead0dca57edf547a5541d7c1a12b86
refs/heads/master
2020-05-25T09:21:07.572771
2019-05-30T10:34:23
2019-05-30T10:34:23
187,732,430
0
0
null
null
null
null
UTF-8
Java
false
false
2,291
java
package com.zp.security.authentication.sms; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityCoreVersion; import java.util.Collection; /** * Description: im * Created by Zhu Peng on 2019/5/21 */ public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final Object principal; /** * This constructor can be safely used by any code that wishes to create a * <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()} * will return <code>false</code>. * */ public SmsCodeAuthenticationToken(String mobile) { super(null); this.principal = mobile; setAuthenticated(false); } /** * This constructor should only be used by <code>AuthenticationManager</code> or * <code>AuthenticationProvider</code> implementations that are satisfied with * producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>) * authentication token. * * @param principal * @param authorities */ public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; super.setAuthenticated(true); // must use super, as we override } // ~ Methods // ======================================================================================================== public Object getCredentials() { return null; } public Object getPrincipal() { return this.principal; } public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { if (isAuthenticated) { throw new IllegalArgumentException( "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); } super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); } }
4c9d7b788a03d13cc066b6e301080fbf66bbdf29
e3d707b39ad07706e29929bbe6f81d03b38e2668
/app/src/main/java/com/aiteu/training/teach4/dialog/PopupWin.java
d776a6f81b451cb953d7c91b6ab416a12c7e4037
[ "Apache-2.0" ]
permissive
aiteu/AndroidTrainingDemo
68300408b81715166beeb8b8da47990bae327f32
ebdba0bb271adb04ad54c9b6b453097041f07f35
refs/heads/master
2020-05-02T11:55:51.739745
2019-08-30T06:19:26
2019-08-30T06:19:26
177,945,429
1
0
null
null
null
null
UTF-8
Java
false
false
815
java
package com.aiteu.training.teach4.dialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import com.aiteu.training.R; public class PopupWin extends PopupWindow { public PopupWin(Context context) { super(context); setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); View view = LayoutInflater.from(context).inflate(R.layout.popup_tips_layout, null); setContentView(view); setBackgroundDrawable(new ColorDrawable(Color.BLUE)); setTouchable(true); setFocusable(true); setOutsideTouchable(true); } }
[ "leo@bbb96" ]
leo@bbb96
c50aac162b5a253400ce6d68a4fdfb2b13ceb369
19adc3cc56126e4746186f8a49b0b7d27568d7d5
/HibernateConfig/src/main/java/com/shop/Product.java
86fb12151c221f3f8941239d727f798ea40baab6
[]
no_license
amydosh/Phase2-BackEnd
242caab46d3242e52952d253d6ba390012b3b983
6ceb2e99bb5efb2ccb7322a49585abdc90c7627b
refs/heads/master
2023-08-18T10:15:08.470926
2021-10-03T21:58:25
2021-10-03T21:58:25
403,084,030
0
0
null
null
null
null
UTF-8
Java
false
false
865
java
package com.shop; import java.math.BigDecimal; import java.math.BigInteger; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="tbl_product") public class Product { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int productID; private String name; private double price; public Product() { super(); } public Product(String name, double price) { super(); this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getProductID() { return productID; } }
66f29fcef0dcd68ab81681559b86202ee2552679
4a4c1228a3e1d16ee2243e4e40e095bbdeb13f93
/super-devops-common/src/main/java/com/wl4g/devops/common/exception/ci/PipelineDeployingException.java
43c8ce17cff2e2a6d779345ac16a04ada7f1e0e6
[ "Apache-2.0" ]
permissive
August2016/super-devops
fcdf2d713965faadfcb3030abe80b1a270dcd510
9a03245da3d9c3bc758bf61aecb8888b336c79aa
refs/heads/master
2021-02-22T09:02:55.955105
2020-02-27T09:54:30
2020-02-27T09:54:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,099
java
/* * Copyright 2017 ~ 2025 the original author or authors. <[email protected], [email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wl4g.devops.common.exception.ci; import com.wl4g.devops.common.exception.restful.BizInvalidArgRestfulException; public class PipelineDeployingException extends CiException implements BizInvalidArgRestfulException { private static final long serialVersionUID = -7034899390745766939L; /** * Constructs a new runtime exception with {@code null} as its detail * message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ public PipelineDeployingException() { super(); } /** * Constructs a new runtime exception with the specified detail message. The * cause is not initialized, and may subsequently be initialized by a call * to {@link #initCause}. * * @param message * the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public PipelineDeployingException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause. * <p> * Note that the detail message associated with {@code cause} is <i>not</i> * automatically incorporated in this runtime exception's detail message. * * @param message * the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param cause * the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public PipelineDeployingException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new runtime exception with the specified cause and a detail * message of <tt>(cause==null ? null : cause.toString())</tt> (which * typically contains the class and detail message of <tt>cause</tt>). This * constructor is useful for runtime exceptions that are little more than * wrappers for other throwables. * * @param cause * the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public PipelineDeployingException(Throwable cause) { super(cause); } }
47c74d0bd3f49d8f1824cfc5fc0de5f2f9b75ef0
898f513d9cc6027486a29d5fcf7ae78ba1b706a3
/src/com/lishunan/gpm/People.java
ebe1b450e9a4a85148f7775e8aa9ca52e77677c7
[]
no_license
lishunan246/srtp
e5c7220fdd63f488b8fbe774da1d26a78ae2ea6d
fe135f8b8941fc03daa97606c86c64132da71afe
refs/heads/master
2020-04-09T05:50:51.704245
2015-11-27T05:21:43
2015-11-27T05:21:43
30,059,772
1
0
null
null
null
null
UTF-8
Java
false
false
771
java
package com.lishunan.gpm; /** * Created by Administrator on 2015/2/2. */ public class People { private String account; private String password; private String name; private String type; public void setAccount (String account) { this.account = account; } public void setPassword (String password) { this.password = password; } public void setName (String name) { this.name = name; } public void setType (String type) { this.type = type; } public String getAccount () { return account; } public String getPassword () { return password; } public String getName () { return name; } public String getType () { return type; } }
c4bb2bf12627c128d93aa5d395cf2cf242730dc0
af29709faf48b2cfeeac344b9fb62ff2ad41aa6c
/src/main/java/com/calypso/SampleWebUiApplication.java
40bcf82702ecc8aab12c70ec86c610b6536a5ae8
[ "Apache-2.0" ]
permissive
hbrahi1/calypso_cnc
0aeaabcdd28fe3dcdf7c918c69bca1cbb088a622
4f6f4eefae4a70395e9b5fb0e3203e01cf41c37f
refs/heads/master
2021-01-19T02:38:09.859076
2016-07-25T23:30:59
2016-07-25T23:30:59
64,171,250
0
0
null
null
null
null
UTF-8
Java
false
false
1,559
java
/* * Copyright 2012-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.calypso; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.system.ApplicationPidFileWriter; import org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @ComponentScan @Configuration @EnableAutoConfiguration @EnableConfigurationProperties public class SampleWebUiApplication { public static void main(String[] args) throws Exception { SpringApplication springApplication = new SpringApplication(SampleWebUiApplication.class); springApplication.addListeners(new ApplicationPidFileWriter(), new EmbeddedServerPortFileWriter()); springApplication.run(args); } }
d1090225771e807a54b45467fba59acf7a0a00f0
176d8a531aab283760f89d1a64db5a672a050f27
/detect-doctor/src/main/java/com/synopsys/detect/doctor/DoctorException.java
9c867e3833466a87420486bd798ade121838e444
[ "Apache-2.0" ]
permissive
blackducksoftware/hub-detect
432e968ec8ff7433615bd377562cca4a71951428
dc528aa57240fc849f19a19d666564176a6b9679
refs/heads/master
2021-06-03T08:38:19.811849
2021-01-05T15:39:41
2021-01-05T15:39:41
87,969,126
48
56
Apache-2.0
2019-09-24T16:04:31
2017-04-11T18:59:32
Java
UTF-8
Java
false
false
166
java
package com.synopsys.detect.doctor; public class DoctorException extends Exception { public DoctorException(final String s) { super(s); } }
f86d52c5b69f2501e108322984be6b3527b520c4
a002c836246e172486a2953492e9e8bdeadaf2e3
/app/libs/library/src/main/java/com/google/android/exoplayer/hls/HlsChunkSource.java
dc70320f0dd8a22e55f2fe50097b435f7380c2ba
[]
no_license
VitaliyLytvyn/android_iptv
6a1f53dcb5027497557da76e06cdce1d4c8243f9
106a6b21d39bc50b8a6e71e77caaf0cc05d24e65
refs/heads/master
2021-04-15T12:38:36.003238
2017-06-18T10:35:09
2017-06-18T10:35:09
94,578,850
4
1
null
null
null
null
UTF-8
Java
false
false
24,653
java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.hls; import com.google.android.exoplayer.C; import com.google.android.exoplayer.MediaFormat; import com.google.android.exoplayer.hls.parser.AdtsExtractor; import com.google.android.exoplayer.hls.parser.HlsExtractor; import com.google.android.exoplayer.hls.parser.TsExtractor; import com.google.android.exoplayer.upstream.Aes128DataSource; import com.google.android.exoplayer.upstream.BandwidthMeter; import com.google.android.exoplayer.upstream.BufferPool; import com.google.android.exoplayer.upstream.DataSource; import com.google.android.exoplayer.upstream.DataSpec; import com.google.android.exoplayer.upstream.HttpDataSource.InvalidResponseCodeException; import com.google.android.exoplayer.util.Assertions; import com.google.android.exoplayer.util.Util; import android.net.Uri; import android.os.SystemClock; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; /** * A temporary test source of HLS chunks. * <p> * TODO: Figure out whether this should merge with the chunk package, or whether the hls * implementation is going to naturally diverge. */ public class HlsChunkSource { /** * Adaptive switching is disabled. * <p> * The initially selected variant will be used throughout playback. */ public static final int ADAPTIVE_MODE_NONE = 0; /** * Adaptive switches splice overlapping segments of the old and new variants. * <p> * When performing a switch from one variant to another, overlapping segments will be requested * from both the old and new variants. These segments will then be spliced together, allowing * a seamless switch from one variant to another even if keyframes are misaligned or if keyframes * are not positioned at the start of each segment. * <p> * Note that where it can be guaranteed that the source content has keyframes positioned at the * start of each segment, {@link #ADAPTIVE_MODE_ABRUPT} should always be used in preference to * this mode. */ public static final int ADAPTIVE_MODE_SPLICE = 1; /** * Adaptive switches are performed at segment boundaries. * <p> * For this mode to perform seamless switches, the source content is required to have keyframes * positioned at the start of each segment. If this is not the case a visual discontinuity may * be experienced when switching from one variant to another. * <p> * Note that where it can be guaranteed that the source content does have keyframes positioned at * the start of each segment, this mode should always be used in preference to * {@link #ADAPTIVE_MODE_SPLICE} because it requires fetching less data. */ public static final int ADAPTIVE_MODE_ABRUPT = 3; /** * The default target buffer size in bytes. */ public static final int DEFAULT_TARGET_BUFFER_SIZE = 18 * 1024 * 1024; /** * The default target buffer duration in milliseconds. */ public static final long DEFAULT_TARGET_BUFFER_DURATION_MS = 40000; /** * The default minimum duration of media that needs to be buffered for a switch to a higher * quality variant to be considered. */ public static final long DEFAULT_MIN_BUFFER_TO_SWITCH_UP_MS = 5000; /** * The default maximum duration of media that needs to be buffered for a switch to a lower * quality variant to be considered. */ public static final long DEFAULT_MAX_BUFFER_TO_SWITCH_DOWN_MS = 20000; private static final String TAG = "HlsChunkSource"; private static final String AAC_FILE_EXTENSION = ".aac"; private static final float BANDWIDTH_FRACTION = 0.8f; private final BufferPool bufferPool; private final DataSource upstreamDataSource; private final HlsPlaylistParser playlistParser; private final Variant[] enabledVariants; private final BandwidthMeter bandwidthMeter; private final int adaptiveMode; private final Uri baseUri; private final int maxWidth; private final int maxHeight; private final int targetBufferSize; private final long targetBufferDurationUs; private final long minBufferDurationToSwitchUpUs; private final long maxBufferDurationToSwitchDownUs; /* package */ byte[] scratchSpace; /* package */ final HlsMediaPlaylist[] mediaPlaylists; /* package */ final boolean[] mediaPlaylistBlacklistFlags; /* package */ final long[] lastMediaPlaylistLoadTimesMs; /* package */ boolean live; /* package */ long durationUs; private int variantIndex; private DataSource encryptedDataSource; private Uri encryptionKeyUri; private String encryptedDataSourceIv; private byte[] encryptedDataSourceSecretKey; public HlsChunkSource(DataSource dataSource, String playlistUrl, HlsPlaylist playlist, BandwidthMeter bandwidthMeter, int[] variantIndices, int adaptiveMode) { this(dataSource, playlistUrl, playlist, bandwidthMeter, variantIndices, adaptiveMode, DEFAULT_TARGET_BUFFER_SIZE, DEFAULT_TARGET_BUFFER_DURATION_MS, DEFAULT_MIN_BUFFER_TO_SWITCH_UP_MS, DEFAULT_MAX_BUFFER_TO_SWITCH_DOWN_MS); } /** * @param dataSource A {@link DataSource} suitable for loading the media data. * @param playlistUrl The playlist URL. * @param playlist The hls playlist. * @param bandwidthMeter provides an estimate of the currently available bandwidth. * @param variantIndices A subset of variant indices to consider, or null to consider all of the * variants in the master playlist. * @param adaptiveMode The mode for switching from one variant to another. One of * {@link #ADAPTIVE_MODE_NONE}, {@link #ADAPTIVE_MODE_ABRUPT} and * {@link #ADAPTIVE_MODE_SPLICE}. * @param targetBufferSize The targeted buffer size in bytes. The buffer will not be filled more * than one chunk beyond this amount of data. * @param targetBufferDurationMs The targeted duration of media to buffer ahead of the current * playback position. The buffer will not be filled more than one chunk beyond this position. * @param minBufferDurationToSwitchUpMs The minimum duration of media that needs to be buffered * for a switch to a higher quality variant to be considered. * @param maxBufferDurationToSwitchDownMs The maximum duration of media that needs to be buffered * for a switch to a lower quality variant to be considered. */ public HlsChunkSource(DataSource dataSource, String playlistUrl, HlsPlaylist playlist, BandwidthMeter bandwidthMeter, int[] variantIndices, int adaptiveMode, int targetBufferSize, long targetBufferDurationMs, long minBufferDurationToSwitchUpMs, long maxBufferDurationToSwitchDownMs) { this.upstreamDataSource = dataSource; this.bandwidthMeter = bandwidthMeter; this.adaptiveMode = adaptiveMode; this.targetBufferSize = targetBufferSize; targetBufferDurationUs = targetBufferDurationMs * 1000; minBufferDurationToSwitchUpUs = minBufferDurationToSwitchUpMs * 1000; maxBufferDurationToSwitchDownUs = maxBufferDurationToSwitchDownMs * 1000; baseUri = playlist.baseUri; playlistParser = new HlsPlaylistParser(); bufferPool = new BufferPool(256 * 1024); if (playlist.type == HlsPlaylist.TYPE_MEDIA) { enabledVariants = new Variant[] {new Variant(0, playlistUrl, 0, null, -1, -1)}; mediaPlaylists = new HlsMediaPlaylist[1]; mediaPlaylistBlacklistFlags = new boolean[1]; lastMediaPlaylistLoadTimesMs = new long[1]; setMediaPlaylist(0, (HlsMediaPlaylist) playlist); } else { Assertions.checkState(playlist.type == HlsPlaylist.TYPE_MASTER); enabledVariants = filterVariants((HlsMasterPlaylist) playlist, variantIndices); mediaPlaylists = new HlsMediaPlaylist[enabledVariants.length]; mediaPlaylistBlacklistFlags = new boolean[enabledVariants.length]; lastMediaPlaylistLoadTimesMs = new long[enabledVariants.length]; } int maxWidth = -1; int maxHeight = -1; // Select the first variant from the master playlist that's enabled. long minOriginalVariantIndex = Integer.MAX_VALUE; for (int i = 0; i < enabledVariants.length; i++) { if (enabledVariants[i].index < minOriginalVariantIndex) { minOriginalVariantIndex = enabledVariants[i].index; variantIndex = i; } maxWidth = Math.max(enabledVariants[i].width, maxWidth); maxHeight = Math.max(enabledVariants[i].height, maxHeight); } // TODO: We should allow the default values to be passed through the constructor. this.maxWidth = maxWidth > 0 ? maxWidth : 1920; this.maxHeight = maxHeight > 0 ? maxHeight : 1080; } public long getDurationUs() { return live ? C.UNKNOWN_TIME_US : durationUs; } /** * Adaptive implementations must set the maximum video dimensions on the supplied * {@link MediaFormat}. Other implementations do nothing. * <p> * Only called when the source is enabled. * * @param out The {@link MediaFormat} on which the maximum video dimensions should be set. */ public void getMaxVideoDimensions(MediaFormat out) { out.setMaxVideoDimensions(maxWidth, maxHeight); } /** * Returns the next {@link HlsChunk} that should be loaded. * * @param previousTsChunk The previously loaded chunk that the next chunk should follow. * @param seekPositionUs If there is no previous chunk, this parameter must specify the seek * position. If there is a previous chunk then this parameter is ignored. * @param playbackPositionUs The current playback position. * @return The next chunk to load. */ public HlsChunk getChunkOperation(TsChunk previousTsChunk, long seekPositionUs, long playbackPositionUs) { if (previousTsChunk != null && (previousTsChunk.isLastChunk || previousTsChunk.endTimeUs - playbackPositionUs >= targetBufferDurationUs) || bufferPool.getAllocatedSize() >= targetBufferSize) { // We're either finished, or we have the target amount of data or time buffered. return null; } int nextVariantIndex = variantIndex; boolean switchingVariant = false; boolean switchingVariantSpliced = false; if (adaptiveMode == ADAPTIVE_MODE_NONE) { // Do nothing. } else { nextVariantIndex = getNextVariantIndex(previousTsChunk, playbackPositionUs); switchingVariant = nextVariantIndex != variantIndex; switchingVariantSpliced = switchingVariant && adaptiveMode == ADAPTIVE_MODE_SPLICE; } HlsMediaPlaylist mediaPlaylist = mediaPlaylists[nextVariantIndex]; if (mediaPlaylist == null) { // We don't have the media playlist for the next variant. Request it now. return newMediaPlaylistChunk(nextVariantIndex); } variantIndex = nextVariantIndex; int chunkMediaSequence = 0; boolean liveDiscontinuity = false; if (live) { if (previousTsChunk == null) { chunkMediaSequence = getLiveStartChunkMediaSequence(variantIndex); } else { chunkMediaSequence = switchingVariantSpliced ? previousTsChunk.chunkIndex : previousTsChunk.chunkIndex + 1; if (chunkMediaSequence < mediaPlaylist.mediaSequence) { // If the chunk is no longer in the playlist. Skip ahead and start again. chunkMediaSequence = getLiveStartChunkMediaSequence(variantIndex); liveDiscontinuity = true; } } } else { // Not live. if (previousTsChunk == null) { chunkMediaSequence = Util.binarySearchFloor(mediaPlaylist.segments, seekPositionUs, true, true) + mediaPlaylist.mediaSequence; } else { chunkMediaSequence = switchingVariantSpliced ? previousTsChunk.chunkIndex : previousTsChunk.chunkIndex + 1; } } int chunkIndex = chunkMediaSequence - mediaPlaylist.mediaSequence; if (chunkIndex >= mediaPlaylist.segments.size()) { if (mediaPlaylist.live && shouldRerequestMediaPlaylist(variantIndex)) { return newMediaPlaylistChunk(variantIndex); } else { return null; } } HlsMediaPlaylist.Segment segment = mediaPlaylist.segments.get(chunkIndex); Uri chunkUri = Util.getMergedUri(mediaPlaylist.baseUri, segment.url); // Check if encryption is specified. if (HlsMediaPlaylist.ENCRYPTION_METHOD_AES_128.equals(segment.encryptionMethod)) { Uri keyUri = Util.getMergedUri(mediaPlaylist.baseUri, segment.encryptionKeyUri); if (!keyUri.equals(encryptionKeyUri)) { // Encryption is specified and the key has changed. HlsChunk toReturn = newEncryptionKeyChunk(keyUri, segment.encryptionIV); return toReturn; } if (!Util.areEqual(segment.encryptionIV, encryptedDataSourceIv)) { initEncryptedDataSource(keyUri, segment.encryptionIV, encryptedDataSourceSecretKey); } } else { clearEncryptedDataSource(); } // Configure the data source and spec for the chunk. DataSource dataSource = encryptedDataSource != null ? encryptedDataSource : upstreamDataSource; DataSpec dataSpec = new DataSpec(chunkUri, segment.byterangeOffset, segment.byterangeLength, null); // Compute start and end times, and the sequence number of the next chunk. long startTimeUs; if (live) { if (previousTsChunk == null) { startTimeUs = 0; } else if (switchingVariantSpliced) { startTimeUs = previousTsChunk.startTimeUs; } else { startTimeUs = previousTsChunk.endTimeUs; } } else /* Not live */ { startTimeUs = segment.startTimeUs; } long endTimeUs = startTimeUs + (long) (segment.durationSecs * C.MICROS_PER_SECOND); boolean isLastChunk = !mediaPlaylist.live && chunkIndex == mediaPlaylist.segments.size() - 1; // Configure the extractor that will read the chunk. HlsExtractor extractor; if (previousTsChunk == null || segment.discontinuity || switchingVariant || liveDiscontinuity) { extractor = chunkUri.getLastPathSegment().endsWith(AAC_FILE_EXTENSION) ? new AdtsExtractor(switchingVariantSpliced, startTimeUs, bufferPool) : new TsExtractor(switchingVariantSpliced, startTimeUs, bufferPool); } else { extractor = previousTsChunk.extractor; } return new TsChunk(dataSource, dataSpec, extractor, enabledVariants[variantIndex].index, startTimeUs, endTimeUs, chunkMediaSequence, isLastChunk); } /** * Invoked when an error occurs loading a chunk. * * @param chunk The chunk whose load failed. * @param e The failure. * @return True if the error was handled by the source. False otherwise. */ public boolean onLoadError(HlsChunk chunk, IOException e) { if ((chunk instanceof MediaPlaylistChunk) && (e instanceof InvalidResponseCodeException)) { InvalidResponseCodeException responseCodeException = (InvalidResponseCodeException) e; int responseCode = responseCodeException.responseCode; if (responseCode == 404 || responseCode == 410) { MediaPlaylistChunk playlistChunk = (MediaPlaylistChunk) chunk; mediaPlaylistBlacklistFlags[playlistChunk.variantIndex] = true; if (!allPlaylistsBlacklisted()) { // We've handled the 404/410 by blacklisting the playlist. Log.w(TAG, "Blacklisted playlist (" + responseCode + "): " + playlistChunk.dataSpec.uri); return true; } else { // This was the last non-blacklisted playlist. Don't blacklist it. Log.w(TAG, "Final playlist not blacklisted (" + responseCode + "): " + playlistChunk.dataSpec.uri); mediaPlaylistBlacklistFlags[playlistChunk.variantIndex] = false; return false; } } } return false; } private int getNextVariantIndex(TsChunk previousTsChunk, long playbackPositionUs) { int idealVariantIndex = getVariantIndexForBandwdith( (int) (bandwidthMeter.getBitrateEstimate() * BANDWIDTH_FRACTION)); if (idealVariantIndex == variantIndex) { // We're already using the ideal variant. return variantIndex; } // We're not using the ideal variant for the available bandwidth, but only switch if the // conditions are appropriate. long bufferedPositionUs = previousTsChunk == null ? playbackPositionUs : adaptiveMode == ADAPTIVE_MODE_SPLICE ? previousTsChunk.startTimeUs : previousTsChunk.endTimeUs; long bufferedUs = bufferedPositionUs - playbackPositionUs; if (mediaPlaylistBlacklistFlags[variantIndex] || (idealVariantIndex > variantIndex && bufferedUs < maxBufferDurationToSwitchDownUs) || (idealVariantIndex < variantIndex && bufferedUs > minBufferDurationToSwitchUpUs)) { // Switch variant. return idealVariantIndex; } // Stick with the current variant for now. return variantIndex; } private int getVariantIndexForBandwdith(int bandwidth) { int lowestQualityEnabledVariant = 0; for (int i = 0; i < enabledVariants.length; i++) { if (!mediaPlaylistBlacklistFlags[i]) { if (enabledVariants[i].bandwidth <= bandwidth) { return i; } lowestQualityEnabledVariant = i; } } return lowestQualityEnabledVariant; } private boolean shouldRerequestMediaPlaylist(int variantIndex) { // Don't re-request media playlist more often than one-half of the target duration. HlsMediaPlaylist mediaPlaylist = mediaPlaylists[variantIndex]; long timeSinceLastMediaPlaylistLoadMs = SystemClock.elapsedRealtime() - lastMediaPlaylistLoadTimesMs[variantIndex]; return timeSinceLastMediaPlaylistLoadMs >= (mediaPlaylist.targetDurationSecs * 1000) / 2; } private int getLiveStartChunkMediaSequence(int variantIndex) { // For live start playback from the third chunk from the end. HlsMediaPlaylist mediaPlaylist = mediaPlaylists[variantIndex]; int chunkIndex = mediaPlaylist.segments.size() > 3 ? mediaPlaylist.segments.size() - 3 : 0; return chunkIndex + mediaPlaylist.mediaSequence; } private MediaPlaylistChunk newMediaPlaylistChunk(int variantIndex) { Uri mediaPlaylistUri = Util.getMergedUri(baseUri, enabledVariants[variantIndex].url); DataSpec dataSpec = new DataSpec(mediaPlaylistUri, 0, C.LENGTH_UNBOUNDED, null); Uri baseUri = Util.parseBaseUri(mediaPlaylistUri.toString()); return new MediaPlaylistChunk(variantIndex, upstreamDataSource, dataSpec, baseUri); } private EncryptionKeyChunk newEncryptionKeyChunk(Uri keyUri, String iv) { DataSpec dataSpec = new DataSpec(keyUri, 0, C.LENGTH_UNBOUNDED, null); return new EncryptionKeyChunk(upstreamDataSource, dataSpec, iv); } /* package */ void initEncryptedDataSource(Uri keyUri, String iv, byte[] secretKey) { String trimmedIv; if (iv.toLowerCase(Locale.getDefault()).startsWith("0x")) { trimmedIv = iv.substring(2); } else { trimmedIv = iv; } byte[] ivData = new BigInteger(trimmedIv, 16).toByteArray(); byte[] ivDataWithPadding = new byte[16]; int offset = ivData.length > 16 ? ivData.length - 16 : 0; System.arraycopy(ivData, offset, ivDataWithPadding, ivDataWithPadding.length - ivData.length + offset, ivData.length - offset); encryptedDataSource = new Aes128DataSource(secretKey, ivDataWithPadding, upstreamDataSource); encryptionKeyUri = keyUri; encryptedDataSourceIv = iv; encryptedDataSourceSecretKey = secretKey; } private void clearEncryptedDataSource() { encryptionKeyUri = null; encryptedDataSource = null; encryptedDataSourceIv = null; encryptedDataSourceSecretKey = null; } /* package */ void setMediaPlaylist(int variantIndex, HlsMediaPlaylist mediaPlaylist) { lastMediaPlaylistLoadTimesMs[variantIndex] = SystemClock.elapsedRealtime(); mediaPlaylists[variantIndex] = mediaPlaylist; live |= mediaPlaylist.live; durationUs = mediaPlaylist.durationUs; } private static Variant[] filterVariants(HlsMasterPlaylist masterPlaylist, int[] variantIndices) { List<Variant> masterVariants = masterPlaylist.variants; ArrayList<Variant> enabledVariants = new ArrayList<Variant>(); if (variantIndices != null) { for (int i = 0; i < variantIndices.length; i++) { enabledVariants.add(masterVariants.get(variantIndices[i])); } } else { // If variantIndices is null then all variants are initially considered. enabledVariants.addAll(masterVariants); } ArrayList<Variant> definiteVideoVariants = new ArrayList<Variant>(); ArrayList<Variant> definiteAudioOnlyVariants = new ArrayList<Variant>(); for (int i = 0; i < enabledVariants.size(); i++) { Variant variant = enabledVariants.get(i); if (variant.height > 0 || variantHasExplicitCodecWithPrefix(variant, "avc")) { definiteVideoVariants.add(variant); } else if (variantHasExplicitCodecWithPrefix(variant, "mp4a")) { definiteAudioOnlyVariants.add(variant); } } if (!definiteVideoVariants.isEmpty()) { // We've identified some variants as definitely containing video. Assume variants within the // master playlist are marked consistently, and hence that we have the full set. Filter out // any other variants, which are likely to be audio only. enabledVariants = definiteVideoVariants; } else if (definiteAudioOnlyVariants.size() < enabledVariants.size()) { // We've identified some variants, but not all, as being audio only. Filter them out to leave // the remaining variants, which are likely to contain video. enabledVariants.removeAll(definiteAudioOnlyVariants); } else { // Leave the enabled variants unchanged. They're likely either all video or all audio. } Collections.sort(enabledVariants, new Variant.DecreasingBandwidthComparator()); Variant[] enabledVariantsArray = new Variant[enabledVariants.size()]; enabledVariants.toArray(enabledVariantsArray); return enabledVariantsArray; } private static boolean variantHasExplicitCodecWithPrefix(Variant variant, String prefix) { String[] codecs = variant.codecs; if (codecs == null) { return false; } for (int i = 0; i < codecs.length; i++) { if (codecs[i].startsWith(prefix)) { return true; } } return false; } private boolean allPlaylistsBlacklisted() { for (int i = 0; i < mediaPlaylistBlacklistFlags.length; i++) { if (!mediaPlaylistBlacklistFlags[i]) { return false; } } return true; } private class MediaPlaylistChunk extends DataChunk { @SuppressWarnings("hiding") /* package */ final int variantIndex; private final Uri playlistBaseUri; public MediaPlaylistChunk(int variantIndex, DataSource dataSource, DataSpec dataSpec, Uri playlistBaseUri) { super(dataSource, dataSpec, scratchSpace); this.variantIndex = variantIndex; this.playlistBaseUri = playlistBaseUri; } @Override protected void consume(byte[] data, int limit) throws IOException { HlsPlaylist playlist = playlistParser.parse(new ByteArrayInputStream(data, 0, limit), null, null, playlistBaseUri); Assertions.checkState(playlist.type == HlsPlaylist.TYPE_MEDIA); HlsMediaPlaylist mediaPlaylist = (HlsMediaPlaylist) playlist; setMediaPlaylist(variantIndex, mediaPlaylist); // Recycle the allocation. scratchSpace = data; } } private class EncryptionKeyChunk extends DataChunk { private final String iv; public EncryptionKeyChunk(DataSource dataSource, DataSpec dataSpec, String iv) { super(dataSource, dataSpec, scratchSpace); this.iv = iv; } @Override protected void consume(byte[] data, int limit) throws IOException { initEncryptedDataSource(dataSpec.uri, iv, Arrays.copyOf(data, limit)); // Recycle the allocation. scratchSpace = data; } } }
25315ed557ad1c7c003d043aa556d6d4653fc09c
aba071e2f2b4f57724c3f1829cf629cbe76c201f
/src/com/library/Web/Servlet/Normal/LoginServlet.java
1f32ecf7887fc607aee1c9e28a35e962c51743d2
[]
no_license
Remilia-NULL/javaee_simple_library_crm
f66640d08abb93afc7caa4e3ad3daac958001e33
12ba5b47abfd6b96a20e3278e499247108531c27
refs/heads/master
2023-02-10T10:37:28.297462
2021-01-07T02:52:08
2021-01-07T02:52:08
327,486,629
0
0
null
null
null
null
UTF-8
Java
false
false
891
java
package com.library.Web.Servlet.Normal; import com.library.Domain.NormalUser; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NormalUser normalUser = (NormalUser) req.getSession().getAttribute("USER_DATA"); if (normalUser == null) { req.getRequestDispatcher("/normal/login.jsp").forward(req, resp); } else { resp.sendRedirect("/"); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
197ea89489087982155c792b8a0538d52fd43a17
0576ff5ae33977de639362dc3b100ff076f0ffea
/mod-webapp-codebase/src/main/java/com/cebedo/pmsys/bean/OrderingEstimateCost.java
6fbed573c80ad4f73592b39daddb52973b09d6e3
[]
no_license
lawrenceshava/Chimera
f7cc28d0a615fc15406a166009729ec05b839c64
ada6c3434a3679c53da789681d17135ee512444e
refs/heads/master
2022-02-26T20:00:59.284308
2016-05-16T09:02:36
2016-05-16T09:02:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,047
java
package com.cebedo.pmsys.bean; import com.cebedo.pmsys.domain.EstimateCost; import com.cebedo.pmsys.enums.TypeEstimateCost; import com.cebedo.pmsys.enums.SortOrder; import com.google.common.collect.Ordering; public class OrderingEstimateCost extends Ordering<EstimateCost> { private int subType = TypeEstimateCost.SUB_TYPE_PLANNED; private SortOrder order = SortOrder.ASCENDING; public OrderingEstimateCost() { ; } public OrderingEstimateCost(int sub, SortOrder order) { this.subType = sub; this.order = order; } @Override public int compare(EstimateCost left, EstimateCost right) { double leftValue = this.subType == TypeEstimateCost.SUB_TYPE_PLANNED ? left.getCost() : left.getActualCost(); double rightValue = this.subType == TypeEstimateCost.SUB_TYPE_PLANNED ? right.getCost() : right.getActualCost(); // And all results are valid. int comparison = leftValue > rightValue ? 1 : rightValue > leftValue ? -1 : 0; return this.order == SortOrder.ASCENDING ? comparison : comparison * -1; } }
fdff153848f5a37324a5b884c7d1176e037ac6e4
bd3915904e8281477e9fa89ea24fa8b832a5668f
/app/src/main/java/com/azens/searchlyrics/MainActivity.java
c9f87e240ac61d4c0b8eb80fecddff0757e70c07
[]
no_license
azens1995/SearchLyrics
2ff571eeebf1882482b548f4adb7bfbfde9747c8
cbb4a643212bd3a558dca8e6a2e59a842475d9f3
refs/heads/master
2020-03-25T19:06:11.209128
2018-08-08T23:02:45
2018-08-08T23:02:45
144,064,810
0
0
null
null
null
null
UTF-8
Java
false
false
3,097
java
package com.azens.searchlyrics; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.azens.searchlyrics.api.LyricsClient; import com.azens.searchlyrics.api.ServiceGenerator; import com.azens.searchlyrics.model.Lyrics; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private static final String LOG_TAG = ""; EditText inputArtist, inputSongsName; Button btnSearch; Call<Lyrics> call; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); inputArtist = (EditText) findViewById(R.id.inputArtist); inputSongsName = (EditText) findViewById(R.id.inputSongName); btnSearch = (Button) findViewById(R.id.buttonSearch); btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isNetworkConnected()){ String artist = inputArtist.getText().toString(); String name = inputSongsName.getText().toString(); LyricsClient client = ServiceGenerator.createService(LyricsClient.class); call = client.getLyrics(artist,name); loadLyrics(); }else { Toast.makeText(MainActivity.this, "No Internet connection...", Toast.LENGTH_SHORT).show(); } } }); } private void loadLyrics() { call.enqueue(new Callback<Lyrics>() { @Override public void onResponse(Call<Lyrics> call, Response<Lyrics> response) { if (!response.isSuccessful()){ Toast.makeText(MainActivity.this, "No lyrics found...", Toast.LENGTH_SHORT).show(); }else { Lyrics lyrics = response.body(); Intent intent = new Intent(MainActivity.this, LyricsActivity.class); intent.putExtra("lyrics", lyrics.getLyrics()); MainActivity.this.startActivity(intent); } } @Override public void onFailure(Call<Lyrics> call, Throwable t) { Toast.makeText(MainActivity.this, "Error occured...", Toast.LENGTH_SHORT).show(); t.printStackTrace(); } }); } private boolean isNetworkConnected () { ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } else { return false; } } }
ddad5d79dd3e537e9310928c302c71d4d1155e65
58992baff16ea41356bfb962bbfa632b4d6aae03
/src/main/java/com/mali/interfaces/DeliveryRepository.java
3f18386d7b7b3553af8fc4cae45916edd34caa7d
[]
no_license
Aharonabadi/Supplytrack-unsafe
beb7022f0b3a55b45a4c06dc817d59fe21105cc0
14d1dbdcb721a196b87d8399974b091de51c2d26
refs/heads/main
2023-01-21T17:23:11.782042
2020-11-16T11:38:04
2020-11-16T11:38:04
313,282,149
0
0
null
null
null
null
UTF-8
Java
false
false
205
java
package com.mali.interfaces; import org.springframework.data.jpa.repository.JpaRepository; import com.mali.model.Delivery; public interface DeliveryRepository extends JpaRepository<Delivery, Long> { }
0bdf804a29d7c811d1d2e0730b7abad3ad240c56
9b60184e23ac02c978a23c4784b533349a645ca8
/src/main/java/com/weibo/ad/sdk/constant/CreativeConfiguredStatusConstant.java
9a7f1f58be28d02710c3aeb782809882dc591d16
[]
no_license
weiboad/weibo-ads-java-sdk
c9cbd0482029b0bc59a600722a28610f7f625729
77d45711e5c79f6ccd6f54726eb7d21cc7850452
refs/heads/master
2020-04-05T03:19:49.766259
2018-12-19T07:02:11
2018-12-19T07:02:11
156,510,503
0
0
null
null
null
null
UTF-8
Java
false
false
466
java
package com.weibo.ad.sdk.constant; /** * Package: com.weibo.ad.sdk.constant * * @Author: [email protected] * @Date: Creatd at 2017/7/20 下午5:20 */ public class CreativeConfiguredStatusConstant { public static final String PAUSE = "pause"; public static final String OPEN = "open"; public static final String STOP = "stop"; public static final String RECYCLE = "recycle"; public static final String RECOVER = "recover"; }
eeed02225f3006cb9c22aa6044bd7589f9e70656
dbf5adca095d04d7d069ecaa916e883bc1e5c73d
/x_crm_assemble_control/src/test/java/x_crm_assemble_control/Test.java
07282193485d0fd8ad55fbc077b19a016ba06950
[ "BSD-3-Clause" ]
permissive
fancylou/o2oa
713529a9d383de5d322d1b99073453dac79a9353
e7ec39fc586fab3d38b62415ed06448e6a9d6e26
refs/heads/master
2020-03-25T00:07:41.775230
2018-08-02T01:40:40
2018-08-02T01:40:40
143,169,936
0
0
BSD-3-Clause
2018-08-01T14:49:45
2018-08-01T14:49:44
null
UTF-8
Java
false
false
487
java
package x_crm_assemble_control; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Test { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("java"); list.add("world"); list.add("android"); ListIterator lit = list.listIterator(); while (lit.hasNext()) { String s = (String) lit.next(); if ("android".equals(s)) { lit.add("javaee"); } } System.out.println(list); } }
ccb91f34254dbc5682f4a3e581c6ced7e50c146c
f9d466aeeaa98b391ef6f8f4dfbde02270845c3e
/src/main/java/cn/authing/sdk/java/dto/CreateAsaAccountsBatchDto.java
7ae14b1f506abbaf89607f0a23349899a696b287
[ "MIT" ]
permissive
Authing/authing-java-sdk
2be7eb849b052d1ff49bbf251e4ec49103b0be79
69586520aa0ecad1bd86b53dc4456533cc0f5380
refs/heads/master
2023-08-28T14:10:33.506537
2023-08-15T07:21:30
2023-08-15T07:21:30
122,724,916
217
15
MIT
2023-08-15T07:21:31
2018-02-24T09:25:56
Java
UTF-8
Java
false
false
750
java
package cn.authing.sdk.java.dto; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import cn.authing.sdk.java.dto.CreateAsaAccountsBatchItemDto; public class CreateAsaAccountsBatchDto { /** * 账号列表 */ @JsonProperty("list") private List<CreateAsaAccountsBatchItemDto> list; /** * 所属应用 ID */ @JsonProperty("appId") private String appId; public List<CreateAsaAccountsBatchItemDto> getList() { return list; } public void setList(List<CreateAsaAccountsBatchItemDto> list) { this.list = list; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } }
dbc81885164bdd032fec81c19aaffaad9ac92884
8aea95c114e07d043d217f51a30807b4642d49a7
/core/typesystemEngine/source/jetbrains/mps/lang/typesystem/runtime/SubstituteType_Runtime.java
024ac936e4ab4a90ca7f92099fde908b5a38b5a7
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JetBrains/MPS
ec03a005e0eda3055c4e4856a28234b563af92c6
0d2aeaf642e57a86b23268fc87740214daa28a67
refs/heads/master
2023-09-03T15:14:10.508189
2023-09-01T13:25:35
2023-09-01T13:30:22
2,209,077
1,242
309
Apache-2.0
2023-07-25T18:10:10
2011-08-15T09:48:06
JetBrains MPS
UTF-8
Java
false
false
1,070
java
/* * Copyright 2003-2015 JetBrains s.r.o. * * 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 jetbrains.mps.lang.typesystem.runtime; import jetbrains.mps.typesystem.inference.TypeSubstitution; import jetbrains.mps.typesystem.inference.TypeCheckingContext; import org.jetbrains.mps.openapi.model.SNode; /** * @author fyodor on 13.05.2015. */ public interface SubstituteType_Runtime extends Rule_Runtime { TypeSubstitution substitution(SNode ruleNode, SNode termType, TypeCheckingContext typeCheckingContext, IsApplicableStatus applicableStatus); }
88572af4a054fd002810b92e82ad08d11f89782f
8d3c54983e1e57e166b0e946baeda38e2b7aeb15
/jnpf-datareport/report-core/src/main/java/com/bstek/ureport/definition/Scope.java
7424a12c0253710425c0cc7280fad58986c1ef6b
[]
no_license
houzhanwu/lowCodePlatform
01d3c6f8fc30eb6dfd6d0beea55c705231fd97a5
88c0822c974b129d6c5423fec59d7de9fa907527
refs/heads/master
2023-08-30T04:07:23.106710
2021-11-17T02:33:20
2021-11-17T02:33:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
861
java
/******************************************************************************* * Copyright 2017 Bstek * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.bstek.ureport.definition; /** * @author * @since 4月24日 */ public enum Scope { cell,row,column }
b0594b31f43ef08a529fdb0424dd3791eb3fe0a0
02ed16f0d6b3b19ee11e1efd46d9c7b9fbace9d4
/chattingus-support/src/main/java/com/chattingus/dao/Result.java
f9a1a272c192ebcf22261482e01bc23631526137
[]
no_license
lifengboy/chattingus
247d2fbfca33804a8f934517b2edd3de9081b5c1
8e9cf81a320b786b5ad8d00e01845e3e92700251
refs/heads/master
2021-01-20T08:06:31.325783
2017-05-26T04:19:47
2017-05-26T04:19:47
90,094,781
0
0
null
null
null
null
UTF-8
Java
false
false
813
java
package com.chattingus.dao; import java.util.List; import java.io.Serializable; /** * * @author */ public class Result<T> implements Serializable { /** * 序列化ID */ private static final long serialVersionUID = 1L; private boolean isSuccess = true; private List<T> list; private int count; private String errorMsg; public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean isSuccess) { this.isSuccess = isSuccess; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } }
d207a4b87e8b2dc48e0b02fd64082cd042891b09
4e223d8eafae42cf44233ee3fdeca7a895016ed4
/app/src/main/java/com/example/admin/service_test_app/display/menu/MenuFactory.java
31e1300aeb229c4bbf841c0021ec5245c70383b9
[]
no_license
oschumac/Service_test_app
8bd2d3c5d96145f987e3b2d57f4cab43e8be7a71
4a948c969865be9b3173692eabeb72ab8020b18d
refs/heads/master
2021-08-15T12:22:06.668977
2017-10-13T15:56:55
2017-10-13T15:56:55
105,177,895
0
0
null
null
null
null
UTF-8
Java
false
false
87,461
java
package com.example.admin.service_test_app.display.menu; import com.example.admin.service_test_app.display.Menu; import com.example.admin.service_test_app.display.MenuAttribute; import com.example.admin.service_test_app.display.MenuType; import com.example.admin.service_test_app.display.Symbol; import com.example.admin.service_test_app.display.Token; import com.example.admin.service_test_app.display.parser.CharacterPattern; import com.example.admin.service_test_app.display.parser.NumberPattern; import com.example.admin.service_test_app.display.parser.Pattern; import com.example.admin.service_test_app.display.parser.SymbolPattern; import java.util.LinkedList; /** * Created by fishermen21 on 22.05.17. */ public class MenuFactory { public static Menu get(LinkedList<Token>[] tokens) { if(tokens[0].size()>0) { Pattern p = tokens[0].getFirst().getPattern(); if(isSymbol(p,Symbol.CLOCK)) { if(tokens[1].size()==1) { if(isSymbol(tokens[1].get(0).getPattern(),Symbol.LARGE_STOP)) return makeStopMenu(tokens); } else { for(Token t:tokens[0]) if(isSymbol(t.getPattern(),Symbol.MINUS)) return makeBasalSet(tokens); } return makeMainMenu(tokens); } } if(tokens[2].size()==1) { String s0 = parseString(tokens[0],true); Pattern p = tokens[2].get(0).getPattern(); if(p instanceof NumberPattern && isSymbol(tokens[1].get(0).getPattern(),Symbol.LARGE_BASAL_SET)) { return makeBasalTotal(tokens); } String s1 = parseString(tokens[1],true); if(isSymbol(p,Symbol.LARGE_STOP)) { tokens[2].removeFirst(); return new Menu(MenuType.STOP_MENU); } if(isSymbol(p,Symbol.LARGE_BOLUS)) { tokens[2].removeFirst(); return new Menu(MenuType.BOLUS_MENU); } if(isSymbol(p,Symbol.LARGE_EXTENDED_BOLUS)) { tokens[2].removeFirst(); return new Menu(MenuType.EXTENDED_BOLUS_MENU); } if(isSymbol(p,Symbol.LARGE_MULTIWAVE)) { tokens[2].removeFirst(); return new Menu(MenuType.MULTIWAVE_BOLUS_MENU); } if(isSymbol(p,Symbol.LARGE_TBR)) { tokens[2].removeFirst(); return new Menu(MenuType.TBR_MENU); } if(isSymbol(p,Symbol.LARGE_MY_DATA)) { tokens[2].removeFirst(); return new Menu(MenuType.MY_DATA_MENU); } if(isSymbol(p,Symbol.LARGE_BASAL)) { tokens[2].removeFirst(); return new Menu(MenuType.BASAL_MENU); } if(isSymbol(p,Symbol.LARGE_ALARM_SETTINGS)) { tokens[2].removeFirst(); return new Menu(MenuType.ALARM_MENU); } if(isSymbol(p,Symbol.LARGE_CALENDAR)) { tokens[2].removeFirst(); return new Menu(MenuType.DATE_AND_TIME_MENU); } if(isSymbol(p,Symbol.LARGE_PUMP_SETTINGS)) { tokens[2].removeFirst(); return new Menu(MenuType.PUMP_MENU); } if(isSymbol(p,Symbol.LARGE_THERAPIE_SETTINGS)) { tokens[2].removeFirst(); return new Menu(MenuType.THERAPY_MENU); } if(isSymbol(p,Symbol.LARGE_BLUETOOTH_SETTINGS)) { tokens[2].removeFirst(); return new Menu(MenuType.BLUETOOTH_MENU); } if(isSymbol(p,Symbol.LARGE_MENU_SETTINGS)) { tokens[2].removeFirst(); return new Menu(MenuType.MENU_SETTINGS_MENU); } if(isSymbol(p,Symbol.LARGE_CHECK)) { tokens[2].removeFirst(); return new Menu(MenuType.START_MENU); } } else if(tokens[2].size()==2) { Pattern p1 = tokens[2].removeFirst().getPattern(); Pattern p2 = tokens[2].removeFirst().getPattern(); if(isSymbol(p1,Symbol.LARGE_BASAL)) { if(p2 instanceof NumberPattern) { int num = ((NumberPattern)p2).getNumber(); parseString(tokens[0],true); parseString(tokens[1],true); switch(num) { case 1: return new Menu(MenuType.BASAL_1_MENU); case 2: return new Menu(MenuType.BASAL_2_MENU); case 3: return new Menu(MenuType.BASAL_3_MENU); case 4: return new Menu(MenuType.BASAL_4_MENU); case 5: return new Menu(MenuType.BASAL_5_MENU); } } } return null; } else if(tokens[0].size()>1) { String title = parseString(tokens[0],false); Title t = TitleResolver.resolve(title); if(t!=null) { //resolved so we can consume parseString(tokens[0],true); switch (t) { case BOLUS_AMOUNT: return makeBolusEnter(tokens); case BOLUS_DURATION: return makeBolusDuration(tokens); case IMMEDIATE_BOLUS: return makeImmediateBolus(tokens); case QUICK_INFO: return makeQuickInfo(tokens); case BOLUS_DATA: return makeBolusData(tokens); case DAILY_TOTALS: return makeDailyData(tokens); case ERROR_DATA: return makeErrorData(tokens); case TBR_DATA: return makeTBRData(tokens); case TBR_SET: return makeTBRSet(tokens); case TBR_DURATION: return makeTBRDuration(tokens); } Pattern p = tokens[1].get(0).getPattern(); } } if(tokens[0].size()>0 && tokens[3].size()>0) { String m = parseString(tokens[0], false); Token t30 = tokens[3].getFirst(); if(isSymbol(t30.getPattern(),Symbol.CHECK) && m.length()>0) return makeWarning(tokens); } return null; } private static Menu makeWarning(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.WARNING_OR_ERROR); String message = parseString(tokens[0],true); m.setAttribute(MenuAttribute.MESSAGE,message); int stage = 0; int warning = 0; int type = 0; while(tokens[1].size()>0) { Pattern p = tokens[1].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.LARGE_WARNING)) { type = 1; stage++; } else if(isSymbol(p,Symbol.LARGE_ERROR)) { type = 2; stage++; } else return null; break; case 1: if(p instanceof CharacterPattern) { char w = ((CharacterPattern)p).getCharacter(); if(type == 1 && w == 'W') { stage++; } else if(type == 2 && w == 'E') { stage++; } else return null; } else return null; break; case 2: if(p instanceof NumberPattern) { warning = ((NumberPattern)p).getNumber(); stage++; } else return null; break; case 3: if(p instanceof NumberPattern) { warning *= 10; warning += ((NumberPattern) p).getNumber(); stage++; } else if(isSymbol(p,Symbol.LARGE_STOP)) stage+=2; else return null; break; case 4: if(isSymbol(p,Symbol.LARGE_STOP)) stage++; else return null; break; default: return null; } } if(type == 1) { m.setAttribute(MenuAttribute.WARNING, warning); } else if(type == 2) { m.setAttribute(MenuAttribute.ERROR, warning); } else { m.setAttribute(MenuAttribute.ERROR_OR_WARNING, warning); } if(isSymbol(tokens[3].getFirst().getPattern(),Symbol.CHECK)) { tokens[3].removeFirst(); parseString(tokens[3],true);//ignore result } return m; } private static Menu makeBasalSet(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.BASAL_SET); LinkedList<Pattern> from = new LinkedList<>(); LinkedList<Pattern> to = new LinkedList<>(); int stage = 0; while(tokens[0].size()>0) { Pattern p = tokens[0].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.CLOCK)) stage++; else return null; break; case 1: if(isSymbol(p,Symbol.MINUS)) stage++; else if(isSymbol(p,Symbol.SEPERATOR)) from.add(p); else if(p instanceof CharacterPattern) from.add(p); else if(p instanceof NumberPattern) from.add(p); else return null; break; case 2: if(p instanceof CharacterPattern) to.add(p); else if(p instanceof NumberPattern) to.add(p); else if(isSymbol(p,Symbol.SEPERATOR)) to.add(p); else return null; break; default: return null; } } if(from.size()>0 && to.size()>0) { try { int f10 = ((NumberPattern) from.removeFirst()).getNumber(); int f1 = ((NumberPattern) from.removeFirst()).getNumber(); int a = 0; if (from.size() > 0) { if(from.getFirst() instanceof CharacterPattern) { char c0 = ((CharacterPattern) from.removeFirst()).getCharacter(); char c1 = ((CharacterPattern) from.removeFirst()).getCharacter(); if (c0 == 'P' && c1 == 'M' && !(f10 == 1 && f1 == 2)) a += 12; else if (c0 == 'A' && c1 == 'M' && f10 == 1 && f1 == 2) a -= 12; } else if(isSymbol(from.getFirst(),Symbol.SEPERATOR)) {}//ignore else return null; } m.setAttribute(MenuAttribute.BASAL_START, new MenuTime((f10 * 10) + f1 + a, 0)); int t10 = ((NumberPattern) to.removeFirst()).getNumber(); int t1 = ((NumberPattern) to.removeFirst()).getNumber(); a = 0; if (to.size() > 0) { if(to.getFirst() instanceof CharacterPattern) { char c0 = ((CharacterPattern) to.removeFirst()).getCharacter(); char c1 = ((CharacterPattern) to.removeFirst()).getCharacter(); if (c0 == 'P' && c1 == 'M' && !(t10==1 && t1 == 2)) a += 12; else if (c0 == 'A' && c1 == 'M' && t10 == 1 && t1 == 2) a -= 12; } else if(isSymbol(to.getFirst(),Symbol.SEPERATOR)) {}//ignore else return null; } m.setAttribute(MenuAttribute.BASAL_END, new MenuTime((t10 * 10) + t1 + a, 0)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; stage = 0; LinkedList<Pattern> basal = new LinkedList<>(); while(tokens[1].size()>0) { Pattern p = tokens[1].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.LARGE_BASAL)) stage++; else return null; break; case 1: if(isSymbol(p,Symbol.LARGE_UNITS_PER_HOUR)) stage++; else if(isSymbol(p,Symbol.LARGE_DOT)) basal.add(p); else if(p instanceof NumberPattern) basal.add(p); else return null; break; default: return null; } } if(basal.size()>0) { try { String n = ""; for(Pattern p: basal) { if(p instanceof NumberPattern) n+=((NumberPattern)p).getNumber(); else if(isSymbol(p,Symbol.LARGE_DOT)) n+="."; else return null; } double d = Double.parseDouble(n); m.setAttribute(MenuAttribute.BASAL_RATE,d); }catch(Exception e) { e.printStackTrace(); return null; } } else { m.setAttribute(MenuAttribute.BASAL_RATE,new MenuBlink()); } if(tokens[2].size()==1 && tokens[2].get(0).getPattern() instanceof NumberPattern) { m.setAttribute(MenuAttribute.BASAL_SELECTED,((NumberPattern)tokens[2].removeFirst().getPattern()).getNumber()); } else return null; return m; } private static Menu makeBasalTotal(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.BASAL_TOTAL); LinkedList<Pattern> basal = new LinkedList<>(); int stage = 0; while(tokens[1].size()>0) { Pattern p = tokens[1].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.LARGE_BASAL_SET)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) basal.add(p); else if (isSymbol(p,Symbol.LARGE_DOT)) basal.add(p); else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='u') stage++; else return null; break; default: return null; } } if(basal.size()>0) { try { String n = ""; for (Pattern p : basal) if (p instanceof NumberPattern) n += ((NumberPattern) p).getNumber(); else if (isSymbol(p, Symbol.LARGE_DOT)) n += "."; else return null; double d = Double.parseDouble(n); m.setAttribute(MenuAttribute.BASAL_TOTAL,d); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; if(tokens[2].size()==1 && tokens[2].get(0).getPattern() instanceof NumberPattern) { m.setAttribute(MenuAttribute.BASAL_SELECTED,((NumberPattern)tokens[2].removeFirst().getPattern()).getNumber()); } else { return null; } stage = 0; while(tokens[3].size()>0) { Pattern p = tokens[3].removeFirst().getPattern(); switch(stage) { case 0: if(isSymbol(p,Symbol.CHECK)) { String s = parseString(tokens[3],true); if(s!=null) stage++; else return null; } else return null; break; default: return null; } } return m; } private static Menu makeStopMenu(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.STOP); if(!isSymbol(tokens[1].removeFirst().getPattern(),Symbol.LARGE_STOP)) return null; int stage = 0; LinkedList<Pattern> clock = new LinkedList<>(); LinkedList<Pattern> date = new LinkedList<>(); while(tokens[0].size()>0) { Pattern p = tokens[0].removeFirst().getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.CLOCK)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) clock.add(p); else if(p instanceof CharacterPattern) clock.add(p); else if (isSymbol(p, Symbol.SEPERATOR)) {} else if(isSymbol(p,Symbol.CALENDAR)) stage++; else return null; break; case 2: if(p instanceof NumberPattern) date.add(p); else if (isSymbol(p, Symbol.DIVIDE)) date .add(p); else if (isSymbol(p, Symbol.DOT)) date .add(p); else return null; break; case 3: return null; } } if(clock.size()>=4) { try { int hour10 = ((NumberPattern) clock.removeFirst()).getNumber(); int hour1 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute10 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute1 = ((NumberPattern) clock.removeFirst()).getNumber(); int timeadd = 0; if (clock.size() == 2) { CharacterPattern p0 = (CharacterPattern) clock.removeFirst(); CharacterPattern p1 = (CharacterPattern) clock.removeFirst(); if(p0.getCharacter()=='A' && p1.getCharacter()=='M' && hour10==1 && hour1 == 2) timeadd-=12; else if(p0.getCharacter()=='P' && p1.getCharacter()=='M') timeadd+=12; } m.setAttribute(MenuAttribute.TIME,new MenuTime((hour10*10)+hour1+timeadd,(minute10*10)+minute1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; if(date.size()==5) { try { int f10 = ((NumberPattern) date.removeFirst()).getNumber(); int f1 = ((NumberPattern) date.removeFirst()).getNumber(); boolean divide = isSymbol(date.removeFirst(),Symbol.DIVIDE); int s10 = ((NumberPattern) date.removeFirst()).getNumber(); int s1 = ((NumberPattern) date.removeFirst()).getNumber(); if(divide) m.setAttribute(MenuAttribute.DATE, new MenuDate((s10*10)+s1,(f10*10)+f1)); else m.setAttribute(MenuAttribute.DATE, new MenuDate((f10*10)+f1,(s10*10)+s1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; stage = 0; int lowInsulin = 0; boolean lowBattery= false; boolean waranty= true; int lockState = 0; while(tokens[3].size()>0) { Token t = tokens[3].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.LOW_BAT)) { lowBattery = true; } else if (isSymbol(p, Symbol.LOW_INSULIN)) { lowInsulin= 1; } else if (isSymbol(p, Symbol.NO_INSULIN)) { lowInsulin= 2; } else if (isSymbol(p, Symbol.LOCK_CLOSED)) { lockState=2; } else if (isSymbol(p, Symbol.LOCK_OPENED)) { lockState=2; } else if (isSymbol(p, Symbol.WARANTY)) { waranty = false; } else { return null; } break; case 2: return null; } } if(lowBattery) m.setAttribute(MenuAttribute.LOW_BATTERY,new Boolean(true)); else m.setAttribute(MenuAttribute.LOW_BATTERY,new Boolean(false)); m.setAttribute(MenuAttribute.INSULIN_STATE,lowInsulin); m.setAttribute(MenuAttribute.WARANTY,new Boolean(waranty)); m.setAttribute(MenuAttribute.LOCK_STATE,new Integer(lockState)); return m; } private static Menu makeTBRSet(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.TBR_SET); int stage = 0; LinkedList<NumberPattern> number = new LinkedList<>(); while(tokens[1].size()>0) { Pattern p = tokens[1].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.LARGE_BASAL)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) { number.add((NumberPattern)p); } else if (isSymbol(p,Symbol.LARGE_PERCENT)) { stage++; } break; case 2: return null; } } if(number.size()>0) { String n = ""; while(number.size()>0) { n += number.removeFirst().getNumber(); } try{ double d = Double.parseDouble(n); m.setAttribute(MenuAttribute.BASAL_RATE,d); }catch(Exception e){e.printStackTrace();return null;} } else if(number.size()==0) m.setAttribute(MenuAttribute.BASAL_RATE, new MenuBlink()); else return null; if(tokens[3].size()>0) { stage = 0; number.clear(); while (tokens[3].size() > 0) { Pattern p = tokens[3].removeFirst().getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.ARROW)) stage++; else return null; break; case 1: if (p instanceof NumberPattern) number.add((NumberPattern) p); else if (isSymbol(p, Symbol.SEPERATOR)) {} else return null; break; case 2: return null; } } if (number.size() == 4) { int hour10 = number.removeFirst().getNumber(); int hour1 = number.removeFirst().getNumber(); int minute10 = number.removeFirst().getNumber(); int minute1 = number.removeFirst().getNumber(); m.setAttribute(MenuAttribute.RUNTIME, new MenuTime((hour10 * 10) + hour1, (minute10 * 10) + minute1)); } else return null; } else m.setAttribute(MenuAttribute.RUNTIME,new MenuTime(0,0)); return m; } private static Menu makeTBRDuration(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.TBR_DURATION); int stage = 0; LinkedList<NumberPattern> number = new LinkedList<>(); while(tokens[1].size()>0) { Pattern p = tokens[1].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.LARGE_ARROW)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) { number.add((NumberPattern)p); } else if (isSymbol(p,Symbol.LARGE_PERCENT)) { stage++; } else if (isSymbol(p,Symbol.LARGE_SEPERATOR)) { } else return null; break; case 2: return null; } } if(number.size()==4) { int hour10 = number.removeFirst().getNumber(); int hour1 = number.removeFirst().getNumber(); int minute10 = number.removeFirst().getNumber(); int minute1 = number.removeFirst().getNumber(); m.setAttribute(MenuAttribute.RUNTIME,new MenuTime((hour10*10)+hour1,(minute10*10)+minute1)); } else if(number.size()==0) m.setAttribute(MenuAttribute.RUNTIME,new MenuBlink()); else return null; stage = 0; number.clear(); while(tokens[3].size()>0) { Pattern p = tokens[3].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.BASAL)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) number.add((NumberPattern)p); else if(isSymbol(p,Symbol.PERCENT)) stage++; else return null; break; case 3: return null; } } if(number.size()>0) { String n = ""; while(number.size()>0) { n += number.removeFirst().getNumber(); } try{ double d = Double.parseDouble(n); m.setAttribute(MenuAttribute.BASAL_RATE,d); }catch(Exception e){e.printStackTrace();return null;} } return m; } private static Menu makeTBRData(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.TBR_DATA); int stage = 0; LinkedList<NumberPattern> percent = new LinkedList<>(); LinkedList<NumberPattern> cr = new LinkedList<>(); LinkedList<NumberPattern> tr = new LinkedList<>(); while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.UP)) stage++; else if (isSymbol(p, Symbol.DOWN)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) percent.add((NumberPattern) p); else if(isSymbol(p,Symbol.PERCENT)) stage++; else return null; break; case 2: if(p instanceof NumberPattern) cr.add((NumberPattern) p); else if(isSymbol(p,Symbol.DIVIDE)) stage++; else return null; break; case 3: if(p instanceof NumberPattern) tr.add((NumberPattern) p); else return null; break; default: return null; } } if(percent.size()>0) { try { String n = ""; for(NumberPattern p : percent) { n+=p.getNumber(); } double d = Double.parseDouble(n); m.setAttribute(MenuAttribute.TBR,d); }catch(Exception e) { e.printStackTrace(); return null; } } if(cr.size()==2 && tr.size() == 2) { int c = cr.removeFirst().getNumber()*10; c+=cr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.CURRENT_RECORD,new Integer(c)); int t = tr.removeFirst().getNumber()*10; t+=tr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.TOTAL_RECORD,new Integer(t)); } else return null; LinkedList<Pattern> clock = new LinkedList<>(); stage = 0; while(tokens[2].size()>0) { Pattern p = tokens[2].removeFirst().getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.ARROW)) stage++; else return null; break; case 1: if (p instanceof NumberPattern) clock.add(p); else if (isSymbol(p, Symbol.SEPERATOR)) { } else return null; break; default: return null; } } if(clock.size()==4) { try { int hour10 = ((NumberPattern) clock.removeFirst()).getNumber(); int hour1 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute10 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute1 = ((NumberPattern) clock.removeFirst()).getNumber(); m.setAttribute(MenuAttribute.RUNTIME,new MenuTime((hour10*10)+hour1,(minute10*10)+minute1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; clock.clear(); LinkedList<Pattern> date = new LinkedList<>(); stage = 0; while(tokens[3].size()>0) { Pattern p = tokens[3].removeFirst().getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.CLOCK)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) clock.add(p); else if(p instanceof CharacterPattern) clock.add(p); else if (isSymbol(p, Symbol.SEPERATOR)) {} else if(isSymbol(p,Symbol.CALENDAR)) stage++; else return null; break; case 2: if(p instanceof NumberPattern) date.add(p); else if (isSymbol(p, Symbol.DIVIDE)) date .add(p); else if (isSymbol(p, Symbol.DOT)) date .add(p); else return null; break; case 3: return null; } } if(clock.size()>=4) { try { int hour10 = ((NumberPattern) clock.removeFirst()).getNumber(); int hour1 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute10 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute1 = ((NumberPattern) clock.removeFirst()).getNumber(); int timeadd = 0; if (clock.size() == 2) { CharacterPattern p0 = (CharacterPattern) clock.removeFirst(); CharacterPattern p1 = (CharacterPattern) clock.removeFirst(); if(p0.getCharacter()=='A' && p1.getCharacter()=='M' && hour10==1 && hour1 == 2) timeadd-=12; else if(p0.getCharacter()=='P' && p1.getCharacter()=='M') timeadd+=12; } m.setAttribute(MenuAttribute.TIME,new MenuTime((hour10*10)+hour1+timeadd,(minute10*10)+minute1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; if(date.size()==5) { try { int f10 = ((NumberPattern) date.removeFirst()).getNumber(); int f1 = ((NumberPattern) date.removeFirst()).getNumber(); boolean divide = isSymbol(date.removeFirst(),Symbol.DIVIDE); int s10 = ((NumberPattern) date.removeFirst()).getNumber(); int s1 = ((NumberPattern) date.removeFirst()).getNumber(); if(divide) m.setAttribute(MenuAttribute.DATE, new MenuDate((s10*10)+s1,(f10*10)+f1)); else m.setAttribute(MenuAttribute.DATE, new MenuDate((f10*10)+f1,(s10*10)+s1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; return m; } private static Menu makeErrorData(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.ERROR_DATA); boolean error = false; boolean warning = false; int code = 0; LinkedList<NumberPattern> cr = new LinkedList<>(); LinkedList<NumberPattern> tr = new LinkedList<>(); int stage = 0; while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.WARNING)) { warning=true; stage++; } else if (isSymbol(p, Symbol.ERROR)) { error=true; stage++; } else return null; break; case 1: if(p instanceof CharacterPattern && ((((CharacterPattern)p).getCharacter()=='W' && warning) || (((CharacterPattern)p).getCharacter()=='E' && error))) stage++; else return null; break; case 2: if(p instanceof NumberPattern) { code = ((NumberPattern) p).getNumber(); stage++; } else return null; break; case 3: if(p instanceof NumberPattern) cr.add((NumberPattern) p); else if(isSymbol(p,Symbol.DIVIDE)) stage++; else return null; break; case 4: if(p instanceof NumberPattern) tr.add((NumberPattern) p); else return null; break; case 5: return null; } } if(error) m.setAttribute(MenuAttribute.ERROR,new Integer(code)); else if(warning) m.setAttribute(MenuAttribute.WARNING,new Integer(code)); else return null; if(cr.size()==2 && tr.size() == 2) { int c = cr.removeFirst().getNumber()*10; c+=cr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.CURRENT_RECORD,new Integer(c)); int t = tr.removeFirst().getNumber()*10; t+=tr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.TOTAL_RECORD,new Integer(t)); } else return null; String message = parseString(tokens[2],true); if(message!=null) m.setAttribute(MenuAttribute.MESSAGE,message); else return null; LinkedList<Pattern> clock = new LinkedList<>(); LinkedList<Pattern> date = new LinkedList<>(); stage = 0; while(tokens[3].size()>0) { Pattern p = tokens[3].removeFirst().getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.CLOCK)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) clock.add(p); else if(p instanceof CharacterPattern) clock.add(p); else if (isSymbol(p, Symbol.SEPERATOR)) {} else if(isSymbol(p,Symbol.CALENDAR)) stage++; else return null; break; case 2: if(p instanceof NumberPattern) date.add(p); else if (isSymbol(p, Symbol.DIVIDE)) date .add(p); else if (isSymbol(p, Symbol.DOT)) date .add(p); else return null; break; case 3: return null; } } if(clock.size()>=4) { try { int hour10 = ((NumberPattern) clock.removeFirst()).getNumber(); int hour1 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute10 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute1 = ((NumberPattern) clock.removeFirst()).getNumber(); int timeadd = 0; if (clock.size() == 2) { CharacterPattern p0 = (CharacterPattern) clock.removeFirst(); CharacterPattern p1 = (CharacterPattern) clock.removeFirst(); if(p0.getCharacter()=='A' && p1.getCharacter()=='M' && hour10==1 && hour1 == 2) timeadd-=12; else if(p0.getCharacter()=='P' && p1.getCharacter()=='M') timeadd+=12; } m.setAttribute(MenuAttribute.TIME,new MenuTime((hour10*10)+hour1+timeadd,(minute10*10)+minute1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; if(date.size()==5) { try { int f10 = ((NumberPattern) date.removeFirst()).getNumber(); int f1 = ((NumberPattern) date.removeFirst()).getNumber(); boolean divide = isSymbol(date.removeFirst(),Symbol.DIVIDE); int s10 = ((NumberPattern) date.removeFirst()).getNumber(); int s1 = ((NumberPattern) date.removeFirst()).getNumber(); if(divide) m.setAttribute(MenuAttribute.DATE, new MenuDate((s10*10)+s1,(f10*10)+f1)); else m.setAttribute(MenuAttribute.DATE, new MenuDate((f10*10)+f1,(s10*10)+s1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; return m; } private static Menu makeDailyData(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.DAILY_DATA); LinkedList<NumberPattern> cr = new LinkedList<>(); LinkedList<NumberPattern> tr = new LinkedList<>(); int stage = 0; while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if(p instanceof NumberPattern) cr.add((NumberPattern) p); else if(isSymbol(p,Symbol.DIVIDE)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) tr.add((NumberPattern) p); else return null; break; case 2: return null; } } if(cr.size()==2 && tr.size() == 2) { int c = cr.removeFirst().getNumber()*10; c+=cr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.CURRENT_RECORD,new Integer(c)); int t = tr.removeFirst().getNumber()*10; t+=tr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.TOTAL_RECORD,new Integer(t)); } else return null; LinkedList<Pattern> sum = new LinkedList<>(); stage = 0; while (tokens[2].size()>0) { Token t = tokens[2].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.SUM)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) sum.add((NumberPattern) p); else if(isSymbol(p,Symbol.DOT)) sum.add(p); else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='U') stage++; else return null; break; case 2: return null; } } if(sum.size()>0) { try { String n = ""; for(Pattern p : sum) { if(p instanceof NumberPattern) n+=((NumberPattern)p).getNumber(); else if(isSymbol(p,Symbol.DOT)) n+="."; else return null; } double d = Double.parseDouble(n); m.setAttribute(MenuAttribute.DAILY_TOTAL,d); }catch(Exception e) { e.printStackTrace(); return null; } } LinkedList<Pattern> date = new LinkedList<>(); stage = 0; while(tokens[3].size()>0) { Pattern p = tokens[3].removeFirst().getPattern(); switch (stage) { case 0: if(isSymbol(p,Symbol.CALENDAR)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) date.add(p); else if (isSymbol(p, Symbol.DIVIDE)) date .add(p); else if (isSymbol(p, Symbol.DOT)) date .add(p); else return null; break; case 2: return null; } } if(date.size()==5) { try { int f10 = ((NumberPattern) date.removeFirst()).getNumber(); int f1 = ((NumberPattern) date.removeFirst()).getNumber(); boolean divide = isSymbol(date.removeFirst(),Symbol.DIVIDE); int s10 = ((NumberPattern) date.removeFirst()).getNumber(); int s1 = ((NumberPattern) date.removeFirst()).getNumber(); if(divide) m.setAttribute(MenuAttribute.DATE, new MenuDate((s10*10)+s1,(f10*10)+f1)); else m.setAttribute(MenuAttribute.DATE, new MenuDate((f10*10)+f1,(s10*10)+s1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; return m; } private static Menu makeBolusData(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.BOLUS_DATA); LinkedList<Pattern> bolus = new LinkedList<>(); LinkedList<NumberPattern> cr = new LinkedList<>(); LinkedList<NumberPattern> tr = new LinkedList<>(); BolusType bt = null; int stage = 0; while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.BOLUS)) { bt = BolusType.NORMAL; stage++; } else if (isSymbol(p, Symbol.EXTENDED_BOLUS)) { bt = BolusType.EXTENDED; stage++; } else if (isSymbol(p, Symbol.MULTIWAVE)) { bt = BolusType.MULTIWAVE; stage++; } else return null; break; case 1: if(isSymbol(p,Symbol.DOT)) bolus.add(p); else if(p instanceof NumberPattern) bolus.add(p); else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='U') stage++; else return null; break; case 2: if(p instanceof NumberPattern) cr.add((NumberPattern) p); else if(isSymbol(p,Symbol.DIVIDE)) stage++; else return null; break; case 3: if(p instanceof NumberPattern) tr.add((NumberPattern) p); else if(isSymbol(p,Symbol.DIVIDE)) stage++; else return null; break; case 4: return null; } } if(bt!=null) { m.setAttribute(MenuAttribute.BOLUS_TYPE,bt); try { String n = ""; for(Pattern p: bolus) { if(p instanceof NumberPattern) n+=((NumberPattern)p).getNumber(); else if(isSymbol(p,Symbol.DOT)) n+="."; else return null; } double d = Double.parseDouble(n); m.setAttribute(MenuAttribute.BOLUS,d); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; if(cr.size()==2 && tr.size() == 2) { int c = cr.removeFirst().getNumber()*10; c+=cr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.CURRENT_RECORD,new Integer(c)); int t = tr.removeFirst().getNumber()*10; t+=tr.removeFirst().getNumber(); m.setAttribute(MenuAttribute.TOTAL_RECORD,new Integer(t)); } else return null; LinkedList<Pattern> clock = new LinkedList<>(); stage = 0; while(tokens[2].size()>0) { Pattern p = tokens[2].removeFirst().getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.ARROW)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) clock.add(p); else if(p instanceof CharacterPattern) clock.add(p); else if (isSymbol(p, Symbol.SEPERATOR)) {} else return null; break; case 2: return null; } } if(clock.size()>=4) { try { int hour10 = ((NumberPattern) clock.removeFirst()).getNumber(); int hour1 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute10 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute1 = ((NumberPattern) clock.removeFirst()).getNumber(); int timeadd = 0; if (clock.size() == 2) { CharacterPattern p0 = (CharacterPattern) clock.removeFirst(); CharacterPattern p1 = (CharacterPattern) clock.removeFirst(); if(p0.getCharacter()=='A' && p1.getCharacter()=='M' && hour10==1 && hour1 == 2) timeadd-=12; else if(p0.getCharacter()=='P' && p1.getCharacter()=='M') timeadd+=12; } m.setAttribute(MenuAttribute.RUNTIME,new MenuTime((hour10*10)+hour1+timeadd,(minute10*10)+minute1)); }catch(Exception e) { e.printStackTrace(); return null; } } else if(bt != BolusType.NORMAL)//we need a runtime if not normal/quick bolus return null; clock.clear(); LinkedList<Pattern> date = new LinkedList<>(); stage = 0; while(tokens[3].size()>0) { Pattern p = tokens[3].removeFirst().getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.CLOCK)) stage++; else return null; break; case 1: if(p instanceof NumberPattern) clock.add(p); else if(p instanceof CharacterPattern) clock.add(p); else if (isSymbol(p, Symbol.SEPERATOR)) {} else if(isSymbol(p,Symbol.CALENDAR)) stage++; else return null; break; case 2: if(p instanceof NumberPattern) date.add(p); else if (isSymbol(p, Symbol.DIVIDE)) date .add(p); else if (isSymbol(p, Symbol.DOT)) date .add(p); else return null; break; case 3: return null; } } if(clock.size()>=4) { try { int hour10 = ((NumberPattern) clock.removeFirst()).getNumber(); int hour1 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute10 = ((NumberPattern) clock.removeFirst()).getNumber(); int minute1 = ((NumberPattern) clock.removeFirst()).getNumber(); int timeadd = 0; if (clock.size() == 2) { CharacterPattern p0 = (CharacterPattern) clock.removeFirst(); CharacterPattern p1 = (CharacterPattern) clock.removeFirst(); if(p0.getCharacter()=='A' && p1.getCharacter()=='M' && hour10==1 && hour1 == 2) timeadd-=12; else if(p0.getCharacter()=='P' && p1.getCharacter()=='M') timeadd+=12; } m.setAttribute(MenuAttribute.TIME,new MenuTime((hour10*10)+hour1+timeadd,(minute10*10)+minute1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; if(date.size()==5) { try { int f10 = ((NumberPattern) date.removeFirst()).getNumber(); int f1 = ((NumberPattern) date.removeFirst()).getNumber(); boolean divide = isSymbol(date.removeFirst(),Symbol.DIVIDE); int s10 = ((NumberPattern) date.removeFirst()).getNumber(); int s1 = ((NumberPattern) date.removeFirst()).getNumber(); if(divide) m.setAttribute(MenuAttribute.DATE, new MenuDate((s10*10)+s1,(f10*10)+f1)); else m.setAttribute(MenuAttribute.DATE, new MenuDate((f10*10)+f1,(s10*10)+s1)); }catch(Exception e) { e.printStackTrace(); return null; } } else return null; return m; } private static Menu makeQuickInfo(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.QUICK_INFO); LinkedList<Pattern> number = new LinkedList<>(); int stage = 0; while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.LARGE_AMPULE_FULL)) { stage++; } else return null; break; case 1: if(p instanceof NumberPattern || isSymbol(p,Symbol.LARGE_DOT)) { number.add(p); } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='u') { stage++; } else return null; break; case 3: return null; } } double doubleNumber = 0d; String d = ""; for(Pattern p : number) { if(p instanceof NumberPattern) { d+=""+((NumberPattern)p).getNumber(); } else if(isSymbol(p,Symbol.LARGE_DOT)) { d += "."; } else { return null;//violation! } } try { doubleNumber = Double.parseDouble(d);} catch (Exception e){return null;}//violation, there must something parseable m.setAttribute(MenuAttribute.REMAINING_INSULIN,new Double(doubleNumber)); //FIXME 4th line tokens[3].clear(); return m; } private static String parseString(LinkedList<Token> tokens, boolean consume) { String s = ""; Token last =null; for(Token t : new LinkedList<>(tokens)) { Pattern p = t.getPattern(); if(consume) tokens.removeFirst(); if(last!=null) { int x = last.getColumn()+last.getWidth()+1+3; if(x < t.getColumn()) { s+=" "; } } if(p instanceof CharacterPattern) { s += ((CharacterPattern)p).getCharacter(); } else if(isSymbol(p,Symbol.DOT)) { s+="."; } else if(isSymbol(p,Symbol.SEPERATOR)) { s+=":"; } else if(isSymbol(p,Symbol.DIVIDE)) { s+="/"; } else if(isSymbol(p,Symbol.BRACKET_LEFT)) { s+="("; } else if(isSymbol(p,Symbol.BRACKET_RIGHT)) { s+=")"; } else if(isSymbol(p,Symbol.MINUS)) { s+="-"; } else { return null; } last = t; } return s; } private static Menu makeBolusDuration(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.BOLUS_DURATION); LinkedList<Integer> time = new LinkedList<>(); int stage = 0; while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.LARGE_ARROW)) { stage++; } else return null; break; case 1: case 2: case 4: case 5: if (p instanceof NumberPattern) { time.add(((NumberPattern) p).getNumber()); stage++; } else return null; break; case 3: if (isSymbol(p, Symbol.LARGE_SEPERATOR)) stage++; else return null; break; } } if(time.size()==4) { int minute1 = time.removeLast(); int minute10 = time.removeLast(); int hour1 = time.removeLast(); int hour10 = time.removeLast(); m.setAttribute(MenuAttribute.RUNTIME,new MenuTime((hour10*10)+hour1,(minute10*10)+minute1)); } else if(time.size()==0) { m.setAttribute(MenuAttribute.RUNTIME,new MenuBlink()); } else return null; LinkedList<Pattern> number = new LinkedList<>(); LinkedList<Pattern> number2 = new LinkedList<>(); Symbol sym1 = null; Symbol sym2 = null; stage = 0; while (tokens[3].size()>0) { Token t = tokens[3].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.EXTENDED_BOLUS)) { sym1 = Symbol.EXTENDED_BOLUS; stage++; } else if (isSymbol(p, Symbol.MULTIWAVE)) { sym1 = Symbol.MULTIWAVE; stage++; } else return null; break; case 1: if (p instanceof NumberPattern || isSymbol(p, Symbol.DOT)) { number.add(p); } else if (p instanceof CharacterPattern && ((CharacterPattern) p).getCharacter() == 'U') { stage++; } else return null; break; case 2: if (isSymbol(p, Symbol.BOLUS)) { sym2 = Symbol.BOLUS; stage++; } else return null; break; case 3: if (p instanceof NumberPattern || isSymbol(p,Symbol.DOT)) { number2.add(p); } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='U') { stage++; } else return null; break; } } double doubleNumber = 0d; String d = ""; for(Pattern p : number) { if(p instanceof NumberPattern) { d+=""+((NumberPattern)p).getNumber(); } else if(isSymbol(p,Symbol.DOT)) { d += "."; } else { return null;//violation! } } try { doubleNumber = Double.parseDouble(d);} catch (Exception e){return null;}//violation, there must something parseable if(sym1 == Symbol.EXTENDED_BOLUS) m.setAttribute(MenuAttribute.BOLUS,new Double(doubleNumber)); else if(sym1 == Symbol.MULTIWAVE) { m.setAttribute(MenuAttribute.BOLUS, new Double(doubleNumber)); doubleNumber = 0d; d = ""; for (Pattern p : number2) { if (p instanceof NumberPattern) { d += "" + ((NumberPattern) p).getNumber(); } else if (isSymbol(p, Symbol.DOT)) { d += "."; } else { return null;//violation! } } try { doubleNumber = Double.parseDouble(d); } catch (Exception e) { return null; }//violation, there must something parseable m.setAttribute(MenuAttribute.MULTIWAVE_BOLUS, new Double(doubleNumber)); } return m; } private static Menu makeImmediateBolus(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.IMMEDIATE_BOLUS); LinkedList<Pattern> number = new LinkedList<>(); int stage = 0; while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.LARGE_MULTIWAVE_BOLUS)) { stage++; } else return null; break; case 1: if (p instanceof NumberPattern) { number.add(p); } else if(isSymbol(p,Symbol.LARGE_DOT)) { number.add(p); } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='u') { stage++; } else return null; break; case 3: return null; } } double doubleNumber = 0d; String d = ""; if(number.size()==0) { m.setAttribute(MenuAttribute.MULTIWAVE_BOLUS,new MenuBlink()); } else { for (Pattern p : number) { if (p instanceof NumberPattern) { d += "" + ((NumberPattern) p).getNumber(); } else if (isSymbol(p, Symbol.LARGE_DOT)) { d += "."; } else { return null;//violation! } } try { doubleNumber = Double.parseDouble(d); } catch (Exception e) { return null; }//violation, there must something parseable m.setAttribute(MenuAttribute.MULTIWAVE_BOLUS, new Double(doubleNumber)); } LinkedList<Integer> time = new LinkedList<>(); number.clear(); stage = 0; while (tokens[3].size() > 0) { Token t = tokens[3].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.ARROW)) { stage++; } else return null; break; case 1: case 2: case 4: case 5: if (p instanceof NumberPattern) { time.add(((NumberPattern) p).getNumber()); stage++; } else return null; break; case 3: if (isSymbol(p, Symbol.SEPERATOR)) stage++; else return null; break; case 6: if (isSymbol(p, Symbol.MULTIWAVE)) { stage++; } else return null; break; case 7: if (p instanceof NumberPattern || isSymbol(p,Symbol.DOT)) { number.add(p); } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='U') { stage++; } else return null; break; case 8: return null; } } if (time.size() == 4) { int minute1 = time.removeLast(); int minute10 = time.removeLast(); int hour1 = time.removeLast(); int hour10 = time.removeLast(); m.setAttribute(MenuAttribute.RUNTIME, new MenuTime((hour10 * 10) + hour1, (minute10 * 10) + minute1)); } else return null; if(number.size()>0) { d=""; for (Pattern p : number) { if (p instanceof NumberPattern) { d += "" + ((NumberPattern) p).getNumber(); } else if (isSymbol(p, Symbol.DOT)) { d += "."; } else { return null;//violation! } } try { doubleNumber = Double.parseDouble(d); } catch (Exception e) { return null; }//violation, there must something parseable m.setAttribute(MenuAttribute.BOLUS, new Double(doubleNumber)); } else return null; return m; } private static Menu makeBolusEnter(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.BOLUS_ENTER); LinkedList<Pattern> number = new LinkedList<>(); int stage = 0; BolusType bt = null; //main part while (tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.LARGE_BOLUS)) { bt = BolusType.NORMAL; stage++; } else if (isSymbol(p, Symbol.LARGE_MULTIWAVE)) { bt = BolusType.MULTIWAVE; stage++; } else if (isSymbol(p, Symbol.LARGE_EXTENDED_BOLUS)) { bt = BolusType.EXTENDED; stage++; } else if(p instanceof NumberPattern) { number.add(p); stage++; } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='u') { stage=2; }else return null; break; case 1: if (p instanceof NumberPattern) { number.add(p); } else if(isSymbol(p,Symbol.LARGE_DOT)) { number.add(p); } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='u') { stage++; } else return null; break; case 2: return null; } } if(bt!=null) m.setAttribute(MenuAttribute.BOLUS_TYPE,bt); else m.setAttribute(MenuAttribute.BOLUS_TYPE,new MenuBlink()); double doubleNumber = 0d; String d = ""; if(number.size()>0) { for (Pattern p : number) { if (p instanceof NumberPattern) { d += "" + ((NumberPattern) p).getNumber(); } else if (isSymbol(p, Symbol.LARGE_DOT)) { d += "."; } else { return null;//violation! } } try { doubleNumber = Double.parseDouble(d); } catch (Exception e) { return null; }//violation, there must something parseable m.setAttribute(MenuAttribute.BOLUS, new Double(doubleNumber)); } else m.setAttribute(MenuAttribute.BOLUS,new MenuBlink()); //4th line LinkedList<Integer> time = new LinkedList<>(); number.clear(); stage = 0; while (tokens[3].size() > 0) { Token t = tokens[3].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.ARROW)) { stage++; } else return null; break; case 1: case 2: case 4: case 5: if (p instanceof NumberPattern) { time.add(((NumberPattern) p).getNumber()); stage++; } else return null; break; case 3: if (isSymbol(p, Symbol.SEPERATOR)) stage++; else return null; break; case 6: if (isSymbol(p, Symbol.BOLUS)) { stage++; } else return null; break; case 7: if (p instanceof NumberPattern) { number.add(p); } else if(isSymbol(p,Symbol.DOT)) { number.add(p); } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='U') { stage++; } else return null; break; case 8: return null; } } if(time.size()>0) { int minute1 = time.removeLast(); int minute10 = time.removeLast(); int hour1 = time.removeLast(); int hour10 = time.removeLast(); m.setAttribute(MenuAttribute.RUNTIME, new MenuTime((hour10 * 10) + hour1, (minute10 * 10) + minute1)); if(number.size() > 0) { doubleNumber = 0d; d = ""; for(Pattern p : number) { if(p instanceof NumberPattern) { d+=""+((NumberPattern)p).getNumber(); } else if(isSymbol(p,Symbol.DOT)) { d += "."; } else if(p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='U'){ //irgnore } else { return null;//violation! } } try { doubleNumber = Double.parseDouble(d);} catch (Exception e){return null;}//violation, there must something parseable m.setAttribute(MenuAttribute.MULTIWAVE_BOLUS, new Double(doubleNumber)); } } else { m.setAttribute(MenuAttribute.RUNTIME, new MenuTime(0,0)); m.setAttribute(MenuAttribute.MULTIWAVE_BOLUS, new Double(0)); } return m; } private static Menu makeMainMenu(LinkedList<Token>[] tokens) { Menu m = new Menu(MenuType.MAIN_MENU); LinkedList<Integer> time = new LinkedList<>(); LinkedList<Integer> runtime = new LinkedList<>(); LinkedList<Character> timeC = new LinkedList<>(); boolean hasRunning=false; int stage = 0; while(tokens[0].size()>0) { Token t = tokens[0].removeFirst(); Pattern p = t.getPattern(); switch(stage) { case 0://clock if(!isSymbol(p,Symbol.CLOCK)) return null;//wrong stage++; break; case 1://hour10 case 2://hour1 case 4://minute10 case 5://minute1 if (p instanceof NumberPattern) { time.add(((NumberPattern) p).getNumber()); } else return null;//Wrong stage++; break; case 3://: or number (: blinks) if(isSymbol(p,Symbol.SEPERATOR)) { stage++; } else if (p instanceof NumberPattern) { time.add(((NumberPattern) p).getNumber()); stage += 2; } else return null;//wr break; case 6://P(m), A(M), or running if(p instanceof CharacterPattern) { timeC.add(((CharacterPattern) p).getCharacter()); stage++; } else if(isSymbol(p,Symbol.ARROW)) { hasRunning = true; stage = 9; } else return null;//wrong break; case 7://it should be an M if(p instanceof CharacterPattern) { timeC.add(((CharacterPattern) p).getCharacter()); stage++; } else return null;//nothing else matters break; case 8://can onbly be running arrow if(isSymbol(p,Symbol.ARROW)) { hasRunning = true; stage++; } else return null; break; case 9://h10 case 10://h1 case 12://m10 case 13://m1 if (p instanceof NumberPattern) { runtime.add(((NumberPattern) p).getNumber()); } else return null;//Wrong stage++; break; case 11://: or number (: blinks) if(isSymbol(p,Symbol.SEPERATOR)) { stage++; } else return null;//wr break; default: return null;//the impossible girl } } //set time int minute1 = time.removeLast(); int minute10 = time.removeLast(); int hour1 = time.removeLast(); int hour10 = 0; if(time.size()>0) hour10 = time.removeLast(); int tadd = 0; if(timeC.size()>0) { if(timeC.get(0)=='P' && timeC.get(1)=='M' && !(hour10==1 && hour1 == 2)) { tadd += 12; } else if(timeC.get(0)=='A' && timeC.get(1)=='M' && hour10 == 1 && hour1 == 2) { tadd -= 12; } } m.setAttribute(MenuAttribute.TIME,new MenuTime((hour10*10)+tadd+hour1,(minute10*10)+minute1)); if(hasRunning) { minute1 = runtime.removeLast(); minute10 = runtime.removeLast(); hour1 = runtime.removeLast(); hour10 = runtime.removeLast(); m.setAttribute(MenuAttribute.RUNTIME, new MenuTime((hour10 * 10) + hour1, (minute10 * 10) + minute1)); } stage = 0; BolusType bt = null; int tbr = 0; LinkedList<Pattern> number = new LinkedList<>(); while(tokens[1].size()>0) { Token t = tokens[1].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (isSymbol(p, Symbol.SEPERATOR.LARGE_EXTENDED_BOLUS)) { bt = BolusType.EXTENDED; stage++; } else if (isSymbol(p, Symbol.SEPERATOR.LARGE_MULTIWAVE)) { bt = BolusType.MULTIWAVE_EXTENDED; stage++; } else if(isSymbol(p,Symbol.SEPERATOR.LARGE_MULTIWAVE_BOLUS)) { bt = BolusType.MULTIWAVE_BOLUS; stage++; } else if(isSymbol(p,Symbol.SEPERATOR.LARGE_BOLUS)) { bt = BolusType.NORMAL; stage++; } else if (isSymbol(p, Symbol.SEPERATOR.LARGE_BASAL)) { bt = null; stage++; } else { return null; } break; case 1: if (isSymbol(p, Symbol.UP)) { tbr = 1; stage++; } else if (isSymbol(p, Symbol.DOWN)) { tbr = 2; stage++; } else if (p instanceof NumberPattern) { number.add(p); stage += 2; } else return null;// break; case 2: if (p instanceof NumberPattern) { number.add(p); stage++; } else return null;// break; case 3: if (p instanceof NumberPattern) { number.add(p); } else if (p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='u') { number.add(p); } else if (isSymbol(p, Symbol.LARGE_DOT) || isSymbol(p, Symbol.LARGE_PERCENT) || isSymbol(p,Symbol.LARGE_UNITS_PER_HOUR)) { number.add(p); } else return null;// break; } } double doubleNUmber = 0d; String d = ""; for(Pattern p : number) { if(p instanceof NumberPattern) { d+=""+((NumberPattern)p).getNumber(); } else if(isSymbol(p,Symbol.LARGE_DOT)) { d += "."; } else if(isSymbol(p,Symbol.LARGE_PERCENT) || isSymbol(p,Symbol.LARGE_UNITS_PER_HOUR) || (p instanceof CharacterPattern && ((CharacterPattern)p).getCharacter()=='u')){ //irgnore } else { return null;//violation! } } try { doubleNUmber = Double.parseDouble(d);} catch (Exception e){return null;}//violation, there must something parseable if(bt != null) { //running bolus m.setAttribute(MenuAttribute.BOLUS_TYPE,bt); m.setAttribute(MenuAttribute.BOLUS_REMAINING,doubleNUmber); } else { switch(tbr) { case 0: m.setAttribute(MenuAttribute.TBR,new Double(100)); m.setAttribute(MenuAttribute.BASAL_RATE,doubleNUmber); break; case 1: case 2: m.setAttribute(MenuAttribute.TBR,new Double(doubleNUmber)); break; } } if(tokens[2].size()==1 && tokens[2].get(0).getPattern() instanceof NumberPattern) m.setAttribute(MenuAttribute.BASAL_SELECTED,new Integer(((NumberPattern)tokens[2].removeFirst().getPattern()).getNumber())); else return null; stage = 0; number.clear(); int lowInsulin = 0; boolean lowBattery= false; boolean waranty = true; int lockState = 0; while(tokens[3].size()>0) { Token t = tokens[3].removeFirst(); Pattern p = t.getPattern(); switch (stage) { case 0: if (p instanceof NumberPattern) { number.add(p); } else if (isSymbol(p, Symbol.DOT)) { number.add(p); } else if (isSymbol(p, Symbol.UNITS_PER_HOUR)) { number.add(p); stage++; } else if (isSymbol(p, Symbol.LOW_BAT)) { lowBattery = true; } else if (isSymbol(p, Symbol.LOW_INSULIN)) { lowInsulin= 1; } else if (isSymbol(p, Symbol.NO_INSULIN)) { lowInsulin= 2; } else if (isSymbol(p, Symbol.LOCK_CLOSED)) { lockState=2; } else if (isSymbol(p, Symbol.LOCK_OPENED)) { lockState=2; } else if (isSymbol(p, Symbol.WARANTY)) { waranty = false; } else { return null; } break; case 1: if (isSymbol(p, Symbol.LOW_BAT)) { lowBattery = true; } else if (isSymbol(p, Symbol.LOW_INSULIN)) { lowInsulin = 1; } else if (isSymbol(p, Symbol.NO_INSULIN)) { lowInsulin= 2; } else if (isSymbol(p, Symbol.LOCK_CLOSED)) { lockState=2; } else if (isSymbol(p, Symbol.LOCK_OPENED)) { lockState=2; } else if (isSymbol(p, Symbol.WARANTY)) { waranty = false; } else { return null; } break; } } if(lowBattery) m.setAttribute(MenuAttribute.LOW_BATTERY,new Boolean(true)); else m.setAttribute(MenuAttribute.LOW_BATTERY,new Boolean(false)); m.setAttribute(MenuAttribute.INSULIN_STATE,lowInsulin); m.setAttribute(MenuAttribute.WARANTY,new Boolean(waranty)); m.setAttribute(MenuAttribute.LOCK_STATE,new Integer(lockState)); if(number.size()>0) { doubleNUmber = 0d; d = ""; for (Pattern p : number) { if (p instanceof NumberPattern) { d += "" + ((NumberPattern) p).getNumber(); } else if (isSymbol(p, Symbol.DOT)) { d += "."; } else if (isSymbol(p, Symbol.UNITS_PER_HOUR)) { //irgnore } else { return null;//violation! } } try { doubleNUmber = Double.parseDouble(d); } catch (Exception e) { return null; }//violation, there must something parseable m.setAttribute(MenuAttribute.BASAL_RATE, doubleNUmber); } return m; } private static boolean isSymbol(Pattern p, Symbol symbol) { return (p instanceof SymbolPattern) && ((SymbolPattern) p).getSymbol() == symbol; } }
18fb633b7fcd4d014562f93c99d76743cec3c078
51cc76927e0026b51bcbf9cc4ae53f24214f28cf
/src/main/java/kr/ac/kopo/account/controller/AccountController.java
9ecf020407fc59896118e2a52b17ed8dafd8af9e
[]
no_license
miheeee/hanati_final_project
de1c8276e48865efc176babaa91ba68bf4cb7f1c
058db9e57d985b027a05baf9c01a6fa4e885f0ba
refs/heads/master
2022-12-23T11:10:10.317365
2020-10-07T03:21:15
2020-10-07T03:21:15
297,259,138
0
0
null
null
null
null
UTF-8
Java
false
false
1,516
java
package kr.ac.kopo.account.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.sun.org.glassfish.external.statistics.annotations.Reset; import kr.ac.kopo.account.service.AccountService; import kr.ac.kopo.account.vo.AccountVO; @Controller public class AccountController { @Autowired private AccountService accountService; @Autowired private AccountVO account; @ResponseBody @PostMapping("/account/checkPassword") public String checkMatchPassword(AccountVO accountVO) { //입력받은 계좌번호와 비밀번호에 맞는 계좌가 있는지 select해서 가져옴 account = accountService.checkMatchPassword(accountVO); //*AccountVO객체를 바로 넘기면 안됨. null인지 아닌지 판별할 수 없음 if(account == null) { return "no"; }else { return "yes"; } } /* * @PostMapping("/account/checkPassword") public ModelAndView * checkMatchPassword(AccountVO accountVO) { * * //입력받은 계좌번호와 비밀번호에 맞는 계좌가 있는지 select해서 가져옴 account = * accountService.checkMatchPassword(accountVO); * * ModelAndView mav = new ModelAndView("gatherinig/apply"); * mav.addObject("account", account); return mav; } */ }
9343ad453e083a67b3a56fc2a8a3e3973c5f8e7a
59cda0429c2e1ee28862273b26bdd244de700ccd
/src/main/java/me/webapp/support/statistics/MethodTimingAspect.java
e5be0c88ca6c748f46b392cf307493f88a0f4606
[]
no_license
paranoidq/archetype-springmvc
5c48b75cac86fae3daa95d169cd5725be9e5834c
5ec3c4dd3d82fb35e2b9f07aaf360b30ec796ccf
refs/heads/master
2020-03-17T09:55:03.800794
2018-06-06T13:02:01
2018-06-06T13:02:01
133,493,157
0
0
null
null
null
null
UTF-8
Java
false
false
3,183
java
package me.webapp.support.statistics; /*- * ========================LICENSE_START================================= * springmvc * %% * Copyright (C) 2018 Wei Qian * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * =========================LICENSE_END================================== */ import me.webapp.config.condition.StatisticsCondition; import me.webapp.log.LogTag; import org.apache.commons.lang.time.StopWatch; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component; /** * * 记录方法调用耗时 * * 必须同时满足{@link me.webapp.config.condition.StatisticsCondition}才能使得该AOP生效 * * @author paranoidq * @since 1.0.0 */ @Aspect @Component @Conditional(StatisticsCondition.class) public class MethodTimingAspect { private static final Logger logger = LoggerFactory.getLogger(MethodTimingAspect.class); /** * 拦截所有的标记了ElapsedTimeCounter注解的方法 */ @Pointcut("@annotation(me.webapp.support.statistics.MethodTiming)") public void methodTimeingPointcut() {} @Around("methodTimeingPointcut()") public Object logMethodTime(ProceedingJoinPoint joinPoint) { Object retVal = null; Object[] args = joinPoint.getArgs(); StopWatch stopWatch = new StopWatch(); stopWatch.start(); try { retVal = joinPoint.proceed(args); } catch (Throwable throwable) { logger.error("统计某方法执行耗时环绕通知出错", throwable); } stopWatch.stop(); long elapsed = stopWatch.getTime(); String className = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); logger.info(LogTag.Statis.METHOD_TIMING + "方法执行耗时("+ className + "#" + methodName + "): " + elapsed + "ms"); return retVal; } }
19b11d86645d8a68e4748c1c46dff34431a56e97
22752c19622bdd957a88ef9aedd63bc0043cacee
/src/main/java/org/iota/ict/api/RestApi.java
e3f37b093cb4a8d4b402ee10933b50e03eae28cf
[ "Apache-2.0" ]
permissive
ben-75/ict
570b7b7aa8c38921399910c0bcf4197ab274f0f9
d938f746f71eaca68581326e8bf5096eebbd6ba3
refs/heads/master
2020-04-29T11:15:13.659321
2019-04-09T22:12:53
2019-04-09T22:12:53
176,090,942
0
0
null
null
null
null
UTF-8
Java
false
false
5,067
java
package org.iota.ict.api; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.iota.ict.IctInterface; import org.iota.ict.utils.*; import org.iota.ict.utils.properties.FinalProperties; import org.iota.ict.utils.properties.Properties; import org.iota.ict.utils.properties.PropertiesUser; import spark.*; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class RestApi extends RestartableThread implements PropertiesUser { protected static final Logger LOGGER = LogManager.getLogger("RestAPI"); protected Service service; protected final JsonIct jsonIct; protected FinalProperties properties; protected Set<RouteImpl> routes = new HashSet<>(); protected boolean initialized = false; private Map<String, Long> timeoutsByIP = new HashMap<>(); static { try { if (Constants.RUN_MODUS == Constants.RunModus.MAIN && !new File(Constants.WEB_GUI_PATH).exists()) IOHelper.extractDirectoryFromJarFile(RestApi.class, "web/", Constants.WEB_GUI_PATH); } catch (IOException e) { LOGGER.error("Failed to extract Web GUI into " + new File(Constants.WEB_GUI_PATH).getAbsolutePath(), e); throw new RuntimeException(e); } } public RestApi(IctInterface ict) { super(LOGGER); this.properties = ict.getProperties(); this.jsonIct = new JsonIct(ict); } @Override public void run() { ; } private void initRoutes() { routes.add(new RouteGetInfo(jsonIct)); routes.add(new RouteGetLogs(jsonIct)); routes.add(new RouteUpdate(jsonIct)); routes.add(new RouteSetConfig(jsonIct)); routes.add(new RouteGetConfig(jsonIct)); routes.add(new RouteGetNeighbors(jsonIct)); routes.add(new RouteAddNeighbor(jsonIct)); routes.add(new RouteRemoveNeighbor(jsonIct)); routes.add(new RouteGetModules(jsonIct)); routes.add(new RouteAddModule(jsonIct)); routes.add(new RouteRemoveModule(jsonIct)); routes.add(new RouteUpdateModule(jsonIct)); routes.add(new RouteGetModuleConfig(jsonIct)); routes.add(new RouteSetModuleConfig(jsonIct)); routes.add(new RouteGetModuleResponse(jsonIct)); initialized = true; } @Override public void onStart() { if (!properties.guiEnabled()) return; if (!initialized) initRoutes(); service = Service.ignite(); int guiPort = properties.guiPort(); service.port(guiPort); service.staticFiles.externalLocation(Constants.WEB_GUI_PATH); for (RouteImpl route : routes) service.post(route.getPath(), route); service.before(new Filter() { @Override public void handle(Request request, Response response) { if(timeoutsByIP.containsKey(request.ip()) && System.currentTimeMillis() < timeoutsByIP.get(request.ip())) service.halt(429, "Authentication failed, try again in "+( timeoutsByIP.get(request.ip())-System.currentTimeMillis())/1000+" seconds."); if(request.requestMethod().equals("GET") && !request.pathInfo().matches("^[/]?$") && !request.pathInfo().startsWith("/modules/")) { response.redirect("/"); } String queryPassword = request.queryParams("password"); if (!queryPassword.equals(properties.guiPassword())) { timeoutsByIP.put(request.ip(), System.currentTimeMillis()+5000); service.halt(401, "Access denied: password incorrect."); } } }); service.after(new Filter() { @Override public void handle(Request request, Response response) { response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Allow-Methods", "GET"); } }); service.init(); service.awaitInitialization(); LOGGER.info("Started Web GUI on port " + guiPort + ". Access it by visiting '{HOST}:" + guiPort + "' from your web browser."); } @Override public void onTerminate() { if (service == null) // wasn't running return; for (RouteImpl route : routes) service.delete(route.getPath(), route); service.stop(); service = null; } @Override public void updateProperties(FinalProperties newProp) { Properties oldProp = this.properties; this.properties = newProp; if (oldProp.guiEnabled() && !newProp.guiEnabled()) terminate(); else if (!oldProp.guiEnabled() && newProp.guiEnabled()) start(); else if (oldProp.guiEnabled() && newProp.guiEnabled() && oldProp.guiPort() != newProp.guiPort()) { terminate(); start(); } } }
d0c9c44793af6332eb9f7af3257bafd3c93ce9ed
219bc641c2e4c0e6647bac7cb885ede493bf9140
/src/main/java/com/stelo/simpleops/common/exception/GlobalExceptionHandler.java
ec20e2d117bfa7fcf2a718487e40e6090a1203af
[]
no_license
Stel000/simpleops
0ef83dcaa990cb1e30648ae76d2b7c3a6d3fede2
815a2315df3a1fd5435c52f9043892c1f4aedf84
refs/heads/master
2020-09-23T21:01:24.491167
2019-12-03T09:57:33
2019-12-03T09:57:33
225,585,990
0
0
null
null
null
null
UTF-8
Java
false
false
6,689
java
package com.stelo.simpleops.common.exception; import com.stelo.simpleops.common.dto.BaseResponse; import com.stelo.simpleops.common.enums.BusinessError; import com.stelo.simpleops.common.enums.CustomHttpStatus; import com.stelo.simpleops.utils.LanguageHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.HttpMediaTypeException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.List; @ControllerAdvice @Order(Ordered.LOWEST_PRECEDENCE) public class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @Resource private LanguageHelper languageHelper; private static final Integer ARGUMENT_NOT_VALID_CODE = 100005; @ExceptionHandler(Throwable.class) @ResponseBody public ResponseEntity<BaseResponse> process(Throwable exception) { loggerException(exception); String message = languageHelper.getMessage("system.error"); BaseResponse baseResponse = BaseResponse.newBuilder() .code(BusinessError.GENERAL_SERVER_ERR.getCode()) .httpStatus(CustomHttpStatus.INTERNAL_SERVER_ERROR) .message(message).build(); return ResponseEntity.status(baseResponse.getHttpStatus().value()).body(baseResponse); } @ExceptionHandler(BusinessException.class) @ResponseBody public ResponseEntity<BaseResponse> process(BusinessException exception) { return generateBaseResponse(exception); } @ExceptionHandler(AuthenticationException.class) @ResponseBody public ResponseEntity<BaseResponse> process(AuthenticationException exception) { BusinessException result = new BusinessException( exception.getMessage(), BusinessError.CLIENT_PARAM_ERR ); return generateBaseResponse(result); } @ExceptionHandler(AccessDeniedException.class) @ResponseBody public ResponseEntity<BaseResponse> process(AccessDeniedException exception) { BusinessException result = new BusinessException( exception.getMessage(), BusinessError.GENERAL_FORBID_ERR ); return generateBaseResponse(result); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody public ResponseEntity<BaseResponse> processHttpRequestMethodNotSupportedException() { return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build(); } @ExceptionHandler(HttpMediaTypeException.class) @ResponseBody public ResponseEntity<BaseResponse> processHttpMediaTypeException() { return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).build(); } @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseBody public ResponseEntity<BaseResponse> process(HttpMessageNotReadableException exception) { loggerException(exception); String message = languageHelper.getMessage("system.error.param"); BaseResponse baseResponse = BaseResponse.newBuilder() .code(BusinessError.CLIENT_PARAM_ERR.getCode()) .httpStatus(CustomHttpStatus.BAD_REQUEST) .message(message).build(); return ResponseEntity.status(baseResponse.getHttpStatus().value()).body(baseResponse); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ResponseEntity<BaseResponse> process(MethodArgumentNotValidException exception) { return this.processBindingResult(exception.getBindingResult()); } @ExceptionHandler(BindException.class) @ResponseBody public ResponseEntity<BaseResponse> process(BindException exception) { return this.processBindingResult(exception.getBindingResult()); } private ResponseEntity<BaseResponse> processBindingResult(BindingResult bindingResult) { if (bindingResult.getErrorCount() > 0) { List<ObjectError> list = bindingResult.getAllErrors(); StringBuilder sb = new StringBuilder(); for (ObjectError tmp : list) { if (tmp instanceof FieldError) { FieldError fieldError = (FieldError) tmp; sb.append(languageHelper .getMessage(fieldError.getDefaultMessage(), fieldError.getArguments())); sb.append("\n"); } } return generateBaseResponse(sb.toString(), CustomHttpStatus.BAD_REQUEST, ARGUMENT_NOT_VALID_CODE); } return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } private void loggerException(Throwable e) { LOGGER.error("exception process", e); } private ResponseEntity<BaseResponse> generateBaseResponse(BusinessException exception) { String message = languageHelper .getMessage(exception.getMessage(), exception.getParameters()); BaseResponse baseResponse = BaseResponse.newBuilder() .code(exception.getBusinessError().getCode()) .httpStatus(exception.getBusinessError().getHttpStatus()) .message(message).build(); return ResponseEntity.status(baseResponse.getHttpStatus().value()).body(baseResponse); } private ResponseEntity<BaseResponse> generateBaseResponse(String msg, CustomHttpStatus status, int code) { BaseResponse baseResponse = BaseResponse.newBuilder() .code(code) .httpStatus(status) .message(msg).build(); return ResponseEntity.status(baseResponse.getHttpStatus().value()).body(baseResponse); } }
49fdd8437e24e8e7e6db8ba9624f1e1f0dba7fa9
90a4c5f89565692313b4540f3e8eaf9df2411a48
/1/test2.java
c598245070bac3bc0d208c194f6fec4347650e57
[]
no_license
rohitner/MA39011
f1468fbe74ae99859578381e3cf1f4f3931de127
2db8ff7fbfd1c6c9ad74e9f00339824e440e90a0
refs/heads/master
2020-04-05T11:51:55.147605
2018-11-20T15:13:45
2018-11-20T15:13:45
156,847,716
0
1
null
null
null
null
UTF-8
Java
false
false
510
java
import java.io.*; class test2 { public static int palindrome(String i) { Integer count = 0, flag =0; char a[] = i.toCharArray(); for (int j = 0 ; j<i.length() ; j++) { if(a[j] != a[i.length()-j-1]) { flag = 1; break; } } if(flag == 1) return 0; return 1; } public static void main(String args[]) throws Exception { BufferedReader t = new BufferedReader(new InputStreamReader(System.in)); String i= t.readLine(); int p = palindrome(i); System.out.println(p); } }
85f409b2104f3eed04f419ef0e618ae438a8bb5c
cdf939bd8fcd02d22df1dd35ad54cea32022a7fd
/130-Surrounded-Regions/solution.java
e5682b59c6ecee153c830cee1980234200467bf6
[]
no_license
AnthonyShuyu/My-LeetCode
f93535f95e8a134cbc8ca521e20083a5fcc4af27
0d9377e426d874012de221cdb54e3fef853af21e
refs/heads/master
2021-03-22T04:40:27.579017
2016-10-13T00:11:57
2016-10-13T00:11:57
46,031,214
0
0
null
null
null
null
UTF-8
Java
false
false
7,689
java
/** * * 130. Surrounded Regions * Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. * * 3 solutions * */ // s1: dfs again // O(m * n), O(m * n) // tricky, from the edges 'O', change all the adjacent 'O' to 'D', then change back at last // stack overflow error /* public class Solution { public void solve(char[][] board) { // corner case if (board == null || board.length == 0) { return; } if (board[0] == null || board[0].length == 0) { return; } int m = board.length; int n = board[0].length; for (int i = 0; i < m; i++) { if (board[i][0] == 'O') { dfs(i, 0, board); } if (board[i][n - 1] == 'O') { dfs(i, n - 1, board); } } for (int i = 1; i < n - 1; i++) { if (board[0][i] == 'O') { dfs(0, i, board); } if (board[m - 1][i] == 'O') { dfs(m - 1, i, board); } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'A') { board[i][j] = 'O'; } else if (board[i][j] == 'O') { board[i][j] = 'X'; } } } } public void dfs(int x, int y, char[][] board) { int m = board.length; int n = board[0].length; if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O') { board[x][y] = 'A'; dfs(x - 1, y, board); dfs(x + 1, y, board); dfs(x, y + 1, board); dfs(x, y - 1, board); } } } */ // s2: bfs, since use dfs will get Stack Overflow error // O(m * n), O(m * n) // tricky, from 4 sides to iterate, then change the 'O' to 'A' first /* public class Solution { public void solve(char[][] board) { // corner case if (board == null || board.length == 0) { return; } if (board[0] == null || board[0].length == 0) { return; } int m = board.length; int n = board[0].length; Queue<Integer> queue = new LinkedList<Integer>(); for (int i = 0; i < m; i++) { if (board[i][0] == 'O') { queue.offer(change(i, 0, board)); } if (board[i][n - 1] == 'O') { queue.offer(change(i, n - 1, board)); } } for (int i = 1; i < n - 1; i++) { if (board[0][i] == 'O') { queue.offer(change(0, i , board)); } if (board[m - 1][i] == 'O') { queue.offer(change(m - 1, i, board)); } } int[] dx = {-1, 0, 1, 0}; int[] dy = {0, -1, 0, 1}; while (!queue.isEmpty()) { int num = queue.poll(); int x = num / n; int y = num % n; if (board[x][y] == 'O') { board[x][y] = 'A'; for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (valid(nx, ny, board)) { queue.offer(change(nx, ny, board)); } } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'A') { board[i][j] = 'O'; } else if (board[i][j] == 'O') { board[i][j] = 'X'; } } } } public int change(int x, int y, char[][] board) { int n = board[0].length; return x * n + y; } public boolean valid(int x, int y, char[][] board) { int m = board.length; int n = board[0].length; if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O') { return true; } return false; } } */ // s3: use union find // O(m * n), O(m * n) // triky public class Solution { Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); public void solve(char[][] board) { // corner case if (board == null || board.length == 0) { return; } if (board[0] == null || board[0].length == 0) { return; } int m = board.length; int n = board[0].length; // first traverse, put element and itself for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'O') { hashMap.put(change(i, j, board), change(i, j, board)); } } } int[] dx = {-1, 0, 1, 0}; int[] dy = {0, 1, 0, -1}; // second traverse, union adjacent elements for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'O') { for (int k = 0; k < 4; k++) { int nx = i + dx[k]; int ny = j + dy[k]; if (isValid(nx, ny, board)) { int index1 = i * n + j; int index2 = nx * n + ny; if (find(index1) != find(index2)) { union(index1, index2); } } } } } } // use hashSet to store the elements in the 4 sides Set<Integer> hashSet = new HashSet<Integer>(); for (int i = 0; i < m; i++) { if (board[i][0] == 'O') { hashSet.add(find(i * n)); } if (board[i][n - 1] == 'O') { hashSet.add(find(i * n + n - 1)); } } for (int i = 1; i < n - 1; i++) { if (board[0][i] == 'O') { hashSet.add(find(i)); } if (board[m - 1][i] == 'O') { hashSet.add(find((m - 1) * n + i)); } } // third traverse, change 'O' to 'X' for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'O' && !hashSet.contains(find(i * n + j))) { board[i][j] = 'X'; } } } } public boolean isValid(int x, int y, char[][] board) { int m = board.length; int n = board[0].length; if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O') { return true; } return false; } public int change(int x, int y, char[][] board) { int m = board.length; int n = board[0].length; return x * n + y; } public int find(int x) { int parent = x; while (parent != hashMap.get(parent)) { parent = hashMap.get(parent); } int next; while (x != hashMap.get(x)) { next = hashMap.get(x); hashMap.put(x, parent); x = next; } return parent; } public void union(int x, int y) { int parentX = hashMap.get(x); int parentY = hashMap.get(y); if (parentX != parentY) { hashMap.put(parentX, parentY); } } }
1cbc6bc2766c1576e04f2401f8cbb373704f5e66
98e5cb60a3dbc5943aca813fb19caa53a1ee4802
/djisktra&co/Java/src/lab8/Main.java
51003d22713aa7528a2f83f77abf10e9abeb5484
[]
no_license
OanceaLucian/Lab-pa-2014
16d32bb36b4255fbf6266db571d1bdb5176745f2
fecc1c8badc9e1deadb9a1b750fef17523d89afb
refs/heads/master
2021-01-01T18:42:49.867712
2014-06-16T12:01:00
2014-06-16T12:01:00
20,886,877
0
1
null
null
null
null
UTF-8
Java
false
false
1,907
java
/** * Proiectarea Algoritmilor, 2014 * Lab 8: Drumuri minime * * @author Radu Iacob * @email [email protected] */ package lab8; import java.util.ArrayList; import minCost.BellmanFord; import minCost.Dijkstra; import minCost.RoyFloyd; import graph.Graph; import graph.Node; public class Main{ public enum Task{ ROY_FLOYD, DIJKSTRA, BELLMAN_FORD } final public static String dataSet1 = "./date1"; final public static String dataSet2 = "./date2"; /** * Problem configuration */ final public static String startLabel = "Bucuresti"; final public static String endLabel = "Paris"; public static String dataSet = dataSet1; public static Task currentTask = Task.DIJKSTRA; public static void main( String[] args ) { Graph graph = new Graph(dataSet); Node source = graph.getNode(startLabel); Node dest = graph.getNode(endLabel); switch( currentTask ) { case ROY_FLOYD: { RoyFloyd solver = new RoyFloyd( graph.getNodeCount() ); solver.computeRoyFloyd( graph ); solver.PrintMinPath( graph, source, dest ); break; } case DIJKSTRA: { System.out.println("Dijkstra"); Dijkstra solver = new Dijkstra( graph ); ArrayList<Integer> distance = solver.computeDistance(source); printDistance(graph, distance); break; } case BELLMAN_FORD: { BellmanFord solver = new BellmanFord( graph ); ArrayList<Integer> distance = solver.computeDistance(source); printDistance(graph, distance); break; } default: { break; } } } static public void printDistance( Graph graph, ArrayList<Integer> distance ) { System.out.println("Result: "); int nodeCount = graph.getNodeCount(); ArrayList<Node> nodes = graph.getNodes(); for( int i = 0; i < nodeCount; ++i ){ System.out.println( nodes.get(i).getCity() + " , " + distance.get(i) ); } } }
01d26f62a103cbeddebbb28ec3f3ccfa60fa002a
09b61cdfa3ef985b4518677d00b875a782702949
/app/src/main/java/com/example/weather/base/BaseRecyclerAdapter.java
71253e414c048dad984679e492291b2ee59901d6
[]
no_license
kangliangup/KWeather
39a9ddb69ae29a19b232bcc195f4a57f89f9a087
96b25fb3eeb37b470b69ed33731659951cf80a2e
refs/heads/master
2020-03-17T09:16:39.664687
2019-05-09T06:41:30
2019-05-09T06:41:30
133,468,176
0
0
null
null
null
null
UTF-8
Java
false
false
4,908
java
package com.example.weather.base; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** * RecyclerView adapter基类 * * @param <D> 数据类型 * @param <T> ViewHolder类型 */ public abstract class BaseRecyclerAdapter<D, T extends RecyclerView.ViewHolder> extends RecyclerView.Adapter implements View.OnClickListener, View.OnLongClickListener { private OnItemClickListener mOnItemClickListener; private OnItemLongClickListener OnItemLongClickListener; protected LayoutInflater mLayoutInflater; protected abstract RecyclerView.ViewHolder getViewHolder(ViewGroup parent, int viewType); protected abstract void onBindViewHolderConvert(T holder, int position); protected List<D> list = new ArrayList<>(); public interface OnItemClickListener { void onItemClick(View view, List list, int position); } public interface OnItemLongClickListener { void onItemLongClick(View view, List list, int position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { mLayoutInflater = LayoutInflater.from(parent.getContext()); RecyclerView.ViewHolder viewHolder = getViewHolder(parent, viewType); // View view = LayoutInflater.from(parent.getContext()).inflate(getLayoutId(viewType), parent, false); viewHolder.itemView.setOnClickListener(this); viewHolder.itemView.setOnLongClickListener(this); return viewHolder; } @SuppressWarnings("unchecked") @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { onBindViewHolderConvert((T) holder, position); holder.itemView.setTag(position); } @Override public int getItemCount() { return list.size(); } public void setOnItemClickListener(OnItemClickListener listener) { this.mOnItemClickListener = listener; } public void setOnItemLongClickListener(OnItemLongClickListener listener) { this.OnItemLongClickListener = listener; } @Override public void onClick(View v) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(v, list, (int) v.getTag()); } } @Override public boolean onLongClick(View v) { if (OnItemLongClickListener != null) { OnItemLongClickListener.onItemLongClick(v, list, (int) v.getTag()); } return true; } /** * 判断数据是否为空 */ public boolean isEmpty() { return list.isEmpty(); } /** * 在原有的数据起始处添加新数据 */ public void addItemsFromFirst(List<D> itemList) { this.list.addAll(0, itemList); notifyDataSetChanged(); } /** * 在原有的数据上添加新数据 */ public void addItems(List<D> itemList) { this.list.addAll(itemList); notifyDataSetChanged(); } /** * 在原有的数据上添加新数据 */ public void addItem(D data) { this.list.add(data); notifyDataSetChanged(); } /** * 在原有的数据上添加新数据 */ public void addItem(int index, D data) { this.list.add(index, data); notifyDataSetChanged(); } /** * 在原有的数据上添加新数据 */ public void removeItem(D data) { this.list.remove(data); notifyDataSetChanged(); } /** * 设置为新的数据,旧数据会被清空 */ public void setItems(List<D> itemList) { if (itemList != null) { list.clear(); list.addAll(itemList); } notifyDataSetChanged(); } /** * 获取列表数据 */ public List<D> getItems() { return list; } /** * 清空数据 */ public void clearItems() { list.clear(); notifyDataSetChanged(); } public void moveToPosition(RecyclerView recyclerView, int n) { LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager(); // int firstItem = manager.findFirstVisibleItemPosition(); // int lastItem = manager.findLastVisibleItemPosition(); // System.out.println(firstItem + " " + lastItem); // if (n <= firstItem) { // recyclerView.scrollToPosition(n); // } else if (n <= lastItem) { // int top = recyclerView.getChildAt(n - firstItem).getTop(); // recyclerView.scrollBy(0, top); // } else { // recyclerView.scrollToPosition(n); // } manager.scrollToPositionWithOffset(n, 0); manager.setStackFromEnd(true); } }
[ "kl" ]
kl
c76d1c5fa4f781722b7e93b0d79e4941b23764fa
daca0c2b13506d19ee4eb5d78f730df84bbc2014
/PinLockout.java
80005561609c67a4ebac84b823d5e1aea36596ce
[]
no_license
jordanarcherdev/ProgrammingByDoingSolutions
daf81ba446f6f7e89a513702307c43b27a432e36
fcfdb08b10b330f8ddb64f5ea08cd09023fbe836
refs/heads/master
2021-04-09T11:33:56.648215
2018-03-17T00:01:17
2018-03-17T00:01:17
125,582,158
0
0
null
null
null
null
UTF-8
Java
false
false
877
java
import java.util.Scanner; public class PinLockout { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int pin = 1234; int tries = 0; System.out.println("WELCOME TO THE BANK OF ARCHER."); System.out.print("YOUR PIN: "); int entry = keyboard.nextInt(); int max = 4; tries++; while (entry != pin && tries < max) { System.out.println("\nINCORRECT PIN. TRY AGAIN."); System.out.print("YOUR PIN: "); entry = keyboard.nextInt(); tries++; } if (entry == pin) { System.out.println("\nACCESS GRANTED!"); } else if ( tries >= max) { System.out.println("\nYOU HAVE RUN OUT OF TRIES. ACCOUNT LOCKED"); } } }
4ccef1b9d34404df550b01a38b73cf98075b4c92
5e2cab8845e635b75f699631e64480225c1cf34d
/modules/core/org.jowidgets.api/src/main/java/org/jowidgets/api/widgets/blueprint/builder/ITreeViewerSetupBuilder.java
f05738039709be8e76da204856250108b8a95980
[ "BSD-3-Clause" ]
permissive
alec-liu/jo-widgets
2277374f059500dfbdb376333743d5507d3c57f4
a1dde3daf1d534cb28828795d1b722f83654933a
refs/heads/master
2022-04-18T02:36:54.239029
2018-06-08T13:08:26
2018-06-08T13:08:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,136
java
/* * Copyright (c) 2014, Michael Grossmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the jo-widgets.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.jowidgets.api.widgets.blueprint.builder; import org.jowidgets.api.model.tree.ITreeNodeModel; import org.jowidgets.api.types.TreeViewerCreationPolicy; public interface ITreeViewerSetupBuilder<INSTANCE_TYPE extends ITreeViewerSetupBuilder<?, ?>, ROOT_NODE_VALUE_TYPE> extends ITreeSetupBuilder<INSTANCE_TYPE> { INSTANCE_TYPE setRootNodeModel(ITreeNodeModel<ROOT_NODE_VALUE_TYPE> model); INSTANCE_TYPE setCreationPolicy(TreeViewerCreationPolicy policy); INSTANCE_TYPE setPageSize(Integer pageSize); }
e3152af230d9e1ef72d3fca3cfee333bccc280f7
ce98390f6defff92df53d049c1f2a27d4886690b
/java_src/InsertionSort.java
0c11ad05fc16ca4c60568370a55daeea9165af06
[]
no_license
jucimarjr/jaraki
03439fa816a89af5d8539dcdfe58a50695b97166
372f16c364a1ad41a48a89743b8d4ed9b1cb9114
refs/heads/master
2021-01-19T19:36:09.439040
2012-11-09T23:56:16
2012-11-09T23:56:16
3,565,264
1
0
null
null
null
null
UTF-8
Java
false
false
574
java
//package insertionSort; public class InsertionSort { public static int[] insertionSort (int vetor[]) { int a; for (int i = 1; i < vetor.length; i++) { a = vetor[i]; for (int j = i - 1; j >= 0; j--) { if(vetor[j] > a) { vetor[j + 1] = vetor[j]; vetor[j] = a; } } } return vetor; } public static void main(String[] args) { int vetor[] = {8,5,2,7,1,10,4,3,6,50,9,25}; vetor = insertionSort(vetor); for (int i = 0; i < vetor.length; i++) { System.out.print(vetor[i]+" "); } } }
b904f923437a682e56a3ca5491b11cdeb7c47de2
6b33947f676afeecf1f6aa6df84b7190de6836e2
/java_templates/dao/java/base/MyBatisSupport.java
9423b470fdd0f6f4c2e4c44f0a9d9f5121c54ba3
[]
no_license
Kevin922/gen_code
adb9fc771d96e03280406003249d5fab1149d423
50c3e674f285d05d7d1111f5d217f685e3ff761a
refs/heads/master
2016-08-12T19:21:23.488336
2016-04-13T09:33:06
2016-04-13T09:33:06
48,244,917
0
0
null
null
null
null
UTF-8
Java
false
false
3,275
java
package {{ base_package }}.dao.base; import org.mybatis.spring.SqlSessionTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * 对mybatis的支持<br/> * spring配置文件需定义sqlTemplate与batchSqlTemplate * * @author dev-center * @since 2014-05-10 */ abstract class MyBatisSupport { protected static final Logger LOGGER = LoggerFactory.getLogger(MyBatisSupport.class); @Resource private SqlSessionTemplate sqlTemplate; @Resource private SqlSessionTemplate batchSqlTemplate; /** * SqlSessionTemplate * * @param batch * 是否批处理 * @param readonly * 是否只读 * @return */ protected SqlSessionTemplate getSqlTemplate(boolean batch, boolean readonly) { if (readonly) { } if (batch) { return batchSqlTemplate; } return sqlTemplate; } /** * 新增对象 * * @param statement * @param parameter * @return */ protected int insert(String statement, Object parameter) { int res = 0; try { if (parameter != null) { res = getSqlTemplate(false, false).insert(statement, parameter); } } catch (Exception ex) { throw new AppException("Mybatis执行新增异常", ex); } return res; } /** * 删除对象 * * @param statement * @param parameter * @return */ protected int delete(String statement, Object parameter) { int res = 0; try { res = getSqlTemplate(false, false).delete(statement, parameter); } catch (Exception ex) { throw new AppException("Mybatis执行删除异常", ex); } return res; } /** * 更新对象 * * @param statement * @param parameter * @return */ protected int update(String statement, Object parameter) { int res = 0; try { if (parameter != null) { res = getSqlTemplate(false, false).update(statement, parameter); } } catch (Exception ex) { throw new AppException("Mybatis执行更新异常", ex); } return res; } /** * 查询一条记录 * * @param <T> * @param statement * @param parameter * @return */ @SuppressWarnings("unchecked") protected <T> T select(String statement, Object parameter) { T obj = null; try { obj = (T) getSqlTemplate(false, true).selectOne(statement, parameter); } catch (Exception ex) { throw new AppException("Mybatis执行单条查询异常", ex); } return obj; } /** * 查询列表 * * @param <T> * @param statement * @param parameter * @return */ protected <T> List<T> selectList(String statement, Object parameter) { List<T> list = null; try { list = getSqlTemplate(false, true).selectList(statement, parameter); } catch (Exception ex) { throw new AppException("Mybatis执行列表查询异常", ex); } return list; } /** * 查询Map * * @param <K> * @param <V> * @param statement * @param parameter * @param mapKey * @return */ protected <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { Map<K, V> map = null; try { map = getSqlTemplate(false, true).selectMap(statement, parameter, mapKey); } catch (Exception ex) { throw new AppException("Mybatis执行Map查询异常", ex); } return map; } }
dd53631ecb1078991a07c54883c38d2bf77ae162
7d9e9956d6fea32e6a0a61be4f45fb7464554cee
/src/chessPackage/Superclass_WhiteRook.java
5df257ba922a9cf8d9e831e4f68bcc25d354d2e6
[]
no_license
ras3638/ChessGame
5d5c4b71b1e93672036e6cffca2fcacfc25171d3
93a5447ec85650d20d077cd3ca92fa693da430a7
refs/heads/master
2021-01-19T08:35:44.499099
2014-08-03T00:12:27
2014-08-03T00:12:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,424
java
package chessPackage; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import javax.swing.ImageIcon; public class Superclass_WhiteRook extends WhitePiece { static ImageIcon getIcon(){ URL White_Rook_URL = Chess.class.getResource("chess_piece_white_rook.png"); ImageIcon White_Rook_Icon = new ImageIcon(White_Rook_URL); return White_Rook_Icon; } static ArrayList<int[]> movementHandler(int CurrentX, int CurrentY, int StartingPositionX, int StartingPositionY){ ArrayList<int[]> MoveList = new ArrayList<int []>(); MoveList = searcherTopTiles(MoveList,CurrentX,CurrentY); MoveList = searcherLeftTiles(MoveList,CurrentX,CurrentY); MoveList = searcherBottomTiles(MoveList,CurrentX,CurrentY); MoveList = searcherRightTiles(MoveList,CurrentX,CurrentY); return MoveList; } static int [][] checkPreventer( int[][]MultiArray,int CurrentX, int CurrentY, int[] ComXY, String CurrentTitle){ //this function prevents check against Black King //top tiles outerloop_TopTiles: for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX + 0; NewXY[1] = CurrentY - j; if (NewXY[1] < 0){ //break due to out of bounds break outerloop_TopTiles; } for(int i = 0 ; i < aggregateBlacksEXKing(CurrentTitle,ComXY).length ; i++) { int[] Coordinate = aggregateBlacksEXKing(CurrentTitle,ComXY)[i]; if(Arrays.equals(Coordinate, NewXY)){ break outerloop_TopTiles; } } for(int[] i: aggregateWhitesForCheck(CurrentTitle, ComXY)){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ break outerloop_TopTiles; } } if(Arrays.equals(NewXY,ComXY) && CurrentTitle != "Black King (E8)"){ //this if statement is necessary to allow pieces to block rook's line of sight ////System.out.println("Outerbreak3.3"); break outerloop_TopTiles; } for(int i = 0 ; i < MultiArray.length ; i++) { if(Arrays.equals(MultiArray[i], NewXY)){ //System.out.println("White Rook threatining check from the bottom"); MultiArray[i]=null; break outerloop_TopTiles; } } } //left tiles outerloop_LeftTiles: for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX - j; NewXY[1] = CurrentY + 0; if (NewXY[0] < 0){ //break due to out of bounds break outerloop_LeftTiles; } for(int i = 0 ; i < aggregateBlacksEXKing(CurrentTitle,ComXY).length ; i++) { int[] Coordinate = aggregateBlacksEXKing(CurrentTitle,ComXY)[i]; if(Arrays.equals(Coordinate, NewXY)){ break outerloop_LeftTiles; } } for(int[] i: aggregateWhitesForCheck(CurrentTitle, ComXY)){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ break outerloop_LeftTiles; } } if(Arrays.equals(NewXY,ComXY) && CurrentTitle != "Black King (E8)"){ //this if statement is necessary to allow pieces to block rook's line of sight break outerloop_LeftTiles; } for(int i = 0 ; i < MultiArray.length ; i++) { if(Arrays.equals(MultiArray[i], NewXY)){ //System.out.println("White Rook threatining check from the right"); MultiArray[i]=null; break outerloop_LeftTiles; } } } //bottom tiles outerloop_BottomTiles: for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX + 0; NewXY[1] = CurrentY + j; if (NewXY[1] > 7){ //break due to out of bounds break outerloop_BottomTiles; } for(int i = 0 ; i < aggregateBlacksEXKing(CurrentTitle,ComXY).length ; i++) { int[] Coordinate = aggregateBlacksEXKing(CurrentTitle,ComXY)[i]; if(Arrays.equals(Coordinate, NewXY)){ ////System.out.println("Outerbreak3.1"); break outerloop_BottomTiles; } } for(int[] i: aggregateWhitesForCheck(CurrentTitle, ComXY)){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ ////System.out.println("Outerbreak3.2"); break outerloop_BottomTiles; } } if(Arrays.equals(NewXY,ComXY) && CurrentTitle != "Black King (E8)"){ //this if statement is necessary to allow pieces to block rook's line of sight ////System.out.println("Outerbreak3.3"); break outerloop_BottomTiles; } for(int i = 0 ; i < MultiArray.length ; i++) { if(Arrays.equals(MultiArray[i], NewXY)){ ////System.out.println("Outerbreak3.4"); //System.out.println("White Rook threatining check from the top"); MultiArray[i]=null; break outerloop_BottomTiles; } } } //right tiles outerloop_RightTiles: for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX + j; NewXY[1] = CurrentY + 0; if (NewXY[0] > 7){ //break due to out of bounds break outerloop_RightTiles; } for(int i = 0 ; i < aggregateBlacksEXKing(CurrentTitle,ComXY).length ; i++) { int[] Coordinate = aggregateBlacksEXKing(CurrentTitle,ComXY)[i]; if(Arrays.equals(Coordinate, NewXY)){ break outerloop_RightTiles; } } for(int[] i: aggregateWhitesForCheck(CurrentTitle, ComXY)){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ break outerloop_RightTiles; } } if(Arrays.equals(NewXY,ComXY) && CurrentTitle != "Black King (E8)"){ //this if statement is necessary to allow pieces to block rook's line of sight break outerloop_RightTiles; } for(int i = 0 ; i < MultiArray.length ; i++) { if(Arrays.equals(MultiArray[i], NewXY)){ //System.out.println("White Rook threatining check from the left"); MultiArray[i]=null; break outerloop_RightTiles; } } } return MultiArray; } static ArrayList<int[]> searcherTopTiles(ArrayList<int[]> MoveList,int CurrentX, int CurrentY){ //this function looks for black pieces blocking this rook top tiles for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX + 0; NewXY[1] = CurrentY - j; if(NewXY[1] < 0){ return MoveList; } for(int [] i: aggregateBlacks()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a valid black piece to kill " + j + " tiles top of this rook"); MoveList.add(NewXY); return MoveList; } } for(int [] i: aggregateWhites()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a white piece " + j + " tiles top of this Queen"); return MoveList; } } MoveList.add(NewXY); } return MoveList; } static ArrayList<int[]> searcherLeftTiles(ArrayList<int[]> MoveList,int CurrentX, int CurrentY){ //this function looks for black pieces blocking this rook left tiles for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX - j; NewXY[1] = CurrentY + 0; if(NewXY[0] < 0){ return MoveList; } for(int [] i: aggregateBlacks()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a valid black piece to kill " + j + " tiles left of this rook"); MoveList.add(NewXY); return MoveList; } } for(int [] i: aggregateWhites()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a white piece " + j + " tiles top of this Queen"); return MoveList; } } MoveList.add(NewXY); } return MoveList; } static ArrayList<int[]> searcherBottomTiles(ArrayList<int[]> MoveList,int CurrentX, int CurrentY){ //this function looks for black pieces blocking this rook left tiles for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX + 0; NewXY[1] = CurrentY + j; if(NewXY[1] > 7){ return MoveList; } for(int [] i: aggregateBlacks()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a valid blacks piece to kill " + j + " tiles bottom of this rook"); MoveList.add(NewXY); return MoveList; } } for(int [] i: aggregateWhites()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a white piece " + j + " tiles top of this Queen"); return MoveList; } } MoveList.add(NewXY); } return MoveList; } static ArrayList<int[]> searcherRightTiles(ArrayList<int[]> MoveList,int CurrentX, int CurrentY){ //this function looks for black pieces blocking this rook left tiles for(int j = 1; j <=7 ; j++){ int [] NewXY = new int[2]; NewXY[0] = CurrentX + j; NewXY[1] = CurrentY + 0; if(NewXY[0] > 7){ return MoveList; } for(int [] i: aggregateBlacks()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a valid black piece to kill " + j + " tiles right of this rook"); MoveList.add(NewXY); return MoveList; } } for(int [] i: aggregateWhites()){ int[] Coordinate = i; if(Arrays.equals(Coordinate, NewXY)){ //System.out.println("We have found a white piece " + j + " tiles top of this Queen"); return MoveList; } } MoveList.add(NewXY); } return MoveList; } }
a303d8223b0b786c3bb8d31b290f3a1f9c18b28e
961016a614c6785e6fe8f6bfd7214676f0d91064
/Portlets/ProgateServiceBuilder-portlet/docroot/WEB-INF/src/larion/progate/cds/model/impl/CdsPerformanceAppraisalSlotRatingImpl.java
af9513558bc1194230da6b1dfd4ad5ef68530005
[]
no_license
thaond/progate-lmis
f58c447c58c11217e2247c7ca3349a44ad7f3bbd
d143b7e7d56a22cc9ce6256ca6fb77a11459e6d6
refs/heads/master
2021-01-10T03:00:26.888869
2011-07-28T14:12:54
2011-07-28T14:12:54
44,992,742
0
0
null
null
null
null
UTF-8
Java
false
false
1,596
java
/** * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package larion.progate.cds.model.impl; import larion.progate.cds.model.CdsPerformanceAppraisalSlotRating; /** * <a href="CdsPerformanceAppraisalSlotRatingImpl.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * */ public class CdsPerformanceAppraisalSlotRatingImpl extends CdsPerformanceAppraisalSlotRatingModelImpl implements CdsPerformanceAppraisalSlotRating { public CdsPerformanceAppraisalSlotRatingImpl() { } }
27dd9235625b355e64bfd64ed0614a2b7df468f0
92fcc69fc93177640f1c53a3cfce1c423eac0fd8
/src/test/java/kr/or/ddit/ioc/SpringIocCollectionTest.java
7611d45c2086fc930aac1bfcb061b9c60e36b71c
[]
no_license
maze51/springTest
83d426137dcea224e8bf4a7ceddf76cdbb9893c1
a5d1cfba64eee312c44c032ce9d7b64f1d706440
refs/heads/master
2022-11-17T06:16:04.281319
2019-07-08T01:36:41
2019-07-08T01:36:41
192,683,588
0
0
null
null
null
null
UTF-8
Java
false
false
1,101
java
package kr.or.ddit.ioc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import kr.or.ddit.ioc.collection.IocCollection; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:kr/or/ddit/ioc/application-ioc-collection.xml") public class SpringIocCollectionTest { @Resource(name="collectionBean") private IocCollection collectionBean; @Test public void springCollectionTest() { /***Given***/ /***When***/ /***Then***/ assertNotNull(collectionBean.getList()); assertNotNull(collectionBean.getMap()); assertEquals("brown", collectionBean.getList().get(0)); assertEquals("2019-08-08", collectionBean.getMap().get("birth")); assertTrue(collectionBean.getSet().contains("james")); assertEquals(2, collectionBean.getProperties().size()); } }
d80ba47e76cc45a12cc62136e993afdc0f5e1002
a4a51084cfb715c7076c810520542af38a854868
/src/main/java/com/shopee/protocol/action/ResponseSetLikeItemComment.java
494c373806cf0475f8f63cb24e03733ce19556b0
[]
no_license
BharathPalanivelu/repotest
ddaf56a94eb52867408e0e769f35bef2d815da72
f78ae38738d2ba6c9b9b4049f3092188fabb5b59
refs/heads/master
2020-09-30T18:55:04.802341
2019-12-02T10:52:08
2019-12-02T10:52:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,364
java
package com.shopee.protocol.action; import com.squareup.wire.Message; import com.squareup.wire.ProtoField; public final class ResponseSetLikeItemComment extends Message { public static final Integer DEFAULT_ERRCODE = 0; public static final Integer DEFAULT_LIKE_COUNT = 0; public static final String DEFAULT_REQUESTID = ""; private static final long serialVersionUID = 0; @ProtoField(label = Message.Label.REQUIRED, tag = 2, type = Message.Datatype.INT32) public final Integer errcode; @ProtoField(tag = 3, type = Message.Datatype.INT32) public final Integer like_count; @ProtoField(tag = 1, type = Message.Datatype.STRING) public final String requestid; public ResponseSetLikeItemComment(String str, Integer num, Integer num2) { this.requestid = str; this.errcode = num; this.like_count = num2; } private ResponseSetLikeItemComment(Builder builder) { this(builder.requestid, builder.errcode, builder.like_count); setBuilder(builder); } public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ResponseSetLikeItemComment)) { return false; } ResponseSetLikeItemComment responseSetLikeItemComment = (ResponseSetLikeItemComment) obj; if (!equals((Object) this.requestid, (Object) responseSetLikeItemComment.requestid) || !equals((Object) this.errcode, (Object) responseSetLikeItemComment.errcode) || !equals((Object) this.like_count, (Object) responseSetLikeItemComment.like_count)) { return false; } return true; } public int hashCode() { int i = this.hashCode; if (i != 0) { return i; } String str = this.requestid; int i2 = 0; int hashCode = (str != null ? str.hashCode() : 0) * 37; Integer num = this.errcode; int hashCode2 = (hashCode + (num != null ? num.hashCode() : 0)) * 37; Integer num2 = this.like_count; if (num2 != null) { i2 = num2.hashCode(); } int i3 = hashCode2 + i2; this.hashCode = i3; return i3; } public static final class Builder extends Message.Builder<ResponseSetLikeItemComment> { public Integer errcode; public Integer like_count; public String requestid; public Builder() { } public Builder(ResponseSetLikeItemComment responseSetLikeItemComment) { super(responseSetLikeItemComment); if (responseSetLikeItemComment != null) { this.requestid = responseSetLikeItemComment.requestid; this.errcode = responseSetLikeItemComment.errcode; this.like_count = responseSetLikeItemComment.like_count; } } public Builder requestid(String str) { this.requestid = str; return this; } public Builder errcode(Integer num) { this.errcode = num; return this; } public Builder like_count(Integer num) { this.like_count = num; return this; } public ResponseSetLikeItemComment build() { checkRequiredFields(); return new ResponseSetLikeItemComment(this); } } }
62b04183b380880592d92ca9a3291c0510e44c72
4c7be0cb9748c2bb8571c48090b299f8c8278797
/app/endpoint/src/main/java/com/dzjk/ams/endpoint/share/converter/AccountConvert.java
66499115d7ebf5b0572eaf537fd4b14e7ab3243f
[]
no_license
ZuoShouShiJie/ams
ff71f5b495968556b3b608e0929ca60adbcd673c
fd5e791e6ce8719cbcb26b933dc10f24316916ac
refs/heads/master
2020-03-29T04:40:59.433436
2018-09-20T03:02:29
2018-09-20T03:02:50
149,542,480
0
0
null
null
null
null
UTF-8
Java
false
false
17,216
java
package com.dzjk.ams.endpoint.share.converter; import com.alibaba.common.lang.StringUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.basic.framework.core.model.Money; import com.dzjk.ams.core.common.enums.ResultEnum; import com.dzjk.ams.core.common.exception.CommonException; import com.dzjk.ams.core.common.util.DateUtils; import com.dzjk.ams.core.common.util.MoneyUtils; import com.dzjk.ams.dal.dataobject.*; import com.dzjk.ams.endpoint.action.account.AccountFacadeRestImpl; import com.dzjk.ams.facade.form.account.*; import com.dzjk.ams.facade.model.*; import com.sun.jdi.DoubleValue; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by daixiaohu on 2018/2/26. */ public class AccountConvert { private static final Logger logger = LoggerFactory.getLogger(AccountFacadeRestImpl.class); public static List<QueryAccountRespForm> accountListreConverter(CustomerInfoDO customerInfoDO, List<AccountBorrowDO> list) { List<QueryAccountRespForm> listResp = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { listResp.add(accountreConverter(customerInfoDO, list.get(i))); } return listResp; } public static QueryAccountRespForm accountreConverter(CustomerInfoDO customerInfoDO, AccountBorrowDO borrowDO) { QueryAccountRespForm form = new QueryAccountRespForm(); form.setUserName(customerInfoDO.getUserName()); form.setIdType(customerInfoDO.getIdType()); form.setIdNo(customerInfoDO.getIdNo()); form.setBoId(borrowDO.getBoId()); form.setOrgId(borrowDO.getOrgId() == null ? "" : borrowDO.getOrgId().toString()); form.setBoId(borrowDO.getBoId()); form.setTotalCapital(borrowDO.getLendAmount()); form.setTotalInterest(borrowDO.getInterestAdvance()); form.setTotalServiceFee(borrowDO.getServiceFeeAccu()); form.setTotalFine(borrowDO.getPunishFeeAccu()); form.setRepayDate(borrowDO.getRepayDate()); form.setRepayPeriod(borrowDO.getRepayPeriod()); if (borrowDO.getFirstRepayDate() != null) { form.setFirstRepayDate(DateUtils.dateToString(borrowDO.getFirstRepayDate(), DateUtils.SIMPLE_DATE_PATTERN)); } if (borrowDO.getLastRepayDate() != null) { form.setLastRepayDate(DateUtils.dateToString(borrowDO.getLastRepayDate(), DateUtils.SIMPLE_DATE_PATTERN)); } if (borrowDO.getNextRepayDate() != null) { form.setNextRepayDate(DateUtils.dateToString(borrowDO.getNextRepayDate(), DateUtils.SIMPLE_DATE_PATTERN)); } form.setRepayStatus(borrowDO.getRepayStatus()); form.setOverdueTimes(borrowDO.getOverdueTimes()); form.setMaxOverdueDay(borrowDO.getMaxOverdueDay()); form.setCurrOverdueDay(borrowDO.getCurrOverdueDay()); return form; } public static List<QueryRepayPlanVo> repayPlanListConverter(List<AccountRepayExDO> list) { List<QueryRepayPlanVo> listResp = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { listResp.add(repayPlanVoConverter(list.get(i))); } return listResp; } public static QueryRepayPlanVo repayPlanVoConverter(AccountRepayExDO borrowDO) { QueryRepayPlanVo form = new QueryRepayPlanVo(); List<AccountRepayServiceFeeDO> feeList = borrowDO.getFeeList(); List<FeeVo> feeVos = new ArrayList<>(); for (AccountRepayServiceFeeDO exDO : feeList) { FeeVo vo = new FeeVo(); vo.setFeeName(exDO.getFeeName()); vo.setFeeAmount(exDO.getFeeAmount()); feeVos.add(vo); } form.setPeriodNum(borrowDO.getPeriodNum()); form.setCapitalAmount(borrowDO.getCapitalAmount()); form.setInterestAmount(borrowDO.getInterestAmount()); form.setServiceFee(borrowDO.getServiceFee()); if (borrowDO.getRepayDate() != null) { form.setRepayDate(DateUtils.dateToString(borrowDO.getRepayDate(), DateUtils.SIMPLE_DATE_PATTERN)); } if (borrowDO.getRealRepayDate() != null) { form.setRepaidDate(DateUtils.dateToString(borrowDO.getRealRepayDate(), DateUtils.SIMPLE_DATE_PATTERN)); } form.setServiceFeeDetails(JSON.toJSONString(feeVos));//相关服务费明细,待定 form.setRepayStatus(borrowDO.getRepayStatus());//还款状态,需要枚举 form.setOverdueDay(borrowDO.getOverdueDay()); form.setTotalCapitalLeft(borrowDO.getTotalCapitalLeft()); form.setTotalCapitalAccu(borrowDO.getTotalCapitalAccu()); form.setInterestAccu(borrowDO.getInterestAccu()); form.setServiceFeeAccu(borrowDO.getServiceFeeAccu()); form.setFineAccu(borrowDO.getPunishFee()); if (borrowDO.getPunishUpdatedTime() != null) { form.setFineUpdatedTime(DateUtils.dateToString(borrowDO.getPunishUpdatedTime(), DateUtils.SIMPLE_DATE_HOURS_PATTERN)); } return form; } public static LoanDetailInfoVo customerConverter(CustomerInfoDO cust, QueryRepayPlanReqForm vo, Integer count) { LoanDetailInfoVo form = new LoanDetailInfoVo(); form.setUserName(cust.getUserName()); form.setUserId(cust.getUserId()); form.setIdType(cust.getIdType()); form.setIdNo(cust.getIdNo()); form.setOrgId(String.valueOf(cust.getOrgId())); form.setBoId(vo.getBoId()); form.setPageNo(vo.getPageNo()); form.setPageRec(vo.getPageRec()); form.setPageCount(count); return form; } /** * 平台收益查询 * * @param list * @return */ public static List<QueryPlatEarningsVo> platEarningsListConverter(List<AccountEarningsExDO> list) { if (list != null && list.size() > 0) { List<QueryPlatEarningsVo> listResp = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { listResp.add(platEarningsVoConverter(list.get(i))); } return listResp; } return null; } public static QueryPlatEarningsVo platEarningsVoConverter(AccountEarningsExDO borrowDO) { QueryPlatEarningsVo form = new QueryPlatEarningsVo(); List<AccountEarningsServiceFeeDO> feeList = borrowDO.getFeeDOS(); List<FeeVo> feeVos = new ArrayList<>(); BigDecimal platService = new BigDecimal(0);//平台服务费 BigDecimal fine = new BigDecimal(0);//当期应收逾期导致的罚息或违约费用 for (AccountEarningsServiceFeeDO exDO : feeList) { FeeVo vo = new FeeVo(); vo.setFeeName(exDO.getFeeName()); vo.setFeeAmount(exDO.getFeeAmount()); feeVos.add(vo); if ("12004".equals(exDO.getFeeType())) { platService = exDO.getFeeAmount(); } if ("2".equals(exDO.getFeeType().substring(0, 1))) { fine = fine.add(exDO.getFeeAmount()); } } form.setServiceFee(platService); form.setFine(fine); form.setBoId(borrowDO.getBoId()); form.setPeriodNum(borrowDO.getPeriodNum()); form.setOrgId(String.valueOf(borrowDO.getOrgId())); form.setIsFullFee(borrowDO.getIsFullFee()); //是否一次性收取平台费,枚举,待定 form.setTotalServiceFee(borrowDO.getServiceFee());//应收平台服务总费 form.setTotalServiceFeeDetails(JSON.toJSONString(feeVos));//服务费明细,json form.setCapitalAmount(borrowDO.getCapitalAmount()); form.setInterestAmount(borrowDO.getInterestAmount()); if (borrowDO.getRepayDate() != null) { form.setRepayDate(DateUtils.dateToString(borrowDO.getRepayDate(), DateUtils.SIMPLE_DATE_PATTERN)); } if (borrowDO.getRealRepayDate() != null) { form.setRepaidDate(DateUtils.dateToString(borrowDO.getRealRepayDate(), DateUtils.SIMPLE_DATE_PATTERN)); } form.setRepayStatus(borrowDO.getRepayStatus());//收款状态,枚举。 form.setOverdueDay(borrowDO.getOverdueDay()); form.setServiceFeeAccu(borrowDO.getServiceFeeAccu()); form.setFineAccu(borrowDO.getPunishFeeAccu()); if (borrowDO.getPunishUpdatedTime() != null) { form.setFineUpdatedTime(DateUtils.dateToString(borrowDO.getPunishUpdatedTime(), DateUtils.SIMPLE_DATE_HOURS_PATTERN)); } return form; } public static TrialLoanDetailInfoVo queryTrialLoanDetail(AccountTrialReqForm vo, String interest, String service) throws ParseException { TrialLoanDetailInfoVo form = new TrialLoanDetailInfoVo(); Integer repayPeriod = Integer.valueOf(vo.getRepayPeriod()); BigDecimal loanAmount = vo.getLoanAmount(); form.setUserName(vo.getUserName()); form.setIdType(vo.getIdType()); form.setIdNo(vo.getIdNo()); form.setOrgId(vo.getOrgId()); form.setTotalCapital(vo.getLoanAmount().setScale(2, BigDecimal.ROUND_UP)); BigDecimal totalInterestAccu = new BigDecimal(0); //如果通过减息券等变更利率 BigDecimal totalService = new BigDecimal(0); BigDecimal totalCapitalAccu = new BigDecimal(0); BigDecimal perAmount = MoneyUtils.getPerAmount(loanAmount, Integer.valueOf(vo.getRepayPeriod()));//每期应该本金 //总利息(每期利息累计) for (int j = 1; j < repayPeriod + 1; j++) {// getPerAmount(BigDecimal invest,int totalmonth) totalCapitalAccu = totalCapitalAccu.add(perAmount); totalInterestAccu = totalInterestAccu.add(MoneyUtils.getPerInterest(loanAmount, interest, repayPeriod, j)); totalService = totalService.add((loanAmount.subtract(totalCapitalAccu).add(perAmount)).multiply(new BigDecimal(service)).setScale(2, BigDecimal.ROUND_UP)); } form.setTotalInterest(totalInterestAccu); form.setTotalServiceFee(totalService); if (StringUtils.isNotBlank(vo.getRepayDate())) { form.setRepayDate(vo.getRepayDate()); } form.setRepayPeriod(vo.getRepayPeriod()); String applyDate = vo.getApplyDate(); if (StringUtils.isNotBlank(applyDate)) { Date applyDates = DateUtils.parseDatetime(applyDate, DateUtils.SIMPLE_DATE_PATTERN); Date firstRepayDate = DateUtils.addMonths(applyDates, 1); form.setFirstRepayDate(DateUtils.dateToString(firstRepayDate, DateUtils.SIMPLE_DATE_PATTERN)); Date lastRepayDate = DateUtils.addMonths(applyDates, repayPeriod); form.setLastRepayDate(DateUtils.dateToString(lastRepayDate, DateUtils.SIMPLE_DATE_PATTERN)); // form.setRepayDate(DateUtils.); } return form; } public static List<TrialDetailListVo> queryTrialDetailList(AccountTrialReqForm vo, String interest, String service) throws ParseException { List<TrialDetailListVo> trialDetailListVos = new ArrayList<>(); String repayPeriod = vo.getRepayPeriod(); Integer period = Integer.valueOf(repayPeriod); for (int i = 1; i < period + 1; i++) { trialDetailListVos.add(queryTrialDetail(vo.getLoanAmount(), vo.getApplyDate(), interest, repayPeriod, service, i)); } return trialDetailListVos; } public static TrialDetailListVo queryTrialDetail(BigDecimal loanAmount, String applyDate, String rate, String repayPeriod, String service, int i) throws ParseException { Integer totalMonth = Integer.valueOf(repayPeriod); TrialDetailListVo vo = new TrialDetailListVo(); vo.setPeriodNum(String.valueOf(i)); BigDecimal capitalAmount = MoneyUtils.getPerAmount(loanAmount, totalMonth); vo.setCapitalAmount(capitalAmount);//每月偿还本金 vo.setInterestAmount(MoneyUtils.getPerInterest(loanAmount, rate, totalMonth, i));//每月偿还利息 BigDecimal totalCapitalAccu = new BigDecimal(0); BigDecimal totalInterestAccu = new BigDecimal(0); BigDecimal totalServiceFeeAccu = new BigDecimal(0); for (int j = 1; j < i + 1; j++) { totalCapitalAccu = totalCapitalAccu.add(capitalAmount); totalInterestAccu = totalInterestAccu.add(MoneyUtils.getPerInterest(loanAmount, rate, totalMonth, j)); totalServiceFeeAccu = totalServiceFeeAccu.add((loanAmount.subtract(totalCapitalAccu).add(capitalAmount)).multiply(new BigDecimal(service)).setScale(2, BigDecimal.ROUND_UP)); } logger.info("loanAmount:" + loanAmount + "totalCapitalAccu:" + totalCapitalAccu + "capitalAmount:" + capitalAmount + "service:" + service); vo.setServiceFee((loanAmount.subtract(totalCapitalAccu).add(capitalAmount)).multiply(new BigDecimal(service)).setScale(2, BigDecimal.ROUND_UP)); //相关费用 logger.info("serviceFee:" + vo.getServiceFee()); Date repayDate = DateUtils.addMonths(DateUtils.stringToDate(applyDate, DateUtils.SIMPLE_DATE_PATTERN), i); vo.setRepayDate(DateUtils.dateToString(repayDate, DateUtils.SIMPLE_DATE_PATTERN));//计划划款日 BigDecimal totalCapitalLeft = loanAmount.subtract(totalCapitalAccu).setScale(2, BigDecimal.ROUND_UP); if (i == totalMonth) { totalCapitalLeft = new BigDecimal(0).setScale(2, BigDecimal.ROUND_UP); totalCapitalAccu = loanAmount.setScale(2, BigDecimal.ROUND_UP); } vo.setTotalCapitalLeft(totalCapitalLeft);//截至当期剩余本金 vo.setTotalCapitalAccu(totalCapitalAccu);//截至当期累计已还本金金额 vo.setInterestAccu(totalInterestAccu);//截至当期累计已还利息总额 vo.setServiceFeeAccu(totalServiceFeeAccu);//截至当期累计服务费用总额 return vo; } public static PreRepayTryRespForm getPreRepayTry(PreRepayTryReqForm form, AccountBorrowDO borrowDO, BigDecimal preRepayFine, BigDecimal preRepayServiceFee0,BigDecimal preRepayServiceFee2, BigDecimal preRepayServiceFee3) throws ParseException { BigDecimal totalCapitalLeft = borrowDO.getTotalCapitalLeft();//需提前还款本金 Date lendDate = borrowDO.getLendDate(); //实际放款时间 BigDecimal lendAmount = borrowDO.getLendAmount(); String repayPeriod = borrowDO.getRepayPeriod();//还款期数 String repayDate = form.getApplyDate();//还款日期 BigDecimal repayRate = borrowDO.getRate();//正常利率 Date d2 = DateUtils.stringToDate(repayDate, DateUtils.SIMPLE_DATE_PATTERN); Date d1 = DateUtils.date2date(lendDate, DateUtils.SIMPLE_DATE_PATTERN); int a = (int) ((d2.getTime() - d1.getTime()) / (1000 * 3600 * 24)); if (a <= 0) { throw new CommonException(ResultEnum.RepayDateLessApply, ResultEnum.RepayDateLessApply.getMsg()); } //提前还款利息=剩余金额*(月利率/30)*(还款日期-实际放款日期) //提前还款金额 = 剩余本金+提前还款利息+罚息费+罚息服务费+技术服务费+平台服务费 BigDecimal preRepayInterest = totalCapitalLeft.multiply(new BigDecimal(a)).multiply(repayRate).divide(new BigDecimal(30), 2, BigDecimal.ROUND_UP); BigDecimal preRepayAmount = totalCapitalLeft.add(preRepayInterest).add(preRepayFine).add(preRepayServiceFee0).add(preRepayServiceFee2).add(preRepayServiceFee3).setScale(2, BigDecimal.ROUND_UP);//需提前还款本金+还款利息+还款罚息; PreRepayTryRespForm respForm = new PreRepayTryRespForm(); respForm.setUserName(form.getUserName()); respForm.setIdType(form.getIdType()); respForm.setIdNo(form.getIdNo()); respForm.setBoId(form.getBoId()); respForm.setPreRepayApplyDate(form.getApplyDate()); respForm.setPreRepayAmount(preRepayAmount); respForm.setPreRepayCapitalLeft(totalCapitalLeft); respForm.setPreRepayInterest(preRepayInterest); respForm.setPreRepayFine(preRepayFine); respForm.setOverDueFine(new BigDecimal(0));//滞纳金,目前滞纳金为0,等接入资产端再算。 respForm.setPreRepayServiceFee0(preRepayServiceFee0);//逾期服务费 respForm.setPreRepayServiceFee1(new BigDecimal(0)); respForm.setPreRepayServiceFee2(preRepayServiceFee2);//技术服务费 respForm.setPreRepayServiceFee3(preRepayServiceFee3);//平台服务费 return respForm; } public static PreRepayTryReqForm reqManualRepay(ManualRepayReqForm form) { PreRepayTryReqForm tryReqForm = new PreRepayTryReqForm(); tryReqForm.setUserName(form.getUserName()); tryReqForm.setIdType(form.getIdType()); tryReqForm.setIdNo(form.getIdNo()); tryReqForm.setUserId(form.getUserId()); tryReqForm.setOrgId(form.getOrgId()); tryReqForm.setBoId(form.getBoId()); tryReqForm.setApplyDate(form.getApplyDate()); tryReqForm.setApplyTime(form.getApplyTime()); return tryReqForm; } }
d426c812ebc2d1ac7afe1e7e73828ab5e0e67056
addb53299fc70a9ecb0a06b9b206a3ae92defd13
/Jellyfish.Parser.v4/src/jellyfish/matcher/AliasTreeNode.java
696f82dd3e6e9009dd1b4db0938d46b314ce52e1
[]
no_license
amjed/Universal-Structured-Language-Parser
a393901e81b5a29c6b761676c54aaccea29a2c0c
38f098453f363d5a9e1d36240e342a19209c3df5
refs/heads/master
2021-01-25T07:34:30.510937
2011-02-10T09:07:14
2011-02-10T09:07:14
1,357,912
1
0
null
null
null
null
UTF-8
Java
false
false
12,708
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jellyfish.matcher; import java.util.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jellyfish.common.Common; import jellyfish.common.Pair; import jellyfish.common.PatternExtractor; /** * * @author Umran */ public class AliasTreeNode implements Comparable<AliasTreeNode> { private static final PatternExtractor ALIAS_EXTRACTOR = new PatternExtractor( "([^\\[])\\[([0-9]+)\\]" ); // public static final String ROOT_ALIAS_NAME = "ROOT"; public static AliasTreeNode createRoot( String rootName ) { return new AliasTreeNode( rootName, 0 ) { @Override public boolean isRoot() { return true; } @Override public boolean isNormalNode() { return false; } }; } public static AliasTreeNode createSysInc() { return new AliasTreeNode( "SYS_INC", 2 ) { @Override public boolean isSysInc() { return true; } @Override public boolean isNormalNode() { return false; } }; } public static Pair<AliasTreeNode, Map<AliasTreeNode, AliasTreeNode>> copyAliasTree( AliasTreeNode root, AliasTreeNode newParent ) { Map<AliasTreeNode, AliasTreeNode> origToCopyMapping = new IdentityHashMap<AliasTreeNode, AliasTreeNode>(); AliasTreeNode newRoot = null; if (newParent==null) newRoot = AliasTreeNode.createRoot( root.name ); else { newRoot = new AliasTreeNode( root.name ); newRoot.setParent( newParent ); } origToCopyMapping.put( root, newRoot ); newRoot.copySubTree( root, origToCopyMapping ); return Pair.create( newRoot, origToCopyMapping ); } private static int hashCodeIncr = 3; private int hashCode; private String name; private int index; private AliasTreeNode actualParent; // actual parent of this node private AliasTreeNode normalParent; // first parent that is normal (i.e. not sys-inc) or root private boolean childrenInitialized; private List<AliasTreeNode> children; private Map<String, List<AliasTreeNode>> childNames; private String completeName[]; private AliasTreeNode( String name, int hashCode ) { this.hashCode = hashCode; this.name = Common.firstCharToUpper( name ); this.actualParent = null; this.normalParent = null; this.index = 0; this.childrenInitialized = false; this.children = Collections.EMPTY_LIST; this.childNames = Collections.EMPTY_MAP; this.completeName = computeCompleteName(); } public AliasTreeNode( String name ) { this( name, hashCodeIncr++ ); } private void copySubTree( AliasTreeNode otherRoot, Map<AliasTreeNode, AliasTreeNode> origToCopyMapping ) { ArrayDeque<Pair<AliasTreeNode,AliasTreeNode>> que = new ArrayDeque<Pair<AliasTreeNode,AliasTreeNode>>(100); que.add( Pair.create(this,otherRoot) ); while (!que.isEmpty()) { Pair<AliasTreeNode,AliasTreeNode> head = que.remove(); AliasTreeNode thisParent = head.getFirst(); AliasTreeNode otherParent = head.getSecond(); for ( AliasTreeNode otherChild : otherParent.children ) { AliasTreeNode thisChild = new AliasTreeNode( otherChild.name ); thisChild.setParent( thisParent ); origToCopyMapping.put( otherChild, thisChild ); if (!otherChild.getChildren().isEmpty()) { que.add( Pair.create(thisChild, otherChild) ); } } } } private synchronized void initChildList() { if ( childrenInitialized ) { return; } children = new ArrayList( 10 ); childNames = new TreeMap( new jellyfish.common.CaseInsensitiveStringComparator() ); childrenInitialized = true; } /* * If true, means this is a root node. */ public boolean isRoot() { assert(actualParent!=null); return false; } /* * If true, means this node is a SYS-INC node (i.e. space holder nodes created by the system) */ public boolean isSysInc() { return false; } /* * If true, means this node is not a system node i.e. root or SYS-INC */ public boolean isNormalNode() { return true; } public Set<String> getChildAliasSet() { return childNames.keySet(); } public List<AliasTreeNode> getChildrenWithAlias( String alias ) { return childNames.get( alias ); } public List<AliasTreeNode> getChildren() { if ( !childrenInitialized ) { return Collections.EMPTY_LIST; } else { return Collections.unmodifiableList( children ); } } public String getName() { return name; } public AliasTreeNode getActualParent() { return actualParent; } public AliasTreeNode getNormalParent() { return normalParent; } public int getIndex() { return index; } public AliasTreeNode getRoot() { if ( normalParent != null ) { return normalParent.getRoot(); } else { return this; } } public void setParent( AliasTreeNode parent ) { if ( this.normalParent != null ) { this.normalParent.unregisterChild( this ); } if ( this.actualParent != null && this.actualParent!=this.normalParent ) { this.actualParent.unregisterChild( this ); } this.actualParent = parent; this.normalParent = computeNormalParent( parent ); if ( this.normalParent != null ) { this.index = this.normalParent.registerChild( this ); } if ( this.actualParent != null && this.actualParent!=this.normalParent ) { this.actualParent.registerChild( this ); } this.completeName = computeCompleteName(); } private AliasTreeNode computeNormalParent(AliasTreeNode actualParent) { AliasTreeNode _nonSysIncParent = actualParent; if (!_nonSysIncParent.isRoot() && _nonSysIncParent.isSysInc()) { _nonSysIncParent = _nonSysIncParent.getNormalParent(); } return _nonSysIncParent; } /* * Registers a child and returns the index of the child */ private int registerChild( AliasTreeNode child ) { if (child.isSysInc()) return 0; if ( !childrenInitialized ) { initChildList(); } children.add( child ); List<AliasTreeNode> aliasTreeNodes = childNames.get( child.name ); if ( aliasTreeNodes == null ) { aliasTreeNodes = new ArrayList<AliasTreeNode>( 1 ); childNames.put( child.name, aliasTreeNodes ); } synchronized ( aliasTreeNodes ){ int childIndex = aliasTreeNodes.size(); aliasTreeNodes.add( child ); return childIndex; } } private void unregisterChild( AliasTreeNode child ) { assert children != null; assert childNames != null; children.remove( child ); childNames.remove( child.name ); } public List<AliasTreeNode> findChild( String name ) { if ( name.isEmpty() || childNames == null ) { return Collections.EMPTY_LIST; } else { return childNames.get( name ); } } public String getIndexedName() { if ( normalParent != null && normalParent.findChild( name ).size() > 1 ) { return name + "[" + index + "]"; } else { return name; } } private synchronized String[] computeCompleteName() { int len = 1; String parentCompleteName[] = null; if ( normalParent != null ) { parentCompleteName = normalParent.getCompleteName(); len = parentCompleteName.length + 1; } String[] myCompleteName = new String[len]; if ( parentCompleteName != null ) { for ( int i = 0; i < parentCompleteName.length; ++i ) { myCompleteName[i] = parentCompleteName[i]; } } myCompleteName[myCompleteName.length - 1] = name; return myCompleteName; } public String[] getCompleteName() { return completeName; } public boolean hasCompleteName( String completeName ) { String namePortions[] = completeName.split( "\\." ); String thisName[] = getCompleteName(); if ( namePortions.length != thisName.length ) { return false; } for ( int i = 0; i < thisName.length; ++i ) { if ( !namePortions[i].equalsIgnoreCase( thisName[i] ) ) { return false; } } return true; } private AliasTreeNode internGetSpecificAlias( String[] completeName, int index ) { AliasTreeNode selectedChild = null; List<String> indexStrs = new ArrayList<String>( 1 ); ALIAS_EXTRACTOR.extractMatchingGroups( completeName[index], indexStrs ); if ( indexStrs.size() <= 1 ) { List<AliasTreeNode> foundChildren = findChild( indexStrs.get( 0 ).trim() ); if ( !foundChildren.isEmpty() ) { selectedChild = foundChildren.get( 0 ); } } else { List<AliasTreeNode> foundChildren = findChild( indexStrs.get( 0 ).trim() ); int i = Integer.parseInt( indexStrs.get( 1 ).trim() ); if ( i >= 0 && i < foundChildren.size() ) { selectedChild = foundChildren.get( i ); } } if ( selectedChild == null ) { return null; } if ( index == completeName.length - 1 ) { return selectedChild; } else { return selectedChild.internGetSpecificAlias( completeName, index + 1 ); } } public AliasTreeNode getSpecificAlias( String[] completeName ) { return internGetSpecificAlias( completeName, 0 ); } private void internGetGeneralAlias( String[] completeName, int index, List<AliasTreeNode> output ) { String indexedName = completeName[index]; List<AliasTreeNode> nodes = childNames.get( indexedName ); if ( index == completeName.length - 1 ) { output.addAll( nodes ); } else { for ( AliasTreeNode node : nodes ) { node.internGetGeneralAlias( completeName, index + 1, output ); } } } public List<AliasTreeNode> getAliases( String[] generalCompleteName ) { List<AliasTreeNode> output = new ArrayList<AliasTreeNode>(); internGetGeneralAlias( generalCompleteName, 0, output ); return output; } @Override public String toString() { return (normalParent == null ? "/" : "") + Arrays.toString( getCompleteName() ) + ":" + hashCode; } @Override public boolean equals( Object obj ) { if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } final AliasTreeNode other = (AliasTreeNode) obj; if ( this.hashCode != other.hashCode ) { return false; } return true; } @Override final public int hashCode() { return this.hashCode; } public int getTreeSize() { int treeSize = 1; for ( AliasTreeNode v : children ) { treeSize += v.getTreeSize(); } return treeSize; } private void internGetAllSubTreeNodes( List<AliasTreeNode> nodes ) { nodes.add( this ); if ( children != null ) { for ( AliasTreeNode node : children ) { node.internGetAllSubTreeNodes( nodes ); } } } private void internGetTreeLeftNodes( List<AliasTreeNode> nodes ) { if ( this.normalParent != null ) { this.normalParent.internGetTreeLeftNodes( nodes ); for ( AliasTreeNode node : this.normalParent.children ) { if ( node.equals( this ) ) { break; } node.internGetAllSubTreeNodes( nodes ); } } nodes.add( this ); } // returns all nodes that lie to the left of this node... // e.g. <Root> // <a> <b> <c> // <d> <e> <f> <g> <h> // if this node is node b, then the returned nodes // will be: Root, a, d, e, b, f public List<AliasTreeNode> getTreeLeftNodes() { if ( this.normalParent == null ) { return Collections.EMPTY_LIST; } List<AliasTreeNode> nodes = new ArrayList<AliasTreeNode>(); internGetTreeLeftNodes( nodes ); return nodes; } private void internGetAllSubTreeLeafNodes( List<AliasTreeNode> nodes ) { if ( children != null && !children.isEmpty() ) { for ( AliasTreeNode node : children ) { node.internGetAllSubTreeNodes( nodes ); } } else { nodes.add( this ); } } private void internGetTreeLeftLeafNodes( List<AliasTreeNode> nodes ) { if ( this.normalParent != null ) { this.normalParent.internGetTreeLeftLeafNodes( nodes ); for ( AliasTreeNode node : this.normalParent.children ) { if ( node.equals( this ) ) { break; } node.internGetAllSubTreeLeafNodes( nodes ); } } if ( this.children == null || this.children.isEmpty() ) { nodes.add( this ); } } // returns all nodes that lie to the left of this node... // e.g. <Root> // <a> <b> <c> // <d> <e> <f> <g> <h> // if this node is node b, then the returned nodes // will be: d, e, f public List<AliasTreeNode> getTreeLeftLeafNodes() { if ( this.normalParent == null ) { return Collections.EMPTY_LIST; } List<AliasTreeNode> nodes = new ArrayList<AliasTreeNode>(); internGetTreeLeftLeafNodes( nodes ); return nodes; } public int compareTo( AliasTreeNode other ) { String[] thisName = this.getCompleteName(); String[] otherName = other.getCompleteName(); int i = thisName.length - otherName.length; if ( i == 0 ) { for ( int j = 0; j < thisName.length; ++j ) { i = thisName[j].compareTo( otherName[j] ); if ( i != 0 ) { break; } } } return i; } }
[ "Umran@.(none)" ]
Umran@.(none)
0ec61d9104afdc537030a4f0a9556e739c91c9a4
eeaeddeab4775a1742dba5c8898686fd38caf669
/base/base-repository/src/main/java/com/zsw/peprsistence/entity/Ticket.java
33333b35000902e4ba046516bdc0758b69576ef6
[ "Apache-2.0" ]
permissive
MasterOogwayis/spring
8250dddd5d6ee9730c8aec4a7aeab1b80c3bf750
c9210e8d3533982faa3e7b89885fd4c54f27318e
refs/heads/master
2023-07-23T09:49:37.930908
2023-07-21T03:04:27
2023-07-21T03:04:27
89,329,352
0
0
Apache-2.0
2023-06-14T22:51:13
2017-04-25T07:13:03
Java
UTF-8
Java
false
false
887
java
package com.zsw.peprsistence.entity; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.io.Serial; import java.io.Serializable; /** * This is a demo. * * @author ZhangShaowei on 2018/3/23 13:17 **/ @Getter @Setter @Entity @Table(name = "TICKET") public class Ticket implements Serializable { @Serial private static final long serialVersionUID = 8999738356793348139L; /** * */ @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") @Column(name = "ID", unique = true, nullable = false, length = 32) private String id; /** * */ @Column(name = "NUMBER", nullable = false, columnDefinition = "INT(11) DEFAULT 0") private Integer number; @Column private Long customerId; }
49830eecfbc9d6ed373f0133d01b62fab1888c38
462cdaa99b3f76e4af3d428e3010946dfd8b83f0
/Projects/Project3/src/main/java/Project3.java
84998bdbf063a5dc4937b0dc5c3b21d57b99ae45
[]
no_license
Stoozy/Java_212
c420e2cc8cbd85e696c1d40d5082a6bd30c760ed
e5b2e3735790ee8cfeaed23f8e7e47a35e4975e3
refs/heads/master
2021-01-03T03:22:25.014307
2020-04-29T00:34:04
2020-04-29T00:34:04
239,900,993
0
0
null
null
null
null
UTF-8
Java
false
false
282
java
/** * @author Khademul Mahin * * Simply instantiate a clock gui. * The rest is handled by the FileMenuHandler class */ import java.util.StringTokenizer; public class Project3 { public static void main(String[] args){ ClockGUI gui = new ClockGUI(); } }
8894f75129be5cebc3f90b1e3e92e598fc7a5ab7
f30a59657e9b85d2c6e38a7642ed6ba8acc7bd5f
/src/main/java/utils/HibernateSessionFactoryUtil.java
ee7011e8c83b17916926003da916d8e03c2f8fd9
[]
no_license
MariaDashkova/MovieMT
06ffde9fdcebfe57fe8ea4838c3cc0603fea01c1
ae29a2220417aa8b43969f2d69bb4be1a2aafd72
refs/heads/master
2020-04-24T15:12:59.460713
2019-02-25T12:28:54
2019-02-25T12:28:54
172,057,034
1
0
null
null
null
null
UTF-8
Java
false
false
1,269
java
package utils; import botBase.*; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateSessionFactoryUtil { private static SessionFactory sessionFactory; private HibernateSessionFactoryUtil() {} public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { Configuration configuration = new Configuration().configure(); configuration.addAnnotatedClass(CustomersEntity.class); configuration.addAnnotatedClass(PostEntity.class); configuration.addAnnotatedClass(FollowerActorEntity.class); configuration.addAnnotatedClass(FollowerAnalystEntity.class); configuration.addAnnotatedClass(FollowerStudioEntity.class); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); sessionFactory = configuration.buildSessionFactory(builder.build()); } catch (Exception e) { System.out.println("Исключение!" + e); } } return sessionFactory; } }
e4dbc9f90ace7f9e6e7dc3ed95088b72b3ac0426
544845e239c8f84e9662f7dab78f46e5a0e70291
/micro-invoked/src/main/java/com/xs/micro/invoked/config/prop/sub/SmsConfig.java
546d7918f15cdaf02cb2f058e4e9729f6180aff1
[]
no_license
topwqp/micro-pro
dfded7b0dac55befc4f6888e1c2bac7f37eb25f9
066c3dcdcd45e81b35c70842d5c7efe256e8fc3c
refs/heads/main
2023-05-13T23:03:42.310384
2021-05-28T03:49:22
2021-05-28T03:49:22
371,564,497
0
0
null
null
null
null
UTF-8
Java
false
false
1,719
java
package com.xs.micro.invoked.config.prop.sub; /** * @author wangqiupeng * @description: 短信服务配置 * @date 2019-10-21 2:57 下午 */ public class SmsConfig { /** * 国家代码 */ private String countryCode; /** * 账号 **/ private String account; /** * 密码 */ private String password; /** * 发送短信Url */ private String sendSmsUrl; /** * 群发短信Url */ private String batchSendSmsUrl; public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSendSmsUrl() { return sendSmsUrl; } public void setSendSmsUrl(String sendSmsUrl) { this.sendSmsUrl = sendSmsUrl; } public String getBatchSendSmsUrl() { return batchSendSmsUrl; } public void setBatchSendSmsUrl(String batchSendSmsUrl) { this.batchSendSmsUrl = batchSendSmsUrl; } @Override public String toString() { return "SmsConfig{" + "countryCode='" + countryCode + '\'' + ", account='" + account + '\'' + ", password='" + password + '\'' + ", sendSmsUrl='" + sendSmsUrl + '\'' + ", batchSendSmsUrl='" + batchSendSmsUrl + '\'' + '}'; } }
466bf15107099dcf70559a088cbee5c93dad3421
c32ea8e76a54929d62d53ca5b0917731fd6f459b
/src/com/zyyknx/android/models/VersionInfo.java
82a108f531652dcbe9a9095aea2a6c52966451f8
[]
no_license
shuishang/KNX
c77ab2fc6e1ea9edd9edc8232bcff1708ccc5fd4
bc58eb37199884ac7331adea546eef7746e6efdd
refs/heads/master
2020-12-03T03:55:38.134343
2016-01-31T07:11:18
2016-01-31T07:11:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
859
java
package com.zyyknx.android.models; public class VersionInfo { private String version; private String url; private String apkName; private String appName; private String description; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAPKName() { return apkName; } public void setAPKName(String apkName) { this.apkName = apkName; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
77dbb1f37cf7936b1d8c305864d318e13d19559b
7e14a944b5e26a919d9bd286a4c7f62cf42a4ca7
/RM-EMPRESARIAL-ejb/src/main/java/com/rm/empresarial/dao/FuncionDao.java
2febca3f936ee2e4f0003a7026d1d3ce0a3b88c7
[]
no_license
bryan1090/RegistroPropiedad
7bcca20dbb1a67da97c85716b67d516916aee3fa
182406c840187a6cc31458f38522f717cc34e258
refs/heads/master
2022-07-07T08:06:20.251959
2020-01-02T03:02:34
2020-01-02T03:02:34
231,295,897
0
0
null
2022-06-30T20:22:05
2020-01-02T02:50:13
Java
UTF-8
Java
false
false
1,947
java
/* * 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 com.rm.empresarial.dao; import com.rm.empresarial.excepciones.ServicioExcepcion; import com.rm.empresarial.generico.Generico; import com.rm.empresarial.modelo.Funcion; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.LocalBean; import javax.ejb.Stateless; /** * * @author Bryan_Mora */ @LocalBean @Stateless public class FuncionDao extends Generico<Funcion> implements Serializable { public List<Funcion> listarTodo() throws ServicioExcepcion { return listarPorConsultaJpaNombrada(Funcion.LISTAR_TODO, null); } public Funcion buscarPorNombrePagina(String nombrePagina) throws ServicioExcepcion { try { Map<String, Object> parametros = new HashMap<>(); parametros.put("funPrograma", nombrePagina); return obtenerPorConsultaJpaNombrada(Funcion.ENCONTRAR_POR_PROGRAMA, parametros); } catch (Exception e) { return null; } } public boolean validarIngresoCrear(Long rolId, String funPrograma) throws ServicioExcepcion{ Map<String, Object> parametros = new HashMap<>(); parametros.put("rolId", rolId); parametros.put("funPrograma", funPrograma); return listarPorConsultaJpaNombrada(Funcion.VALIDAR_INGRESO, parametros).isEmpty(); } public boolean validarIngresoEditar(Long funId, Long rolId, String funPrograma) throws ServicioExcepcion { Map<String, Object> parametros = new HashMap<>(); parametros.put("funId", funId); parametros.put("rolId", rolId); parametros.put("funPrograma", funPrograma); return listarPorConsultaJpaNombrada(Funcion.VALIDAR_INGRESO_EDITAR, parametros).isEmpty(); } }
d3a0d7a8dd2a877071ceaa23101b5a95aab9c5c8
82123a08a71036bdd50229662e4ad0db08d1ba27
/Beginner/maximum.java
c0f42d5f05710ac0c8ad3312431f269bc6ff6645
[]
no_license
Meenaraju/Codekata
4a15ba24ba7751d0bc98e6516a401d2c05c9071c
082c58bcd8011329b1a6c2e89a31901633b9d796
refs/heads/master
2021-04-28T04:10:04.107512
2020-02-01T04:48:33
2020-02-01T04:48:33
122,156,612
0
0
null
null
null
null
UTF-8
Java
false
false
730
java
import java.util.*; import java.lang.*; import java.io.*; import java.util.Scanner; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); try{ int n = Integer.parseInt(s); if(n>=1 && n<=100000){ int a[] = new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } int max = a[0]; for(int i=0;i<n;i++){ if(a[i]>max) { max = a[i]; } } System.out.print(max); } else{ System.out.println("size exceeds"); } } catch(NumberFormatException nef){ System.out.println("invalid input"); } } }
b5abfdb67f8d1b5978b1f7c869b2d21c4451feab
240c3ba91d3dec2dcab48af67a5677a71d82da65
/Lanqiao/src/JavaA/Candy.java
07c9b6dec1d56a5b58e34a110eb8ee834b43d2d3
[]
no_license
LZCai/---
c4d0b9d8939f365222384a045ea39312b851b18b
284c3a99cdb1b0479d54c4355a6c276a491f111c
refs/heads/master
2020-03-19T04:06:34.213988
2018-06-02T07:36:51
2018-06-02T07:36:51
135,795,743
1
0
null
null
null
null
UTF-8
Java
false
false
1,543
java
package JavaA; import java.util.Scanner; /** * @author 64621 -- lzcai * @time 2018年3月16日 下午4:07:40 * */ public class Candy { public static void main(String[] args){ Scanner scan = new Scanner(System.in) ; int student_num = scan.nextInt() ; int[] candy_num = new int[student_num] ; int sum = 0 ; for(int i=0 ; i<student_num ; i++){ candy_num[i] = scan.nextInt() ; sum += candy_num[i] ; } int add_num = 0 ; while(isAverage(candy_num, sum+add_num)){ for(int i=0 ; i<student_num ; i++){ if(candy_num[i]%2 != 0){ candy_num[i] += 1 ; add_num ++ ; } } if(isAverage(candy_num, sum+add_num)){ int last_num = candy_num[student_num-1] ; for(int i=student_num-1 ; i>=0 ; i--){ if(i == 0){ candy_num[i] = (candy_num[i]+last_num)/2 ; }else{ candy_num[i] = (candy_num[i]+candy_num[i-1])/2 ; } } } } System.out.println(add_num); scan.close(); } public static boolean isAverage(int[] candy_num, int sum){ int mod = sum%candy_num.length ; int student_num = candy_num.length ; if(mod == 0){ int count = 0 ; for(int i=0 ; i<student_num-1 ; i++){ if(candy_num[i] != candy_num[i+1]){ break ; }else{ count ++ ; } } if(count == student_num -1){ return false ; } } return true ; } }
a13a22475746dfbd02673d3322f354fa979d194a
ca3d62f7564eb559f5ab5ec0823e984fd4564ec9
/Practica4/src/practica4/Lienzo.java
a38c77890f8b952cdd822657245c18332346fcb3
[]
no_license
msmaldonado/SistemasMultimedia
7bc3fd30273a16ea11960b428476f32d6c1a80ae
738bf0b121a5005b768731da34800a56a6aac76d
refs/heads/master
2021-01-01T05:23:45.242846
2016-09-19T07:03:27
2016-09-19T07:03:27
57,397,070
0
0
null
null
null
null
UTF-8
Java
false
false
6,611
java
/* * 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 practica4; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; /** * * @author Migue */ public class Lienzo extends javax.swing.JPanel { Point puntoInicial, puntoFinal;//Declaramos los dos puntos con los que dibujar private Color color ;//El color seleccionado boolean relleno ;//boolenano para saber si esta relleno String formaDibujo ;//Forma del dibujo /** * Creates new form Lienzo */ public Lienzo() {//Constructor de lienzo this.puntoInicial = null; this.puntoFinal = null ; this.relleno = false; this.formaDibujo = "Punto";//iniciamos a color negro this.color = Color.black ;//iniciamos a negro initComponents(); } /* Métodos get y set para cambiar las variables de Lienzo*/ public String getForma(){ return formaDibujo; } public void setForma(String nuevaforma) { this.formaDibujo = nuevaforma; } public Color getColor() { return color; } public void setColor(Color nuevoColor) { this.color = nuevoColor; } public boolean isRelleno() { return relleno; } public void setRelleno(boolean nuevorelleno) { this.relleno = nuevorelleno; } /*Metodo limpiarVentana que pone a null los dos puntos*/ public void LimpiarVentana(){ this.puntoInicial = null; this.puntoFinal = null ; } @Override public void paint(Graphics g){ super.paint (g); g.setColor(color); /*Vemos si los puntos estan a null para no pintar nada*/ if (puntoInicial == null && puntoFinal == null){ this.repaint(); } else{ //Si los puntos tienen algun valor switch(formaDibujo){//Comprobamos que forma hay que dibujar y pintamos case "Punto": g.fillOval(puntoInicial.x, puntoInicial.y, 6, 6); break; case "Linea": g.drawLine(puntoInicial.x,puntoInicial.y,puntoFinal.x, puntoFinal.y); break; case "Rectangulo": if(relleno) g.fillRect( Math.min(puntoInicial.x, puntoFinal.x), Math.min(puntoInicial.y, puntoFinal.y), Math.abs( puntoFinal.x - puntoInicial.x), Math.abs(puntoFinal.y - puntoInicial.y )); else g.drawRect( Math.min(puntoInicial.x, puntoFinal.x), Math.min(puntoInicial.y, puntoFinal.y), Math.abs( puntoFinal.x - puntoInicial.x), Math.abs(puntoFinal.y - puntoInicial.y )); break; case"Ovalo": if (relleno) g.fillOval(Math.min(puntoInicial.x, puntoFinal.x), Math.min(puntoInicial.y, puntoFinal.y), Math.abs( puntoFinal.x- puntoInicial.x ), Math.abs( puntoFinal.y- puntoInicial.y)); else g.drawOval(Math.min(puntoInicial.x, puntoFinal.x), Math.min(puntoInicial.y, puntoFinal.y), Math.abs( puntoFinal.x- puntoInicial.x ), Math.abs( puntoFinal.y- puntoInicial.y)); break; } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { formMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { formMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { formMouseReleased(evt); } }); addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { formMouseDragged(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked // TODO add your handling code here: puntoInicial=evt.getPoint(); this.repaint(); }//GEN-LAST:event_formMouseClicked private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged // TODO add your handling code here: puntoFinal=evt.getPoint(); this.repaint(); }//GEN-LAST:event_formMouseDragged private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed // TODO add your handling code here: puntoInicial=evt.getPoint(); }//GEN-LAST:event_formMousePressed private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased // TODO add your handling code here: puntoFinal=evt.getPoint(); this.repaint(); }//GEN-LAST:event_formMouseReleased /* private void formMouseClicked(java.awt.event.MouseEvent evt) { // En nuestro caso, utilizamos mouseClicked para dibujar puntos } */ // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }
6004e3e96f2096414884381ede61cc4a6863d091
d2cb1f4f186238ed3075c2748552e9325763a1cb
/methods_all/nonstatic_methods/javax_swing_plaf_metal_DefaultMetalTheme_getMenuTextFont.java
0e416eae42549f8d43aa25675d2cf9dc313e5f25
[]
no_license
Adabot1/data
9e5c64021261bf181b51b4141aab2e2877b9054a
352b77eaebd8efdb4d343b642c71cdbfec35054e
refs/heads/master
2020-05-16T14:22:19.491115
2019-05-25T04:35:00
2019-05-25T04:35:00
183,001,929
4
0
null
null
null
null
UTF-8
Java
false
false
213
java
class javax_swing_plaf_metal_DefaultMetalTheme_getMenuTextFont{ public static void function() {javax.swing.plaf.metal.DefaultMetalTheme obj = new javax.swing.plaf.metal.DefaultMetalTheme();obj.getMenuTextFont();}}
c43f1a254dc2c1cd33b7c529009e0078458d3f4f
70e7f154b1af116a1743109b004d8a23572a3a6f
/src/main/java/com/xxl/job/admin/service/XxlJobService.java
2256f138ebe55f8c13403d05bbc8ea3f6f55ffa7
[]
no_license
wfeng/xxl-job-admin
93ecbf80333d32106ede1c5a5e0291d7748d4bde
99be498b0a60aafa761c0948f95e31c9edadad48
refs/heads/master
2023-04-29T20:52:03.685727
2020-10-14T04:09:17
2020-10-14T04:09:17
136,106,360
1
2
null
2023-04-25T05:41:22
2018-06-05T02:09:22
Java
UTF-8
Java
false
false
1,651
java
package com.xxl.job.admin.service; import com.xxl.job.admin.core.model.XxlJobInfo; import com.xxl.job.core.biz.model.ReturnT; import java.util.Date; import java.util.Map; /** * core job action for xxl-job * * @author xuxueli 2016-5-28 15:30:33 */ public interface XxlJobService { /** * page list * * @param start * @param length * @param jobGroup * @param jobDesc * @param executorHandler * @param filterTime * @return */ public Map<String, Object> pageList(int start, int length, int jobGroup, String jobDesc, String executorHandler, String filterTime); /** * add job * * @param jobInfo * @return */ public ReturnT<String> add(XxlJobInfo jobInfo); /** * update job * * @param jobInfo * @return */ public ReturnT<String> update(XxlJobInfo jobInfo); /** * remove job * * @param id * @return */ public ReturnT<String> remove(int id); /** * pause job * * @param id * @return */ public ReturnT<String> pause(int id); /** * resume job * * @param id * @return */ public ReturnT<String> resume(int id); /** * trigger job * * @param id * @return */ public ReturnT<String> triggerJob(int id); /** * dashboard info * * @return */ public Map<String, Object> dashboardInfo(); /** * chart info * * @param startDate * @param endDate * @return */ public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate); }
40eefdef255d5d64c92727622e0f230ace34965e
88242b78396f7c5b2d3c348ae6ca8b39330ea69c
/src/main/java/com/bianjp/blog/controller/LoginController.java
919184517938d1ecfacda7e4f8cb122ad5341e7a
[ "MIT" ]
permissive
plaidshirtakos/blog-spring
b4b4efe348282f8e1c5bcde8b7c88122ad7d81b6
5de42e959f932e1292758176d4e6d25b0d5ba061
refs/heads/master
2020-12-13T11:14:36.978097
2020-01-16T19:57:51
2020-01-16T19:57:51
234,400,284
0
0
MIT
2020-01-16T19:56:53
2020-01-16T19:56:52
null
UTF-8
Java
false
false
476
java
package com.bianjp.blog.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class LoginController { @GetMapping("login") public String loginPage(Model model, @RequestParam(required = false) String error) { model.addAttribute("hasError", error != null); return "login"; } }
5be597412ada3f941161c8820042fc99dffeacfb
91fc1de3165a91a79124f41af538239d0d676ab4
/task6/src/com/itacademy/java/oop/basics/Vehicle.java
f0bb9eedf7c1a4dd3b4fcdbbb5ce3ed7c4a35f64
[ "MIT" ]
permissive
MadRavingMan/oop_basics1
ed2fa40bbebf48c26262482246c720974ab8f046
ce3696241e147a520ccf3acee363e2b19aeac2fd
refs/heads/master
2023-02-26T01:35:21.577395
2021-02-04T11:53:17
2021-02-04T11:53:17
335,939,069
0
0
null
null
null
null
UTF-8
Java
false
false
795
java
package com.itacademy.java.oop.basics; public class Vehicle { private String name; private String brand; private int fuel; private int consumption; public Vehicle() { } public Vehicle(String name, String brang, int fuel, int consumption) { this.name = name; this.brand = brang; this.fuel = fuel; this.consumption = consumption; } public int getFuel() { return fuel; } public int getConsumption() { return consumption; } @Override public String toString() { return "Vehicle{" + "name='" + name + '\'' + ", brang='" + brand + '\'' + ", fuel=" + fuel + ", consumption=" + consumption + '}'; } }
5a6f81a88a2fd77aaa7d1f033f381a29fc3f9639
73f7fd7cf33df5152d1c4d974cedfc9f4b8ad60d
/src/main/java/com/netcracker/airlines/mvc/TicketController.java
5e7ae16a48dc7c82b2c0221c66428f1f923c7daa
[]
no_license
andreyermilovv/NetCrackerProject
d7ced9ee02b26d7964bbcfdc60e244c75032c0e0
520823fe2432958d0d89b25078a37cea5f25ebb0
refs/heads/main
2023-04-10T10:53:32.312878
2021-04-21T17:29:31
2021-04-21T17:29:31
352,538,981
1
0
null
2021-05-12T15:26:31
2021-03-29T06:29:03
Java
UTF-8
Java
false
false
923
java
package com.netcracker.airlines.mvc; import com.netcracker.airlines.service.FlightService; import com.netcracker.airlines.service.TicketService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequiredArgsConstructor @RequestMapping("flights/{flight}/tickets") public class TicketController { private final TicketService ticketService; private final FlightService flightService; @GetMapping public String get(@PathVariable Long flight, Model model){ model.addAttribute("flight", flight); model.addAttribute("tickets", ticketService.findByFlight(flightService.getOne(flight))); return "tickets"; } }
e91770930878d16406dc2dc0c903eba9532b5d70
c28af0352edaec3549808fcbebc11927a20729bb
/lightadapter/src/main/java/com/zfy/lxadapter/helper/query/LxQuerySimple.java
2d64570523598bd15c30553af21ebef8cba9b680
[ "Apache-2.0" ]
permissive
chendongMarch/LxAdapter
2dfff554529474d2ca3b574a9da51c5a570a12a4
d72c8bc1871636b60585d230bf8fa1bdfb559ebd
refs/heads/master
2022-02-25T17:33:08.195363
2019-10-31T08:54:33
2019-10-31T08:54:33
53,908,703
10
2
null
null
null
null
UTF-8
Java
false
false
5,937
java
package com.zfy.lxadapter.helper.query; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.zfy.lxadapter.Lx; import com.zfy.lxadapter.LxList; import com.zfy.lxadapter.data.Idable; import com.zfy.lxadapter.data.LxModel; import com.zfy.lxadapter.function._Consumer; import com.zfy.lxadapter.function._LoopPredicate; import com.zfy.lxadapter.function._Predicate; import com.zfy.lxadapter.helper.LxSource; import java.util.ArrayList; import java.util.List; /** * CreateAt : 2019-10-18 * Describe : 一个类型属于一个 class,一个 class 可能有多个 type * * @author chendong */ public class LxQuerySimple { private LxList list; public LxQuerySimple(LxList list) { this.list = list; } @Nullable public <E> E findOneById(Class<E> clazz, Object id) { if (id == null) { return null; } E result = null; for (LxModel t : list) { if (!t.unpack().getClass().equals(clazz)) { continue; } E unpack = t.unpack(); if (unpack instanceof Idable && id.equals(((Idable) unpack).getObjId())) { result = unpack; break; } } return result; } @Nullable public <E> E findOne(Class<E> clazz, _Predicate<E> test) { List<E> list = find(clazz, test); return list.isEmpty() ? null : list.get(0); } @Nullable public <E> E findOne(Class<E> clazz, int type) { List<E> list = find(clazz, type); return list.isEmpty() ? null : list.get(0); } @NonNull public <E> List<E> find(Class<E> clazz, _Predicate<E> test) { List<E> l = new ArrayList<>(); for (LxModel t : list) { if (!t.unpack().getClass().equals(clazz)) { continue; } E unpack = t.unpack(); if (test.test(unpack)) { l.add(unpack); } } return l; } @NonNull public <E> List<E> find(Class<E> clazz, int type) { List<E> l = new ArrayList<>(); for (LxModel t : list) { if (!t.unpack().getClass().equals(clazz)) { continue; } E unpack = t.unpack(); if (t.getItemType() == type) { l.add(unpack); } } return l; } public <E> void updateSet4Type(Class<E> clazz, int type, _Consumer<E> consumer) { list.updateSet(data -> data.getItemType() == type, new ClazzConsumer<>(clazz, consumer)); } public void updateRemove4Type(int type) { list.updateRemove(data -> data.getItemType() == type); } public <E> void updateSet(Class<E> clazz, _Predicate<E> predicate, _Consumer<E> consumer) { list.updateSet(new ClazzPredicate<>(clazz, predicate), new ClazzConsumer<>(clazz, consumer)); } public <E> void updateSetX(Class<E> clazz, _LoopPredicate<E> predicate, _Consumer<E> consumer) { list.updateSetX(new ClazzLoopPredicate<>(clazz, predicate), new ClazzConsumer<>(clazz, consumer)); } public <E> void updateSet(Class<E> clazz, int index, _Consumer<E> consumer) { list.updateSet(index, new ClazzConsumer<>(clazz, consumer)); } public <E> void updateSet(Class<E> clazz, LxModel model, _Consumer<E> consumer) { list.updateSet(model, new ClazzConsumer<>(clazz, consumer)); } public <E> void updateRemove(Class<E> clazz, _Predicate<E> predicate) { list.updateRemove(new ClazzPredicate<>(clazz, predicate)); } public <E> void updateRemoveX(Class<E> clazz, _LoopPredicate<E> predicate) { list.updateRemoveX(new ClazzLoopPredicate<>(clazz, predicate)); } public <E> void updateRemoveLast(Class<E> clazz, _Predicate<E> predicate) { list.updateRemove(new ClazzPredicate<>(clazz, predicate)); } public <E> void updateRemoveLastX(Class<E> clazz, _LoopPredicate<E> predicate) { list.updateRemoveX(new ClazzLoopPredicate<>(clazz, predicate)); } public boolean updateAdd(LxSource source) { return list.updateAddAll(source.asModels()); } public boolean updateAdd(int index, LxSource source) { return list.updateAddAll(index, source.asModels()); } static class ClazzPredicate<E> implements _Predicate<LxModel> { private Class clazz; private _Predicate<E> predicate; ClazzPredicate(Class clazz, _Predicate<E> predicate) { this.clazz = clazz; this.predicate = predicate; } @Override public boolean test(LxModel data) { if (!clazz.equals(data.unpack().getClass())) { return false; } return predicate.test(data.unpack()); } } static class ClazzLoopPredicate<E> implements _LoopPredicate<LxModel> { private Class clazz; private _LoopPredicate<E> predicate; ClazzLoopPredicate(Class clazz, _LoopPredicate<E> predicate) { this.clazz = clazz; this.predicate = predicate; } @Override public int test(LxModel data) { if (!clazz.equals(data.unpack().getClass())) { return Lx.Loop.FALSE_NOT_BREAK; } return predicate.test(data.unpack()); } } static class ClazzConsumer<E> implements _Consumer<LxModel> { private Class clazz; private _Consumer<E> consumer; ClazzConsumer(Class clazz, _Consumer<E> consumer) { this.clazz = clazz; this.consumer = consumer; } @Override public void accept(LxModel data) { if (!clazz.equals(data.unpack().getClass())) { return; } consumer.accept(data.unpack()); } } }
1bac19567f3edbf0bdcd8d998c221f885643fe52
c6ef481c008c027ae08ab6ad3f39b3321a5c9196
/src/main/java/net/titanscraft/launchercore/install/user/User.java
ee4bdddc5f8f4e1f9181d1406b5dea3f259a009d
[]
no_license
RoboGameplays/LauncherCore
7b42cc8a0bf3b6030f89a014cede0eb36f260594
5fe6e6cf7df2934a2ddf2a622b0a3d0ed4581214
refs/heads/master
2016-08-08T05:57:00.258818
2015-02-16T00:10:32
2015-02-16T00:10:32
21,021,333
0
0
null
null
null
null
UTF-8
Java
false
false
2,266
java
package net.titanscraft.launchercore.install.user; import com.google.gson.JsonObject; import net.titanscraft.launchercore.auth.AuthResponse; import net.titanscraft.launchercore.auth.Profile; import net.titanscraft.launchercore.util.Utils; public class User { private String username; private String accessToken; private String clientToken; private String displayName; private Profile profile; private JsonObject userProperties; private transient boolean isOffline; public User() { isOffline = false; } //This constructor is used to build a user for offline mode public User(String username) { this.username = username; this.displayName = username; this.accessToken = "0"; this.clientToken = "0"; this.profile = new Profile("0", ""); this.isOffline = true; this.userProperties = Utils.getGson().fromJson("{}", JsonObject.class); } public User(String username, AuthResponse response) { this.isOffline = false; this.username = username; this.accessToken = response.getAccessToken(); this.clientToken = response.getClientToken(); this.displayName = response.getSelectedProfile().getName(); this.profile = response.getSelectedProfile(); if (response.getUser() == null) { this.userProperties = Utils.getGson().fromJson("{}", JsonObject.class); } else { this.userProperties = response.getUser().getUserProperties(); } } public String getUsername() { return username; } public String getAccessToken() { return accessToken; } public String getClientToken() { return clientToken; } public String getDisplayName() { return displayName; } public Profile getProfile() { return profile; } public boolean isOffline() { return isOffline; } public String getSessionId() { return "token:" + accessToken + ":" + profile.getId(); } public void rotateAccessToken(String newToken) { this.accessToken = newToken; } public String getUserPropertiesAsJson() { return Utils.getGson().toJson(this.userProperties); } }
8159f9ff0323759ffe21b989ac33533f331a846b
e155d45a45fa9c07cd5af5c4702c1b47afdff1ac
/example/android/app/src/main/java/com/example/mobilesoc_font_awesome_example/MainActivity.java
ee167bc5b9dd38c80723aba4ee4753653cce3abc
[]
no_license
sadiga80/mobilesoc_font_awesome
6c000676cae26ddf5785aef3e480ce0552cdfc95
b20889cee17549d27eacfb955479ed0030662435
refs/heads/master
2020-07-06T21:01:03.608784
2019-05-09T04:25:30
2019-05-09T04:25:30
203,137,586
1
0
null
2019-08-19T09:07:22
2019-08-19T09:07:21
null
UTF-8
Java
false
false
387
java
package com.example.mobilesoc_font_awesome_example; import android.os.Bundle; import io.flutter.app.FlutterActivity; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); } }
5426c8e39d617311baf85cd55ed674a8473d4064
cc866de17733a3a84c43b75e6f0fa9123e9e7af3
/MetaModel/src/main/java/ust/hk/praisehk/metamodelcalibration/matsimIntegration/AnaModelControlerListener.java
01792c1266e212c63689c2b55496d5682cffc7f1
[]
no_license
auzpatwary37/MetaModel
eaaa7b70718d9409aa36bf5ff9006590a1f286cf
ae1cbaa12a15e47e1de79a2d6803a296093014c9
refs/heads/master
2021-06-13T18:19:27.525845
2019-03-20T17:21:10
2019-03-20T17:21:10
170,119,268
0
0
null
2021-03-31T20:56:12
2019-02-11T11:42:52
Java
UTF-8
Java
false
false
5,296
java
package ust.hk.praisehk.metamodelcalibration.matsimIntegration; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.matsim.api.core.v01.Id; import org.matsim.api.core.v01.Scenario; import org.matsim.api.core.v01.network.Link; import org.matsim.core.api.experimental.events.EventsManager; import org.matsim.core.controler.events.AfterMobsimEvent; import org.matsim.core.controler.events.BeforeMobsimEvent; import org.matsim.core.controler.events.IterationEndsEvent; import org.matsim.core.controler.events.ShutdownEvent; import org.matsim.core.controler.events.StartupEvent; import org.matsim.core.controler.listener.AfterMobsimListener; import org.matsim.core.controler.listener.BeforeMobsimListener; import org.matsim.core.controler.listener.IterationEndsListener; import org.matsim.core.controler.listener.ShutdownListener; import org.matsim.core.controler.listener.StartupListener; import com.google.inject.Inject; import com.google.inject.name.Named; import dynamicTransitRouter.fareCalculators.FareCalculator; import ust.hk.praisehk.metamodelcalibration.analyticalModel.AnalyticalModel; import ust.hk.praisehk.metamodelcalibration.measurements.Measurements; import ust.hk.praisehk.metamodelcalibration.measurements.MeasurementsWriter; public class AnaModelControlerListener implements StartupListener,BeforeMobsimListener, AfterMobsimListener,IterationEndsListener, ShutdownListener{ private boolean generateOD=true; private Scenario scenario; @Inject private AnalyticalModel SueAssignment; @Inject private @Named("CalibrationCounts") Measurements calibrationMeasurements; private String fileLoc; @Inject private LinkCountEventHandler pcuVolumeCounter; private MeasurementsStorage storage; @Inject private @Named("CurrentParam") paramContainer currentParam; private int maxIter; private final Map<String, FareCalculator> farecalc; private int AverageCountOverNoOfIteration=5; private boolean shouldAverageOverIteration=true; private Map<String, Map<Id<Link>, Double>> counts=null; @Inject public AnaModelControlerListener(Scenario scenario,AnalyticalModel sueAssignment, Map<String,FareCalculator> farecalc,@Named("fileLoc") String fileLoc,@Named("generateRoutesAndOD") boolean generateRoutesAndOD, MeasurementsStorage storage){ this.SueAssignment=sueAssignment; this.farecalc=farecalc; this.scenario=scenario; this.fileLoc=fileLoc; this.generateOD=generateRoutesAndOD; this.storage=storage; } @Inject private EventsManager eventsManager; @Override public void notifyStartup(StartupEvent event) { this.eventsManager.addHandler(pcuVolumeCounter); this.maxIter=event.getServices().getConfig().controler().getLastIteration(); } @Override public void notifyBeforeMobsim(BeforeMobsimEvent event) { this.pcuVolumeCounter.resetLinkCount(); } public void notifyAfterMobsim(AfterMobsimEvent event) { if(this.shouldAverageOverIteration) { int counter=event.getIteration(); if(counter>this.maxIter-5) { if(this.counts==null) { counts=new HashMap<>(this.pcuVolumeCounter.geenerateLinkCounts()); }else { Map<String,Map<Id<Link>,Double>> newcounts=this.pcuVolumeCounter.geenerateLinkCounts(); for(String s:this.counts.keySet()) { for(Id<Link> lId:this.counts.get(s).keySet()) { counts.get(s).put(lId, counts.get(s).get(lId)+newcounts.get(s).get(lId)); } } } } if(counter==this.maxIter) { for(String s:this.counts.keySet()) { for(Id<Link> lId:this.counts.get(s).keySet()) { counts.get(s).put(lId, counts.get(s).get(lId)/this.AverageCountOverNoOfIteration); } } Measurements m=storage.getCalibrationMeasurements().clone(); m.updateMeasurements(counts); //new MeasurementsWriter(m).write(); this.storage.storeMeasurements(this.currentParam.getParam(), m); } }else { int counter=event.getIteration(); if(counter==this.maxIter) { Measurements m=storage.getCalibrationMeasurements().clone(); m.updateMeasurements(this.pcuVolumeCounter.geenerateLinkCounts()); //m.writeCSVMeasurements(fileLoc); this.storage.storeMeasurements(this.currentParam.getParam(), m); } } } @Override public void notifyIterationEnds(IterationEndsEvent event) { } @Override public void notifyShutdown(ShutdownEvent event) { if(this.generateOD) { this.SueAssignment.generateRoutesAndOD(event.getServices().getScenario().getPopulation(), event.getServices().getScenario().getNetwork(), event.getServices().getScenario().getTransitSchedule(), event.getServices().getScenario(), this.farecalc); } } public int getAverageCountOverNoOfIteration() { return AverageCountOverNoOfIteration; } public void setAverageCountOverNoOfIteration(int averageCountOverNoOfIteration) { AverageCountOverNoOfIteration = averageCountOverNoOfIteration; } public boolean isShouldAverageOverIteration() { return shouldAverageOverIteration; } public void setShouldAverageOverIteration(boolean shouldAverageOverIteration) { this.shouldAverageOverIteration = shouldAverageOverIteration; } }
[ "h@DESKTOP-DDS6EO6" ]
h@DESKTOP-DDS6EO6
0d3f49b9fa57debc239c355aaf6c80f959b2f68d
ad542aa5a4355e84289186fd89db36a42cacbc67
/WolverineRoboticsCode-gold/src/org/usfirst/frc/team949/robot/subsystems/Grab.java
94d8b42ee822a8a36bbd71d0373a3afebae06a9b
[]
no_license
uc1309/WolverineRoboticsCode-gold
452a8634b11ef0b93478ad51f364ca8fb11efce1
8155e412667ed4fb266ee903d5a4a6c890e6ac17
refs/heads/master
2020-05-31T14:50:09.536298
2015-02-25T18:10:13
2015-02-25T18:10:13
29,572,655
0
2
null
null
null
null
UTF-8
Java
false
false
539
java
package org.usfirst.frc.team949.robot.subsystems; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.Talon; import org.usfirst.frc.team949.robot.RobotMap; import org.usfirst.frc.team949.robot.commands.GrabCommand; public class Grab extends Subsystem{ private Talon grabMotor; public Grab(){ grabMotor = new Talon(RobotMap.grabMotor); } @Override protected void initDefaultCommand() { setDefaultCommand(new GrabCommand()); } public void setSpeed(double speed){ grabMotor.set(speed); } }
ae1c3e85278b63b1278f8de3c988556ba139d867
d73226d4cfb0d1a4609422c0753678777bee5eeb
/src/com/aof/component/helpdesk/AbstractCustConfigTableType.java
8719d940ef2c233273d4fb3e6a5719e468f34ccc
[]
no_license
Novthirteen/PMS
842132b8fd5d60e4b1b66716e741b4156b318959
65c8fd709bf6d88f80ee03341b9a7d950ace740f
refs/heads/master
2021-01-16T18:28:03.582398
2014-04-04T03:27:37
2014-04-04T03:28:55
18,425,558
0
1
null
null
null
null
UTF-8
Java
false
false
4,193
java
/* * WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized * by MyEclipse Hibernate tool integration. * * Created Wed Nov 24 09:25:16 CST 2004 by MyEclipse Hibernate Tool. */ package com.aof.component.helpdesk; import java.io.Serializable; import java.util.List; /** * A class that represents a row in the CustConfigTableType table. * You can customize the behavior of this class by editing the class, {@link CustConfigTableType()}. * WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized * by MyEclipse Hibernate tool integration. */ public abstract class AbstractCustConfigTableType implements Serializable { /** The cached hash code value for this instance. Settting to 0 triggers re-calculation. */ private int hashValue = 0; /** The composite primary key value. */ private java.lang.Integer id; /** The value of the simple name property. */ private java.lang.String name; /** The value of the simple disabled property. */ private Boolean disabled; private ModifyLog modifyLog=new ModifyLog(); private List columns; /** * Simple constructor of AbstractCustConfigTableType instances. */ public AbstractCustConfigTableType() { } /** * Constructor of AbstractCustConfigTableType instances given a simple primary key. * @param id */ public AbstractCustConfigTableType(java.lang.Integer typeId) { this.setId(typeId); } /** * Return the simple primary key value that identifies this object. * @return java.lang.Integer */ public java.lang.Integer getId() { return id; } /** * Set the simple primary key value that identifies this object. * @param id */ public void setId(java.lang.Integer typeId) { this.hashValue = 0; this.id = typeId; } /** * Return the value of the type_name column. * @return java.lang.String */ public java.lang.String getName() { return this.name; } /** * Set the value of the type_name column. * @param name */ public void setName(java.lang.String typeName) { this.name = typeName; } /** * Return the value of the disabled column. * @return java.lang.Byte */ public Boolean getDisabled() { return this.disabled; } /** * Set the value of the disabled column. * @param disabled */ public void setDisabled(Boolean disabled) { this.disabled = disabled; } /** * Implementation of the equals comparison on the basis of equality of the primary key values. * @param rhs * @return boolean */ public boolean equals(Object rhs) { if (rhs == null) return false; if (! (rhs instanceof CustConfigTableType)) return false; CustConfigTableType that = (CustConfigTableType) rhs; if (this.getId() != null && that.getId() != null) { if (! this.getId().equals(that.getId())) { return false; } } return true; } /** * Implementation of the hashCode method conforming to the Bloch pattern with * the exception of array properties (these are very unlikely primary key types). * @return int */ public int hashCode() { if (this.hashValue == 0) { int result = 17; int typeIdValue = this.getId() == null ? 0 : this.getId().hashCode(); result = result * 37 + typeIdValue; this.hashValue = result; } return this.hashValue; } /** * @return Returns the columns. */ public List getColumns() { return columns; } /** * @param columns The columns to set. */ public void setColumns(List columns) { this.columns = columns; } /** * @return Returns the modifyLog. */ public ModifyLog getModifyLog() { return modifyLog; } /** * @param modifyLog The modifyLog to set. */ public void setModifyLog(ModifyLog modifyLog) { this.modifyLog = modifyLog; } }
7922906fa1ab8a628305493287e521d4bd20d466
3300969adbb82ac81afd660130905acf31c89e2a
/src/Tree/LowestCommonAncestorBT.java
e66261ab880336b8b921611488c8f651e1657320
[]
no_license
araj2805/Data-Structure-Algorithm
820feda149d13f6d2fb3f55d84222e2ccd602a46
1bf3cbcdf60295293724c05444e4f128809f84d8
refs/heads/master
2022-05-01T18:48:47.003793
2022-03-08T07:59:14
2022-03-08T07:59:14
237,584,143
0
0
null
2022-03-08T07:56:37
2020-02-01T08:19:11
Java
UTF-8
Java
false
false
741
java
package Tree; public class LowestCommonAncestorBT { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) return null; if (root.val == p.val || root.val == q.val) return root; TreeNode leftLca = lowestCommonAncestor(root.left, p, q); TreeNode rightLca = lowestCommonAncestor(root.right, p, q); if (leftLca != null && rightLca != null) return root; if (leftLca != null) return leftLca; else return rightLca; } static class TreeNode { int val; TreeNode left, right; public TreeNode(int val) { this.val = val; } } }
022a95a6328112c1263c583e687ba970f2828e42
e2197a85274e545d5fde166e5522afbbf740ec7c
/springmvcloginhibernate/src/main/java/net/projectGroup2/dao/InformationDAO.java
3add1e662fe10129e27d42f7b911e14a9a6c2bbb
[]
no_license
VenkatSambandhan/Social-Networking-Site-CIRCULUS
f794d0f0b63e16a094108248b6a24a4109680932
14cb175c7e4a4c38c719c5c021ca57fe952e8726
refs/heads/master
2020-12-24T18:55:50.651437
2016-05-16T04:03:48
2016-05-16T04:03:48
58,902,406
0
0
null
null
null
null
UTF-8
Java
false
false
352
java
/* Created by: Maaz Syed Date: 4/23/2016 2:29am */ package net.projectGroup2.dao; import java.util.List; import net.projectGroup2.model.*; public interface InformationDAO{ public List<Users> getUserInformation(String userName); public List<Tags> getUserTags(String userName); public List<Votes> getUserVotes(String userName); }
19fbf655fe031efa2894848142e9854a35c4bcd2
8ecb83b82a24c066874f1ab6bb391c2dbf0b1816
/xiaomaigou_cms_service/src/main/java/com/xiaomaigou/cms/service/controller/SourceTypeController.java
37e0d39ea4abaa8402f686ce99fdff17127a195c
[ "Apache-2.0" ]
permissive
jangocheng/xiaomaigou_cms
0dbb2636caf120dbe15d0f8c599e157b1ef818d1
0a9e8498e61ca057bc7a24fb32b81e7521cff2b9
refs/heads/master
2022-11-11T19:45:43.245935
2020-06-07T15:14:01
2020-06-07T15:14:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,344
java
package com.xiaomaigou.cms.service.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.xiaomaigou.cms.common.dto.Result; import com.xiaomaigou.cms.dao.entity.SourceTypeEntity; import com.xiaomaigou.cms.service.dto.SourceTypeDTO; import com.xiaomaigou.cms.service.service.SourceTypeService; import java.util.Arrays; import java.util.List; import java.util.Date; /** * 来源类型 * * @author xiaomaiyun * @version 1.2.3 * @date 2020/06/07 18:02:13 */ @Api(tags = "来源类型", description = "来源类型相关接口") @RestController @RequestMapping("service/sourceType") public class SourceTypeController { private static final Logger logger = LoggerFactory.getLogger(SourceTypeController.class); @Autowired private SourceTypeService sourceTypeService; @ApiOperation(value = "所有来源类型", notes = "获取所有来源类型") @GetMapping("listAll") public Result<List<SourceTypeEntity>> listAll() { Result<List<SourceTypeEntity>> result = new Result<>(); try { List<SourceTypeEntity> sourceTypeEntityList = sourceTypeService.listAll(); return result.success(sourceTypeEntityList); } catch (Exception e) { logger.error("获取来源类型失败!", e); return result.fail("获取来源类型失败,请稍后重试!"); } } @ApiOperation(value = "来源类型(分页)", notes = "获取来源类型(分页)") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "当前页,默认1", paramType = "query", required = false, dataType = "int", defaultValue = "1"), @ApiImplicitParam(name = "pageSize", value = "每页显示条数,默认10", paramType = "query", required = false, dataType = "int", defaultValue = "10") }) @GetMapping("listAllPage") public Result<Page<SourceTypeEntity>> listAllPage(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) { Result<Page<SourceTypeEntity>> result = new Result<>(); try { Page<SourceTypeEntity> sourceTypeEntityPage = sourceTypeService.listAllPage(pageNo, pageSize); return result.success(sourceTypeEntityPage); } catch (Exception e) { logger.error(String.format("获取来源类型失败!pageNo=[%s],pageSize=[%s]", pageNo, pageSize), e); return result.fail("获取来源类型失败,请稍后重试!"); } } @ApiOperation(value = "搜索来源类型(分页)", notes = "搜索来源类型(分页)") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNo", value = "当前页,默认1", paramType = "query", required = false, dataType = "int", defaultValue = "1"), @ApiImplicitParam(name = "pageSize", value = "每页显示条数,默认10", paramType = "query", required = false, dataType = "int", defaultValue = "10"), @ApiImplicitParam(name = "sourceTypeCode", value = "来源code", paramType = "query", required = false, dataType = "String"), @ApiImplicitParam(name = "sourceTypeName", value = "来源名称", paramType = "query", required = false, dataType = "String"), @ApiImplicitParam(name = "createPersonId", value = "创建人ID", paramType = "query", required = false, dataType = "String"), @ApiImplicitParam(name = "status", value = "状态,-1删除,0无效,1有效", paramType = "query", required = false, dataType = "Integer")}) @GetMapping("search") public Result<Page<SourceTypeEntity>> search(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize, @RequestParam(value = "sourceTypeCode", required = false) String sourceTypeCode, @RequestParam(value = "sourceTypeName", required = false) String sourceTypeName, @RequestParam(value = "createPersonId", required = false) String createPersonId, @RequestParam(value = "status", required = false) Integer status) { Result<Page<SourceTypeEntity>> result = new Result<>(); try { Page<SourceTypeEntity> sourceTypeEntityPage = sourceTypeService.search(pageNo, pageSize, sourceTypeCode, sourceTypeName, createPersonId, status); return result.success(sourceTypeEntityPage); } catch (Exception e) { logger.error(String.format("搜索来源类型失败!sourceTypeCode=[%s],sourceTypeName=[%s],createPersonId=[%s],status=[%s]", sourceTypeCode, sourceTypeName, createPersonId, status), e); return result.fail("搜索来源类型失败,请稍后重试!"); } } @ApiOperation(value = "来源类型详情", notes = "根据来源类型ID获取来源类型详情") @ApiImplicitParams({ @ApiImplicitParam(name = "sourceTypeId", value = "来源类型ID", paramType = "path", required = true, dataType = "String") }) @GetMapping("detail/{sourceTypeId}") public Result<SourceTypeEntity> detail(@PathVariable(value = "sourceTypeId", required = true) String sourceTypeId) { Result<SourceTypeEntity> result = new Result<>(); try { SourceTypeEntity sourceTypeEntity = sourceTypeService.detail(sourceTypeId); if (sourceTypeEntity == null) { return result.notFound("查询的来源类型不存在!"); } else { return result.success(sourceTypeEntity); } } catch (Exception e) { logger.error(String.format("获取来源类型详情失败!sourceTypeId=[%s]", sourceTypeId), e); return result.fail("获取来源类型详情失败,请稍后重试!"); } } @ApiOperation(value = "新增来源类型", notes = "新增来源类型") @ApiImplicitParams({ @ApiImplicitParam(name = "sourceTypeDTO", value = "来源类型信息", paramType = "body", required = true, dataType = "SourceTypeDTO") }) @PostMapping("add") public Result add(@RequestBody SourceTypeDTO sourceTypeDTO) { Result result = new Result<>(); try { Boolean success = sourceTypeService.add(sourceTypeDTO); if (success) { return result.success("新增来源类型成功!"); } else { logger.warn(String.format("新增来源类型失败!sourceTypeDTO=[%s]", sourceTypeDTO.toString())); return result.fail("新增来源类型失败,请稍后重试!"); } } catch (Exception e) { logger.error(String.format("新增来源类型失败!sourceTypeDTO=[%s]", sourceTypeDTO.toString()), e); return result.fail("新增来源类型失败,请稍后重试!"); } } @ApiOperation(value = "更新来源类型", notes = "根据来源类型ID更新来源类型详情") @ApiImplicitParams({ @ApiImplicitParam(name = "sourceTypeId", value = "来源类型ID", paramType = "path", required = true, dataType = "String"), @ApiImplicitParam(name = "sourceTypeDTO", value = "来源类型信息", paramType = "body", required = true, dataType = "SourceTypeDTO") }) @PutMapping("update/{sourceTypeId}") public Result update(@PathVariable(value = "sourceTypeId", required = true) String sourceTypeId, @RequestBody SourceTypeDTO sourceTypeDTO) { Result result = new Result<>(); try { Boolean success = sourceTypeService.update(sourceTypeId, sourceTypeDTO); if (success) { return result.success("更新来源类型成功!"); } else { logger.warn(String.format("更新来源类型失败!sourceTypeId=[%s],sourceTypeDTO=[%s]", sourceTypeId, sourceTypeDTO.toString())); return result.fail("更新来源类型失败,请稍后重试!"); } } catch (Exception e) { logger.error(String.format("更新来源类型失败!sourceTypeId=[%s],sourceTypeDTO=[%s]", sourceTypeId, sourceTypeDTO.toString()), e); return result.fail("更新来源类型失败,请稍后重试!"); } } @ApiOperation(value = "删除来源类型", notes = "根据来源类型ID删除来源类型") @ApiImplicitParams({ @ApiImplicitParam(name = "sourceTypeId", value = "来源类型ID", paramType = "path", required = true, dataType = "String") }) @DeleteMapping("delete/{sourceTypeId}") public Result delete(@PathVariable(value = "sourceTypeId", required = true) String sourceTypeId) { Result result = new Result<>(); try { Boolean success = sourceTypeService.delete(sourceTypeId); if (success) { return result.success("删除来源类型成功!"); } else { logger.warn(String.format("删除来源类型失败!sourceTypeId=[%s]", sourceTypeId)); return result.fail("删除来源类型失败,请稍后重试!"); } } catch (Exception e) { logger.error(String.format("删除来源类型失败!sourceTypeId=[%s]", sourceTypeId), e); return result.fail("删除来源类型失败,请稍后重试!"); } } @ApiOperation(value = "删除来源类型(多条记录)", notes = "根据来源类型ID删除来源类型(多条记录)") @ApiImplicitParams({ @ApiImplicitParam(name = "sourceTypeIds", value = "来源类型ID(多个ID之间使用逗号\",\"分隔)", paramType = "query", required = true, dataType = "String") }) @DeleteMapping("delete") public Result deletes(@RequestParam(value = "sourceTypeIds", required = true) String sourceTypeIds) { Result result = new Result<>(); List<String> sourceTypeIdList = Arrays.asList(sourceTypeIds.split(",")); if (sourceTypeIdList.isEmpty()) { return result.badRequest("请至少选择一条记录!"); } try { Boolean success = sourceTypeService.delete(sourceTypeIdList); if (success) { return result.success("删除来源类型成功!"); } else { logger.warn(String.format("删除来源类型失败!sourceTypeIdList=[%s]", sourceTypeIdList.toString())); return result.fail("删除来源类型失败,请稍后重试!"); } } catch (Exception e) { logger.error(String.format("删除来源类型失败!sourceTypeIdList=[%s]", sourceTypeIdList.toString()), e); return result.fail("删除来源类型失败,请稍后重试!"); } } }
9058d3ebebb2929208e40c0924b3ce7f1c85a3a3
efc696b0f1f58f5ee2af6e75a7acace921de4c61
/src/main/java/com/fargo/basis/common/Constant.java
7084c861fc27fbf9e0bf5aefef9f886f47a43c07
[]
no_license
EnseiBestia/Fargo
3701cc0c729306cdfc951e6cb6fb495b1cc3dc68
41688251aaff93f73804534658a0a3789341fa1c
refs/heads/master
2021-01-12T03:19:24.912582
2017-01-06T09:45:32
2017-01-06T09:45:32
78,194,473
0
0
null
null
null
null
UTF-8
Java
false
false
16,149
java
package com.fargo.basis.common; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Session; import com.fargo.basis.model.CfgEnumInfo; import com.fargo.basis.model.CfgEnumValueInfo; /** * * @author Administrator * */ public class Constant { public static final String SERVER_TYPE_BMS="BMS"; public static final String SERVER_TYPE_EPG="EPG"; public static final String SERVER_TYPE_UNKNOWE="unknowe"; public static final String ABNORMAL_TYPE_OFFLINE="OFFLINE"; public static final String ABNORMAL_TYPE_JMXBLOCKED="JMXBLOCKED"; public static final String ABNORMAL_TYPE_LOADOVERTOP="LOADOVERTOP"; /******是否状态******/ public static final String TRUE = "10A";//是 public static final String FALSE = "10B";//否 /******用户自定义属性数据类型******/ public static final String PROPERTY_DATA_TYPE_BOOLEAN = "AVA";//布尔型 public static final String PROPERTY_DATA_TYPE_LONG = "AVB";//整型 public static final String PROPERTY_DATA_TYPE_DOUBLE = "AVC";//浮点型 public static final String PROPERTY_DATA_TYPE_STRING = "AVD";//字符串 public static final String PROPERTY_DATA_TYPE_TEXT = "AVE";//文本型 public static final String PROPERTY_DATA_TYPE_ENUM = "AVF";//列表 public static final String PROPERTY_DATA_TYPE_DATE = "AVG";//日期 public static final String PROPERTY_DATA_TYPE_EMAIL = "AVH";//Email /******权限类型******/ public static final String PVIVILEGE_TYPE_CATALOG = "AWA";//目录 public static final String PVIVILEGE_TYPE_MENU = "AWB";//菜单项 public static final String PVIVILEGE_TYPE_OPERATOR = "AWC";//操作项 /******固有属性值类型******/ public static final String FIXED_PROPERTY_VALUE_TYPE_LIST = "AXA";//列表 public static final String FIXED_PROPERTY_VALUE_TYPE_MULITI_LIST = "AXB";//二级列表 public static final String FIXED_PROPERTY_VALUE_TYPE_TREE_LIST = "AXC";//树列表 /******模板类型******/ public static final String TPL_TYPE_TEST = "AYA";//测试模板 public static final String TPL_TYPE_12 = "AY12";//12 /******生成报告类型******/ public static final String REPORT_TYPE_WORD = "9FA";//WORD报告 public static final String REPORT_TYPE_HTML = "9FB";//HTML报告 public static final String REPORT_TYPE_PDF = "9FC";//PDF报告 /******函数类型******/ public static final String FUN_TYPE_SYSTEM_JAVA = "9AA";//系统JAVA函数 public static final String FUN_TYPE_OFFICE_TABLE = "9AB";//OFFICE表函数 public static final String FUN_TYPE_OFFICE_CHART = "9AC";//OFFICE图函数 public static final String FUN_TYPE_FREEMARKER = "9AD";//FREEMARKER函数 /******函数参数类型******/ public static final String FUN_PARAM_TYPE_BOOLEAN = "9BA";//布尔型 public static final String FUN_PARAM_TYPE_LONG = "9BB";//整型 public static final String FUN_PARAM_TYPE_DOUBLE = "9BC";//浮点型 public static final String FUN_PARAM_TYPE_STRING = "9BD";//字符串 public static final String FUN_PARAM_TYPE_ENUM = "9BE";//枚举 public static final String FUN_PARAM_TYPE_FIXED_PROPERTY = "9BP";//系统可变属性 public static final String FUN_PARAM_TYPE_CACULATE = "9BM";//计算项 public static final String FUN_PARAM_TYPE_DIMENSION = "9BF";//维度 public static final String FUN_PARAM_TYPE_TOPIC = "9BG";//题目 public static final String FUN_PARAM_TYPE_TOPIC_OPTION = "9BH";//题目选项 public static final String FUN_PARAM_TYPE_TABLE = "9BI";//统计表 public static final String FUN_PARAM_TYPE_COLUMN = "9BJ";//统计列 public static final String FUN_PARAM_TYPE_ONE_DIMENSIONA_ARRAY = "9BQ";//一维行列对象 public static final String FUN_PARAM_TYPE_TWO_DIMENSIONA_ARRAY = "9BK";//二维行列对象 public static final String FUN_PARAM_TYPE_MULITI_DIMENSIONA_ARRAY = "9BN";//多维行列对象 public static final String FUN_PARAM_TYPE_JSON_OBJECT = "9BL";//JSON对象 public static final String FUN_PARAM_TYPE_CHART_STYLE = "9BO";//图表样式 /******函数返回值类型******/ public static final String FUN_RETURN_TYPE_BOOLEAN = "9CA";//布尔型 public static final String FUN_RETURN_TYPE_LONG = "9CB";//整型 public static final String FUN_RETURN_TYPE_DOUBLE = "9CC";//浮点型 public static final String FUN_RETURN_TYPE_STRING = "9CD";//字符串 public static final String FUN_RETURN_TYPE_ONE_DIMENSIONA_ARRAY = "9CE";//一级行列对象 public static final String FUN_RETURN_TYPE_TWO_DIMENSIONA_ARRAY = "9CF";//二级行列对象 public static final String FUN_RETURN_TYPE_JSON = "9CG";//JSON对象 public static final String FUN_RETURN_TYPE_VBA_TABLE = "9CH";//VBA表代码 public static final String FUN_RETURN_TYPE_VBA_CHART = "9CI";//VBA图代码 /******统计数据状态******/ public static final String STAT_DATA_STATUS_NEW = "3FA";//新建 public static final String STAT_DATA_STATUS_COLLECT_PAPERINFO_ING = "3FB";//正在收集问卷信息 public static final String STAT_DATA_STATUS_COLLECT_PAPERINFO_END = "3FC";//收集问卷信息完成 public static final String STAT_DATA_STATUS_COLLECT_QUIZINFO_ING = "3FD";//收集测评数据并算分中 public static final String STAT_DATA_STATUS_COLLECT_QUIZINFO_END = "3FE";//收集测评数据并算分完毕 public static final String STAT_DATA_STATUS_DATA_STAT_ING = "3FF";//数据统计中 public static final String STAT_DATA_STATUS_DATA_STAT_END = "3FG";//数据统计完成 /******权限操作类型******/ public static final String PVIVILEGE_OPERATE_TYPE_LIST = "AZA";//列表 public static final String PVIVILEGE_OPERATE_TYPE_ADD = "AZB";//添加 public static final String PVIVILEGE_OPERATE_TYPE_EDIT = "AZC";//修改 public static final String PVIVILEGE_OPERATE_TYPE_DELETE = "AZD";//删除 public static final String PVIVILEGE_OPERATE_TYPE_VIEW = "AZE";//查看 /******审读问题状态******/ public static final String status_NEW = "7BA";//新建 public static final String status_UNDERWAY = "7BB";//进行中 public static final String status_FINISHED = "7BC";//已解决 public static final String status_FEEDBACK = "7BD";//反馈 public static final String status_CLOSED = "7BE";//已关闭 /******Form对象数据变化拦截类型******/ public static final String FORM_DATA_CHANGE_DOTYPE_NONE = "BBA";//None public static final String FORM_DATA_CHANGE_DOTYPE_COMMON = "BBB";//通用拦截 public static final String FORM_DATA_CHANGE_DOTYPE_SPECIAL = "BBC";//自定义拦截 /******统计列类型******/ public static final String STAT_COLUMN_OBJECT = "BAA";//对象 public static final String STAT_COLUMN_OBJECT_ATTRIBUTE = "BAB";//对象属性 public static final String STAT_COLUMN_QUESTION = "BAC";//问题 /******题目状态******/ public static final String QUESTION_STATUS_NEW = "BCA";//新建 public static final String QUESTION_STATUS_NORMAL = "BCB";//可用 public static final String QUESTION_STATUS_IN_USE = "BCC";//在用 public static final String QUESTION_STATUS_DELETE = "BCD";//删除 /******对象属性类型******/ public static final String OBJECT_ATT_TYPE_OBJECT = "BDA";//对象 public static final String OBJECT_ATT_TYPE_NAME = "BDB";//名称 public static final String OBJECT_ATT_TYPE_FIXED_PROPERTY = "BDC";//系统可变属性 public static final String OBJECT_ATT_TYPE_VALUE = "BDD";//文本或数值 /******对象索引类型******/ public static final String OBJECT_INDEX_TYPE_UNIQUE = "BEA";//唯一索引 public static final String OBJECT_INDEX_TYPE_COMMON = "BEB";//普通索引 /******任务类型******/ public static final String TASK_TYPE_OBJECT_INDEX_REBUILD = "BFA";//对象索引重建 public static final String TASK_TYPE_OBJECT_IMPORT = "BFB";//导入对象 public static final String TASK_TYPE_QUESTION_IMPORT = "BFC";//题目导入 public static final String TASK_TYPE_DATA_STAT = "BFD";//数据统计 public static final String TASK_TYPE_DATA_TPL_HANDLE = "BF1";//模板处理 public static final String TASK_TYPE_DATA_REPORT_GEN = "BF2";//生成报告VBA public static final String TASK_TYPE_DATA_RPT_INST_GEN = "BF3";//生成报告实例 public static final String TASK_TYPE_DATA_RPT_FUN_GEN = "BF4";//生成报告函数实例 public static final String TASK_TYPE_DATA_RPT_FUN_EXEC = "BF5";//执行报告函数实例 public static final String TASK_TYPE_DATA_RPT_CHART = "BF6";//生成图表 public static final String TASK_TYPE_DATA_RPT_VBA_RUN = "BF7";//执行VBA生成报告 /******任务状态******/ public static final String TASK_STATUS_NEW = "BGA";//新建 public static final String TASK_STATUS_WAITING = "BGB";//队列等待 public static final String TASK_STATUS_RUNNING = "BGC";//执行中 public static final String TASK_STATUS_DONE = "BGD";//执行成功 public static final String TASK_STATUS_FAILURE = "BGE";//执行失败 /******任务状态******/ public static final String TASK_SERVER_TYPE_ADMIN_SERVER = "BYA";//管理服务端 public static final String TASK_SERVER_TYPE_REPORT_SERVER = "BYB";//报告服务端 /******测评类别******/ public static final String QUIZ_TYPE_ONLINE = "3BA";//电子测评 public static final String QUIZ_TYPE_OFFLINE = "3BB";//纸质测评 /******题目类型******/ public static final String QUESTION_TYPE_SELECT_BOOLEAN = "1HA";//判断题 public static final String QUESTION_TYPE_SELECT_ONE = "1HB";//单选题 public static final String QUESTION_TYPE_SELECT_MULIT = "1HC";//多选题 public static final String QUESTION_TYPE_SELECT_LKT = "1HD";//里克特题 public static final String QUESTION_TYPE_FILL_TEXT = "1HE";//填空题 public static final String QUESTION_TYPE_ANSWER = "1HF";//问答题 public static final String QUESTION_TYPE_SORT = "1HG";//排序题 public static final String QUESTION_TYPE_LINE = "1HK";//连线题 public static final String QUESTION_TYPE_UNDERSTAND = "1HL";//阅读理解题 public static final String QUESTION_TYPE_HXT = "1HM";//划消题 public static final String QUESTION_TYPE_TEXT = "1HN";//文本 public static final String QUESTION_TYPE_SELECT_XLXZ = "1HP";//下拉选择题 /******模板状态******/ public static final String TPL_STATUS_NEW = "9DA";//新建 public static final String TPL_STATUS_HANDLE = "9DB";//翻译中 public static final String TPL_STATUS_HANDLE_FAILRE = "9DC";//翻译失败 public static final String TPL_STATUS_HANDLE_SUCCESS = "9DD";//翻译成功 /******模板类型******/ public static final String TPL_TYPE_WORD = "9EA";//WORD public static final String TPL_TYPE_HTML = "9EB";//HTML public static final String TPL_TYPE_PPT = "9EC";//PPT /******报告类型******/ public static final String RPT_TYPE_WORD = "9FA";//WORD public static final String RPT_TYPE_HTML = "9FB";//HTML public static final String RPT_TYPE_PPT = "9FC";//PPT public static final String RPT_TYPE_PDF = "9FD";//PDF /******报告状态******/ public static final String RPT_STATUS_NEW = "9LA";//新建 public static final String RPT_STATUS_INST = "9LB";//正在生成报告实例 public static final String RPT_STATUS_INST_SUCCESS = "9LC";//生成报告实例成功 public static final String RPT_STATUS_INST_FAILURE = "9LD";//报告实例生成失败 public static final String RPT_STATUS_FUN_INST = "9LK";//正在生成函数实例 public static final String RPT_STATUS_FUN_INST_FAILURE = "9LL";//生成函数实例失败 public static final String RPT_STATUS_FUN_INST_SUCCESS = "9LM";//生成函数实例成功 public static final String RPT_STATUS_FUN = "9LE";//正在计算函数 public static final String RPT_STATUS_FUN_SUCCESS = "9LF";//函数计算成功 public static final String RPT_STATUS_FUN_FAILURE = "9LG";//函数计算失败 public static final String RPT_STATUS_GEN = "9LH";//正在生成报告 public static final String RPT_STATUS_GEN_SUCCESS = "9LI";//报告生成成功 public static final String RPT_STATUS_GEN_FAILURE = "9LJ";//报告生成失败 /******报告实例状态******/ public static final String RPT_INST_STATUS_NEW = "9NA";//新建 public static final String RPT_INST_STATUS_FUN_INST = "9NH";//正在生成函数实例 public static final String RPT_INST_STATUS_FUN_INST_FAILURE = "9NI";//生成函数实例失败 public static final String RPT_INST_STATUS_FUN_INST_SUCCESS = "9NJ";//生成函数实例成功 public static final String RPT_INST_STATUS_EXEC_FUN = "9NB";//正在计算函数 public static final String RPT_INST_STATUS_EXEC_FAILURE = "9NC";//函数计算失败 public static final String RPT_INST_STATUS_EXEC_SUCCESS = "9ND";//函数计算成功 public static final String RPT_INST_STATUS_REPORT = "9NE";//正在生成报告 public static final String RPT_INST_STATUS_REPORT_FAILURE = "9NF";//报告生成失败 public static final String RPT_INST_STATUS_REPROT_SUCCESS = "9NG";//报告生成成功 /******报告函数实例状态******/ public static final String RPT_FUN_INST_STATUS_EXEC_NEW = "9MA";//新建 public static final String RPT_FUN_INST_STATUS_EXEC_FUN = "9MB";//正在计算函数 public static final String RPT_FUN_INST_STATUS_EXEC_FAILURE = "9MC";//函数计算失败 public static final String RPT_FUN_INST_STATUS_EXEC_SUCCESS = "9MD";//函数计算成功 /******表达式******/ public static final String EXPRESSION_TYPE_DAYU = "CBA"; public static final String EXPRESSION_TYPE_DAYU_DENGYU = "CBB"; public static final String EXPRESSION_TYPE_XIAOYU = "CBC"; public static final String EXPRESSION_TYPE_XIAOYU_DENGYU = "CBD"; public static final String EXPRESSION_TYPE_DENGYU = "CBE"; public static final String EXPRESSION_TYPE_NOT_DENGYU = "CBF"; /******审读类型******/ public static final String CKB_TYPE_DATA = "7CA"; public static final String CKB_TYPE_REPORT = "7CB"; public static final String CKB_TYPE_TEMPLATE = "7CC"; /******范围标识*****/ public static final String SCOPE_MARK = "s"; public static final String CATALOG_MARK = "c"; public static final String OPTION_INDEX = "i"; /******函数定义状态*****/ public static final String FUNDEFINE_STATUS_NEW = "9RA";//新建 public static final String FUNDEFINE_STATUS_PENDING_AUDIT = "9RB";//待审核 public static final String FUNDEFINE_STATUS_AUDITING = "9RC";//审核中 public static final String FUNDEFINE_STATUS_OK = "9RD";//审核通过 public static final String FUNDEFINE_STATUS_NOT_OK = "9RE";//审核不通过 public static final String FUNDEFINE_STATUS_ONLINE = "9RF";//已发布 public static final String FUNDEFINE_STATUS_OFFLINE = "9RG";//已下线 public static void main(String[] args) { // TODO Auto-generated method stub //SpringContext.getDatastore(); Session session = SpringContext.getHibernateSession(); Map<String,String> map=new HashMap<String,String>(); StringBuffer sb=new StringBuffer(); List<CfgEnumInfo> list=session.createCriteria(CfgEnumInfo.class).list(); for(CfgEnumInfo one:list){ if(!map.containsKey(one.getEnumId())){ if(one.getConstantName()!=null && !"".equals(one.getConstantName().trim()) && one.getEnumCode()!=null && !"".equals(one.getEnumCode().trim())){ if(one.getValues()!=null && one.getValues().size()>0){ sb.append(" /******"+one.getEnumName()+"******/\r\n"); for(CfgEnumValueInfo v1:one.getValues()){ if(v1.getConstantName()!=null && v1.getCode()!=null ){ sb.append(" public static final String "+one.getConstantName()+"_"+v1.getConstantName()+" = \""+one.getEnumCode()+""+v1.getCode()+"\";//"+v1.getValue()+"\r\n"); } } } } } } System.out.println(sb.toString()); } }
[ "van" ]
van
0d40c45629d5ab741edc50dcdca7cf23fa8da76c
b57abe760bc42aa09750656e6f7460401ea9e844
/NewsApp/app/src/main/java/udacity/android/newsapp/utility/QueryUtility.java
3cdcb61d9e57a5722f9ca5c5962da4a0e1d65980
[]
no_license
JPS13/Android-News-App
06c0a4a1f3283d8b07e5763bf4b2e7e46329dc27
acdc5b10f95bdad2107a13d5573ea4e7e0024985
refs/heads/master
2021-06-16T06:18:45.773964
2017-02-09T04:17:49
2017-02-09T04:17:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,255
java
package udacity.android.newsapp.utility; import android.content.Context; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import udacity.android.newsapp.R; import udacity.android.newsapp.model.NewsArticle; /** * This class provides utility methods to make network requests over the internet * to the Guardian API based on the passed in query url string. The query results * are added to a list and returned. * * @author Joseph Stewart * @version 2.2 */ public final class QueryUtility { private static final String LOG_TAG = QueryUtility.class.getSimpleName(); /** * Private constructor that throws AssertionError to prevent instantiation. */ private QueryUtility() { throw new AssertionError("The QueryUtility cannot be instantiated."); } /** * This method extracts a List of NewsArticles from the passed in query URL. * * @param context The requesting context to provide access to string resources. * @param urlString the query URL. * @return The populated List. */ public static List<NewsArticle> extractArticles(Context context, String urlString) { // Create a list to hold NewsArticles List<NewsArticle> articles = new ArrayList<>(); try { // Create URL object URL urlQuery = createUrl(urlString); // Perform HTTP request to the URL and receive a JSON response back String jsonResponse = null; try { jsonResponse = makeHttpRequest(urlQuery); } catch (IOException e) { Log.e(LOG_TAG, "Error closing input stream", e); } // Create a JSONObject from the received string response JSONObject response = new JSONObject(jsonResponse); // Extract the data from the response JSONObject responseObject = response.getJSONObject(context.getString(R.string.response)); JSONArray resultsArray = responseObject.getJSONArray(context.getString(R.string.results)); // Traverse the results of the JSON array for(int i = 0; i < resultsArray.length(); i++) { // Get the properties object from the earthquake object JSONObject articleObject = resultsArray.getJSONObject(i); // The desired article attributes String title = null; String date = null; String section = null; String url = null; // Ensure each attribute exists to avooid errors if(articleObject.has(context.getString(R.string.web_title))) { title = articleObject.getString(context.getString(R.string.web_title)); } if(articleObject.has(context.getString(R.string.date))) { date = articleObject.getString(context.getString(R.string.date)); } if(articleObject.has(context.getString(R.string.section))) { section = articleObject.getString(context.getString(R.string.section)); } if(articleObject.has(context.getString(R.string.url))) { url = articleObject.getString(context.getString(R.string.url)); } // Construct and add a new NewsArticle object from the data NewsArticle article = new NewsArticle(title, date, section, url); articles.add(article); } } catch (JSONException e) { Log.e(LOG_TAG, "Problem parsing the JSON results", e); } // Return the list of articles return articles; } /** * This method takes in a string and converts it into a URL object. * * @param stringUrl The string to be converted. * @return The constructed URL object. */ private static URL createUrl(String stringUrl) { URL url = null; try { url = new URL(stringUrl); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Error creating URL ", e); } return url; } /** * This method makes an http request using the passed in url. * * @param url The url to which the request is made. * @return The JSON response as a string. * @throws IOException Thrown if there is an issue with the request. */ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000); urlConnection.setConnectTimeout(15000); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; } /** * This method reads and inputStream and converts it into a string. * * @param inputStream The inputStream to be read. * @return Returns the string representation of the inputStream. * @throws IOException Thrown if there is a problem reading from the input stream. */ private static String readFromStream(InputStream inputStream) throws IOException { StringBuilder output = new StringBuilder(); if (inputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); BufferedReader reader = new BufferedReader(inputStreamReader); String line = reader.readLine(); while (line != null) { output.append(line); line = reader.readLine(); } } return output.toString(); } }
b9ed7d82e912fd02daade2a0833dd190edc9aae6
90c33f0f6c707ed346a25f466333662a13938eef
/app/src/test/java/com/example/a15017274/p01_dailygoals/ExampleUnitTest.java
0608d1cdbd05eb3d158ad9db84077c343a2513d7
[]
no_license
jiaajiee/P01-DailyGoals
28848aa3e9c8a6c8c0df2bb09265a3757db7600a
48a41d63fdea2b833fd5af0cc9bd54d46fccc5c0
refs/heads/master
2021-01-19T22:40:43.723281
2017-04-20T08:35:20
2017-04-20T08:35:20
88,840,728
0
0
null
null
null
null
UTF-8
Java
false
false
414
java
package com.example.a15017274.p01_dailygoals; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
beaa51dfa6d5cbdf18365a39d79b899c0de08d20
3c9b43b47b30bd861c140d0f8d91c9e349c52094
/src/dcm4che-2.0.29/dcm4che-audit/src/main/java/org/dcm4che2/audit/message/QueryMessage.java
06e0d942417a4c35556fe013da59aae507728c2d
[]
no_license
evgenyorlov1/Dicom-Viewer
2c591a437f523646fa007fb172c206fd7f314509
2089472e87091455879fb49415f27b5d02bfcf28
refs/heads/master
2021-01-01T05:17:07.218349
2016-05-20T03:17:16
2016-05-20T03:17:16
57,183,548
0
1
null
null
null
null
UTF-8
Java
false
false
7,348
java
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * Gunter Zeilinger, Huetteldorferstr. 24/10, 1150 Vienna/Austria/Europe. * Portions created by the Initial Developer are Copyright (C) 2002-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * See listed authors below. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4che2.audit.message; import java.util.List; /** * This message describes the event of a Query being issued or received. * The message does not record the response to the query, but merely * records the fact that a query was issued. For example, this would report * queries using the DICOM SOP Classes: * <ul> * <li>Modality Worklist</li> * <li>General Purpose Worklist</li> * <li>Composite Instance Query</li> * </ul> * <blockquote> * Notes: * <ol> * <li>The response to a query may result in one or more Instances Transferred * or Instances Accessed messages, depending on what events transpire after the * query. If there were security-related failures, such as access violations, * when processing a query, those failures should show up in other audit * messages, such as a Security Alert message.</li> * <li>Non-DICOM queries may also be captured by this message. The Participant * Object ID Type Code, the Participant Object ID, and the Query fields may * have values related to such non-DICOM queries.</li> * </ol> * </blockquote> * * @author Gunter Zeilinger <[email protected]> * @version $Revision: 5724 $ $Date: 2008-01-21 12:56:19 +0100 (Mo, 21 Jan 2008) $ * @since Nov 23, 2006 * @see <a href="ftp://medical.nema.org/medical/dicom/supps/sup95_fz.pdf"> * DICOM Supp 95: Audit Trail Messages, A.1.3.13 Query</a> */ public class QueryMessage extends AuditMessage { public QueryMessage() { super(new AuditEvent(AuditEvent.ID.QUERY, AuditEvent.ActionCode.EXECUTE)); } public ActiveParticipant addSourceProcess(String processID, String[] aets, String processName, String hostname, boolean requestor) { return addActiveParticipant( ActiveParticipant.createActiveProcess(processID, aets, processName, hostname, requestor) .addRoleIDCode(ActiveParticipant.RoleIDCode.SOURCE)); } public ActiveParticipant addDestinationProcess(String processID, String[] aets, String processName, String hostname, boolean requestor) { return addActiveParticipant( ActiveParticipant.createActiveProcess(processID, aets, processName, hostname, requestor) .addRoleIDCode(ActiveParticipant.RoleIDCode.DESTINATION)); } public ActiveParticipant addOtherParticipantPerson(String userID, String altUserID, String userName, String hostname, boolean requestor) { return addActiveParticipant( ActiveParticipant.createActivePerson(userID, altUserID, userName, hostname, requestor)); } public ActiveParticipant addOtherParticipantProcess(String processID, String[] aets, String processName, String hostname, boolean requestor) { return addActiveParticipant( ActiveParticipant.createActiveProcess(processID, aets, processName, hostname, requestor)); } public ParticipantObject addQuerySOPClass(String cuid, String tsuid, byte[] query) { return addParticipantObject( ParticipantObject.createQuerySOPClass(cuid, tsuid, query)); } @Override public void validate() { super.validate(); ActiveParticipant source = null; ActiveParticipant dest = null; ActiveParticipant requestor = null; for (ActiveParticipant ap : activeParticipants) { List<ActiveParticipant.RoleIDCode> roleIDCodeIDs = ap.getRoleIDCodes(); if (roleIDCodeIDs.contains( ActiveParticipant.RoleIDCode.SOURCE)) { if (source != null) { throw new IllegalStateException( "Multiple Source identification"); } source = ap; } else if (roleIDCodeIDs.contains( ActiveParticipant.RoleIDCode.DESTINATION)) { if (dest != null) { throw new IllegalStateException( "Multiple Destination identification"); } dest = ap; } if (ap.isUserIsRequestor()) { requestor = ap; } } if (source == null) { throw new IllegalStateException("No Source identification"); } if (dest == null) { throw new IllegalStateException("No Destination identification"); } if (requestor == null) { throw new IllegalStateException("No Requesting User"); } ParticipantObject sopClass = null; for (ParticipantObject po : participantObjects) { if (ParticipantObject.TypeCodeRole.REPORT == po.getParticipantObjectTypeCodeRole() && ParticipantObject.IDTypeCode.SOP_CLASS_UID == po.getParticipantObjectIDTypeCode()) { if (sopClass != null) { throw new IllegalStateException( "Multiple Query SOP Class identification"); } sopClass = po; } } if (sopClass == null) { throw new IllegalStateException("No Query SOP Class identification"); } } }
9126bafe66276778b2d91248d3ad27527b30cef3
2e720dbebd3ad729a98346f34c4656394a9dd94d
/javascope/jScope/JiDim.java
8ae5d6e2f73b6702662d0f9a83c856bea9d6590b
[ "BSD-2-Clause" ]
permissive
AndreaRigoni/mdsplus
673334aced07093f143b428848e4f70366336d00
ea7bd165e0e06e4f71ad9ad6369aace1dbffddcb
refs/heads/alpha
2021-05-23T20:58:23.205897
2018-10-16T13:01:54
2018-10-16T13:01:54
41,412,893
0
0
NOASSERTION
2019-12-05T11:25:39
2015-08-26T08:06:49
C
UTF-8
Java
false
false
854
java
package jScope; /* $Id$ */ import java.io.*; public class JiDim { public int mStart, mCount, mStride; public String mName; public JiDim(String name, int start, int count) { mName = name; mStart = start; mCount = count; mStride = 1; } public JiDim(String name, int start, int count, int stride) { mName = name; mStart = start; mCount = count; mStride = stride; } protected Object clone() { return new JiDim(mName, mStart, mCount, mStride); } public JiDim copy() { return (JiDim)clone(); } public JiVar getCoordVar() throws IOException { throw new IOException("JiDim::getCoordVar() : not supported"); } public String getName() { return mName; } public String toString() { return "(" + mName + "," + mStart + "," + mCount + "," + mStride + ")"; } }
97675342f97bfc0ec48470bb49e468708483db34
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/google--error-prone/d6494a8eadecc6b2e70c7976fb5256c42669cbe7/before/NegativeCase1.java
0437599d87fd3d7f3bab9633a4b079ec34c577f0
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
1,249
java
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package preconditions_expensive_string; import com.google.common.base.Preconditions; /** * Preconditions calls which shouldn't be picked up for expensive string operations * * @author [email protected] (Simon Nickerson) */ public class NegativeCase1 { public void error() { int foo = 42; Preconditions.checkState(true, "The foo %s foo is not a good foo", foo); // This call should not be converted because of the %d, which does some locale specific // behaviour. If it were an %s, it would be fair game. Preconditions.checkState(true, String.format("The foo %d foo is not a good foo", foo)); } }