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
021466487911f3ecd1695fa63795ef79e4ff9f9f
b220f06f194e7d05a9b24fbb2b655e77fcdb9def
/app/src/main/java/br/com/faculdade/dao/DisciplinaDAO.java
eb246ed2069c5d7ee64d0735d2d336c82b83cb87
[]
no_license
cardoso010/Faculdade
8a2072a4f3f449695825158606c4fe46a68f9c57
70662a6a4e38e8c9bdad2ecea8fdd885f72d6d7e
refs/heads/master
2021-01-19T03:17:21.018627
2016-06-30T21:35:17
2016-06-30T21:35:17
62,342,908
0
0
null
null
null
null
UTF-8
Java
false
false
3,650
java
package br.com.faculdade.dao; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.util.ArrayList; import java.util.List; import br.com.faculdade.models.Disciplina; /** * Created by cardoso on 26/04/16. */ public class DisciplinaDAO extends SQLiteOpenHelper{ private static final String DATABASE = "Faculdade"; private static final int VERSAO = 1; public DisciplinaDAO(Context context) { super(context, DATABASE, null, VERSAO); } public void salvar(Disciplina disciplina) { ContentValues values = new ContentValues(); values.put("nome", disciplina.getNome()); values.put("periodo", disciplina.getPeriodo()); values.put("primeira_prova", disciplina.getPrimeiraProva()); values.put("segunda_prova", disciplina.getSegundaProva()); values.put("primeiro_trabalho", disciplina.getPrimeiroTrabalho()); values.put("segundo_trabalho", disciplina.getSegundoTrabalho()); getWritableDatabase().insert("Disciplinas", null, values); } @Override public void onCreate(SQLiteDatabase db) { String ddl = "CREATE TABLE Disciplinas (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "nome TEXT UNIQUE NOT NULL," + "periodo INTEGER NOT NULL," + "primeira_prova REAL," + "segunda_prova REAL," + "primeiro_trabalho REAL," + "segundo_trabalho REAL);"; db.execSQL(ddl); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String ddl = "DROP TABLE IF EXISTS Disciplinas"; db.execSQL(ddl); this.onCreate(db); } public List<Disciplina> getLista() { String[] colunas = {"id", "nome", "periodo", "primeira_prova", "segunda_prova", "primeiro_trabalho", "segundo_trabalho"}; Cursor cursor = getWritableDatabase().query("Disciplinas", colunas, null, null, null, null, null); ArrayList<Disciplina> disciplinas = new ArrayList<Disciplina>(); while (cursor.moveToNext()) { Disciplina disciplina = new Disciplina(); disciplina.setId(cursor.getInt(0)); disciplina.setNome(cursor.getString(1)); disciplina.setPeriodo(cursor.getInt(2)); disciplina.setPrimeiraProva(cursor.getFloat(3)); disciplina.setSegundaProva(cursor.getFloat(4)); disciplina.setPrimeiroTrabalho(cursor.getFloat(5)); disciplina.setSegundoTrabalho(cursor.getFloat(6)); disciplinas.add(disciplina); } return disciplinas; } public void deletar(Disciplina disciplina) { String[] args = {Integer.toString(disciplina.getId())}; getWritableDatabase().delete("Disciplinas", "id=?", args); } public void alterar(Disciplina disciplina) { ContentValues values = new ContentValues(); values.put("nome", disciplina.getNome()); values.put("periodo", disciplina.getPeriodo()); values.put("primeira_prova", disciplina.getPrimeiraProva()); values.put("segunda_prova", disciplina.getSegundaProva()); values.put("primeiro_trabalho", disciplina.getPrimeiroTrabalho()); values.put("segundo_trabalho", disciplina.getSegundoTrabalho()); String[] args = { String.valueOf(disciplina.getId()) }; getWritableDatabase().update("Disciplinas", values, "id=?", args); } }
176ac6242e548615b5b4d1cf8928ee5a512398bc
6ba8be7fff3eeccbf1a5d1f10abd8522fe530099
/src/main/java/com/no3003/fatlonely/util/HttpUtil.java
cc77b934643f60cadda8d8f253f8131df0e25643
[]
no_license
LHH7049/FatLonely
71ccc7e0b0fe953fafcdb45f481109610fbb697a
2af68fcfbb20f9278e29eee6545f78178a62904e
refs/heads/master
2023-05-10T02:25:05.837967
2021-06-01T01:25:57
2021-06-01T01:25:57
361,995,658
0
0
null
null
null
null
UTF-8
Java
false
false
2,788
java
package com.no3003.fatlonely.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Author: lz * @Date: 2021/5/11 10:31 */ public class HttpUtil { private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class); public static String getClientIpAddress(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (ip == null) { return ""; } int pos = ip.indexOf(","); if (pos > 0) { String[] ipArray = ip.split(","); int i = 0; for (i = 0; i < ipArray.length; i++) { String ipSub = ipArray[i].trim(); if (!"unknown".equalsIgnoreCase(ipSub)) { ip = ipSub; break; } } if (i >= ipArray.length) { logger.warn("IP is full of 'unknown'"); ip = ipArray[i - 1].trim(); } } if (ip.length() <= 16) { return ip; } else { logger.warn("IP of length > 16 : " + ip); return ip.substring(0, 16); } } public static String getIP(){ HttpServletRequest request = getHttpServletRequest(); if (request != null){ return getClientIpAddress(request); } return ""; } public static void setCookieValue(HttpServletResponse response, String name, String value, int expire){ Cookie cookie = new Cookie(name, value); cookie.setMaxAge(expire); cookie.setSecure(false); cookie.setHttpOnly(true); cookie.setPath("/"); response.addCookie(cookie); } public static HttpServletRequest getHttpServletRequest(){ try { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); if (attr == null) { return null; } return attr.getRequest(); } catch (Exception e) { return null; } } }
b43620726fa5fcc6e476edb5464aaf6a848a40cb
331fccf22ca45d63e363009dcc873da2147feafd
/BroadWeb/src/main/java/com/springbook/biz/common/AfterThrowingAdvice.java
2b816d20a42119805ed4e3472e7192f9ce4503cb
[]
no_license
cielKim/MVCs
50b87edb84dd6ce58a6696c194f75522706f92da
667d68622729cd3127d7095abd76eb69855db38f
refs/heads/master
2021-04-27T04:13:32.996602
2018-02-24T09:55:45
2018-02-24T09:55:45
122,727,388
0
0
null
null
null
null
UTF-8
Java
false
false
968
java
package com.springbook.biz.common; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Service; @Service @Aspect public class AfterThrowingAdvice { @AfterThrowing(pointcut="PointcutCommon.allPointcut()", throwing="exceptObj") public void exceptionLog(JoinPoint jp, Exception exceptObj) { String method = jp.getSignature().getName(); System.out.println(method + "()메소드 수행 중 예외 발생!"); if(exceptObj instanceof IllegalArgumentException) { System.out.println("부적합한 값이 입력되었습니다."); } else if(exceptObj instanceof NumberFormatException) { System.out.println("숫자 형식의 값이 아닙니다."); } else if(exceptObj instanceof Exception) { System.out.println("문제가 발생했습니다."); } } }
fa6fd792ad6885ff0f01da42d6d15f300545bf9a
05fb5c7f434ced78d09271c04d7d2e290f3d4a5e
/guns-common-api/src/main/java/com/stylefeng/guns/rest/modular/cinema/CinemaServiceAPI.java
457ef509f5336096d3f7a375b1aea66c8dffe9ee
[ "Apache-2.0" ]
permissive
xiaofei20190625/project4_FilmTicketing
7bdd581711f23d1debeacc78a2c3185329b5cb20
58af1f80e5d2c63c50e8a0fab4291c8ee777c9c8
refs/heads/master
2022-10-28T02:29:10.668206
2020-05-09T09:43:30
2020-05-09T09:43:30
196,984,796
2
0
NOASSERTION
2022-10-12T20:29:17
2019-07-15T11:23:16
Java
UTF-8
Java
false
false
1,036
java
package com.stylefeng.guns.rest.modular.cinema; import com.baomidou.mybatisplus.plugins.Page; import com.stylefeng.guns.rest.modular.cinema.vo.*; import java.util.List; public interface CinemaServiceAPI { List<CinemaVo> getCinema(String brandId); //根据CinemaQueryVO查询影院列表 Page<CinemaVo> getCinemas(CinemaQueryVo cinemaQueryVo); CinemaInfo getFields(int cinemaId); List<FilmList> getFilmList(int cinemaId); //获取所有电源信息和对应放映场次信息 List<FilmList> getFilmInfoByCinemaId(int cinemaId); //根据条件获取品牌列表(除99以外其他数字都有效) List<BrandVo> getBrands(int brandId); //行政区域 List<AreaVo> getAreas(int areaId); //影厅类型 List<HallTypeVo> getHallTypes(int hallTypeId); //影院信息 CinemaInfo getCinemaInfoById(int cinemaId); //放映信息 HallInfoVo getFilmFieldInfo(int fieldId); //放映场次-->电源编号-->电影信息 FilmInfo getFilmInfoByFieldId(int fieldId); }
baf986ac7cebb35f252ceb26a43494163f42dd13
bb450bef04f1fab24a03858343f3e8fd9c5061ee
/tests/sources/local/tools/0_monitor/src/main/java/monitor/Matmul.java
e5014958c4bb79187132b2d1e507c8ce13596d0a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bsc-wdc/compss
c02b1c6a611ed50d5f75716d35bd8201889ae9d8
5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092
refs/heads/stable
2023-08-16T02:51:46.073185
2023-08-04T21:43:31
2023-08-04T21:43:31
123,949,037
39
21
Apache-2.0
2022-07-05T04:08:53
2018-03-05T16:44:51
Java
UTF-8
Java
false
false
4,165
java
package monitor; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class Matmul { private static final int MSIZE = 8; private static final int BSIZE = 2; private double[][][] A; private double[][][] B; private double[][][] C; public static void main(String args[]) { // Get parameters if (args.length != 3) { System.out.println("[ERROR] Usage: matmul <Ain> <Bin> <Cout>"); System.exit(-1); } String fA = args[0]; String fB = args[1]; String fC = args[2]; System.out.println("[LOG] MSIZE parameter value = " + MSIZE); System.out.println("[LOG] BSIZE parameter value = " + BSIZE); // Run matmul app Matmul matmul = new Matmul(); matmul.Run(fA, fB); // Check result System.out.println("[LOG] Storing C matrix obtained"); matmul.storeMatrix(fC); System.out.println("[LOG] Main program finished. Result needs to be checked (result script)"); } private void Run(String fileA, String fileB) { // Load Matrices System.out.println("[LOG] Allocating A/B/C matrix space"); A = new double[MSIZE][MSIZE][BSIZE * BSIZE]; B = new double[MSIZE][MSIZE][BSIZE * BSIZE]; C = new double[MSIZE][MSIZE][BSIZE * BSIZE]; System.out.println("[LOG] Loading A Matrix from file"); loadMatrix(A, fileA); System.out.println("[LOG] Loading B Matrix from file"); loadMatrix(B, fileB); // Compute result System.out.println("[LOG] Computing Result"); for (int i = 0; i < MSIZE; i++) { for (int j = 0; j < MSIZE; j++) { for (int k = 0; k < MSIZE; k++) { MatmulImpl.multiplyAccumulative(A[i][k], B[k][j], C[i][j]); } } } } private void loadMatrix(double[][][] matrix, String fileName) { try { FileReader filereader = new FileReader(fileName); BufferedReader br = new BufferedReader(filereader); StringTokenizer tokens; String nextLine; for (int i = 0; i < MSIZE; ++i) { for (int j = 0; j < MSIZE; ++j) { nextLine = br.readLine(); tokens = new StringTokenizer(nextLine); for (int block = 0; block < BSIZE * BSIZE && tokens.hasMoreTokens(); ++block) { String value = tokens.nextToken(); matrix[i][j][block] = Double.parseDouble(value); } } nextLine = br.readLine(); } br.close(); filereader.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(-1); } } private void storeMatrix(String fileName) { try { FileOutputStream fos = new FileOutputStream(fileName); for (int i = 0; i < MSIZE; ++i) { for (int j = 0; j < MSIZE; ++j) { for (int block = 0; block < BSIZE * BSIZE; ++block) { String value = String.valueOf(C[i][j][block]) + " "; fos.write(value.getBytes()); } fos.write("\n".getBytes()); } fos.write("\n".getBytes()); } fos.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(-1); } } @SuppressWarnings("unused") private void printMatrix(double[][][] matrix, String name) { System.out.println("MATRIX " + name); for (int i = 0; i < MSIZE; i++) { for (int j = 0; j < MSIZE; j++) { MatmulImpl.printBlock(matrix[i][j]); } System.out.println(""); } } }
[ "cramonco@9ab3861e-6c05-4e1b-b5ef-99af60850597" ]
cramonco@9ab3861e-6c05-4e1b-b5ef-99af60850597
17e85addd5230f43408491add1d4e97d1a53ad9b
74777ffa4616a589ca954fb83af747656ac26aee
/src/gaopei/Question155.java
0ebeae66347cbe2aab85a1890ea1e42f5ae90870
[]
no_license
gaoppp/LeetCode
84af767f43eb8aa46fdcf8dcd7c1add35bdad01f
2956dd0e03a33317a8f00cf17367614112613ea9
refs/heads/master
2023-01-02T11:21:45.166388
2020-11-02T14:30:54
2020-11-02T14:30:54
299,341,428
0
0
null
null
null
null
UTF-8
Java
false
false
1,426
java
package gaopei; import java.util.Stack; /** * 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 * <p> * push(x) —— 将元素 x 推入栈中。 * pop() —— 删除栈顶的元素。 * top() —— 获取栈顶元素。 * getMin() —— 检索栈中的最小元素。 */ public class Question155 { public static class MinStack { private Stack<Integer> data; private Stack<Integer> min; public MinStack() { data = new Stack<>(); min = new Stack<>(); } public void push(int x) { data.push(x); if (min.isEmpty() || x <= min.peek()) { min.push(x); } } public void pop() { if (data.pop().equals(min.peek())) { min.pop(); } } public int top() { return data.peek(); } public int getMin() { return min.peek(); } } public static void main(String[] args) { MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-2); System.out.println(minStack.getMin()); // --> 返回 -3. minStack.pop(); System.out.println(minStack.top()); // --> 返回 0. System.out.println(minStack.getMin()); // --> 返回 -2. } }
45eb8c0c7b51e97261a00c6eaf06ad92d9e411a5
141141b446bec5af0963b8d5f15245cd0b8d7077
/Module2_Spring_Javacore_Database/blog_management/src/main/java/com/codegym/cms/model/Category.java
6724123e6e4c6336cd76b09c2fd27d516b481b7b
[]
no_license
ledinhquoc/LeDinhQuoc_CodeGymDaNang_C1119G1
41173126b8ef6524b85e581f32238544e7515db8
002d9359a1d4f474ad7e62d30c9eb29c8c6d71ce
refs/heads/master
2023-01-08T19:17:31.303670
2020-04-20T14:53:09
2020-04-20T14:53:09
223,861,203
0
0
null
2023-01-07T21:56:53
2019-11-25T04:31:12
CSS
UTF-8
Java
false
false
777
java
package com.codegym.cms.model; import javax.persistence.*; import java.util.List; @Entity @Table (name = "category") public class Category { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; @OneToMany(targetEntity = Post.class) private List<Post> postList; public Category() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Post> getPostList() { return postList; } public void setPostList(List<Post> postList) { this.postList = postList; } }
2094f9e8522261c5f569dff65e9478b1178b0df6
98d313cf373073d65f14b4870032e16e7d5466f0
/gradle-open-labs/example/src/main/java/se/molybden/Class7771.java
4a3a9d84d98b152cce8cf456c7e2bade056240e0
[]
no_license
Molybden/gradle-in-practice
30ac1477cc248a90c50949791028bc1cb7104b28
d7dcdecbb6d13d5b8f0ff4488740b64c3bbed5f3
refs/heads/master
2021-06-26T16:45:54.018388
2016-03-06T20:19:43
2016-03-06T20:19:43
24,554,562
0
0
null
null
null
null
UTF-8
Java
false
false
109
java
public class Class7771{ public void callMe(){ System.out.println("called"); } }
317aadfa4b1e5c82e30cd8b35c66239f3173afcb
5cefafafa516d374fd600caa54956a1de7e4ce7d
/oasis/web/OasisTags/src/java/dti/oasis/ows/util/impl/FilterViewElementDependencyImpl.java
c9cb2ef5a1b27ea4cb00c7e3f4069e11acf06e42
[]
no_license
TrellixVulnTeam/demo_L223
18c641c1d842c5c6a47e949595b5f507daa4aa55
87c9ece01ebdd918343ff0c119e9c462ad069a81
refs/heads/master
2023-03-16T00:32:08.023444
2019-04-08T15:46:48
2019-04-08T15:46:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,153
java
package dti.oasis.ows.util.impl; import dti.oasis.ows.util.FilterViewElement; import dti.oasis.ows.util.FilterViewElementDependency; import dti.oasis.util.LogUtils; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * <p>(C) 2003 Delphi Technology, inc. (dti)</p> * Date: 4/19/2017 * * @author kshen */ /* * * Revision Date Revised By Description * --------------------------------------------------- * * --------------------------------------------------- */ public class FilterViewElementDependencyImpl implements FilterViewElementDependency { private final Logger l = LogUtils.getLogger(getClass()); public FilterViewElementDependencyImpl(String category) { m_category = category; m_elementDependencyMap = new HashMap<FilterViewElement, Set<FilterViewElement>>(); } @Override public Set<FilterViewElement> getDependencyElements(String filterType, String elementName) { if (l.isLoggable(Level.FINER)) { l.entering(getClass().getName(), "getDependencyElements", new Object[]{filterType, elementName}); } FilterViewElement filterViewElement = new FilterViewElement(filterType, elementName); Set<FilterViewElement> filterViewElements = m_elementDependencyMap.get(filterViewElement); if (l.isLoggable(Level.FINER)) { l.exiting(getClass().getName(), "getDependencyElements", filterViewElements); } return filterViewElements; } @Override public String getCategory() { return m_category; } public void setCategory(String category) { m_category = category; } public Map<FilterViewElement, Set<FilterViewElement>> getElementDependencyMap() { return m_elementDependencyMap; } public void setElementDependencyMap(Map<FilterViewElement, Set<FilterViewElement>> elementDependencyMap) { m_elementDependencyMap = elementDependencyMap; } private String m_category; private Map<FilterViewElement, Set<FilterViewElement>> m_elementDependencyMap; }
432a39cc744b1269879ce9d12159736bbae79ae4
8a4ad9f611b1067b3358fedb7b5b678d08a69502
/GraphTheory/tests/FloydWarshallSolverTest.java
acc371351f6d6e8a1e65536266189377125b8a79
[ "MIT" ]
permissive
mohdanishh/Algorithms
7686defb3e52589fa968492375c839dd1decdb66
f9ce60de1dcfdde41b39f411c5c2aa04ae0128ff
refs/heads/master
2021-04-26T23:20:39.146968
2018-03-02T05:12:30
2018-03-02T05:12:30
123,976,241
0
1
MIT
2018-03-05T20:42:46
2018-03-05T20:42:46
null
UTF-8
Java
false
false
6,852
java
import static com.google.common.truth.Truth.assertThat; import java.util.*; import org.junit.Before; import org.junit.Test; public class FloydWarshallSolverTest { static final double INF = Double.POSITIVE_INFINITY; static final double NEG_INF = Double.NEGATIVE_INFINITY; static double[][] matrix1, matrix2, matrix3; @Before public void setup() { matrix1 = new double[][] { { 0, INF, INF, INF, INF}, { 1, 0, 7, INF, INF}, {INF, 3, 0, INF, INF}, { 13, INF, 4, 0, INF}, {INF, INF, 3, 0, 0} }; matrix2 = new double[][] { { 0, 3, 1, 8, INF}, { 2, 0, 9, 4, INF}, {INF, INF, 0, INF, -2}, {INF, INF, 1, 0, INF}, {INF, INF, INF, 0, 0} }; matrix3 = new double[][] { { 0, 6, INF, 25, 3}, { 1, 0, 6, 1, 3}, { INF, 1, 0, 2, 3}, { 4, 4, 4, 0, INF}, { 4, 3, 5, INF, 0} }; } private static double[][] createMatrix(int n) { double[][] m = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { m[i][j] = Double.POSITIVE_INFINITY; m[i][i] = 0; } } return m; } private static void addRandomEdges(double[][] matrix, int count, boolean allowNegativeEdges) { int n = matrix.length; while(count-- > 0) { int i = (int)(Math.random() * n); int j = (int)(Math.random() * n); if (i == j) continue; int v = (int)(Math.random() * 100); // Allow negative edges but only very rarely since even one // negative edge can start an avalanche of negative cycles. if (allowNegativeEdges) v = (Math.random() > 0.005) ? v : -v; matrix[i][j] = v; } } @Test public void testDirectedGraph() { FloydWarshallSolver solver = new FloydWarshallSolver(matrix1); double[][] soln = solver.getApspMatrix(); assertThat(soln[0][0]).isEqualTo(0.0); assertThat(soln[1][0]).isEqualTo(1.0); assertThat(soln[1][1]).isEqualTo(0.0); assertThat(soln[1][2]).isEqualTo(7.0); assertThat(soln[2][0]).isEqualTo(4.0); assertThat(soln[2][1]).isEqualTo(3.0); assertThat(soln[2][2]).isEqualTo(0.0); assertThat(soln[3][0]).isEqualTo(8.0); assertThat(soln[3][1]).isEqualTo(7.0); assertThat(soln[3][2]).isEqualTo(4.0); assertThat(soln[3][3]).isEqualTo(0.0); assertThat(soln[4][0]).isEqualTo(7.0); assertThat(soln[4][1]).isEqualTo(6.0); assertThat(soln[4][2]).isEqualTo(3.0); assertThat(soln[4][3]).isEqualTo(0.0); assertThat(soln[4][4]).isEqualTo(0.0); } @Test public void testNegativeCycleGraph() { FloydWarshallSolver solver = new FloydWarshallSolver(matrix2); double[][] soln = solver.getApspMatrix(); assertThat(soln[0][0]).isEqualTo(0.0); assertThat(soln[0][1]).isEqualTo(3.0); assertThat(soln[0][2]).isEqualTo(NEG_INF); assertThat(soln[0][3]).isEqualTo(NEG_INF); assertThat(soln[0][4]).isEqualTo(NEG_INF); assertThat(soln[1][0]).isEqualTo(2.0); assertThat(soln[1][1]).isEqualTo(0.0); assertThat(soln[1][2]).isEqualTo(NEG_INF); assertThat(soln[1][3]).isEqualTo(NEG_INF); assertThat(soln[1][4]).isEqualTo(NEG_INF); assertThat(soln[2][2]).isEqualTo(NEG_INF); assertThat(soln[2][3]).isEqualTo(NEG_INF); assertThat(soln[2][4]).isEqualTo(NEG_INF); assertThat(soln[3][2]).isEqualTo(NEG_INF); assertThat(soln[3][3]).isEqualTo(NEG_INF); assertThat(soln[3][4]).isEqualTo(NEG_INF); assertThat(soln[4][2]).isEqualTo(NEG_INF); assertThat(soln[4][3]).isEqualTo(NEG_INF); assertThat(soln[4][4]).isEqualTo(NEG_INF); } @Test public void testApspAgainstBellmanFord_nonNegativeEdgeWeights() { final int TRAILS = 10; for (int n = 2; n <= 25; n++) { for (int trail = 1; trail <= TRAILS; trail++) { double[][] m = createMatrix(n); int numRandomEdges = Math.max(1, (int)(Math.random()*n*n)); addRandomEdges(m, numRandomEdges, false); double[][] fw = new FloydWarshallSolver(m).getApspMatrix(); for (int s = 0; s < n; s++) { double[] bf = new BellmanFordAdjacencyMatrix(s, m).getShortestPaths(); assertThat(bf).isEqualTo(fw[s]); } } } } @Test public void testApspAgainstBellmanFord_withNegativeEdgeWeights() { final int TRAILS = 10; for (int n = 2; n <= 25; n++) { for (int trail = 1; trail <= TRAILS; trail++) { double[][] m = createMatrix(n); int numRandomEdges = Math.max(1, (int)(Math.random()*n*n)); addRandomEdges(m, numRandomEdges, true); double[][] fw = new FloydWarshallSolver(m).getApspMatrix(); for (int s = 0; s < n; s++) { double[] bf = new BellmanFordAdjacencyMatrix(s, m).getShortestPaths(); assertThat(bf).isEqualTo(fw[s]); } } } } // Tests for a mismatch in how both algorithms detect the existence of // a negative cycle on the shortest path from s -> e. @Test public void testPathReconstructionBellmanFord_nonNegativeEdgeWeights() { final int TRAILS = 50; for (int n = 2; n <= 25; n++) { for (int trail = 1; trail <= TRAILS; trail++) { double[][] m = createMatrix(n); int numRandomEdges = Math.max(1, (int)(Math.random()*n*n)); addRandomEdges(m, numRandomEdges, true); FloydWarshallSolver fwSolver = new FloydWarshallSolver(m); fwSolver.solve(); for (int s = 0; s < n; s++) { BellmanFordAdjacencyMatrix bfSolver = new BellmanFordAdjacencyMatrix(s, m); for (int e = 0; e < n; e++) { // Make sure that if 'fwp' returns null that 'bfp' also returns null or // that if 'fwp' is not null that 'bfp' is also not null. List<Integer> fwp = fwSolver.reconstructShortestPath(s, e); List<Integer> bfp = bfSolver.reconstructShortestPath(e); if ((fwp == null) ^ (bfp == null)) { org.junit.Assert.fail("Mismatch."); } } } } } } @Test public void testSimpleNegativeCycleDetection() { int n = 3, s = 0, e = 2; double[][] m = createMatrix(n); m[0][1] = 100; m[0][2] = 5; m[1][2] = 0; m[1][1] = -1; // negative self loop. FloydWarshallSolver fw = new FloydWarshallSolver(m); List<Integer> fwPath = fw.reconstructShortestPath(s, e); assertThat(fwPath).isNull(); } @Test public void testNegativeCyclePropagation() { int n = 100, s = 0, e = n-1; double[][] m = createMatrix(n); for(int i = 1; i < n; i++) m[i-1][i] = 10; m[1][0] = -11; FloydWarshallSolver fw = new FloydWarshallSolver(m); List<Integer> fwPath = fw.reconstructShortestPath(s, e); assertThat(fwPath).isNull(); } }
f84c78606d5927c208cd0ab8121ee2ba7c03f4fa
cb5454f57111c5e6349072537de573ac23ca8cd8
/app/src/main/java/com/example/lee/finalproject/HelpInfo.java
48f3426af496a20bf2e9e1608d6999af537d031c
[]
no_license
praylee/FinalProject2
c2f2146c398b266a181b23e0c679214727c7fc1e
93b8d080514098a96deaff2bc0d4a88fa84bc83b
refs/heads/master
2020-03-25T07:19:17.748670
2018-08-04T18:26:36
2018-08-04T18:26:36
143,554,005
0
0
null
null
null
null
UTF-8
Java
false
false
314
java
package com.example.lee.finalproject; import android.os.Bundle; import android.app.Activity; public class HelpInfo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help_info); } }
4855a838662adbc66a13248945e08be6b1b9668b
92c3d8c1612e230f6459be042c33441a5cb22a42
/app/src/main/java/com/example/android/notes/DBHelper.java
53eb3ff192f7a105932811bbe60b691d6ba87c34
[]
no_license
Hoss3770/androidNotes
1c43d4aa47a28e34db7e66296cda1dde29f9551a
e8986cc3eb20b399528897ce37088c4ff772276f
refs/heads/master
2021-01-18T18:00:32.268491
2017-03-31T15:32:14
2017-03-31T15:32:14
86,834,427
1
0
null
null
null
null
UTF-8
Java
false
false
2,400
java
package com.example.android.notes; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.HashMap; public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "MyDBName.db"; public static final String NOTES_TABLE_NAME = "notes"; public static final String NOTES_COLUMN_ID = "id"; public static final String NOTES_COLUMN_TITLE = "title"; public static final String NOTES_COLUMN_TEXT = "text"; private HashMap hp; public DBHelper(Context context){ super(context,DATABASE_NAME,null,2); } @Override public void onCreate(SQLiteDatabase db){ db.execSQL("create table notes (id INTEGER PRIMARY KEY, title text,text text)"); } @Override public void onUpgrade(SQLiteDatabase db , int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } public boolean insertNote (String title, String text) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues note = new ContentValues(); note.put("title", title); note.put("text",text); db.insert("notes", null, note); return true; } public Cursor getData(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery("select * from notes where id = ? ", new String [] { Integer.toString(id)}); return res; } public int numberOfRows(){ SQLiteDatabase db = this.getReadableDatabase(); int numRows = (int) DatabaseUtils.queryNumEntries(db,NOTES_TABLE_NAME); return numRows; } public boolean updateNote(Integer id,String title,String text){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues note = new ContentValues(); note.put("title",title); note.put("text",text); db.update("notes",note,"id = ?", new String [] {Integer.toString(id)}); return true; } public boolean deleteNote(Integer id){ SQLiteDatabase db = this.getReadableDatabase(); db.delete("notes","id = ?",new String []{Integer.toString(id)}); return true; } }
967e1f3315152f74fa7c1667f3e9bfd03249cab3
32f38cd53372ba374c6dab6cc27af78f0a1b0190
/app/src/main/java/com/autonavi/jni/ae/gmap/gloverlay/GLOverlay.java
7cd54ce1d921afe6fddc0085d081cd67fa28ee04
[]
no_license
shuixi2013/AmapCode
9ea7aefb42e0413f348f238f0721c93245f4eac6
1a3a8d4dddfcc5439df8df570000cca12b15186a
refs/heads/master
2023-06-06T23:08:57.391040
2019-08-29T04:36:02
2019-08-29T04:36:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,814
java
package com.autonavi.jni.ae.gmap.gloverlay; import com.autonavi.ae.gmap.gloverlay.BaseMapOverlay; import com.autonavi.jni.ae.gmap.GLMapEngine; public abstract class GLOverlay { public static final int OverlayDrawEventTypeAll = -1; public static final int OverlayDrawEventTypeFinished = 1; public static final int OverlayDrawEventTypeNone = 0; protected boolean isNightStyle = false; protected int mCode; private OnDrawOverlayListener mDrawOverlayListener = null; protected int mEngineID; protected akq mGLMapView; protected boolean mIsInBundle = false; protected int mItemPriority = 0; protected long mNativeInstance = 0; private int mOverlayDrawObserverType = 0; public enum AnimationStatusType { AnimationStatusTypeNone(0), AnimationStatusTypeStart(1), AnimationStatusTypeDoing(2), AnimationStatusTypeNormalEnd(3), AnimationStatusTypeForceEnd(4), AnimationStatusTypeRemoved(5); private final int value; private AnimationStatusType(int i) { this.value = i; } public final int value() { return this.value; } public static AnimationStatusType valueOf(int i) { switch (i) { case 1: return AnimationStatusTypeStart; case 2: return AnimationStatusTypeDoing; case 3: return AnimationStatusTypeNormalEnd; case 4: return AnimationStatusTypeForceEnd; case 5: return AnimationStatusTypeRemoved; default: return AnimationStatusTypeNone; } } } public enum EAMapOverlayTpye { AMAPOVERLAY_POINT, AMAPOVERLAY_POLYLINE, AMAPOVERLAY_POLYGON, AMAPOVERLAY_NAVI, AMAPOVERLAY_GPS, AMAPOVERLAY_ARC, AMAPOVERLAY_ARROW, AMAPOVERLAY_VECTOR, AMAPOVERLAY_MODEL, AMAPOVERLAY_RCTROUTE, AMAPOVERLAY_ROUTE, AMAPOVERLAY_WATERWAVE, AMAPOVERLAY_PLANE, AMAPOVERLAY_RASTER, AMAPOVERLAY_SKELETON } public enum EOverlaySubType { ESubTypeMember(20180622); private int mValue; private EOverlaySubType(int i) { this.mValue = i; } public final int value() { return this.mValue; } } public interface OnDrawOverlayListener { void onProcessOverlayDrawEvent(OverlayDrawEvent overlayDrawEvent); } public static class OverlayAnimationEvent { public long mAnimationObject; public int mEngineID; public AnimationStatusType mStatus; public OverlayAnimationEvent(int i, int i2, long j) { this.mStatus = AnimationStatusType.valueOf(i); this.mEngineID = i2; this.mAnimationObject = j; } } public interface OverlayAnimationListener { void onProcessOverlayAnimationEvent(OverlayAnimationEvent overlayAnimationEvent); } public static class OverlayDrawEvent { int mEventType; GLOverlay mOverlay; public OverlayDrawEvent(GLOverlay gLOverlay, int i) { this.mOverlay = gLOverlay; this.mEventType = i; } public GLOverlay getOverlay() { return this.mOverlay; } public int getEventType() { return this.mEventType; } } private static native int nativeGetCount(long j); private static native float[] nativeGetDisplayScale(long j); private static native int nativeGetOverlayDrawObserverType(long j, GLOverlay gLOverlay); private static native int nativeGetOverlayPriority(long j); private static native int nativeGetSubType(long j); private static native int nativeGetType(long j); private static native boolean nativeIsClickable(long j); private static native boolean nativeIsVisible(long j); private static native void nativeRemoveAll(long j); private static native void nativeRemoveItem(long j, int i); private static native void nativeSetClickable(long j, boolean z); private static native void nativeSetMaxDisplayLevel(long j, float f); private static native void nativeSetMinDisplayLevel(long j, float f); private static native void nativeSetOverlayDrawObserver(long j, OnDrawOverlayListener onDrawOverlayListener, GLOverlay gLOverlay); private static native void nativeSetOverlayDrawObserverType(long j, int i, GLOverlay gLOverlay); private static native void nativeSetOverlayItemPriority(long j, int i); private static native void nativeSetOverlayOnTop(long j, boolean z); private static native void nativeSetOverlayPriority(long j, int i); private static native void nativeSetOverlayPriority(long j, int i, int i2); private static native void nativeSetOverlaySubType(long j, int i); private static native void nativeSetShownMaxCount(long j, int i); protected static native void nativeSetVisible(long j, boolean z); public void clearFocus() { } public GLOverlay(int i, akq akq, int i2) { this.mEngineID = i; this.mGLMapView = akq; this.mCode = i2; this.mNativeInstance = 0; this.mItemPriority = 0; } public long getNativeInstatnce() { return this.mNativeInstance; } public int getCode() { return this.mCode; } public int getType() { if (this.mNativeInstance == 0) { return -1; } return nativeGetType(this.mNativeInstance); } public int getSubType() { if (this.mNativeInstance == 0) { return -1; } return nativeGetSubType(this.mNativeInstance); } public void removeItem(int i) { if (this.mNativeInstance != 0) { nativeRemoveItem(this.mNativeInstance, i); } } public void removeAll() { if (this.mNativeInstance != 0) { nativeRemoveAll(this.mNativeInstance); if (this.mGLMapView != null) { this.mGLMapView.r(this.mGLMapView.d.getBelongToRenderDeviceId(this.mEngineID)); } } } public int getSize() { if (this.mNativeInstance == 0) { return 0; } return nativeGetCount(this.mNativeInstance); } public void setVisible(boolean z) { if (this.mNativeInstance != 0) { nativeSetVisible(this.mNativeInstance, z); this.mGLMapView.r(this.mGLMapView.d.getBelongToRenderDeviceId(this.mEngineID)); } } public boolean isVisible() { if (this.mNativeInstance == 0) { return false; } return nativeIsVisible(this.mNativeInstance); } public void setClickable(boolean z) { if (this.mNativeInstance != 0) { nativeSetClickable(this.mNativeInstance, z); } } public boolean isClickable() { if (this.mNativeInstance == 0) { return false; } return nativeIsClickable(this.mNativeInstance); } public boolean getIsInBundle() { return this.mIsInBundle; } public void setMaxCountShown(int i) { nativeSetShownMaxCount(this.mNativeInstance, i); } public void setOverlayOnTop(boolean z) { nativeSetOverlayOnTop(this.mNativeInstance, z); } public void setMinDisplayLevel(float f) { nativeSetMinDisplayLevel(this.mNativeInstance, f); } public void setMaxDisplayLevel(float f) { nativeSetMaxDisplayLevel(this.mNativeInstance, f); } public void setOverlayPriority(int i, int i2) { if (0 != this.mNativeInstance) { nativeSetOverlayPriority(this.mNativeInstance, i, i2); this.mGLMapView.p(this.mGLMapView.C(this.mEngineID)); } } public void setOverlayPriority(int i) { nativeSetOverlayPriority(this.mNativeInstance, i); GLOverlayBundle<BaseMapOverlay<?, ?>> s = this.mGLMapView.s(this.mEngineID); if (s != null) { s.sortOverlay(); } } public int getOverlayPriority() { return nativeGetOverlayPriority(this.mNativeInstance); } public void setOverlayItemPriority(int i) { this.mItemPriority = i; } /* access modifiers changed from: protected */ public void finalize() throws Throwable { releaseInstance(); super.finalize(); } public void releaseInstance() { setDrawOverlayListener(null); if (this.mNativeInstance != 0) { long j = this.mNativeInstance; this.mNativeInstance = 0; GLMapEngine.destoryOverlay(this.mEngineID, j); } } public float getMinDisplayLevel() { float[] displayScale = getDisplayScale(); if (displayScale == null || displayScale.length != 2) { return 0.0f; } return displayScale[0]; } public float getMaxDisplayLevel() { float[] displayScale = getDisplayScale(); if (displayScale == null || displayScale.length != 2) { return 0.0f; } return displayScale[1]; } public float[] getDisplayScale() { if (this.mNativeInstance == 0) { return null; } return nativeGetDisplayScale(this.mNativeInstance); } public void setSubType(EOverlaySubType eOverlaySubType) { if (this.mNativeInstance != 0) { nativeSetOverlaySubType(this.mNativeInstance, eOverlaySubType.value()); } } public void useNightStyle(boolean z) { this.isNightStyle = z; } public void setDrawOverlayListener(OnDrawOverlayListener onDrawOverlayListener) { this.mDrawOverlayListener = onDrawOverlayListener; if (this.mNativeInstance != 0) { nativeSetOverlayDrawObserver(this.mNativeInstance, this.mDrawOverlayListener, this); if (!(this.mOverlayDrawObserverType == 0 || this.mDrawOverlayListener == null)) { nativeSetOverlayDrawObserverType(this.mNativeInstance, this.mOverlayDrawObserverType, this); } } } public void setOverlayDrawObserverType(int i) { this.mOverlayDrawObserverType = i; if (this.mNativeInstance != 0) { nativeSetOverlayDrawObserverType(this.mNativeInstance, i, this); } } public int getOverlayDrawObserverType() { if (this.mNativeInstance == 0 || this.mDrawOverlayListener == null) { return this.mOverlayDrawObserverType; } return nativeGetOverlayDrawObserverType(this.mNativeInstance, this); } }
da4488ee4d593e4cab20b3f100e72c596b458727
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/35/35_5d1eb1775570f44c0f5cc327e6fe02eecb5ba85c/AlbumListController/35_5d1eb1775570f44c0f5cc327e6fe02eecb5ba85c_AlbumListController_s.java
d464556174a73708c88d0bf88fdf994eafcc195b
[]
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
16,549
java
/* * Copyright (C) 2005-2009 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC Remote; see the file license. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ package org.xbmc.android.remote.presentation.controller; import java.util.ArrayList; import org.xbmc.android.remote.R; import org.xbmc.android.remote.business.AbstractManager; import org.xbmc.android.remote.business.ManagerFactory; import org.xbmc.android.remote.presentation.activity.DialogFactory; import org.xbmc.android.remote.presentation.activity.ListActivity; import org.xbmc.android.remote.presentation.widget.ThreeLabelsItemView; import org.xbmc.android.util.ImportUtilities; import org.xbmc.api.business.DataResponse; import org.xbmc.api.business.IControlManager; import org.xbmc.api.business.IMusicManager; import org.xbmc.api.business.ISortableManager; import org.xbmc.api.object.Album; import org.xbmc.api.object.Artist; import org.xbmc.api.object.Genre; import org.xbmc.api.type.SortType; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.BitmapFactory; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; /** * TODO Once we move to 1.6+, waste the deprecated code. */ public class AlbumListController extends ListController implements IController { public static final int ITEM_CONTEXT_QUEUE = 1; public static final int ITEM_CONTEXT_PLAY = 2; public static final int ITEM_CONTEXT_INFO = 3; public static final int MENU_PLAY_ALL = 1; public static final int MENU_SORT = 2; public static final int MENU_SORT_BY_ARTIST_ASC = 21; public static final int MENU_SORT_BY_ARTIST_DESC = 22; public static final int MENU_SORT_BY_ALBUM_ASC = 23; public static final int MENU_SORT_BY_ALBUM_DESC = 24; public static final int MENU_SWITCH_VIEW = 3; private static final int VIEW_LIST = 1; private static final int VIEW_GRID = 2; private int mCurrentView = VIEW_LIST; private Artist mArtist; private Genre mGenre; private IMusicManager mMusicManager; private IControlManager mControlManager; private boolean mCompilationsOnly = false; private boolean mLoadCovers = false; private GridView mGrid = null; /** * Defines if only compilations should be listed. * @param co True if compilations only should be listed, false otherwise. */ public void setCompilationsOnly(boolean co) { mCompilationsOnly = co; } /** * If grid reference is set, albums can be displayed as wall view. * @param grid Reference to GridView */ public void setGrid(GridView grid) { mGrid = grid; } public void onCreate(Activity activity, ListView list) { mMusicManager = ManagerFactory.getMusicManager(this); mControlManager = ManagerFactory.getControlManager(this); ((ISortableManager)mMusicManager).setSortKey(AbstractManager.PREF_SORT_KEY_ALBUM); ((ISortableManager)mMusicManager).setPreferences(activity.getPreferences(Context.MODE_PRIVATE)); final String sdError = ImportUtilities.assertSdCard(); mLoadCovers = sdError == null; if (!isCreated()) { super.onCreate(activity, list); if (!mLoadCovers) { Toast toast = Toast.makeText(activity, sdError + " Displaying place holders only.", Toast.LENGTH_LONG); toast.show(); } mArtist = (Artist)mActivity.getIntent().getSerializableExtra(ListController.EXTRA_ARTIST); mGenre = (Genre)mActivity.getIntent().getSerializableExtra(ListController.EXTRA_GENRE); activity.registerForContextMenu(mList); mFallbackBitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.icon_album_dark_big); setupIdleListener(); mList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent nextActivity; final Album album = (Album)mList.getAdapter().getItem(((ThreeLabelsItemView)view).position); nextActivity = new Intent(view.getContext(), ListActivity.class); nextActivity.putExtra(ListController.EXTRA_LIST_CONTROLLER, new SongListController()); nextActivity.putExtra(ListController.EXTRA_ALBUM, album); mActivity.startActivity(nextActivity); } }); mList.setOnKeyListener(new ListControllerOnKeyListener<Album>()); fetch(); } } private void setAdapter(ArrayList<Album> value) { switch (mCurrentView) { case VIEW_LIST: mList.setAdapter(new AlbumAdapter(mActivity, value)); mList.setVisibility(View.VISIBLE); if (mGrid != null) { mGrid.setVisibility(View.GONE); } break; case VIEW_GRID: if (mGrid != null) { mGrid.setAdapter(new AlbumGridAdapter(mActivity, value)); mGrid.setVisibility(View.VISIBLE); mList.setVisibility(View.GONE); } else { mList.setVisibility(View.VISIBLE); mList.setAdapter(new AlbumAdapter(mActivity, value)); } break; } } public void updateLibrary() { final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setMessage("Are you sure you want XBMC to rescan your music library?") .setCancelable(false) .setPositiveButton("Yes!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mControlManager.updateLibrary(new DataResponse<Boolean>() { public void run() { final String message; if (value) { message = "Music library updated has been launched."; } else { message = "Error launching music library update."; } Toast toast = Toast.makeText(mActivity, message, Toast.LENGTH_SHORT); toast.show(); } }, "music"); } }) .setNegativeButton("Uh, no.", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.create().show(); } private void fetch() { final Artist artist = mArtist; final Genre genre = mGenre; if (artist != null) { // albums of an artist setTitle(artist.name + " - Albums..."); showOnLoading(); mMusicManager.getAlbums(new DataResponse<ArrayList<Album>>() { public void run() { if (value.size() > 0) { setTitle(artist.name + " - Albums (" + value.size() + ")"); setAdapter(value); } else { setTitle(artist.name + " - Albums"); setNoDataMessage("No albums found.", R.drawable.icon_album_dark); } } }, artist); } else if (genre != null) { // albums of a genre setTitle(genre.name + " - Albums..."); showOnLoading(); mMusicManager.getAlbums(new DataResponse<ArrayList<Album>>() { public void run() { if (value.size() > 0) { setTitle(genre.name + " - Albums (" + value.size() + ")"); setAdapter(value); } else { setTitle(genre.name + " - Albums"); setNoDataMessage("No albums found.", R.drawable.icon_album_dark); } } }, genre); } else { if (mCompilationsOnly) { // compilations setTitle("Compilations..."); showOnLoading(); mMusicManager.getCompilations(new DataResponse<ArrayList<Album>>() { public void run() { if (value.size() > 0) { setTitle("Compilations (" + value.size() + ")"); setAdapter(value); } else { setTitle("Compilations"); setNoDataMessage("No compilations found.", R.drawable.icon_album_dark); } } }); } else { setTitle("Albums..."); // all albums showOnLoading(); mMusicManager.getAlbums(new DataResponse<ArrayList<Album>>() { public void run() { if (value.size() > 0) { setTitle("Albums (" + value.size() + ")"); setAdapter(value); } else { setTitle("Albums"); setNoDataMessage("No Albums found.", R.drawable.icon_album_dark); } } }); } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { final ThreeLabelsItemView view = (ThreeLabelsItemView)((AdapterContextMenuInfo)menuInfo).targetView; menu.setHeaderTitle(((Album)mList.getItemAtPosition(view.getPosition())).name); menu.add(0, ITEM_CONTEXT_QUEUE, 1, "Queue Album"); menu.add(0, ITEM_CONTEXT_PLAY, 2, "Play Album"); menu.add(0, ITEM_CONTEXT_INFO, 3, "View Details"); } public void onContextItemSelected(MenuItem item) { // final ThreeHolder<Album> holder = (ThreeHolder<Album>)((AdapterContextMenuInfo)item.getMenuInfo()).targetView.getTag(); // final Album album = holder.holderItem; final Album album = (Album)mList.getAdapter().getItem(((ThreeLabelsItemView)((AdapterContextMenuInfo)item.getMenuInfo()).targetView).position); switch (item.getItemId()) { case ITEM_CONTEXT_QUEUE: mMusicManager.addToPlaylist(new QueryResponse( mActivity, "Adding album \"" + album.name + "\" by " + album.artist + " to playlist...", "Error adding album!" ), album); break; case ITEM_CONTEXT_PLAY: mMusicManager.play(new QueryResponse( mActivity, "Playing album \"" + album.name + "\" by " + album.artist + "...", "Error playing album!", true ), album); break; case ITEM_CONTEXT_INFO: DialogFactory.getAlbumDetail(mMusicManager, mActivity, album).show(); break; default: return; } } @Override public void onCreateOptionsMenu(Menu menu) { if (mArtist != null || mGenre != null) { menu.add(0, MENU_PLAY_ALL, 0, "Play all").setIcon(R.drawable.menu_album); } SubMenu sortMenu = menu.addSubMenu(0, MENU_SORT, 0, "Sort").setIcon(R.drawable.menu_sort); sortMenu.add(2, MENU_SORT_BY_ALBUM_ASC, 0, "by Album ascending"); sortMenu.add(2, MENU_SORT_BY_ALBUM_DESC, 0, "by Album descending"); sortMenu.add(2, MENU_SORT_BY_ARTIST_ASC, 0, "by Artist ascending"); sortMenu.add(2, MENU_SORT_BY_ARTIST_DESC, 0, "by Artist descending"); // menu.add(0, MENU_SWITCH_VIEW, 0, "Switch view").setIcon(R.drawable.menu_view); } @Override public void onOptionsItemSelected(MenuItem item) { final SharedPreferences.Editor ed; switch (item.getItemId()) { case MENU_PLAY_ALL: final Artist artist = mArtist; final Genre genre = mGenre; if (artist != null && genre == null) { mMusicManager.play(new QueryResponse( mActivity, "Playing all albums by " + artist.name + "...", "Error playing songs!", true ), genre); } else if (genre != null && artist == null) { mMusicManager.play(new QueryResponse( mActivity, "Playing all albums of genre " + genre.name + "...", "Error playing songs!", true ), genre); } else if (genre != null && artist != null) { mMusicManager.play(new QueryResponse( mActivity, "Playing all songs of genre " + genre.name + " by " + artist.name + "...", "Error playing songs!", true ), artist, genre); } break; case MENU_SORT_BY_ALBUM_ASC: ed = mActivity.getPreferences(Context.MODE_PRIVATE).edit(); ed.putInt(AbstractManager.PREF_SORT_BY_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ALBUM); ed.putString(AbstractManager.PREF_SORT_ORDER_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ORDER_ASC); ed.commit(); fetch(); break; case MENU_SORT_BY_ALBUM_DESC: ed = mActivity.getPreferences(Context.MODE_PRIVATE).edit(); ed.putInt(AbstractManager.PREF_SORT_BY_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ALBUM); ed.putString(AbstractManager.PREF_SORT_ORDER_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ORDER_DESC); ed.commit(); fetch(); break; case MENU_SORT_BY_ARTIST_ASC: ed = mActivity.getPreferences(Context.MODE_PRIVATE).edit(); ed.putInt(AbstractManager.PREF_SORT_BY_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ARTIST); ed.putString(AbstractManager.PREF_SORT_ORDER_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ORDER_ASC); ed.commit(); fetch(); break; case MENU_SORT_BY_ARTIST_DESC: ed = mActivity.getPreferences(Context.MODE_PRIVATE).edit(); ed.putInt(AbstractManager.PREF_SORT_BY_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ARTIST); ed.putString(AbstractManager.PREF_SORT_ORDER_PREFIX + AbstractManager.PREF_SORT_KEY_ALBUM, SortType.ORDER_DESC); ed.commit(); fetch(); break; case MENU_SWITCH_VIEW: mCurrentView = (mCurrentView % 2) + 1; fetch(); break; } } private class AlbumAdapter extends ArrayAdapter<Album> { AlbumAdapter(Activity activity, ArrayList<Album> items) { super(activity, 0, items); } public View getView(int position, View convertView, ViewGroup parent) { final ThreeLabelsItemView view; if (convertView == null) { view = new ThreeLabelsItemView(mActivity, mMusicManager, parent.getWidth()); } else { view = (ThreeLabelsItemView)convertView; } final Album album = getItem(position); view.reset(); view.position = position; view.title = album.name; view.subtitle = album.artist; view.subsubtitle = album.year > 0 ? String.valueOf(album.year) : ""; if (mLoadCovers) { view.getResponse().load(album); } return view; } } private class AlbumGridAdapter extends ArrayAdapter<Album> { AlbumGridAdapter(Activity activity, ArrayList<Album> items) { super(activity, 0, items); } public View getView(int position, View convertView, ViewGroup parent) { /* final ImageView row; final OneHolder<Album> holder; if (convertView == null) { row = new ImageView(mActivity); holder = new OneHolder<Album>(row, null); row.setTag(holder); CrossFadeDrawable transition = new CrossFadeDrawable(mFallbackBitmap, null); transition.setCrossFadeEnabled(true); holder.transition = transition; holder.defaultCover = R.drawable.icon_album_big; } else { row = (ImageView)convertView; holder = (OneHolder<Album>)convertView.getTag(); } final Album album = getItem(position); holder.holderItem = album; holder.coverItem = album; holder.id = album.getCrc(); if (mLoadCovers) { row.setImageResource(R.drawable.icon_album_dark_big); holder.tempBind = true; mMusicManager.getCover(holder.getCoverDownloadHandler(mPostScrollLoader), album, ThumbSize.MEDIUM); } else { row.setImageResource(R.drawable.icon_album); }*/ return convertView/*row*/; } } public void onActivityPause() { if (mMusicManager != null) { mMusicManager.setController(null); mMusicManager.postActivity(); } if (mControlManager != null) { mControlManager.setController(null); } super.onActivityPause(); } public void onActivityResume(Activity activity) { super.onActivityResume(activity); if (mMusicManager != null) { mMusicManager.setController(this); } if (mControlManager != null) { mControlManager.setController(this); } } private static final long serialVersionUID = 1088971882661811256L; }
2df0258378e9b5ccbeda2969ae3be71b3f98adfb
e9ab6bbc4c04b667b01351f6c68d1eafb30ee7b6
/Core/Common/FindElement.java
636ddc53baf9a52e006b8dce1f23707b63b126d8
[]
no_license
hunkbmt/autotest01
46e730c51828e0d5eac6300ad8a434eec072757b
d8bb115ed0d85a68f9ac40a463ef144e170ac18c
refs/heads/master
2023-06-02T11:11:38.995383
2021-06-17T14:54:16
2021-06-17T14:54:16
377,569,807
0
0
null
null
null
null
UTF-8
Java
false
false
654
java
package Common; import org.openqa.selenium.By; import org.openqa.selenium.support.How; public class FindElement { private How _type; private String _value; private By _by; public FindElement(How type, String value) { this._type = type; this._value = value; this._by = type.buildBy(value); } public How getType() { return _type; } public String getValue() { return _value; } public By setBy(By by) { return _by = by; } public By getBy() { return _by; } }
54dddb2f49df5c82507dc155cacaaa3be0b7e650
20a17d6f51d72c63b730d1ec3a57d93843381923
/src/hotel/exceptions/NotFoundException.java
96ebfd6522752f067aad89bd674e578334b37a86
[]
no_license
TanczaceKotki/hotel-manager
a3f10ae12b3e5486567e287b0da1170c17d222b0
c7035ab3f8f8b7cf0dad1db66119bf735df7f105
refs/heads/master
2021-01-10T15:10:32.828860
2015-12-14T11:13:03
2015-12-14T11:13:03
44,100,929
0
0
null
null
null
null
UTF-8
Java
false
false
170
java
package hotel.exceptions; public class NotFoundException extends Exception { public NotFoundException(String message) { super("Error: "+message); } }
af94486c53af20638e6f44f09daeef03584f9f7d
7b73756ba240202ea92f8f0c5c51c8343c0efa5f
/classes2/com/tencent/mobileqq/utils/kapalaiadapter/KapalaiAdapterUtil.java
ffd4d966011052d98021fd4a0d69c109c8d0f66f
[]
no_license
meeidol-luo/qooq
588a4ca6d8ad579b28dec66ec8084399fb0991ef
e723920ac555e99d5325b1d4024552383713c28d
refs/heads/master
2020-03-27T03:16:06.616300
2016-10-08T07:33:58
2016-10-08T07:33:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
23,929
java
package com.tencent.mobileqq.utils.kapalaiadapter; import android.app.Notification; import android.app.Notification.Builder; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.os.Build; import android.os.Build.VERSION; import android.view.Window; import android.view.WindowManager.LayoutParams; import android.widget.EditText; import com.tencent.mobileqq.hotpatch.NotVerifyClass; import com.tencent.mobileqq.utils.kapalaiadapter.sdcardmountinforutil.SDCardMountInforUtil; import com.tencent.qphone.base.util.QLog; import com.tencent.util.VersionUtils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import wea; public class KapalaiAdapterUtil { public int a; private DualSimManager a; private KapalaiAdapterUtil() { boolean bool = NotVerifyClass.DO_VERIFY_CLASS; this.jdField_a_of_type_ComTencentMobileqqUtilsKapalaiadapterDualSimManager = DualSimManager.a(); } public static KapalaiAdapterUtil a() { return wea.a; } private Camera b() { Object localObject2 = null; try { localObject1 = Camera.open(); Camera.Parameters localParameters; if ((localObject1 != null) && (localObject1 == null)) { break label57; } ((Camera)localObject1).release(); } catch (Exception localException1) { try { localParameters = ((Camera)localObject1).getParameters(); if (localParameters != null) { localParameters.set("video_input", "secondary"); ((Camera)localObject1).setParameters(localParameters); } return (Camera)localObject1; } catch (Exception localException2) { for (;;) { Object localObject1; } } localException1 = localException1; localObject1 = null; } localObject1 = localObject2; localException1.printStackTrace(); return (Camera)localObject1; } private Camera c() { Object localObject2 = null; try { localObject1 = Camera.open(); Camera.Parameters localParameters; if ((localObject1 != null) && (localObject1 == null)) { break label57; } ((Camera)localObject1).release(); } catch (Exception localException1) { try { localParameters = ((Camera)localObject1).getParameters(); if (localParameters != null) { localParameters.set("device", "/dev/video1"); ((Camera)localObject1).setParameters(localParameters); } return (Camera)localObject1; } catch (Exception localException2) { for (;;) { Object localObject1; } } localException1 = localException1; localObject1 = null; } localObject1 = localObject2; localException1.printStackTrace(); return (Camera)localObject1; } private Camera d() { Object localObject2 = null; try { localObject1 = Camera.open(); Method localMethod; if ((localObject1 != null) && (localObject1 == null)) { break label76; } ((Camera)localObject1).release(); } catch (Exception localException1) { try { localMethod = localObject1.getClass().getMethod("setSensorID", new Class[] { Integer.TYPE }); if (localMethod != null) { localMethod.invoke(localObject1, new Object[] { Integer.valueOf(1) }); } return (Camera)localObject1; } catch (Exception localException2) { for (;;) { Object localObject1; } } localException1 = localException1; localObject1 = null; } localObject1 = localObject2; localException1.printStackTrace(); return (Camera)localObject1; } private Camera e() { Camera localCamera = null; try { Class localClass = Class.forName("android.hardware.Camera"); Method localMethod = localClass.getMethod("setCurrentCamera", new Class[] { Integer.TYPE }); if (localMethod != null) { localMethod.invoke(localClass, new Object[] { Integer.valueOf(1) }); localCamera = Camera.open(); } return localCamera; } catch (Exception localException) { if (0 != 0) { throw new NullPointerException(); } localException.printStackTrace(); } return null; } private Camera f() { Camera localCamera = null; try { if (VersionUtils.c()) { localCamera = Camera.open(); } return localCamera; } catch (Exception localException) { if (0 != 0) { throw new NullPointerException(); } localException.printStackTrace(); } return null; } public int a() { return this.jdField_a_of_type_Int; } public Notification a(Context paramContext, int paramInt) { for (;;) { try { if (Build.VERSION.SDK_INT < 11) { paramContext = new Notification(paramInt, null, System.currentTimeMillis()); localObject = paramContext; if (paramContext == null) { localObject = new Notification(paramInt, null, System.currentTimeMillis()); } return (Notification)localObject; } paramContext = new Notification.Builder(paramContext); Object localObject = Class.forName("android.app.Notification$Builder").getDeclaredMethod("setInternalApp", new Class[] { Integer.TYPE }); if (localObject != null) { ((Method)localObject).invoke(paramContext, new Object[] { Integer.valueOf(1) }); if (Build.VERSION.SDK_INT >= 16) { paramContext = paramContext.build(); continue; } if ((Build.VERSION.SDK_INT < 16) && (Build.VERSION.SDK_INT >= 11)) { paramContext = paramContext.getNotification(); continue; return null; } } } catch (Exception paramContext) { if (QLog.isColorLevel()) { QLog.e("newNotificationForMeizu", 2, paramContext.getMessage()); } if (0 == 0) { return new Notification(paramInt, null, System.currentTimeMillis()); } } finally { if (0 == 0) { new Notification(paramInt, null, System.currentTimeMillis()); } } paramContext = null; } } /* Error */ public Notification a(Intent paramIntent, Bitmap paramBitmap, String paramString1, String paramString2, String paramString3, boolean paramBoolean, com.tencent.mobileqq.app.QQAppInterface paramQQAppInterface) { // Byte code: // 0: aload 7 // 2: invokevirtual 176 com/tencent/mobileqq/app/QQAppInterface:b ()Z // 5: istore 12 // 7: invokestatic 182 com/tencent/qphone/base/util/BaseApplication:getContext ()Lcom/tencent/qphone/base/util/BaseApplication; // 10: iconst_0 // 11: aload_1 // 12: ldc -73 // 14: invokestatic 189 android/app/PendingIntent:getActivity (Landroid/content/Context;ILandroid/content/Intent;I)Landroid/app/PendingIntent; // 17: astore 8 // 19: invokestatic 162 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 22: ifeq +29 -> 51 // 25: ldc -65 // 27: iconst_2 // 28: new 193 java/lang/StringBuilder // 31: dup // 32: invokespecial 194 java/lang/StringBuilder:<init> ()V // 35: ldc -60 // 37: invokevirtual 200 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder; // 40: aload 8 // 42: invokevirtual 203 java/lang/StringBuilder:append (Ljava/lang/Object;)Ljava/lang/StringBuilder; // 45: invokevirtual 206 java/lang/StringBuilder:toString ()Ljava/lang/String; // 48: invokestatic 209 com/tencent/qphone/base/util/QLog:i (Ljava/lang/String;ILjava/lang/String;)V // 51: ldc -46 // 53: istore 11 // 55: aload_1 // 56: ldc -44 // 58: iconst_m1 // 59: invokevirtual 218 android/content/Intent:getIntExtra (Ljava/lang/String;I)I // 62: sipush 1008 // 65: if_icmpne +151 -> 216 // 68: getstatic 224 com/tencent/mobileqq/app/AppConstants:ae Ljava/lang/String; // 71: aload_1 // 72: ldc -30 // 74: invokevirtual 230 android/content/Intent:getStringExtra (Ljava/lang/String;)Ljava/lang/String; // 77: invokevirtual 236 java/lang/String:equals (Ljava/lang/Object;)Z // 80: ifeq +128 -> 208 // 83: iload 11 // 85: istore 10 // 87: aload_1 // 88: ldc -18 // 90: iconst_0 // 91: invokevirtual 242 android/content/Intent:getBooleanExtra (Ljava/lang/String;Z)Z // 94: ifeq +7 -> 101 // 97: ldc -13 // 99: istore 10 // 101: getstatic 127 android/os/Build$VERSION:SDK_INT I // 104: bipush 11 // 106: if_icmpge +196 -> 302 // 109: new 129 android/app/Notification // 112: dup // 113: iload 10 // 115: aload_3 // 116: invokestatic 135 java/lang/System:currentTimeMillis ()J // 119: invokespecial 138 android/app/Notification:<init> (ILjava/lang/CharSequence;J)V // 122: astore_1 // 123: aload_1 // 124: aload 8 // 126: putfield 247 android/app/Notification:contentIntent Landroid/app/PendingIntent; // 129: iload 12 // 131: ifeq +24 -> 155 // 134: aload_1 // 135: aload_1 // 136: getfield 250 android/app/Notification:flags I // 139: bipush 32 // 141: ior // 142: putfield 250 android/app/Notification:flags I // 145: aload_1 // 146: aload_1 // 147: getfield 250 android/app/Notification:flags I // 150: iconst_2 // 151: ior // 152: putfield 250 android/app/Notification:flags I // 155: invokestatic 182 com/tencent/qphone/base/util/BaseApplication:getContext ()Lcom/tencent/qphone/base/util/BaseApplication; // 158: aload 7 // 160: invokestatic 255 com/tencent/mobileqq/util/NotifyLightUtil:a (Landroid/content/Context;Lcom/tencent/common/app/AppInterface;)Z // 163: ifeq +43 -> 206 // 166: invokestatic 261 java/util/Calendar:getInstance ()Ljava/util/Calendar; // 169: bipush 11 // 171: invokevirtual 265 java/util/Calendar:get (I)I // 174: pop // 175: aload_1 // 176: aload_1 // 177: getfield 250 android/app/Notification:flags I // 180: iconst_1 // 181: ior // 182: putfield 250 android/app/Notification:flags I // 185: aload_1 // 186: ldc_w 266 // 189: putfield 269 android/app/Notification:ledARGB I // 192: aload_1 // 193: sipush 2000 // 196: putfield 272 android/app/Notification:ledOffMS I // 199: aload_1 // 200: sipush 2000 // 203: putfield 275 android/app/Notification:ledOnMS I // 206: aload_1 // 207: areturn // 208: ldc_w 276 // 211: istore 10 // 213: goto -126 -> 87 // 216: aload_1 // 217: ldc -44 // 219: iconst_m1 // 220: invokevirtual 218 android/content/Intent:getIntExtra (Ljava/lang/String;I)I // 223: sipush 1010 // 226: if_icmpne +29 -> 255 // 229: getstatic 279 com/tencent/mobileqq/app/AppConstants:aH Ljava/lang/String; // 232: invokestatic 282 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String; // 235: aload_1 // 236: ldc -30 // 238: invokevirtual 230 android/content/Intent:getStringExtra (Ljava/lang/String;)Ljava/lang/String; // 241: invokevirtual 236 java/lang/String:equals (Ljava/lang/Object;)Z // 244: ifeq +11 -> 255 // 247: ldc_w 283 // 250: istore 10 // 252: goto -165 -> 87 // 255: iload 11 // 257: istore 10 // 259: aload_1 // 260: ldc -44 // 262: iconst_m1 // 263: invokevirtual 218 android/content/Intent:getIntExtra (Ljava/lang/String;I)I // 266: sipush 1001 // 269: if_icmpne -182 -> 87 // 272: iload 11 // 274: istore 10 // 276: getstatic 286 com/tencent/mobileqq/app/AppConstants:ar Ljava/lang/String; // 279: invokestatic 282 java/lang/String:valueOf (Ljava/lang/Object;)Ljava/lang/String; // 282: aload_1 // 283: ldc -30 // 285: invokevirtual 230 android/content/Intent:getStringExtra (Ljava/lang/String;)Ljava/lang/String; // 288: invokevirtual 236 java/lang/String:equals (Ljava/lang/Object;)Z // 291: ifeq -204 -> 87 // 294: ldc_w 287 // 297: istore 10 // 299: goto -212 -> 87 // 302: new 140 android/app/Notification$Builder // 305: dup // 306: invokestatic 182 com/tencent/qphone/base/util/BaseApplication:getContext ()Lcom/tencent/qphone/base/util/BaseApplication; // 309: invokespecial 143 android/app/Notification$Builder:<init> (Landroid/content/Context;)V // 312: iload 10 // 314: invokevirtual 291 android/app/Notification$Builder:setSmallIcon (I)Landroid/app/Notification$Builder; // 317: iconst_1 // 318: invokevirtual 295 android/app/Notification$Builder:setAutoCancel (Z)Landroid/app/Notification$Builder; // 321: invokestatic 135 java/lang/System:currentTimeMillis ()J // 324: invokevirtual 299 android/app/Notification$Builder:setWhen (J)Landroid/app/Notification$Builder; // 327: aload_3 // 328: invokevirtual 303 android/app/Notification$Builder:setTicker (Ljava/lang/CharSequence;)Landroid/app/Notification$Builder; // 331: astore_1 // 332: iload 12 // 334: ifeq +9 -> 343 // 337: aload_1 // 338: iconst_1 // 339: invokevirtual 306 android/app/Notification$Builder:setOngoing (Z)Landroid/app/Notification$Builder; // 342: pop // 343: ldc -111 // 345: invokestatic 107 java/lang/Class:forName (Ljava/lang/String;)Ljava/lang/Class; // 348: ldc -109 // 350: iconst_1 // 351: anewarray 80 java/lang/Class // 354: dup // 355: iconst_0 // 356: getstatic 86 java/lang/Integer:TYPE Ljava/lang/Class; // 359: aastore // 360: invokevirtual 150 java/lang/Class:getDeclaredMethod (Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method; // 363: astore 9 // 365: aload 9 // 367: ifnull +21 -> 388 // 370: aload 9 // 372: aload_1 // 373: iconst_1 // 374: anewarray 4 java/lang/Object // 377: dup // 378: iconst_0 // 379: iconst_1 // 380: invokestatic 94 java/lang/Integer:valueOf (I)Ljava/lang/Integer; // 383: aastore // 384: invokevirtual 100 java/lang/reflect/Method:invoke (Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object; // 387: pop // 388: invokestatic 182 com/tencent/qphone/base/util/BaseApplication:getContext ()Lcom/tencent/qphone/base/util/BaseApplication; // 391: aload 7 // 393: invokestatic 255 com/tencent/mobileqq/util/NotifyLightUtil:a (Landroid/content/Context;Lcom/tencent/common/app/AppInterface;)Z // 396: ifeq +26 -> 422 // 399: invokestatic 261 java/util/Calendar:getInstance ()Ljava/util/Calendar; // 402: bipush 11 // 404: invokevirtual 265 java/util/Calendar:get (I)I // 407: pop // 408: aload_1 // 409: ldc_w 266 // 412: sipush 2000 // 415: sipush 2000 // 418: invokevirtual 310 android/app/Notification$Builder:setLights (III)Landroid/app/Notification$Builder; // 421: pop // 422: iload 6 // 424: ifeq +55 -> 479 // 427: aload_2 // 428: ifnull +9 -> 437 // 431: aload_1 // 432: aload_2 // 433: invokevirtual 314 android/app/Notification$Builder:setLargeIcon (Landroid/graphics/Bitmap;)Landroid/app/Notification$Builder; // 436: pop // 437: aload_1 // 438: aload 4 // 440: invokevirtual 317 android/app/Notification$Builder:setContentTitle (Ljava/lang/CharSequence;)Landroid/app/Notification$Builder; // 443: aload 5 // 445: invokevirtual 320 android/app/Notification$Builder:setContentText (Ljava/lang/CharSequence;)Landroid/app/Notification$Builder; // 448: aload 8 // 450: invokevirtual 324 android/app/Notification$Builder:setContentIntent (Landroid/app/PendingIntent;)Landroid/app/Notification$Builder; // 453: pop // 454: getstatic 127 android/os/Build$VERSION:SDK_INT I // 457: bipush 16 // 459: if_icmplt +50 -> 509 // 462: aload_1 // 463: invokevirtual 154 android/app/Notification$Builder:build ()Landroid/app/Notification; // 466: astore_1 // 467: aload_1 // 468: areturn // 469: astore 9 // 471: aload 9 // 473: invokevirtual 66 java/lang/Exception:printStackTrace ()V // 476: goto -88 -> 388 // 479: aload_1 // 480: aload 4 // 482: invokevirtual 317 android/app/Notification$Builder:setContentTitle (Ljava/lang/CharSequence;)Landroid/app/Notification$Builder; // 485: aload 5 // 487: invokevirtual 320 android/app/Notification$Builder:setContentText (Ljava/lang/CharSequence;)Landroid/app/Notification$Builder; // 490: aload 8 // 492: invokevirtual 324 android/app/Notification$Builder:setContentIntent (Landroid/app/PendingIntent;)Landroid/app/Notification$Builder; // 495: pop // 496: aload_2 // 497: ifnull -43 -> 454 // 500: aload_1 // 501: aload_2 // 502: invokevirtual 314 android/app/Notification$Builder:setLargeIcon (Landroid/graphics/Bitmap;)Landroid/app/Notification$Builder; // 505: pop // 506: goto -52 -> 454 // 509: getstatic 127 android/os/Build$VERSION:SDK_INT I // 512: bipush 16 // 514: if_icmpge +16 -> 530 // 517: getstatic 127 android/os/Build$VERSION:SDK_INT I // 520: bipush 11 // 522: if_icmplt +8 -> 530 // 525: aload_1 // 526: invokevirtual 157 android/app/Notification$Builder:getNotification ()Landroid/app/Notification; // 529: areturn // 530: new 129 android/app/Notification // 533: dup // 534: iload 10 // 536: aload_3 // 537: invokestatic 135 java/lang/System:currentTimeMillis ()J // 540: invokespecial 138 android/app/Notification:<init> (ILjava/lang/CharSequence;J)V // 543: astore_1 // 544: aload_1 // 545: areturn // 546: astore_1 // 547: invokestatic 162 com/tencent/qphone/base/util/QLog:isColorLevel ()Z // 550: ifeq +14 -> 564 // 553: ldc_w 326 // 556: iconst_2 // 557: aload_1 // 558: invokevirtual 168 java/lang/Exception:getMessage ()Ljava/lang/String; // 561: invokestatic 171 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V // 564: new 129 android/app/Notification // 567: dup // 568: iload 10 // 570: aload_3 // 571: invokestatic 135 java/lang/System:currentTimeMillis ()J // 574: invokespecial 138 android/app/Notification:<init> (ILjava/lang/CharSequence;J)V // 577: areturn // Local variable table: // start length slot name signature // 0 578 0 this KapalaiAdapterUtil // 0 578 1 paramIntent Intent // 0 578 2 paramBitmap Bitmap // 0 578 3 paramString1 String // 0 578 4 paramString2 String // 0 578 5 paramString3 String // 0 578 6 paramBoolean boolean // 0 578 7 paramQQAppInterface com.tencent.mobileqq.app.QQAppInterface // 17 474 8 localPendingIntent android.app.PendingIntent // 363 8 9 localMethod Method // 469 3 9 localException Exception // 85 484 10 i int // 53 220 11 j int // 5 328 12 bool boolean // Exception table: // from to target type // 343 365 469 java/lang/Exception // 370 388 469 java/lang/Exception // 454 467 546 java/lang/Exception // 509 530 546 java/lang/Exception // 530 544 546 java/lang/Exception } public Intent a(Intent paramIntent) { paramIntent.putExtra(a(), Integer.parseInt(c())); return null; } public Bitmap a(Bitmap paramBitmap, int paramInt) { if (paramBitmap != null) { return Bitmap.createScaledBitmap(paramBitmap, paramInt, paramInt, true); } return null; } public Camera a() { Camera localCamera = null; if (Build.MANUFACTURER.equalsIgnoreCase("HTC")) { localCamera = b(); } do { return localCamera; if (Build.MANUFACTURER.equalsIgnoreCase("YuLong")) { return c(); } if (Build.MANUFACTURER.equalsIgnoreCase("HISENSE")) { return d(); } if (Build.MANUFACTURER.equalsIgnoreCase("HUAWEI")) { return e(); } } while (!Build.MANUFACTURER.equalsIgnoreCase("LENOVO")); return f(); } public String a() { return DualSimManager.a; } public String a(Camera.Parameters paramParameters) { String str = "off"; List localList = paramParameters.getSupportedFlashModes(); if (localList.contains("torch")) { paramParameters = "torch"; } do { return paramParameters; if (localList.contains("on")) { return "on"; } paramParameters = str; } while (!localList.contains("auto")); return "auto"; } public ArrayList a(Context paramContext) { ArrayList localArrayList1 = b(paramContext); if ((localArrayList1 == null) || (localArrayList1.size() < 1)) { return null; } ArrayList localArrayList2 = new ArrayList(); int i = 0; while (i < localArrayList1.size()) { String str = (String)localArrayList1.get(i); if (SDCardMountInforUtil.a(paramContext).a(str)) { localArrayList2.add(str); } i += 1; } return localArrayList2; } public void a(int paramInt) { this.jdField_a_of_type_Int = paramInt; } public void a(Intent paramIntent) { paramIntent.setFlags(337641472); } public void a(Window paramWindow) { paramWindow.setType(2004); } public void a(WindowManager.LayoutParams paramLayoutParams) { paramLayoutParams.screenBrightness = 0.035F; } public void a(EditText paramEditText) { if (paramEditText != null) { paramEditText.setSelection(this.jdField_a_of_type_Int); } } public boolean a() { return (!this.jdField_a_of_type_ComTencentMobileqqUtilsKapalaiadapterDualSimManager.a(0)) && (this.jdField_a_of_type_ComTencentMobileqqUtilsKapalaiadapterDualSimManager.a(1)); } public boolean a(int paramInt, String paramString1, String paramString2, ArrayList paramArrayList1, ArrayList paramArrayList2, ArrayList paramArrayList3) { return DualSimManager.a().a(paramInt, paramString1, paramString2, paramArrayList1, paramArrayList2, paramArrayList3); } public boolean a(Context paramContext, String paramString) { return SDCardMountInforUtil.a(paramContext).a(paramString); } public boolean a(Camera.Parameters paramParameters, Context paramContext) { return (paramParameters.getSupportedFlashModes() != null) && (paramContext.getPackageManager().hasSystemFeature("android.hardware.camera.flash")) && (paramParameters.getSupportedFlashModes().size() > 1); } public int b() { return 1; } public String b() { return DualSimManager.b; } public ArrayList b(Context paramContext) { return SDCardMountInforUtil.a(paramContext).a(); } public void b(Window paramWindow) { paramWindow.setType(2); } public String c() { return DualSimManager.c; } } /* Location: E:\apk\QQ_91\classes2-dex2jar.jar!\com\tencent\mobileqq\utils\kapalaiadapter\KapalaiAdapterUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
ca7bbd9bb01aee65300abd859de7ac18a10ff185
18f2fc77a61e8cbe4c38ae5b64b05b0347cd8507
/LAB_2/src/business/VitalSignsHistory.java
2e840c216c269fb118ce2cf0d56942d360e97877
[]
no_license
YashPandya2001/AED_ASSIGNMENT
82875ced4d739f5462a6893bb3b88aebe616f2f1
cea00bd945393d8d2f08c36d6f7d424c029bb06c
refs/heads/master
2020-07-30T06:06:30.954975
2019-09-22T08:43:20
2019-09-22T08:43:20
210,112,389
0
0
null
null
null
null
UTF-8
Java
false
false
940
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 business; import java.util.ArrayList; /** * * @author hp */ public class VitalSignsHistory { private ArrayList<VitalSigns> vitalSignsHistory; public VitalSignsHistory() { vitalSignsHistory=new ArrayList<VitalSigns>(); } public ArrayList<VitalSigns> getVitalSignsHistory() { return vitalSignsHistory; } public void setVitalSignsHistory(ArrayList<VitalSigns> vitalSignsHistory) { this.vitalSignsHistory = vitalSignsHistory; } public VitalSigns addVital() { VitalSigns vs=new VitalSigns(); vitalSignsHistory.add(vs); return vs; } public void removeVital(VitalSigns v) { vitalSignsHistory.remove(v); } }
327ffbfcae2c325dbad4de3f5a945b12c2c2c8e3
ca0fabe6f1f48281951796e715329d9e87c0ff8c
/com.icteam.loyalty.ui/src/com/icteam/loyalty/ui/control/NToM.java
75fc258970267cdbaa609f2f79e06e0ede9be69a
[]
no_license
Danipiario/com.icteam.loyalty
11ed58d3764798528c6949f51c3babaea087438f
f2bb4fb0e01552b336bcf860dd111862d8727316
refs/heads/master
2020-04-12T06:43:13.519169
2016-10-01T19:52:05
2016-10-01T19:52:05
60,277,192
0
0
null
null
null
null
UTF-8
Java
false
false
23,123
java
package com.icteam.loyalty.ui.control; import java.util.List; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.beans.PojoObservables; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.list.IObservableList; import org.eclipse.core.databinding.observable.map.IObservableMap; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.property.Properties; import org.eclipse.core.internal.databinding.BindingStatus; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.databinding.viewers.ObservableListContentProvider; import org.eclipse.jface.databinding.viewers.ViewerProperties; import org.eclipse.jface.internal.databinding.swt.WidgetGroupTextProperty; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.rap.rwt.RWT; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import com.icteam.loyalty.api.Messages; import com.icteam.loyalty.model.DtoListModel; import com.icteam.loyalty.model.DtoModel; import com.icteam.loyalty.model.interfaces.IDtoModel; import com.icteam.loyalty.model.interfaces.IModel; import com.icteam.loyalty.model.template.AbstractTemplate; import com.icteam.loyalty.ui.converter.ConvertableObservableMapLabelProvider; import com.icteam.loyalty.ui.converter.ObjectToBooleanConverter; import com.icteam.loyalty.ui.converter.TableInputToBooleanConverter; import com.icteam.loyalty.ui.interfaces.IBindedControl; import com.icteam.loyalty.ui.interfaces.IData; import com.icteam.loyalty.ui.interfaces.IModelProvider; import com.icteam.loyalty.ui.listener.DefaultSortSelectionListener; import com.icteam.loyalty.ui.listener.MapChangeListener; import com.icteam.loyalty.ui.model.NToMModel; import com.icteam.loyalty.ui.util.BinderUtils; import com.icteam.loyalty.ui.util.ControlUtils; import com.icteam.loyalty.ui.util.PropertyViewerComparator; import com.icteam.loyalty.ui.validator.RequiredListValidator; public class NToM<M extends IModel, S extends Object> extends Composite implements IBindedControl, IModelProvider<M, List<S>, NToMModel<M, S>> { private static final long serialVersionUID = -8536935429447636321L; enum Direction { TO_SRC, TO_DEST, ALL_TO_SRC, ALL_TO_DEST; } private DataBindingContext bindingContext; private NToMModel<M, S> modelProperty; private final TableViewer tableViewerSrc; private final TableViewer tableViewerDest; private final Button cmdAllToSrc; private final Button cmdToSrc; private final Button cmdToDest; private final Button cmdAllToDest; private Binding allSrcBinding; private Binding allDestBinding; private Binding srcBinding; private Binding destBinding; private final Group grpMain; private final Label lblDest; private RequiredListValidator<M, S> multiValidator; private final Label lblValidator; private final Label lblSrc; public NToM(Composite parent, int style) { super(parent, style | SWT.NO_FOCUS); setLayout(new GridLayout()); grpMain = new Group(this, SWT.NONE); grpMain.setLayout(new FormLayout()); grpMain.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 0, 0)); Composite controlArea = new Composite(grpMain, SWT.NONE); GridLayout gl_controlArea = new GridLayout(4, true); gl_controlArea.horizontalSpacing = 0; gl_controlArea.verticalSpacing = 0; gl_controlArea.marginWidth = 0; gl_controlArea.marginHeight = 0; controlArea.setLayout(gl_controlArea); FormData fd_controlArea = new FormData(); fd_controlArea.left = new FormAttachment(20); fd_controlArea.right = new FormAttachment(80); fd_controlArea.top = new FormAttachment(0); controlArea.setLayoutData(fd_controlArea); Composite composite = new Composite(controlArea, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); RowLayout rl_composite = new RowLayout(SWT.HORIZONTAL); rl_composite.wrap = false; rl_composite.pack = false; rl_composite.spacing = 0; rl_composite.marginTop = 0; rl_composite.marginRight = 0; rl_composite.marginLeft = 0; rl_composite.marginBottom = 0; rl_composite.justify = true; composite.setLayout(rl_composite); cmdAllToSrc = new Button(composite, SWT.NONE); cmdAllToSrc.setText("<<"); cmdAllToSrc.addSelectionListener(new SelectionAdapter() { private static final long serialVersionUID = 1L; @Override public void widgetSelected(SelectionEvent e) { moveElement(Direction.ALL_TO_SRC); } }); Composite composite_1 = new Composite(controlArea, SWT.NONE); composite_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); RowLayout rl_composite_1 = new RowLayout(SWT.HORIZONTAL); rl_composite_1.wrap = false; rl_composite_1.marginBottom = 0; rl_composite_1.marginLeft = 0; rl_composite_1.marginRight = 0; rl_composite_1.marginTop = 0; rl_composite_1.spacing = 0; rl_composite_1.pack = false; rl_composite_1.justify = true; composite_1.setLayout(rl_composite_1); cmdToSrc = new Button(composite_1, SWT.NONE); cmdToSrc.addSelectionListener(new SelectionAdapter() { private static final long serialVersionUID = 1L; @Override public void widgetSelected(SelectionEvent e) { moveElement(Direction.TO_SRC); } }); cmdToSrc.setText("<"); Composite composite_2 = new Composite(controlArea, SWT.NONE); composite_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); RowLayout rl_composite_2 = new RowLayout(SWT.HORIZONTAL); rl_composite_2.marginBottom = 0; rl_composite_2.marginLeft = 0; rl_composite_2.marginRight = 0; rl_composite_2.marginTop = 0; rl_composite_2.pack = false; rl_composite_2.spacing = 0; rl_composite_2.wrap = false; rl_composite_2.justify = true; composite_2.setLayout(rl_composite_2); cmdToDest = new Button(composite_2, SWT.NONE); cmdToDest.setSize(20, 25); cmdToDest.setText(">"); cmdToDest.addSelectionListener(new SelectionAdapter() { private static final long serialVersionUID = 1L; @Override public void widgetSelected(SelectionEvent e) { moveElement(Direction.TO_DEST); } }); Composite composite_3 = new Composite(controlArea, SWT.NONE); composite_3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); RowLayout rl_composite_3 = new RowLayout(SWT.HORIZONTAL); rl_composite_3.marginBottom = 0; rl_composite_3.marginLeft = 0; rl_composite_3.marginRight = 0; rl_composite_3.marginTop = 0; rl_composite_3.spacing = 0; rl_composite_3.pack = false; rl_composite_3.wrap = false; rl_composite_3.justify = true; composite_3.setLayout(rl_composite_3); cmdAllToDest = new Button(composite_3, SWT.NONE); cmdAllToDest.setText(">>"); cmdAllToDest.addSelectionListener(new SelectionAdapter() { private static final long serialVersionUID = 1L; @Override public void widgetSelected(SelectionEvent e) { moveElement(Direction.ALL_TO_DEST); } }); SashForm sashForm = new SashForm(grpMain, SWT.NONE); FormData fd_sashForm = new FormData(); fd_sashForm.top = new FormAttachment(controlArea, 5); fd_sashForm.bottom = new FormAttachment(100); fd_sashForm.right = new FormAttachment(100); fd_sashForm.left = new FormAttachment(0); sashForm.setLayoutData(fd_sashForm); Composite compSrc = new Composite(sashForm, SWT.NONE); compSrc.setLayout(new FormLayout()); tableViewerSrc = new TableViewer(compSrc, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); Table tblSrc = tableViewerSrc.getTable(); FormData fd_tblSrc = new FormData(); fd_tblSrc.bottom = new FormAttachment(100); fd_tblSrc.right = new FormAttachment(100); fd_tblSrc.left = new FormAttachment(0); tblSrc.setLayoutData(fd_tblSrc); lblSrc = new Label(compSrc, SWT.CENTER); fd_tblSrc.top = new FormAttachment(lblSrc); FormData fd_lblSrc = new FormData(); fd_lblSrc.right = new FormAttachment(100); fd_lblSrc.left = new FormAttachment(0); lblSrc.setLayoutData(fd_lblSrc); lblSrc.setText(Messages.get().nToMSrcLabel); Composite compDest = new Composite(sashForm, SWT.NONE); compDest.setLayout(new FormLayout()); lblDest = new Label(compDest, SWT.CENTER); FormData fd_lblDest = new FormData(); fd_lblDest.right = new FormAttachment(100); fd_lblDest.left = new FormAttachment(0); lblDest.setLayoutData(fd_lblDest); lblDest.setText(Messages.get().nToMDestLabel); tableViewerDest = new TableViewer(compDest, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); Table tblDest = tableViewerDest.getTable(); FormData fd_tblDest = new FormData(); fd_tblDest.top = new FormAttachment(lblDest); fd_tblDest.bottom = new FormAttachment(100); fd_tblDest.right = new FormAttachment(100); fd_tblDest.left = new FormAttachment(0); tblDest.setLayoutData(fd_tblDest); lblValidator = new Label(compDest, SWT.NONE); FormData fd_lblNewLabel = new FormData(); fd_lblNewLabel.left = new FormAttachment(0); lblValidator.setLayoutData(fd_lblNewLabel); sashForm.setWeights(new int[] { 1, 1 }); } @Override public NToMModel<M, S> getModelProperty() { return modelProperty; } public void setModelProperty(M model, String property, List<S> srcList, String... propertyNames) { setModelProperty(model, property, srcList, propertyNames, propertyNames); } public void setModelProperty(M model, String property, List<S> srcList, String[] srcPropertyNames, String[] destPropertyNames) { modelProperty = new NToMModel<>(model, property, srcList, srcPropertyNames, destPropertyNames); initBinding(); } protected void initBinding() { if (bindingContext != null) { bindingContext.dispose(); } bindingContext = new DataBindingContext(); initCustomDataBindings(); initDataBindings(); } private void initCustomDataBindings() { if (modelProperty.isRequired()) { lblDest.setData(RWT.CUSTOM_VARIANT, "required"); } bindTable(tableViewerSrc, modelProperty.getSrcList(), modelProperty.getPropertyItemType(), modelProperty.getSrcPropertyNames()); bindTable(tableViewerDest, modelProperty.getPropertyValue(), modelProperty.getPropertyItemType(), modelProperty.getDestPropertyNames()); tableViewerSrc.addOpenListener(new IOpenListener() { @Override public void open(OpenEvent event) { moveElement(Direction.TO_DEST); } }); tableViewerDest.addOpenListener(new IOpenListener() { @Override public void open(OpenEvent event) { moveElement(Direction.TO_SRC); } }); } void moveElement(Direction direction) { S element = null; List<S> inputSrc = (List<S>) tableViewerSrc.getInput(); List<S> inputDest = (List<S>) tableViewerDest.getInput(); IStructuredSelection selectionSrc = (IStructuredSelection) tableViewerSrc.getSelection(); IStructuredSelection selectionDest = (IStructuredSelection) tableViewerDest.getSelection(); int selSrc = tableViewerSrc.getTable().getSelectionIndex(); int selDest = tableViewerDest.getTable().getSelectionIndex(); switch (direction) { case ALL_TO_SRC: for (S s : inputDest) { if (!inputSrc.contains(s)) { inputSrc.add(s); } } inputDest.clear(); tableViewerSrc.getTable().setSelection(0); break; case TO_SRC: element = (S) selectionDest.getFirstElement(); if (element != null) { inputDest.remove(element); if (!inputSrc.contains(element)) { inputSrc.add(element); } tableViewerSrc.setSelection(new StructuredSelection(element)); tableViewerDest.getTable().setSelection(Math.max(0, Math.min(selDest, inputDest.size() - 1))); } break; case TO_DEST: element = (S) selectionSrc.getFirstElement(); if (element != null) { inputSrc.remove(element); if (!inputDest.contains(element)) { inputDest.add(element); } tableViewerDest.setSelection(new StructuredSelection(element)); tableViewerSrc.getTable().setSelection(Math.max(0, Math.min(selSrc, inputSrc.size() - 1))); } break; case ALL_TO_DEST: for (S s : inputSrc) { if (!inputDest.contains(s)) { inputDest.add(s); } } inputSrc.clear(); tableViewerDest.getTable().setSelection(0); break; } multiValidator.forceRevalidate(); allSrcBinding.updateModelToTarget(); allDestBinding.updateModelToTarget(); srcBinding.updateModelToTarget(); destBinding.updateModelToTarget(); ControlUtils.refresh(tableViewerSrc); ControlUtils.refresh(tableViewerDest); modelProperty.setDirty(true); } protected void initDataBindings() { // IObservableValue observeTextLblControlObserveWidget = new WidgetGroupTextProperty().observe(grpMain); IObservableValue labelModelObserveValue = BeanProperties.value("label").observe(modelProperty); bindingContext.bindValue(observeTextLblControlObserveWidget, labelModelObserveValue, null, null); // IObservableValue observeEnabledCmdAllToSrcObserveWidget = WidgetProperties.enabled().observe(cmdAllToSrc); IObservableValue emptyDestModelObserveValue = PojoProperties.value("empty").observe(tableViewerDest.getInput()); UpdateValueStrategy updateValueStrategy = new UpdateValueStrategy(); updateValueStrategy.setConverter(new TableInputToBooleanConverter(tableViewerDest)); allSrcBinding = bindingContext.bindValue(observeEnabledCmdAllToSrcObserveWidget, emptyDestModelObserveValue, null, updateValueStrategy); // // IObservableValue observeEnabledCmdAllToDestObserveWidget = WidgetProperties.enabled().observe(cmdAllToDest); IObservableValue emptySrcModelObserveValue = PojoProperties.value("empty").observe(tableViewerSrc.getInput()); UpdateValueStrategy updateValueStrategy2 = new UpdateValueStrategy(); updateValueStrategy2.setConverter(new TableInputToBooleanConverter(tableViewerSrc)); allDestBinding = bindingContext.bindValue(observeEnabledCmdAllToDestObserveWidget, emptySrcModelObserveValue, null, updateValueStrategy2); // IObservableValue enabledCmdToDestObserveValue = WidgetProperties.enabled().observe(cmdToDest); IObservableValue selectionTableViewerSrcObserveValue = ViewerProperties.singleSelection().observe(tableViewerSrc); UpdateValueStrategy updateValueStrategy3 = new UpdateValueStrategy(); updateValueStrategy3.setConverter(new ObjectToBooleanConverter(modelProperty.getPropertyItemType())); srcBinding = bindingContext.bindValue(enabledCmdToDestObserveValue, selectionTableViewerSrcObserveValue, null, updateValueStrategy3); // IObservableValue observeEnabledCmdToSrcObserveWidget = WidgetProperties.enabled().observe(cmdToSrc); IObservableValue observeSingleSelectionTableViewer_1 = ViewerProperties.singleSelection().observe(tableViewerDest); UpdateValueStrategy updateValueStrategy4 = new UpdateValueStrategy(); updateValueStrategy4.setConverter(new ObjectToBooleanConverter(modelProperty.getPropertyItemType())); destBinding = bindingContext.bindValue(observeEnabledCmdToSrcObserveWidget, observeSingleSelectionTableViewer_1, null, updateValueStrategy4); // IObservableValue observeEnabledGrpMainObserveWidget = WidgetProperties.enabled().observe(grpMain); IObservableValue enabledModelObserveValue = BeanProperties.value("enabled").observe(modelProperty); bindingContext.bindValue(observeEnabledGrpMainObserveWidget, enabledModelObserveValue, null, null); // multiValidator = new RequiredListValidator<>(modelProperty, lblValidator, SWT.RIGHT | SWT.TOP); bindingContext.addValidationStatusProvider(multiValidator); } @Override public DataBindingContext getBindingContext() { return bindingContext; } @Override public void updateModelToTarget() { allSrcBinding.updateModelToTarget(); allDestBinding.updateModelToTarget(); srcBinding.updateModelToTarget(); destBinding.updateModelToTarget(); ControlUtils.refresh(tableViewerSrc); ControlUtils.refresh(tableViewerDest); } @Override public BindingStatus validate() { multiValidator.forceRevalidate(); return BinderUtils.validate(this); } public <R> void bindSelection(TableViewer tableViewer, List<R> model) { if (model instanceof DtoListModel) { IObservableValue observeTableViewerSelection = ViewerProperties.singleSelection().observe(tableViewer); IObservableValue selectedDtoObserveValue = BeanProperties.value("selectedDto").observe(model); UpdateValueStrategy noUpdateStrategy = new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER); bindingContext.bindValue(observeTableViewerSelection, selectedDtoObserveValue, null, noUpdateStrategy); } if (model.size() > 0) { tableViewer.setSelection(new StructuredSelection(model.get(0))); } } private <R extends Object> void bindContent(TableViewer tableViewer, List<R> model, Class<R> beanClass, String... propertyNames) { ObservableListContentProvider listContentProvider = new ObservableListContentProvider(); IObservableMap[] observeMaps = null; if (IDtoModel.class.isAssignableFrom(beanClass)) { observeMaps = BeansObservables.observeMaps(listContentProvider.getKnownElements(), beanClass, propertyNames); } else { observeMaps = PojoObservables.observeMaps(listContentProvider.getKnownElements(), beanClass, propertyNames); } ConvertableObservableMapLabelProvider labelProvider = new ConvertableObservableMapLabelProvider(observeMaps); tableViewer.setLabelProvider(labelProvider); tableViewer.setContentProvider(listContentProvider); IObservableList selfList = Properties.selfList(beanClass).observe(model); tableViewer.setInput(selfList); for (IObservableMap observableMap : observeMaps) { observableMap.addMapChangeListener(new MapChangeListener(tableViewer)); } bindSelection(tableViewer, model); } private <R extends Object> void bindTable(TableViewer tableViewer, List<R> model, Class<R> beanClass, String[] propertyNames) { bindTableColumn(tableViewer, beanClass, propertyNames); bindContent(tableViewer, model, beanClass, propertyNames); ControlUtils.pack(tableViewer); } private static <T extends AbstractTemplate< ? >, D extends DtoModel> void bindTableColumn(TableViewer tableViewer, Class< ? extends Object> beanClass, String... propertyNames) { Table table = tableViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); // for (TableColumn tableColumn : tableViewer.getTable().getColumns()) { // tableColumn.dispose(); // } // // tableViewer.getTable().removeAll(); tableViewer.setComparator(new PropertyViewerComparator()); for (String propertyName : propertyNames) { createTableColumn(tableViewer, beanClass, propertyName); } } protected static void createTableColumn(TableViewer tableViewer, Class< ? extends Object> beanClass, String propertyName) { for (TableColumn tableColumn : tableViewer.getTable().getColumns()) { String columnName = (String) tableColumn.getData(IData.COLUMN_NAME); if (propertyName.equals(columnName)) { return; } } TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE); TableColumn tableColumn = tableViewerColumn.getColumn(); tableColumn.setData(IData.COLUMN_NAME, propertyName); tableColumn.addSelectionListener(new DefaultSortSelectionListener(tableViewer, beanClass, propertyName)); tableColumn.setMoveable(true); tableColumn.setResizable(true); tableColumn.addSelectionListener(new DefaultSortSelectionListener(tableViewer, beanClass, propertyName)); tableColumn.setText(Messages.get(beanClass, propertyName)); } }
74312dd38f85a119110d75810593bc9655e1c6f6
471bbf2c662e49d840735a1d3a0cf0a22a76da71
/test-framework/src/main/java/org/neo4j/doc/test/rule/SuppressOutput.java
0c710d6c6e5c76dfd97d7a5e1ee4db94327b5060
[]
no_license
hugofirth/neo4j-documentation
42c7813a5fca0cccaed55645e1035f633a1fa99c
1a848a3c7d5074009b5169a3ffdf0bf46bf18fa3
refs/heads/3.5
2021-06-15T13:57:37.208294
2019-01-10T18:46:07
2019-01-10T18:47:22
166,789,789
0
0
null
2019-01-21T09:53:33
2019-01-21T09:53:29
null
UTF-8
Java
false
false
9,708
java
/* * Licensed to Neo4j under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Neo4j 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.neo4j.doc.test.rule; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.logging.StreamHandler; import static java.lang.System.lineSeparator; import static java.util.Arrays.asList; /** * Suppresses outputs such as System.out, System.err and java.util.logging for example when running a test. * It's also a {@link TestRule} which makes it fit in nicely in JUnit. * * The suppressing occurs visitor-style and if there's an exception in the code executed when being muted * all the logging that was temporarily muted will be resent to the peers as if they weren't muted to begin with. */ public final class SuppressOutput implements TestRule { private static final Suppressible java_util_logging = java_util_logging( new ByteArrayOutputStream(), null ); public static SuppressOutput suppress( Suppressible... suppressibles ) { return new SuppressOutput( suppressibles ); } public static SuppressOutput suppressAll() { return suppress( System.out, System.err, java_util_logging ); } public enum System implements Suppressible { out { @Override PrintStream replace( PrintStream replacement ) { PrintStream old = java.lang.System.out; java.lang.System.setOut( replacement ); return old; } }, err { @Override PrintStream replace( PrintStream replacement ) { PrintStream old = java.lang.System.err; java.lang.System.setErr( replacement ); return old; } }; @Override public Voice suppress() { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final PrintStream old = replace( new PrintStream( buffer ) ); return new Voice( this, buffer ) { @Override void restore( boolean failure ) throws IOException { replace( old ).flush(); if ( failure ) { old.write( buffer.toByteArray() ); } } }; } abstract PrintStream replace( PrintStream replacement ); } public static Suppressible java_util_logging( final ByteArrayOutputStream redirectTo, Level level ) { final Handler replacement = redirectTo == null ? null : new StreamHandler( redirectTo, new SimpleFormatter() ); if ( replacement != null && level != null ) { replacement.setLevel( level ); } return new Suppressible() { @Override public Voice suppress() { final Logger logger = LogManager.getLogManager().getLogger( "" ); final Level level = logger.getLevel(); final Handler[] handlers = logger.getHandlers(); for ( Handler handler : handlers ) { logger.removeHandler( handler ); } if ( replacement != null ) { logger.addHandler( replacement ); logger.setLevel( Level.ALL ); } return new Voice( this, redirectTo ) { @Override void restore( boolean failure ) { for ( Handler handler : handlers ) { logger.addHandler( handler ); } logger.setLevel( level ); if ( replacement != null ) { logger.removeHandler( replacement ); } } }; } }; } public <T> T call( Callable<T> callable ) throws Exception { voices = captureVoices(); boolean failure = true; try { T result = callable.call(); failure = false; return result; } finally { releaseVoices( voices, failure ); } } private final Suppressible[] suppressibles; private Voice[] voices; private SuppressOutput( Suppressible[] suppressibles ) { this.suppressibles = suppressibles; } public Voice[] getAllVoices() { return voices; } public Voice getOutputVoice() { return getVoice( System.out ); } public Voice getErrorVoice() { return getVoice( System.err ); } public Voice getVoice( Suppressible suppressible ) { for ( Voice voice : voices ) { if ( suppressible.equals( voice.getSuppressible() ) ) { return voice; } } return null; } @Override public Statement apply( final Statement base, Description description ) { return new Statement() { @Override public void evaluate() throws Throwable { voices = captureVoices(); boolean failure = true; try { base.evaluate(); failure = false; } finally { releaseVoices( voices, failure ); } } }; } public interface Suppressible { Voice suppress(); } public abstract static class Voice { private Suppressible suppressible; private ByteArrayOutputStream voiceStream; public Voice( Suppressible suppressible, ByteArrayOutputStream originalStream ) { this.suppressible = suppressible; this.voiceStream = originalStream; } public Suppressible getSuppressible() { return suppressible; } public boolean containsMessage( String message ) { return voiceStream.toString().contains( message ); } /** Get each line written to this voice since it was suppressed */ public List<String> lines() { return asList( toString().split( lineSeparator() ) ); } @Override public String toString() { try { return voiceStream.toString( StandardCharsets.UTF_8.name() ); } catch ( UnsupportedEncodingException e ) { throw new RuntimeException( e ); } } abstract void restore( boolean failure ) throws IOException; } Voice[] captureVoices() { Voice[] voices = new Voice[suppressibles.length]; boolean ok = false; try { for ( int i = 0; i < voices.length; i++ ) { voices[i] = suppressibles[i].suppress(); } ok = true; } finally { if ( !ok ) { releaseVoices( voices, false ); } } return voices; } void releaseVoices( Voice[] voices, boolean failure ) { List<Throwable> failures = null; try { failures = new ArrayList<>( voices.length ); } catch ( Throwable oom ) { // nothing we can do... } for ( Voice voice : voices ) { if ( voice != null ) { try { voice.restore( failure ); } catch ( Throwable exception ) { if ( failures != null ) { failures.add( exception ); } } } } if ( failures != null && !failures.isEmpty() ) { for ( Throwable exception : failures ) { exception.printStackTrace(); } } } }
362691b1a322ad3a6ba8f3a3f65e3225396c66a6
e578e1dd6f58db78a2c23c3e64ff0265b2fcfb8e
/hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/s3guard/ITestS3GuardToolLocal.java
43cbe93330a757b08e3ff6fd31b084c3226be1cb
[ "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "EPL-1.0", "Classpath-exception-2.0", "CC-BY-3.0", "CC-BY-2.5", "GPL-2.0-only", "CC-PDDC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "GCC-exception-3.1", "CDDL-1.0", "MIT", "CDDL-1.1", "BSD-2-Clause-Views", "MPL-2.0", "AGPL-3.0-only", "LicenseRef-scancode-proprietary-license", "MPL-2.0-no-copyleft-exception", "LicenseRef-scancode-protobuf", "BSD-2-Clause", "LicenseRef-scancode-jdom", "LicenseRef-scancode-unknown-license-reference" ]
permissive
MSDS-ABLE/toposch
ca7c585f61738a262639bc07e27915b30b08221f
181977dae6953f8bca026cadd4722979e9ec0d43
refs/heads/master
2023-09-01T09:25:27.817000
2020-05-31T04:03:08
2020-05-31T04:03:08
267,599,209
5
0
Apache-2.0
2023-08-15T17:41:32
2020-05-28T13:35:50
Java
UTF-8
Java
false
false
8,497
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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.hadoop.fs.s3a.s3guard; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import org.junit.Test; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.s3a.S3AFileSystem; import org.apache.hadoop.fs.s3a.s3guard.S3GuardTool.Diff; import static org.apache.hadoop.fs.s3a.s3guard.S3GuardTool.*; import static org.apache.hadoop.test.LambdaTestUtils.intercept; /** * Test S3Guard related CLI commands against a LocalMetadataStore. */ public class ITestS3GuardToolLocal extends AbstractS3GuardToolTestBase { private static final String LOCAL_METADATA = "local://metadata"; @Override protected MetadataStore newMetadataStore() { return new LocalMetadataStore(); } @Test public void testImportCommand() throws Exception { S3AFileSystem fs = getFileSystem(); MetadataStore ms = getMetadataStore(); Path parent = path("test-import"); fs.mkdirs(parent); Path dir = new Path(parent, "a"); fs.mkdirs(dir); Path emptyDir = new Path(parent, "emptyDir"); fs.mkdirs(emptyDir); for (int i = 0; i < 10; i++) { String child = String.format("file-%d", i); try (FSDataOutputStream out = fs.create(new Path(dir, child))) { out.write(1); } } S3GuardTool.Import cmd = new S3GuardTool.Import(fs.getConf()); cmd.setStore(ms); exec(cmd, "import", parent.toString()); DirListingMetadata children = ms.listChildren(dir); assertEquals("Unexpected number of paths imported", 10, children .getListing().size()); assertEquals("Expected 2 items: empty directory and a parent directory", 2, ms.listChildren(parent).getListing().size()); // assertTrue(children.isAuthoritative()); } @Test public void testDiffCommand() throws Exception { S3AFileSystem fs = getFileSystem(); MetadataStore ms = getMetadataStore(); Set<Path> filesOnS3 = new HashSet<>(); // files on S3. Set<Path> filesOnMS = new HashSet<>(); // files on metadata store. Path testPath = path("test-diff"); mkdirs(testPath, true, true); Path msOnlyPath = new Path(testPath, "ms_only"); mkdirs(msOnlyPath, false, true); filesOnMS.add(msOnlyPath); for (int i = 0; i < 5; i++) { Path file = new Path(msOnlyPath, String.format("file-%d", i)); createFile(file, false, true); filesOnMS.add(file); } Path s3OnlyPath = new Path(testPath, "s3_only"); mkdirs(s3OnlyPath, true, false); filesOnS3.add(s3OnlyPath); for (int i = 0; i < 5; i++) { Path file = new Path(s3OnlyPath, String.format("file-%d", i)); createFile(file, true, false); filesOnS3.add(file); } ByteArrayOutputStream buf = new ByteArrayOutputStream(); Diff cmd = new Diff(fs.getConf()); cmd.setStore(ms); exec(cmd, buf, "diff", "-meta", LOCAL_METADATA, testPath.toString()); Set<Path> actualOnS3 = new HashSet<>(); Set<Path> actualOnMS = new HashSet<>(); boolean duplicates = false; try (BufferedReader reader = new BufferedReader(new InputStreamReader( new ByteArrayInputStream(buf.toByteArray())))) { String line; while ((line = reader.readLine()) != null) { String[] fields = line.split("\\s"); assertEquals("[" + line + "] does not have enough fields", 4, fields.length); String where = fields[0]; Path path = new Path(fields[3]); if (Diff.S3_PREFIX.equals(where)) { duplicates = duplicates || actualOnS3.contains(path); actualOnS3.add(path); } else if (Diff.MS_PREFIX.equals(where)) { duplicates = duplicates || actualOnMS.contains(path); actualOnMS.add(path); } else { fail("Unknown prefix: " + where); } } } String actualOut = buf.toString(); assertEquals("Mismatched metadata store outputs: " + actualOut, filesOnMS, actualOnMS); assertEquals("Mismatched s3 outputs: " + actualOut, filesOnS3, actualOnS3); assertFalse("Diff contained duplicates", duplicates); } @Test public void testDestroyBucketExistsButNoTable() throws Throwable { run(Destroy.NAME, "-meta", LOCAL_METADATA, getLandsatCSVFile()); } @Test public void testImportNoFilesystem() throws Throwable { final Import importer = new S3GuardTool.Import(getConfiguration()); importer.setStore(getMetadataStore()); intercept(IOException.class, new Callable<Integer>() { @Override public Integer call() throws Exception { return importer.run( new String[]{ "import", "-meta", LOCAL_METADATA, S3A_THIS_BUCKET_DOES_NOT_EXIST }); } }); } @Test public void testInfoBucketAndRegionNoFS() throws Throwable { intercept(FileNotFoundException.class, new Callable<Integer>() { @Override public Integer call() throws Exception { return run(BucketInfo.NAME, "-meta", LOCAL_METADATA, "-region", "any-region", S3A_THIS_BUCKET_DOES_NOT_EXIST); } }); } @Test public void testInitNegativeRead() throws Throwable { runToFailure(INVALID_ARGUMENT, Init.NAME, "-meta", LOCAL_METADATA, "-region", "eu-west-1", READ_FLAG, "-10"); } @Test public void testInit() throws Throwable { run(Init.NAME, "-meta", LOCAL_METADATA, "-region", "us-west-1"); } @Test public void testInitTwice() throws Throwable { run(Init.NAME, "-meta", LOCAL_METADATA, "-region", "us-west-1"); run(Init.NAME, "-meta", LOCAL_METADATA, "-region", "us-west-1"); } @Test public void testLandsatBucketUnguarded() throws Throwable { run(BucketInfo.NAME, "-" + BucketInfo.UNGUARDED_FLAG, getLandsatCSVFile()); } @Test public void testLandsatBucketRequireGuarded() throws Throwable { runToFailure(E_BAD_STATE, BucketInfo.NAME, "-" + BucketInfo.GUARDED_FLAG, ITestS3GuardToolLocal.this.getLandsatCSVFile()); } @Test public void testLandsatBucketRequireUnencrypted() throws Throwable { run(BucketInfo.NAME, "-" + BucketInfo.ENCRYPTION_FLAG, "none", getLandsatCSVFile()); } @Test public void testLandsatBucketRequireEncrypted() throws Throwable { runToFailure(E_BAD_STATE, BucketInfo.NAME, "-" + BucketInfo.ENCRYPTION_FLAG, "AES256", ITestS3GuardToolLocal.this.getLandsatCSVFile()); } @Test public void testStoreInfo() throws Throwable { S3GuardTool.BucketInfo cmd = new S3GuardTool.BucketInfo( getFileSystem().getConf()); cmd.setStore(getMetadataStore()); String output = exec(cmd, cmd.getName(), "-" + S3GuardTool.BucketInfo.GUARDED_FLAG, getFileSystem().getUri().toString()); LOG.info("Exec output=\n{}", output); } @Test public void testSetCapacity() throws Throwable { S3GuardTool cmd = new S3GuardTool.SetCapacity(getFileSystem().getConf()); cmd.setStore(getMetadataStore()); String output = exec(cmd, cmd.getName(), "-" + READ_FLAG, "100", "-" + WRITE_FLAG, "100", getFileSystem().getUri().toString()); LOG.info("Exec output=\n{}", output); } }
18a2c47efb6e8eb598fce49debf04d36f0426641
af7345ca23f77ab44018d888fc2ebe554ff3e5b0
/Exam 2/src/Q4SnippetProblem.java
91ab6c7f968afa04950ae58833b42b69c15e3e95
[]
no_license
cbussen7/CPS150
10b9842869f4701f3fada611d8934fc05c2db372
00ddb70d9af3d2e0f787050623ba11d6479a18a2
refs/heads/main
2023-08-17T03:34:17.326603
2021-06-23T14:04:38
2021-06-23T14:04:38
379,623,434
0
0
null
null
null
null
UTF-8
Java
false
false
235
java
public class Q4SnippetProblem { public static void main(String [] args){ System.out.println("The value is: " + val()); } public static String val(){ String result = "candy"; return result; } }
a241b380144bf7872c253d3d18383c8a486b7124
ee2a51f827fd337e6dbb9b018f62cacd8e6399da
/Ch_2_5_Applications/Practise_2_5_01.java
c1ff5da590f615830767853830946d9c741955b5
[]
no_license
pengzhetech/Algorithms
97eab98283575fdef46ad06549dcb29993bea132
c379ff6de3a10dfb1818e84a9ea2516876958288
refs/heads/master
2022-08-16T18:04:59.992353
2022-07-21T16:17:42
2022-07-21T16:17:42
261,119,609
0
0
null
2020-05-04T08:31:22
2020-05-04T08:31:21
null
UTF-8
Java
false
false
293
java
package Ch_2_5_Applications; public class Practise_2_5_01 { public static void main(String[] args) { /* * 如果内存地址相等,那么这两个字符串肯定相等,因此无需比较 * 这样避免了多余的比较操作 * */ } }
767718243ca2470722f6fd6984fe28491ba22b42
283c2daa0289407be992159e0352245aa7d71905
/src/main/java/edu/byu/cstaheli/cs478/toolkit/learner/LearnerData.java
1b471d2070befddeb941156a0d64c2851ee01dbc
[]
no_license
cache117/cs478-clustering
04a39af7391aa7f3ef65c275eb61d28cfbfd7017
bc5a2e8527f67b23322d277061b9e180a7f9e0f5
refs/heads/master
2021-06-14T10:14:34.982141
2017-04-05T03:07:48
2017-04-05T03:07:48
86,467,758
0
0
null
null
null
null
UTF-8
Java
false
false
1,013
java
package edu.byu.cstaheli.cs478.toolkit.learner; import edu.byu.cstaheli.cs478.toolkit.utility.ArgParser; import edu.byu.cstaheli.cs478.toolkit.utility.Matrix; import java.util.Random; /** * Created by cstaheli on 1/20/2017. */ public class LearnerData { private final Random rand; private final ArgParser parser; private final Matrix arffData; public LearnerData(Random rand, ArgParser parser, Matrix arffData) { this.rand = rand; this.parser = parser; this.arffData = arffData; } public Random getRandom() { return rand; } public Matrix getArffData() { return arffData; } public String getEvaluation() { return parser.getEvaluation(); } public String getEvalParameter() { return parser.getEvalParameter(); } public boolean isVerbose() { return parser.isVerbose(); } public boolean isNormalized() { return parser.isNormalized(); } }
217bc0b5c7c2314bd40b160d432b47398e4fcbdc
9c874cb0e9682b220a2992ccb0341009a9753922
/src/main/java/asint/ClaseLexica.java
7cb02f4129d5ceb922d0d496614d34689c14bbc4
[]
no_license
b0r1s/JavaCompiler
8ffb8e8842dcba70beeb9d7de64e86e5180e80a7
d4bbcfcd0cb179798e2c573fbc1619b14cd7dc46
refs/heads/master
2023-07-05T17:55:40.193910
2021-08-14T06:24:33
2021-08-14T06:24:33
395,897,643
0
0
null
null
null
null
UTF-8
Java
false
false
2,222
java
//---------------------------------------------------- // The following code was generated by CUP v0.11b beta 20140220 // Tue Jun 16 01:39:03 CEST 2020 //---------------------------------------------------- package asint; /** CUP generated class containing symbol constants. */ public class ClaseLexica { /* terminals */ public static final int INTERROG = 38; public static final int MAS_MAS = 35; public static final int VALOR_DOUBLE = 10; public static final int POR = 31; public static final int CHAR = 11; public static final int VALOR_CHAR = 12; public static final int PAR_AP = 40; public static final int IDENTIF = 2; public static final int MENOS_MENOS = 36; public static final int DOUBLE = 9; public static final int DOS_PUNTOS = 39; public static final int INT = 7; public static final int FOR = 20; public static final int AND = 22; public static final int IGUAL = 37; public static final int CORCH_CI = 43; public static final int OR = 21; public static final int CLASS = 16; public static final int LLAVE_AP = 44; public static final int DIV = 32; public static final int VALOR_INT = 8; public static final int IF = 18; public static final int THIS = 3; public static final int EOF = 0; public static final int BOOLEAN = 4; public static final int RETURN = 17; public static final int TRUE = 5; public static final int PAR_CI = 41; public static final int NEW = 14; public static final int error = 1; public static final int COMA = 46; public static final int MENOS = 30; public static final int NULL = 15; public static final int MENOR = 25; public static final int MOD = 33; public static final int VOID = 13; public static final int DIST_COMP = 24; public static final int MAYOR = 27; public static final int ELSE = 19; public static final int PUNTO = 48; public static final int MAYOR_IGUAL = 28; public static final int LLAVE_CI = 45; public static final int IGUAL_COMP = 23; public static final int MENOR_IGUAL = 26; public static final int FALSE = 6; public static final int CORCH_AP = 42; public static final int NEGADO = 34; public static final int PYC = 47; public static final int MAS = 29; }
39f0d229254ae75ea13904ac21f2014da831580a
078cc436e424031a1447f3d978dfc3f7ac32a317
/Java/Codigos/CaraySello.java
9549fffb02cd5e4819458b9ea6b25b4d8b444d67
[]
no_license
imgourav/codigosProgramacion
e3bb4f02ca82261fca3349503713d6e96b3e8e81
58c32a35b4205154f6a72d6d4065c86c2cd971f1
refs/heads/master
2022-12-23T05:37:33.240819
2020-10-01T02:13:46
2020-10-01T02:13:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
167
java
public void CaraySello(){ double a; a = Math.random(); if (a>=0.5){ System.out.println ("A"); }else{ System.out.println ("B"); } }
6885d59aa5aeaeeb994d614f724c7664041836d3
bc4d17be4364683a82a10d7913c243c7dd43935d
/app/src/main/java/com/globe/hand/Main/Tab4Alarm/controllers/AlarmAdapter.java
ece510b31c2ae89d11ecc0ff013f37618c8d0242
[]
no_license
tkddn204/HAND
6008cbcf42890853107fd39dccf7352c3c79acdc
27c30fa8e8c3f7d3ee9a6172c76d42a59b87accf
refs/heads/master
2021-09-10T01:17:44.847370
2018-01-10T10:12:17
2018-01-10T10:12:17
126,024,896
1
1
null
null
null
null
UTF-8
Java
false
false
1,230
java
package com.globe.hand.Main.Tab4Alarm.controllers; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.globe.hand.R; import com.google.firebase.firestore.DocumentSnapshot; import java.util.List; /** * Created by baeminsu on 2017. 12. 26.. */ public class AlarmAdapter extends RecyclerView.Adapter<AlarmViewHolder> { private Context mContext; private List<DocumentSnapshot> notiSnapshotList; public AlarmAdapter(Context mContext, List<DocumentSnapshot> notiSnapshotList) { this.mContext = mContext; this.notiSnapshotList = notiSnapshotList; } @Override public AlarmViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new AlarmViewHolder(parent, R.layout.recycler_item_alarm, this); } @Override public void onBindViewHolder(AlarmViewHolder holder, int position) { holder.bindView(mContext, notiSnapshotList.get(position), position); } @Override public int getItemCount() { return notiSnapshotList.size(); } public void removeItem(int position) { notiSnapshotList.remove(position); notifyDataSetChanged(); } }
737f7a7753ded9b9c6dfc0a582d31e92ab7266df
a259df255e7203787fa74704ed454f1bd5a4a76f
/src/main/java/com/jinchuangan/filter/SiteStatusFilter.java
4c331f5847c33ee0419c8d9f8fcb3ea950abbab9
[]
no_license
zhzhd/stock
c301022230a5684dfa9f3a29c8f907ee769db93a
6b635aecfdb319a13b683dd269b2047385861b28
refs/heads/master
2021-01-15T12:59:33.304765
2017-08-08T08:30:00
2017-08-08T08:30:00
99,665,098
1
0
null
null
null
null
UTF-8
Java
false
false
2,586
java
/* * * */ package com.jinchuangan.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jinchuangan.Setting; import com.jinchuangan.util.SettingUtils; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.web.filter.OncePerRequestFilter; /** * Filter - 网站状态 * * * @version 1.0 */ @Component("siteStatusFilter") public class SiteStatusFilter extends OncePerRequestFilter { /** 默认忽略URL */ private static final String[] DEFAULT_IGNORE_URL_PATTERNS = new String[] { "/admin/**" }; /** 默认重定向URL */ private static final String DEFAULT_REDIRECT_URL = "/common/site_close.jhtml"; /** antPathMatcher */ private static AntPathMatcher antPathMatcher = new AntPathMatcher(); /** 忽略URL */ private String[] ignoreUrlPatterns = DEFAULT_IGNORE_URL_PATTERNS; /** 重定向URL */ private String redirectUrl = DEFAULT_REDIRECT_URL; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { Setting setting = SettingUtils.get(); if (setting.getIsSiteEnabled()) { filterChain.doFilter(request, response); } else { String path = request.getServletPath(); if (path.equals(redirectUrl)) { filterChain.doFilter(request, response); return; } if (ignoreUrlPatterns != null) { for (String ignoreUrlPattern : ignoreUrlPatterns) { if (antPathMatcher.match(ignoreUrlPattern, path)) { filterChain.doFilter(request, response); return; } } } response.sendRedirect(request.getContextPath() + redirectUrl); } } /** * 获取忽略URL * * @return 忽略URL */ public String[] getIgnoreUrlPatterns() { return ignoreUrlPatterns; } /** * 设置忽略URL * * @param ignoreUrlPatterns * 忽略URL */ public void setIgnoreUrlPatterns(String[] ignoreUrlPatterns) { this.ignoreUrlPatterns = ignoreUrlPatterns; } /** * 获取重定向URL * * @return 重定向URL */ public String getRedirectUrl() { return redirectUrl; } /** * 设置重定向URL * * @param redirectUrl * 重定向URL */ public void setRedirectUrl(String redirectUrl) { this.redirectUrl = redirectUrl; } }
82364d4c58b98cb4d488f20044d1a64b29593676
ab6c0bc74dff2b522618ae4192b63ca879f3d07a
/utp-trade-ht/utp-sdk/utp-sdk-precard/src/main/java/cn/kingnet/utp/sdk/precard/dto/DownloadIndustryReconcileFileReqDTO.java
db0a454b0116bd16e802625053682ac9d70454de
[]
no_license
exyangbang/learngit
9669cb329c9686db96bd250a6ceceaf44f02e945
12c92df41a6b778a9db132c37dd136bedfd5b56f
refs/heads/master
2023-02-16T20:49:57.437363
2021-01-16T07:45:17
2021-01-16T07:45:17
330,107,905
0
0
null
null
null
null
UTF-8
Java
false
false
490
java
package cn.kingnet.utp.sdk.precard.dto; import cn.kingnet.utp.sdk.core.dto.BaseRequestDTO; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @Description * @Author WJH * @Date 2018年11月07日 */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class DownloadIndustryReconcileFileReqDTO extends BaseRequestDTO { /** * 源文件清算日期对账日期 */ private String settleDate; }
4e8b469ba4bffb23ef7b53827b32cb653d3b76c3
1f162386869a0d29348d0d2451341c76d0dbb900
/src/main/java/com/peterstovka/universe/bricksbreaking/orm/Database.java
8e34c244eefdb4835e0007edb8782251331a5deb
[ "MIT" ]
permissive
ptrstovka/bricksbreaking
8939bc10a40db3e647f9baa42883cf6240dabf02
246d44f9d6dc317ba2fcf810ed6e7f259cbe57fb
refs/heads/master
2021-04-18T18:49:30.211659
2018-03-22T18:53:03
2018-03-22T18:53:03
126,150,186
0
0
null
null
null
null
UTF-8
Java
false
false
5,014
java
package com.peterstovka.universe.bricksbreaking.orm; import com.peterstovka.universe.BuildConfig; import java.sql.*; import java.util.List; import java.util.stream.Collectors; import static com.peterstovka.universe.bricksbreaking.foundation.Lists.collect; import static com.peterstovka.universe.bricksbreaking.foundation.Strings.f; public class Database { private static Database instance = null; private static Database testInstance = null; private String url; private String user; private String pass; private Database(String url, String user, String pass) { this.url = url; this.user = user; this.pass = pass; } private Connection connection; public static Database instance() { if (instance == null) { String url = BuildConfig.POSTGRE_DB_URL; String user = BuildConfig.POSTGRE_DB_USER; String pass = BuildConfig.POSTGRE_DB_PASS; instance = new Database(url, user, pass); } return instance; } public static Database test() { if (testInstance == null) { String url = BuildConfig.POSTGRE_TEST_DB_URL; String user = BuildConfig.POSTGRE_TEST_DB_USER; String pass = BuildConfig.POSTGRE_TEST_DB_PASS; testInstance = new Database(url, user, pass); } return testInstance; } public void open() { if (connection != null) { throw new DatabaseException("The database connection is already open."); } try { connection = DriverManager.getConnection(url, user, pass); } catch (SQLException e) { e.printStackTrace(); throw new DatabaseException(f("We could not connect to the [%s] with user [%s] and password [%s].", url, user, pass)); } } public void close() { if (connection == null) { throw new DatabaseException("The database connection is already closed."); } try { connection.close(); connection = null; } catch (SQLException e) { throw new DatabaseException("We could not close the connection."); } } private Connection getConnection() { if (connection == null) { throw new DatabaseException("The database connection must be open."); } return connection; } public void insert(Object model) { InsertStatement insertStatement = new InsertStatement(model); insertStatement.prepare(); PreparedStatement preparedStatement; try { preparedStatement = getConnection().prepareStatement(insertStatement.getStatement()); } catch (SQLException e) { throw new DatabaseException(f("Insert statement is not valid: [%s]", insertStatement.getStatement())); } ReflectionHelpers.bindParameters(preparedStatement, insertStatement.getParameters()); try { preparedStatement.execute(); } catch (SQLException e) { e.printStackTrace(); throw new DatabaseException("The INSERT statement could not be executed."); } } public SelectBuilder select(Class cls) { return new SelectBuilder(this, cls); } public void update(Object object, List<String> primaryKeys) { UpdateStatement statement = new UpdateStatement(object); statement.setKeys(primaryKeys); statement.prepare(); PreparedStatement preparedStatement = prepare(statement.getUpdate()); ReflectionHelpers.bindParameters(preparedStatement, statement.getParameters()); try { preparedStatement.execute(); } catch (SQLException e) { e.printStackTrace(); throw new DatabaseException("The UPDATE statement could not be executed."); } } public void truncate(Class... classes) { List<String> tables = collect(classes) .stream() .map(ReflectionHelpers::tableName) .collect(Collectors.toList()); truncate(tables); } public void truncate(String... tables) { truncate(collect(tables)); } private void truncate(List<String> tables) { TruncateStatement statement = new TruncateStatement(tables); statement.prepare(); try { Statement stmt = getConnection().createStatement(); stmt.executeUpdate(statement.getQuery()); } catch (SQLException e) { e.printStackTrace(); throw new DatabaseException("The TRUNCATE statement could not be executed."); } } protected PreparedStatement prepare(String statement) { try { return getConnection().prepareStatement(statement); } catch (SQLException e) { e.printStackTrace(); throw new DatabaseException(f("Insert statement is not valid: [%s]", statement)); } } }
6351a25a9c65156f37491e4a43f633643287262e
ded702e7cee7d299e2fa5b009999fef48c0cbd35
/piggymetrics/account-service/src/main/java/com/jsd/piggymetrics/accountserver/account/account/controller/ErrorHandler.java
9315608a11cd538dd87f8fbb357147ca380c3c9f
[]
no_license
leiyu19940711/springcloudpiggymetrics
fc04a261a15aa4033e9f279307d5abc5857fc1cc
4a3f7feee429904e10fc2d1613dd589f86734a51
refs/heads/master
2020-05-28T01:25:44.803060
2019-05-27T12:49:36
2019-05-27T12:49:36
188,842,538
0
0
null
null
null
null
UTF-8
Java
false
false
782
java
package com.jsd.piggymetrics.accountserver.account.account.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class ErrorHandler { private final Logger log = LoggerFactory.getLogger(getClass()); // TODO add MethodArgumentNotValidException handler // TODO remove such general handler @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public void processValidationError(IllegalArgumentException e) { log.info("Returning HTTP 400 Bad Request", e); } }
cccc787a4c46f6289b419e6a65478d1fe42015f8
f35284aaaa276db67690cba8e5bc7f88c3c7a084
/app/src/main/java/cloudchen/dodgeball/WorldRecord.java
2f9d7be967e1a20149a12b9c073bb769b491db46
[ "Apache-2.0" ]
permissive
nlrabbit/Dodgeball
43481d900da44bb6806658cbd7ab75740dc505a4
03175ab20f1a0723fe9df15d0a0c2462419bd2fd
refs/heads/master
2021-01-10T22:58:01.732745
2016-06-06T08:24:59
2016-06-06T08:24:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
530
java
package cloudchen.dodgeball; import cn.bmob.v3.BmobObject; public class WorldRecord extends BmobObject { private String deviceName; private long worldRecord; public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public long getWorldRecord() { return worldRecord; } public void setWorldRecord(long worldRecord) { this.worldRecord = worldRecord; } }
cccd5432dd1dad4296b4967678464f259810b171
7b1ace6eaa1b1d097c76f2a18fa94804fb544896
/bigdata-lab/hive/src/main/java/com/luogh/learning/lab/hive/HiveConnector.java
0e3c09db3a62ddd2363e32651d42a04218f0e071
[]
no_license
luoguohao/basecode-lab
b96152846e57a78887ece792a00eb21f70eaeb85
680298fedb805cc3f568ec65e5faedf8bbe4f49f
refs/heads/master
2022-06-25T07:39:54.722036
2020-03-22T14:29:37
2020-03-22T14:29:37
87,285,843
1
0
null
2022-06-21T00:49:27
2017-04-05T08:33:08
Java
UTF-8
Java
false
false
1,788
java
package com.luogh.learning.lab.hive; import java.util.List; import java.util.stream.Collectors; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.ql.metadata.Hive; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.serde2.objectinspector.StructField; public class HiveConnector { public static void main(String[] args) throws Exception { HiveConf hiveConf = new HiveConf(); hiveConf.set("hive.metastore.uris", "thrift://172.23.7.138:9083"); Table table = Hive.get(hiveConf).getTable("cdp", "c24_order"); System.out.println("input format : " + table.getTTable().getSd().getInputFormat()); System.out.println("location : " + table.getTTable().getSd().getLocation()); System.out.println("output format : " + table.getTTable().getSd().getOutputFormat()); System.out.println("skewedColNames : " + table.getTTable().getSd().getSkewedInfo().isSetSkewedColNames()); System.out.println("skewedColNames : " + String .join(",", table.getTTable().getSd().getSkewedInfo().getSkewedColNames())); List<FieldSchema> cols = table.getTTable().getSd().getCols(); for (FieldSchema col : cols) { System.out.println("colName:" + col.getName() + ", colType:" + col.getType()); } List<StructField> fields = table.getFields(); for (StructField field : fields) { System.out.println("fieldName:" + field.getFieldName() + ", fieldId:" + field.getFieldID() + ", fieldTypeCatalog:" + field.getFieldObjectInspector().getCategory().name() + ", field:" + field.getFieldObjectInspector().getTypeName()); } System.out.println(table.getSkewedColNames().stream().collect(Collectors.joining(","))); } }
9ca58a83d2fcd3e6021a685cef9fc794477ab9f1
05d2a1e92090ec35b8be02f4b0fc7ac3695ad2f7
/src/test/java/com/baidu/unbiz/multiengine/transport/DistributedTaskTest.java
29f3bbcf79d323a21f9777516bc682c4a6df5513
[ "Apache-2.0" ]
permissive
lovehoroscoper/multi-engine
e1cec8f80ba9e0482fedd9b9cbbac863420f81e3
8ab36fda46662bf5c5130ec1530286ae756963b6
refs/heads/master
2021-01-11T14:25:39.896985
2017-02-04T03:13:36
2017-02-04T03:13:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,096
java
package com.baidu.unbiz.multiengine.transport; import java.util.List; import java.util.concurrent.CountDownLatch; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import com.baidu.unbiz.multiengine.endpoint.HostConf; import com.baidu.unbiz.multiengine.task.TaskCommand; import com.baidu.unbiz.multiengine.transport.client.SendFuture; import com.baidu.unbiz.multiengine.transport.client.TaskClient; import com.baidu.unbiz.multiengine.transport.client.TaskClientFactory; import com.baidu.unbiz.multiengine.transport.server.TaskServer; import com.baidu.unbiz.multiengine.transport.server.TaskServerFactory; import com.baidu.unbiz.multiengine.vo.DeviceViewItem; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "/applicationContext-test.xml") public class DistributedTaskTest { @Test public void testRunDisTask() { HostConf hostConf = new HostConf(); TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); taskServer.start(); TaskClient taskClient = TaskClientFactory.createTaskClient(hostConf); taskClient.start(); TaskCommand command = new TaskCommand(); command.setTaskBean("deviceStatFetcher"); command.setParams(null); List<DeviceViewItem> result = taskClient.call(command); Assert.notNull(result); System.out.println(result); taskClient.stop(); taskServer.stop(); } @Test public void testAsynRunDisTask() { HostConf hostConf = new HostConf(); TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); taskServer.start(); TaskClient taskClient = TaskClientFactory.createTaskClient(hostConf); taskClient.start(); TaskCommand command = new TaskCommand(); command.setTaskBean("deviceStatFetcher"); command.setParams(null); SendFuture sendFuture = taskClient.asyncCall(command); List<DeviceViewItem> result = sendFuture.get(); Assert.notNull(result); System.out.println(result); taskClient.stop(); taskServer.stop(); } @Test public void testRunDisTaskByBigData() { HostConf hostConf = new HostConf(); TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); taskServer.start(); TaskClient taskClient = TaskClientFactory.createTaskClient(hostConf); taskClient.start(); TaskCommand command = new TaskCommand(); command.setTaskBean("deviceBigDataStatFetcher"); command.setParams(null); List<DeviceViewItem> result = taskClient.call(command); Assert.notNull(result); System.out.println(result); taskClient.stop(); taskServer.stop(); } @Test public void testRunDisTasksByBigResult() { HostConf hostConf = new HostConf(); TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); taskServer.start(); final TaskClient taskClient = TaskClientFactory.createTaskClient(hostConf); taskClient.start(); for (int i = 0; i < 10; i++) { TaskCommand command = new TaskCommand(); command.setTaskBean("deviceBigDataStatFetcher"); command.setParams(null); List<DeviceViewItem> result = taskClient.call(command); Assert.notNull(result); System.out.println(result); } taskClient.stop(); taskServer.stop(); } @Test public void testConcurrentRunDisTask() { HostConf hostConf = new HostConf(); TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); taskServer.start(); final TaskClient taskClient = TaskClientFactory.createTaskClient(hostConf); taskClient.start(); final CountDownLatch latch = new CountDownLatch(50); for (int i = 0; i < 50; i++) { new Thread() { @Override public void run() { TaskCommand command = new TaskCommand(); command.setTaskBean("deviceBigDataStatFetcher"); command.setParams(null); Object result = taskClient.call(command); Assert.notNull(result); System.out.println(result); latch.countDown(); } }.start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } taskClient.stop(); taskServer.stop(); } @Test public void testConcurrentRunDisTaskByBigResult() { HostConf hostConf = new HostConf(); TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); taskServer.start(); final TaskClient taskClient = TaskClientFactory.createTaskClient(hostConf); taskClient.start(); final int loopCnt = 50; final CountDownLatch latch = new CountDownLatch(loopCnt); for (int i = 0; i < loopCnt; i++) { new Thread() { @Override public void run() { TaskCommand command = new TaskCommand(); command.setTaskBean("deviceBigDataStatFetcher"); command.setParams(null); Object result = taskClient.call(command); Assert.notNull(result); System.out.println(result); latch.countDown(); } }.start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } taskClient.stop(); taskServer.stop(); } @Test public void testRunDisTaskByMultiClient() { HostConf hostConf = new HostConf(); TaskServer taskServer = TaskServerFactory.createTaskServer(hostConf); taskServer.start(); TaskClient taskClient1 = TaskClientFactory.createTaskClient(hostConf); taskClient1.start(); TaskClient taskClient2 = TaskClientFactory.createTaskClient(hostConf); taskClient2.start(); TaskCommand command = new TaskCommand(); command.setTaskBean("deviceStatFetcher"); command.setParams(null); Object result1 = taskClient1.call(command); Object result2 = taskClient2.call(command); for (int i = 0; i < 500; i++) { result1 = taskClient1.call(command); result2 = taskClient2.call(command); Assert.isTrue(result1.toString().equals(result2.toString())); } Assert.notNull(result1); Assert.notNull(result2); System.out.println(result1); System.out.println(result2); taskClient1.stop(); taskClient2.stop(); taskServer.stop(); } }
40b7cb92b638defacb0adf09ce08dfdceec1c5ad
7a36817e7eabe8caebd670addba48726a904efa7
/edu/ucla/sspace/util/IteratorDecorator.java
a69369c719ce73e95f0be91917980c727776918c
[]
no_license
carolinemckinnon/Lex
1958f7a50e5d469efbb33f70e4e166220bc3548e
4fc78f209a22cd5b20e21f654a081d09bbeead6e
refs/heads/master
2021-01-19T20:57:33.441323
2017-04-18T04:49:43
2017-04-18T04:49:43
88,582,569
0
0
null
null
null
null
UTF-8
Java
false
false
662
java
package edu.ucla.sspace.util; import java.io.Serializable; import java.util.Iterator; public class IteratorDecorator<T> implements Iterator<T>, Serializable { private static final long serialVersionUID = 1L; private final Iterator<T> iter; protected T cur; public IteratorDecorator(Iterator<T> iter) { if (iter == null) throw new NullPointerException(); this.iter = iter; } public boolean hasNext() { return iter.hasNext(); } public T next() { cur = iter.next(); return cur; } public void remove() { cur = null; iter.remove(); } }
d95fca85d8c4f52eae35febf0d2cd761606a7cd0
53683df8b3f891046fb605dffbc667a038dcb2be
/Web/ProjetPLDL/src/java/entites/ListesdelectureMusiquesPK.java
d947e6842a1bb902cd193b51f1935c3dd1a3c9a6
[]
no_license
jodellevictoria/Projet_Final
7e821b0002b9a3e5063a4d854eb8630adfd9005d
552785ef6538c14bd475c2095ebe2aa7f890434a
refs/heads/master
2021-08-29T23:52:20.007503
2017-12-15T10:17:39
2017-12-15T10:17:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,088
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 entites; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.validation.constraints.NotNull; /** * * @author jodel */ @Embeddable public class ListesdelectureMusiquesPK implements Serializable { @Basic(optional = false) @NotNull @Column(name = "ListeDeLecture") private int listeDeLecture; @Basic(optional = false) @NotNull @Column(name = "Musique") private int musique; public ListesdelectureMusiquesPK() { } public ListesdelectureMusiquesPK(int listeDeLecture, int musique) { this.listeDeLecture = listeDeLecture; this.musique = musique; } public int getListeDeLecture() { return listeDeLecture; } public void setListeDeLecture(int listeDeLecture) { this.listeDeLecture = listeDeLecture; } public int getMusique() { return musique; } public void setMusique(int musique) { this.musique = musique; } @Override public int hashCode() { int hash = 0; hash += (int) listeDeLecture; hash += (int) musique; return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ListesdelectureMusiquesPK)) { return false; } ListesdelectureMusiquesPK other = (ListesdelectureMusiquesPK) object; if (this.listeDeLecture != other.listeDeLecture) { return false; } if (this.musique != other.musique) { return false; } return true; } @Override public String toString() { return "entites.ListesdelectureMusiquesPK[ listeDeLecture=" + listeDeLecture + ", musique=" + musique + " ]"; } }
00449cf3eec0b2b07aab57e72bb02b460e349674
7bb3f29b98be803ecd4f45dad3606998b37fe855
/Terminkalender-Task5/src/Appointment.java
14c0dd88b829b76d6265a219c2d68353a6664df0
[]
no_license
TUBS-ISF/SPL2018.Project.22
64445e53447807016569562a64ef9c97eedafd1d
e3374ad85ca35bdf298c6a29d6f27baae10dfd9b
refs/heads/master
2020-03-13T13:11:06.544666
2018-07-08T17:06:37
2018-07-08T17:06:37
131,133,634
0
0
null
null
null
null
UTF-8
Java
false
false
1,284
java
import java.util.ArrayList; public class Appointment { private ArrayList<String> getData__wrappee__Base () { return new ArrayList<String>(); } private ArrayList<String> getData__wrappee__Title () { ArrayList<String> data = getData__wrappee__Base(); data.add(title); return data; } private ArrayList<String> getData__wrappee__Time () { ArrayList<String> data = getData__wrappee__Title(); data.add(time); return data; } public ArrayList<String> getData() { ArrayList<String> data = getData__wrappee__Time(); data.add(priority.toString()); return data; } private String title = ""; public void setTitle(String title) { this.title = title; } public String getTitle() { // TODO Auto-generated method stub return title; } private String time = ""; public void setTime(String time) { this.time = time; } public String getTime() { // TODO Auto-generated method stub return time; } private Priority priority = Priority.none; public Priority getPriority() { return priority; } public void setPriority(Priority priority) { this.priority = priority; } }
0effad6aa32721bda71c985e7e216bd3d2a84de4
6106a672418cbfd8322c4e70a05c26d1379182ac
/src/wts-exam/src/main/java/com/wts/exam/controller/PaperController.java
0c0f0dced81fcbd995d80a2605bc74cf915af19e
[]
no_license
ljb2546313415/OnlineExamWTC
9adbd9e566fe6e3aead32019405764fd4891148b
b6181e41788ee265dbcca17915523e6137ac3f29
refs/heads/master
2023-03-27T06:28:01.394276
2021-03-24T10:02:11
2021-03-24T10:02:11
351,016,343
0
0
null
null
null
null
UTF-8
Java
false
false
18,935
java
package com.wts.exam.controller; import com.wts.exam.domain.ExamType; import com.wts.exam.domain.Paper; import com.wts.exam.domain.RandomStep; import com.wts.exam.domain.ex.WtsPaperBean; import com.wts.exam.domain.ex.PaperUnit; import com.wts.exam.service.ExamTypeServiceInter; import com.wts.exam.service.PaperServiceInter; import com.wts.exam.service.RandomItemServiceInter; import com.wts.exam.service.SubjectTypeServiceInter; import com.wts.exam.utils.WtsPaperBeanUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.annotation.Resource; import com.farm.web.easyui.EasyUiUtils; import com.farm.web.log.WcpLog; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import javax.servlet.http.HttpSession; import com.farm.core.page.RequestMode; import com.farm.core.page.OperateType; import com.farm.core.sql.query.DBRule; import com.farm.core.sql.query.DataQuery; import com.farm.core.sql.query.DataQuerys; import com.farm.core.sql.result.DataResult; import com.farm.core.time.TimeTool; import com.farm.doc.server.utils.FileDownloadUtils; import com.farm.parameter.service.AloneApplogServiceInter; import com.farm.core.page.ViewMode; import com.farm.web.WebUtils; /* * *功能:考卷控制层 *详细: * *版本:v0.1 *作者:FarmCode代码工程 *日期:20150707114057 *说明: */ @RequestMapping("/paper") @Controller public class PaperController extends WebUtils { private final static Logger log = Logger.getLogger(PaperController.class); @Resource private PaperServiceInter paperServiceImpl; @Resource private ExamTypeServiceInter examTypeServiceImpl; @Resource private AloneApplogServiceInter aloneApplogServiceImpl; @Resource private RandomItemServiceInter randomItemServiceImpl; @Resource private SubjectTypeServiceInter subjectTypeServiceImpl; /** * 查询结果集合 * * @return */ @RequestMapping("/query") @ResponseBody public Map<String, Object> queryall(DataQuery query, HttpServletRequest request, HttpSession session) { try { if (StringUtils.isNotBlank(query.getRule("B.TREECODE")) && query.getRule("B.TREECODE").equals("NONE")) { query.getAndRemoveRule("B.TREECODE"); } query = EasyUiUtils.formatGridQuery(request, query); { // 过滤权限 String typeids_Rule = DataQuerys .parseSqlValues(examTypeServiceImpl.getUserPopTypeids(getCurrentUser(session).getId(), "1")); if (typeids_Rule != null) { query.addSqlRule(" and b.id in (" + typeids_Rule + ")"); } else { query.addSqlRule(" and b.id ='NONE'"); } } DataResult result = paperServiceImpl.createPaperSimpleQuery(query).search(); result.runDictionary("1:新建,0:停用,2:发布", "PSTATE"); result.runformatTime("CTIME", "yyyy-MM-dd HH:mm"); return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 查询结果集合(考场选择试卷) * * @return */ @RequestMapping("/chooseQuery") @ResponseBody public Map<String, Object> chooseQuery(DataQuery query, HttpServletRequest request, HttpSession session) { try { if (StringUtils.isNotBlank(query.getRule("B.TREECODE")) && query.getRule("B.TREECODE").equals("NONE")) { query.getAndRemoveRule("B.TREECODE"); } query = EasyUiUtils.formatGridQuery(request, query); query.addRule(new DBRule("a.PSTATE", "2", "=")); { // 过滤权限 String typeids_Rule = DataQuerys .parseSqlValues(examTypeServiceImpl.getUserPopTypeids(getCurrentUser(session).getId(), "1")); if (typeids_Rule != null) { query.addSqlRule(" and b.id in (" + typeids_Rule + ")"); } } DataResult result = paperServiceImpl.createPaperSimpleQuery(query).search(); result.runDictionary("1:新建,0:停用,2:发布", "PSTATE"); result.runformatTime("CTIME", "yyyy-MM-dd HH:mm"); return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 提交修改数据 * * @return */ @RequestMapping("/edit") @ResponseBody public Map<String, Object> editSubmit(Paper entity, HttpSession session) { try { WcpLog.info("修改答卷[" + entity.getId() + "]:表单提交", getCurrentUser(session).getName(), getCurrentUser(session).getId()); entity = paperServiceImpl.editPaperEntity(entity, getCurrentUser(session)); return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode(); } } /** * 下载word答卷 * * @return */ @RequestMapping("/exportWord") public void exportWord(String paperid, HttpServletRequest request, HttpServletResponse response, HttpSession session) { PaperUnit paper = paperServiceImpl.getPaperUnit(paperid); WcpLog.info("导出WORD答卷" + paperid + "/" + paper.getInfo().getName(), getCurrentUser(session).getName(), getCurrentUser(session).getId()); log.info(getCurrentUser(session).getLoginname() + "/" + getCurrentUser(session).getName() + "导出答卷" + paperid); File file = paperServiceImpl.exprotWord(paper, getCurrentUser(session)); FileDownloadUtils.simpleDownloadFile(file, "paper" + TimeTool.getTimeDate12() + ".docx", "application/octet-stream", response); } /** * 下载Json答卷 * * @return * @throws IOException */ @RequestMapping("/exportWtsp") public void exportWtsp(String paperid, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { WcpLog.info("导出JSON.wtsp答卷" + paperid, getCurrentUser(session).getName(), getCurrentUser(session).getId()); log.info(getCurrentUser(session).getLoginname() + "/" + getCurrentUser(session).getName() + "导出答卷" + paperid); File file = paperServiceImpl.exprotWtsp(paperid, getCurrentUser(session)); FileDownloadUtils.simpleDownloadFile(file, "paper" + paperid + ".wtsp", "application/octet-stream", response); } /** * 进入随机出题界面 * * @return */ @RequestMapping("/addRandomSubjects") public ModelAndView addRandomSubjects(String paperids, HttpSession session) { try { List<Paper> papers = new ArrayList<>(); for (String id : parseIds(paperids)) { Paper paper = paperServiceImpl.getPaperEntity(id); if (paper != null) { papers.add(paper); } } return ViewMode.getInstance().putAttr("papers", papers).putAttr("paperids", paperids) .returnModelAndView("exam/PaperRandomSubjectsForm"); } catch (Exception e) { return ViewMode.getInstance().setError(e + e.getMessage(), e) .returnModelAndView("exam/PaperRandomSubjectsForm"); } } /** * 提交新增数据 * * @return */ @RequestMapping("/add") @ResponseBody public Map<String, Object> addSubmit(Paper entity, HttpSession session) { try { entity = paperServiceImpl.insertPaperEntity(entity, getCurrentUser(session)); WcpLog.info("创建答卷[" + entity.getId() + "]:表单创建", getCurrentUser(session).getName(), getCurrentUser(session).getId()); return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode(); } } /** * 删除数据 * * @return */ @RequestMapping("/del") @ResponseBody public Map<String, Object> delSubmit(String ids, HttpSession session) { try { for (String id : parseIds(ids)) { WcpLog.info("刪除答卷[" + id + "]:表单刪除", getCurrentUser(session).getName(), getCurrentUser(session).getId()); paperServiceImpl.deletePaperEntity(id, getCurrentUser(session)); } return ViewMode.getInstance().returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 批量加载答卷信息 * * @return */ @RequestMapping("/loadPapersInfo") @ResponseBody public Map<String, Object> loadPapersInfo(String ids, HttpSession session) { try { List<PaperUnit> paperunits = new ArrayList<>(); for (String id : parseIds(ids)) { paperunits.add(paperServiceImpl.getPaperUnit(id)); } return ViewMode.getInstance().putAttr("papers", paperunits).returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 添加随机题到答卷中 * * @return */ @RequestMapping("/doAddRandomSubjects") @ResponseBody public Map<String, Object> doAddRandomSubjects(String ids, String typeid, String tiptype, Integer subnum, Integer point, HttpSession session) { try { String warn = ""; for (String paperid : parseIds(ids)) { warn = warn + paperServiceImpl.addRandomSubjects(paperid, typeid, tiptype, subnum, point, getCurrentUser(session)); paperServiceImpl.refreshSubjectNum(paperid); WcpLog.info("修改答卷[" + paperid + "]:添加随机题", getCurrentUser(session).getName(), getCurrentUser(session).getId()); } return ViewMode.getInstance().putAttr("warn", warn).returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } @RequestMapping("/doClearSubjects") @ResponseBody public Map<String, Object> doClearSubjects(String ids, HttpSession session) { try { String warn = ""; for (String paperid : parseIds(ids)) { WcpLog.info("修改答卷[" + paperid + "]:清空答卷所有题目", getCurrentUser(session).getName(), getCurrentUser(session).getId()); paperServiceImpl.clearPaper(paperid); paperServiceImpl.refreshSubjectNum(paperid); } return ViewMode.getInstance().putAttr("warn", warn).returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 进入 批量创建随机卷表单 * * @return */ @RequestMapping("/addRandomsPage") public ModelAndView addRandomsPage(String typeid, HttpSession session) { try { if (typeid == null || typeid.trim().equals("")) { throw new RuntimeException("业务分类不能为空!"); } ExamType type = examTypeServiceImpl.getExamtypeEntity(typeid); // 獲取隨機規則項 List<Map<String, Object>> items = randomItemServiceImpl .createRandomitemSimpleQuery( (new DataQuery()).setPagesize(100).addRule(new DBRule("PSTATE", "1", "="))) .search().getResultList(); return ViewMode.getInstance().putAttr("type", type).putAttr("items", items) .returnModelAndView("exam/PaperRandomsForm"); } catch (Exception e) { return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("exam/PaperRandomsForm"); } } /** * 執行批量随机卷生成 * * @param ids * @param session * @return */ @RequestMapping("/runRandomPapers") @ResponseBody public Map<String, Object> runRandomPapers(Paper entity, int num, String itemid, HttpSession session) { try { List<RandomStep> steps = randomItemServiceImpl.getSteps(itemid); if (StringUtils.isBlank(entity.getExamtypeid())) { throw new RuntimeException("业务分类ID不能为空!"); } String name = entity.getName(); for (int n = 0; n < num; n++) { try { entity.setPstate("1"); entity.setName(name + "-" + (n + 1)); entity = paperServiceImpl.insertPaperEntity(entity, getCurrentUser(session)); WcpLog.info("创建答卷[" + entity.getId() + "]:创建随机答卷[规则ITEMID" + itemid + "]", getCurrentUser(session).getName(), getCurrentUser(session).getId()); for (RandomStep step : steps) { String warnMessage = paperServiceImpl.addRandomSubjects(entity.getId(), step.getTypeid(), step.getTiptype(), step.getSubnum(), step.getSubpoint(), getCurrentUser(session)); if (StringUtils.isNotBlank(warnMessage)) { throw new RuntimeException(warnMessage); } } paperServiceImpl.refreshSubjectNum(entity.getId()); } catch (Exception e) { paperServiceImpl.deletePaperEntity(entity.getId(), getCurrentUser(session)); throw new RuntimeException(e); } } return ViewMode.getInstance().returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } @RequestMapping("/list") public ModelAndView index(HttpSession session) { return ViewMode.getInstance().returnModelAndView("exam/PaperResult"); } @RequestMapping("/view") public ModelAndView view(String paperId, HttpSession session) { PaperUnit paper = paperServiceImpl.getPaperUnit(paperId); return ViewMode.getInstance().putAttr("paper", paper).returnModelAndView("exam/PaperView"); } @RequestMapping("/chooselist") public ModelAndView chooselist(HttpSession session) { return ViewMode.getInstance().returnModelAndView("exam/PaperChooseResult"); } /** * 显示详细信息(修改或浏览时) * * @return */ @RequestMapping("/form") public ModelAndView view(RequestMode pageset, String ids) { try { ExamType examtype = null; Paper paper = null; if (StringUtils.isNotBlank(ids)) { paper = paperServiceImpl.getPaperEntity(ids); if (StringUtils.isNotBlank(paper.getExamtypeid())) { examtype = examTypeServiceImpl.getExamtypeEntity(paper.getExamtypeid()); } } switch (pageset.getOperateType()) { case (0): {// 查看 return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("examType", examtype) .putAttr("entity", paper).returnModelAndView("exam/PaperForm"); } case (1): {// 新增 return ViewMode.getInstance().putAttr("pageset", pageset).returnModelAndView("exam/PaperForm"); } case (2): {// 修改 return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("examType", examtype) .putAttr("entity", paper).returnModelAndView("exam/PaperForm"); } default: break; } return ViewMode.getInstance().returnModelAndView("exam/PaperForm"); } catch (Exception e) { return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("exam/PaperForm"); } } /** * 考试禁用 * * @return */ @RequestMapping("/examPrivate") @ResponseBody public Map<String, Object> examPrivate(String ids, HttpSession session) { try { for (String id : parseIds(ids)) { WcpLog.info("答卷状态变更[" + id + "]:禁用", getCurrentUser(session).getName(), getCurrentUser(session).getId()); paperServiceImpl.editState(id, "0", getCurrentUser(session)); } return ViewMode.getInstance().returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 考试发布 * * @return */ @RequestMapping("/examPublic") @ResponseBody public Map<String, Object> examPublic(String ids, HttpSession session) { try { for (String id : parseIds(ids)) { WcpLog.info("答卷状态变更[" + id + "]:发布", getCurrentUser(session).getName(), getCurrentUser(session).getId()); paperServiceImpl.editState(id, "2", getCurrentUser(session)); } return ViewMode.getInstance().returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 设置考试分类 * * @return */ @RequestMapping("/examtypeSetting") @ResponseBody public Map<String, Object> examtypeSetting(String ids, String examtypeId, HttpSession session) { try { for (String id : parseIds(ids)) { WcpLog.info("修改答卷[" + id + "]:修改分类", getCurrentUser(session).getName(), getCurrentUser(session).getId()); paperServiceImpl.examTypeSetting(id, examtypeId, getCurrentUser(session)); } return ViewMode.getInstance().returnObjMode(); } catch (Exception e) { log.error(e.getMessage()); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } /** * 到达人员导入页面 * * @return ModelAndView */ @RequestMapping("/toWtspImport") public ModelAndView toUserImport() { try { return ViewMode.getInstance().returnModelAndView("exam/PaperWtspImport"); } catch (Exception e) { log.error(e.getMessage(), e); return ViewMode.getInstance().setError(e.getMessage(), e).returnModelAndView("exam/PaperWtspImport"); } } /** * 完成wtsp导入 * * @return Map<String,Object> */ @RequestMapping("/doWtspImport") @ResponseBody public Map<String, Object> doUserImport(@RequestParam(value = "file", required = false) MultipartFile file, String examType, String subjectType, HttpSession session) { try { if (examTypeServiceImpl.getExamtypeEntity(examType) == null || subjectTypeServiceImpl.getSubjecttypeEntity(subjectType) == null) { throw new RuntimeException("请选择有效的业务分类和题库分类 !"); } // 校验数据有效性 CommonsMultipartFile cmfile = (CommonsMultipartFile) file; if (cmfile.getSize() >= 10000000) { throw new RuntimeException("文件不能大于10M"); } if (cmfile.isEmpty()) { throw new RuntimeException("请上传有效文件!"); } InputStream is = cmfile.getInputStream(); try { WtsPaperBean bean = WtsPaperBeanUtils.readFromFile(is); String paperid = paperServiceImpl.importByWtsPaperBean(bean, examType, subjectType, getCurrentUser(session)); WcpLog.info("创建答卷[" + paperid + "]:wtsp文件导入", getCurrentUser(session).getName(), getCurrentUser(session).getId()); } finally { is.close(); } return ViewMode.getInstance().returnObjMode(); } catch (Exception e) { log.error(e.getMessage(), e); return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode(); } } }
56f1c2227dcfdb47c0abc707aa865741d034a186
bc94646980c9196c81b770908414311f71255e5b
/src/main/java/com/elytradev/davincisvessels/common/network/HelmClientAction.java
029191ace62380332bda14e0477b0d5d2f5330f4
[ "Apache-2.0" ]
permissive
jeffreymeng/DavincisVessels
3a653b64449505a8523203e4f4efd3cc9ac93a09
75022af70b11452e6da6337f6aeabbb323cec9d0
refs/heads/1.12
2021-07-04T06:18:52.070957
2018-05-09T18:15:35
2018-05-09T18:15:35
151,132,148
0
0
Apache-2.0
2018-10-01T17:49:41
2018-10-01T17:49:41
null
UTF-8
Java
false
false
857
java
package com.elytradev.davincisvessels.common.network; public enum HelmClientAction { UNKNOWN, ASSEMBLE, MOUNT, UNDOCOMPILE; public static int toInt(HelmClientAction action) { switch (action) { case ASSEMBLE: return (byte) 1; case MOUNT: return (byte) 2; case UNDOCOMPILE: return (byte) 3; default: return (byte) 0; } } public static HelmClientAction fromInt(int actionInt) { switch (actionInt) { case 1: return ASSEMBLE; case 2: return MOUNT; case 3: return UNDOCOMPILE; default: return UNKNOWN; } } public int toInt() { return HelmClientAction.toInt(this); } }
8cc91dcf37d2e9501c6bcedd5ded9b59918aff4d
cce05386a9bc9aee91a041cdb5c8144db3248dad
/Backend/src/main/java/com/devglan/assignment/QuestionRepository.java
3e193e804ae69f5e3e14f002565b1b28b853cd28
[]
no_license
spurthyPramod/Assignment
cd5487620be2c0fe78ed32e2257f12f18f559577
cbf70862f73632d3c0ea9c68b6c5fbdcf7706ab2
refs/heads/master
2020-05-05T02:23:48.238245
2019-04-05T07:34:43
2019-04-05T07:34:43
179,636,060
0
0
null
null
null
null
UTF-8
Java
false
false
328
java
package com.devglan.assignment; import java.util.List; import org.springframework.data.repository.Repository; public interface QuestionRepository extends Repository<Question, Integer> { void delete(Question question); List<Question> findAll(); Question findOne(int id); Question save(Question question); }
[ "" ]
7c7e651e42130b6ed75fee2bac378a17014f4a27
34c0d4baef12bf683a884d00ed82a2a05b605cf4
/addressbook/src/test/java/addressbook/tests/GroupModificationTests.java
f23df1015888944626ffcd6bae0a34216b0aa91d
[ "Apache-2.0" ]
permissive
Sviatlana-Pi/java_pft
0471b70db92f8cdbd108d5a2b260058b0f3df840
5a491cf124946d3f7c07f5b3acc1a98cbc11f722
refs/heads/main
2023-03-17T05:01:36.143833
2021-03-07T17:47:35
2021-03-07T17:47:35
343,521,397
0
0
null
null
null
null
UTF-8
Java
false
false
618
java
package addressbook.tests; import addressbook.model.GroupData; import org.testng.annotations.Test; public class GroupModificationTests extends TestBase { @Test public void testGroupModification(){ app.getNavigationHelper().gotoGroupPage(); app.getGroupHelper().selectGroup(); app.getGroupHelper().initGroupModification(); app.getGroupHelper().fillGroupForm(new GroupData("test_new_group_name","test_new_group_header","test_new_group_footer")); app.getGroupHelper().submitGroupModification(); app.getGroupHelper().returnToGroupPage(); } }
2e323439c168d61ad2fbabae46c995f17ea01331
c8365237a15b7aa005ab75a0f07bd4b87b452692
/Quadratin/app/src/main/java/g4a/quadratin/mx/quadratin/SlidingTabLayout.java
f43ca589b400d6dd30c37b31e341d11d1788c888
[]
no_license
eduardobc88/AndroidStudio
99a6701edc1fdd1be4985c9cd1c0f0685832c712
2649e1aee8d719a96c9fa3dc955655b187ff53d2
refs/heads/master
2021-05-30T14:00:38.076786
2015-05-04T17:10:32
2015-05-04T17:10:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,637
java
package g4a.quadratin.mx.quadratin; /* * Copyright 2014 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 com.google.samples.apps.iosched.ui.widget; import android.content.Context; import android.graphics.Typeface; import android.os.Build; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.SparseArray; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; /** * To be used with ViewPager to provide a tab indicator component which give constant feedback as to * the user's scroll progress. * <p> * To use the component, simply add it to your view hierarchy. Then in your * {@link android.app.Activity} or {@link android.support.v4.app.Fragment} call * {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for. * <p> * The colors can be customized in two ways. The first and simplest is to provide an array of colors * via {@link #setSelectedIndicatorColors(int...)}. The * alternative is via the {@link TabColorizer} interface which provides you complete control over * which color is used for any individual position. * <p> * The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)}, * providing the layout ID of your custom layout. */ public class SlidingTabLayout extends HorizontalScrollView { /** * Allows complete control over the colors drawn in the tab layout. Set with * {@link #setCustomTabColorizer(TabColorizer)}. */ public interface TabColorizer { /** * @return return the color of the indicator used when {@code position} is selected. */ int getIndicatorColor(int position); } private static final int TITLE_OFFSET_DIPS = 24; private static final int TAB_VIEW_PADDING_DIPS = 16; private static final int TAB_VIEW_TEXT_SIZE_SP = 12; private int mTitleOffset; private int mTabViewLayoutId; private int mTabViewTextViewId; private boolean mDistributeEvenly; private ViewPager mViewPager; private SparseArray<String> mContentDescriptions = new SparseArray<String>(); private ViewPager.OnPageChangeListener mViewPagerPageChangeListener; private final SlidingTabStrip mTabStrip; public SlidingTabLayout(Context context) { this(context, null); } public SlidingTabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Disable the Scroll Bar setHorizontalScrollBarEnabled(false); // Make sure that the Tab Strips fills this View setFillViewport(true); mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density); mTabStrip = new SlidingTabStrip(context); addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } /** * Set the custom {@link TabColorizer} to be used. * * If you only require simple custmisation then you can use * {@link #setSelectedIndicatorColors(int...)} to achieve * similar effects. */ public void setCustomTabColorizer(TabColorizer tabColorizer) { mTabStrip.setCustomTabColorizer(tabColorizer); } public void setDistributeEvenly(boolean distributeEvenly) { mDistributeEvenly = distributeEvenly; } /** * Sets the colors to be used for indicating the selected tab. These colors are treated as a * circular array. Providing one color will mean that all tabs are indicated with the same color. */ public void setSelectedIndicatorColors(int... colors) { mTabStrip.setSelectedIndicatorColors(colors); } /** * Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so * that the layout can update it's scroll position correctly. * * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener) */ public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) { mViewPagerPageChangeListener = listener; } /** * Set the custom layout to be inflated for the tab views. * * @param layoutResId Layout id to be inflated * @param textViewId id of the {@link TextView} in the inflated view */ public void setCustomTabView(int layoutResId, int textViewId) { mTabViewLayoutId = layoutResId; mTabViewTextViewId = textViewId; } /** * Sets the associated view pager. Note that the assumption here is that the pager content * (number of tabs and tab titles) does not change after this call has been made. */ public void setViewPager(ViewPager viewPager) { mTabStrip.removeAllViews(); mViewPager = viewPager; if (viewPager != null) { viewPager.setOnPageChangeListener(new InternalViewPagerListener()); populateTabStrip(); } //set background color for the first tab when is running for first time setBackgroundTab(0, R.color.primary_dark); } private void setBackgroundTab(int tabId, int resId) { //set background textview color //((TextView)mTabStrip.getChildAt(tabId)).setBackgroundResource(resId); } /** * Create a default view to be used for tabs. This is called if a custom tab view is not set via * {@link #setCustomTabView(int, int)}. */ protected TextView createDefaultTabView(Context context) { TextView textView = new TextView(context); textView.setGravity(Gravity.CENTER); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP); textView.setTypeface(Typeface.DEFAULT_BOLD); textView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); TypedValue outValue = new TypedValue(); getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true); textView.setBackgroundResource(outValue.resourceId); textView.setAllCaps(true); int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density); textView.setPadding(padding, padding, padding, padding); return textView; } private void populateTabStrip() { final PagerAdapter adapter = mViewPager.getAdapter(); final View.OnClickListener tabClickListener = new TabClickListener(); for (int i = 0; i < adapter.getCount(); i++) { View tabView = null; TextView tabTitleView = null; if (mTabViewLayoutId != 0) { // If there is a custom tab view layout id set, try and inflate it tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false); tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId); } if (tabView == null) { tabView = createDefaultTabView(getContext()); } if (tabTitleView == null && TextView.class.isInstance(tabView)) { tabTitleView = (TextView) tabView; } if (mDistributeEvenly) { LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams(); lp.width = 0; lp.weight = 1; } tabTitleView.setText(adapter.getPageTitle(i)); tabView.setOnClickListener(tabClickListener); String desc = mContentDescriptions.get(i, null); if (desc != null) { tabView.setContentDescription(desc); } mTabStrip.addView(tabView); if (i == mViewPager.getCurrentItem()) { tabView.setSelected(true); } tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector)); //tabTitleView.setTextSize(14); } } public void setContentDescription(int i, String desc) { mContentDescriptions.put(i, desc); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mViewPager != null) { scrollToTab(mViewPager.getCurrentItem(), 0); } } private void scrollToTab(int tabIndex, int positionOffset) { final int tabStripChildCount = mTabStrip.getChildCount(); if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) { return; } View selectedChild = mTabStrip.getChildAt(tabIndex); if (selectedChild != null) { int targetScrollX = selectedChild.getLeft() + positionOffset; if (tabIndex > 0 || positionOffset > 0) { // If we're not at the first child and are mid-scroll, make sure we obey the offset targetScrollX -= mTitleOffset; } scrollTo(targetScrollX, 0); } } private class InternalViewPagerListener implements ViewPager.OnPageChangeListener { private int mScrollState; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int tabStripChildCount = mTabStrip.getChildCount(); if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) { return; } mTabStrip.onViewPagerPageChanged(position, positionOffset); View selectedTitle = mTabStrip.getChildAt(position); int extraOffset = (selectedTitle != null) ? (int) (positionOffset * selectedTitle.getWidth()) : 0; scrollToTab(position, extraOffset); if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageScrollStateChanged(int state) { mScrollState = state; if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageScrollStateChanged(state); } } @Override public void onPageSelected(int position) { int positionId = -1; if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mTabStrip.onViewPagerPageChanged(position, 0f); scrollToTab(position, 0); } for (int i = 0; i < mTabStrip.getChildCount(); i++) { mTabStrip.getChildAt(i).setSelected(position == i); //set background textview color if(i == position) { setBackgroundTab(i,R.color.primary_dark); } else { setBackgroundTab(i,R.color.tabBarColor); } } if (mViewPagerPageChangeListener != null) { mViewPagerPageChangeListener.onPageSelected(position); } } } private class TabClickListener implements View.OnClickListener { @Override public void onClick(View v) { for (int i = 0; i < mTabStrip.getChildCount(); i++) { if (v == mTabStrip.getChildAt(i)) { mViewPager.setCurrentItem(i); return; } } } } }
fd87343d4077b50718dc65bf96fb2b448e9b123d
bc7370cfb5ccc61072444d1dde0701abb7640cb2
/lhitf/src/private/nc/bs/lhitf/bgtask/AutoTransBankAccBgTaskPlugin.java
ef98516f6e23f63438e60bdd5c5a607c48bbdce5
[]
no_license
guowj1/lhprj
a4cf6f715d864a17dcef656cee02965c223777f2
70b5e6fabddeaf1db026591d817f0eab91704b58
refs/heads/master
2021-01-01T19:53:53.324175
2017-09-25T09:14:17
2017-09-25T09:14:17
98,713,984
0
0
null
null
null
null
UTF-8
Java
false
false
1,456
java
package nc.bs.lhitf.bgtask; import nc.bs.lhitf.bgtask.pub.PostDataImp; import nc.bs.pub.pa.PreAlertObject; import nc.bs.pub.taskcenter.BgWorkingContext; import nc.bs.pub.taskcenter.IBackgroundWorkPlugin; import nc.md.persist.framework.IMDPersistenceQueryService; import nc.md.persist.framework.MDPersistenceService; import nc.vo.bd.bankaccount.BankAccbasVO; import nc.vo.pub.BusinessException; public class AutoTransBankAccBgTaskPlugin implements IBackgroundWorkPlugin { private IMDPersistenceQueryService mdQueryService; @Override public PreAlertObject executeTask(BgWorkingContext arg0) throws BusinessException { BankAccbasVO[] vos = null; vos = (BankAccbasVO[]) getMdQueryService().queryBillOfVOByCond( // BankAccbasVO.class, " (def2='~' or def2 is null or def2<ts) and def1='1001A6100000000000XU' ", BankAccbasVO.class, " (def2='~' or def2 is null) and def1='1001A6100000000000XU' ", false).toArray(new BankAccbasVO[0]); if (vos == null || vos.length < 1) { return null; } try { PostDataImp postServ = new PostDataImp(); postServ.sendDataByStr(vos, "bankaccbas"); } catch (Exception e) { throw new BusinessException(e.getMessage()); } return null; } private IMDPersistenceQueryService getMdQueryService() { if (mdQueryService == null) mdQueryService = MDPersistenceService .lookupPersistenceQueryService(); return mdQueryService; } }
2fd8374b6e882cb26664df4c73656f4678ba4031
34f5ab7476ec9c3c1f1e6a8f8dc5efd018210742
/src/main/java/utils/RemoteWebDriverFactory.java
fbefccd83701af689a54dffb8aeb376dfcb2f523
[]
no_license
Starday2009/RCvsWebDriver
c79dc2fe017e2ef9d61e6d23a2318f16bf920a72
54d3d5ab742349f604f29f24172d5676924043ff
refs/heads/master
2021-01-18T12:58:22.866961
2017-08-15T11:20:13
2017-08-15T11:20:13
100,370,008
0
0
null
null
null
null
UTF-8
Java
false
false
1,432
java
package utils; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import java.net.MalformedURLException; import java.net.URL; public class RemoteWebDriverFactory { public static WebDriver createInstance(String browserName) { URL hostURL = null; try { hostURL = new URL("http://127.0.0.1:6666/wd/hub"); } catch (MalformedURLException e) { e.printStackTrace(); } DesiredCapabilities capability = null; if (browserName.toLowerCase().contains("firefox")) { capability = DesiredCapabilities.firefox(); capability.setBrowserName("firefox"); } if (browserName.toLowerCase().contains("internet")) { capability = DesiredCapabilities.internetExplorer(); } if (browserName.toLowerCase().contains("chrome")) { capability = DesiredCapabilities.chrome(); capability.setBrowserName("chrome"); } WebDriver driver = new RemoteWebDriver(hostURL, capability); // Если захотите локально один браузер запустить // WebDriver driver = new FirefoxDriver(); // System.setProperty("webdriver.gecko.driver", "C:\\Windows\\geckodriver.exe"); driver.manage().window().maximize(); return driver; } }
806b551c639506dc56f2860d7d10009c38034de5
27a5c14dc83b3f90ba1262b783d6cc8b01c62dfa
/src/main/java/com/DesignPattern/prototype/prototypeSolution/Client.java
7374ed022454ab32ab3a1bfc613e63db2cd3cf6b
[]
no_license
iadoy/Design-Pattern
5171449d749e26840d02d9129382365a6aa92344
382143a617191d4ec6943316c663bbdb279c83bd
refs/heads/master
2022-12-16T00:34:15.472550
2020-09-08T08:01:34
2020-09-08T08:01:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,879
java
package com.DesignPattern.prototype.prototypeSolution; /** * 原型模式复制对象 */ public class Client { public static void main(String[] args) { //原有的羊 Sheep sheep = new Sheep("lucy", "white"); //复制羊 Sheep sheep1 = sheep.clone(); Sheep sheep2 = sheep.clone(); Sheep sheep3 = sheep.clone(); System.out.println(sheep); System.out.println(sheep1); System.out.println(sheep2); System.out.println(sheep3); //false, 说明使用clone()复制的对象和原来的对象不是同一个 //但这不能说明clone()方法就是深复制, 继续往下看 System.out.println(sheep == sheep1); sheep.setFriend(new Sheep("lilei", "yellow")); Sheep sheep4 = sheep.clone(); //false, 说明使用clone()复制的对象和原来的对象不是同一个 System.out.println(sheep == sheep4); //true, 但是如果成员是引用数据类型, 则这些成员是浅复制 System.out.println(sheep.getFriend() == sheep4.getFriend()); //使用clone()方法实现完全的深复制, 内部的引用数据类型同样需要实现Cloneable接口和重写clone方法 //当类中的引用数据类型比较多时, 写起来就比较麻烦了, 不太推荐使用 Sheep sheep5 = sheep.deepClone(); // sheep5.setFriend(sheep.getFriend().clone()); System.out.println(sheep == sheep5);//false System.out.println(sheep.getFriend() == sheep5.getFriend());//false //使用序列化和反序列化实现深复制 //不管类中的成员如何复杂, 代码都是一样的, 推荐使用 Sheep sheep6 = sheep.serializeClone(); System.out.println(sheep == sheep6);//false System.out.println(sheep.getFriend() == sheep6.getFriend());//false } }
30e7fc97ccff4c60faca9d14c33cafc6f5854256
6252c165657baa6aa605337ebc38dd44b3f694e2
/org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-1000-Files/boiler-To-Generate-1000-Files/syncregions-1000Files/TemperatureController154.java
5d282cb13029bb642daf783a9b915265e10e20a3
[]
no_license
soha500/EglSync
00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638
55101bc781349bb14fefc178bf3486e2b778aed6
refs/heads/master
2021-06-23T02:55:13.464889
2020-12-11T19:10:01
2020-12-11T19:10:01
139,832,721
0
1
null
2019-05-31T11:34:02
2018-07-05T10:20:00
Java
UTF-8
Java
false
false
368
java
package syncregions; public class TemperatureController154 { public int execute(int temperature154, int targetTemperature154) { //sync _bfpnFUbFEeqXnfGWlV2154, behaviour 1-if(temperatureDifference > 0 && boilerStatus == true) { return 1; } else if (temperatureDifference < 0 && boilerStatus == false) { return 2; } else return 0; //endSync } }
3b5faa946d0d4129ce8463bfa35c11f80ceb2270
119c27c0ea3bdf54df8824e1054a55e5faa689ea
/src/main/java/part7/quicksort/QuickSorterMedianInsert.java
3bbd7c3bc596054edd997dbb4faf437f3ad34ba1
[]
no_license
malinovskiy-alex/algorithms-java
28a6de6c21a4d94cfc165daeda30d35ab9159d89
3b8fd04a57577e7cd0f97fc5323b837cfb7b4fd4
refs/heads/master
2021-01-23T01:01:20.778649
2017-09-25T07:32:00
2017-09-25T07:32:00
85,861,528
1
0
null
null
null
null
UTF-8
Java
false
false
1,895
java
package part7.quicksort; import array.BasicIntArray; import array.Sorter; public class QuickSorterMedianInsert extends BasicIntArray implements Sorter { public QuickSorterMedianInsert(int elementsCount) { super(elementsCount); } @Override public void sort() { recSort(0, getElementsCount() - 1); } private void recSort(int left, int right) { int size = right - left + 1; if (size < 10) { insertSort(left, right); } else { int median = getMedianOf3(left, right); int centerPoint = partitionIt(left, right, median); recSort(left, centerPoint - 1); recSort(centerPoint + 1, right); } } private int getMedianOf3(int left, int right) { int center = (right + left) / 2; if (getArray()[left] > getArray()[center]) { swap(left, center); } if (getArray()[center] > getArray()[right]) { swap(center, right); } if (getArray()[left] > getArray()[center]) { swap(left, center); } swap(center, right - 1); return getArray()[right - 1]; } private int partitionIt(int left, int right, int target) { int rightCorner = right - 1; while (rightCorner > left) { while (getArray()[++left] < target) { } while (getArray()[--rightCorner] > target) { } if (left >= rightCorner) { break; } else { swap(left, rightCorner); } } swap(left, right - 1); return left; } private void insertSort(int left, int right) { for (int start = left + 1; start <= right; start++) { int currentElement = getArray()[start]; int currentIndex = start; while (currentIndex > left && currentElement < getArray()[currentIndex - 1]) { swap(currentIndex, currentIndex - 1); currentIndex--; } } } }
ef3a527e22b4e09bd017c17d6a9a9cd2ec62ca59
ab6b8b220fdb131e5d04e1f358788338884127bf
/test1127-1/src/lzp/CollectionData.java
f1e3f2c98b6719b4e3e73579b33ec61d551fb404
[]
no_license
fadinglzp/java
72a3624a7479a5ebe31a967a28b08247a3fdf603
0a67febedcc87d05e9cbe5e205528afbabbe0cf3
refs/heads/master
2020-05-23T11:32:32.761098
2019-12-16T09:05:23
2019-12-16T09:05:23
186,737,635
0
0
null
null
null
null
UTF-8
Java
false
false
325
java
package lzp; import java.util.*; public class CollectionData<T> extends ArrayList<T> { public CollectionData(Generator<T> gen, int size) { for (; size-- > 0;) add(gen.next()); } public static <T> CollectionData<T> list(Generator<T> gen,int quantity){ return new CollectionData<T>(gen,quantity); } }
[ "lzp@LZP" ]
lzp@LZP
225d4daab55ec7d8ad006bab652c454b4687b70d
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/aosp-mirror--platform_frameworks_base/0af6fa7015cd9da08bf52c1efb13641d30fd6bd7/before/VoiceInteractionSession.java
76962c5b607ae4282f9c77be5423daa4b8a3970d
[]
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
63,575
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 android.service.voice; import android.annotation.Nullable; import android.app.Dialog; import android.app.Instrumentation; import android.app.VoiceInteractor; import android.app.assist.AssistContent; import android.app.assist.AssistStructure; import android.content.ComponentCallbacks2; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Rect; import android.graphics.Region; import android.inputmethodservice.SoftInputWindow; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.os.UserHandle; import android.util.ArrayMap; import android.util.DebugUtils; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.FrameLayout; import com.android.internal.app.IVoiceInteractionManagerService; import com.android.internal.app.IVoiceInteractionSessionShowCallback; import com.android.internal.app.IVoiceInteractor; import com.android.internal.app.IVoiceInteractorCallback; import com.android.internal.app.IVoiceInteractorRequest; import com.android.internal.os.HandlerCaller; import com.android.internal.os.SomeArgs; import java.io.FileDescriptor; import java.io.PrintWriter; import java.lang.ref.WeakReference; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; /** * An active voice interaction session, providing a facility for the implementation * to interact with the user in the voice interaction layer. The user interface is * initially shown by default, and can be created be overriding {@link #onCreateContentView()} * in which the UI can be built. * * <p>A voice interaction session can be self-contained, ultimately calling {@link #finish} * when done. It can also initiate voice interactions with applications by calling * {@link #startVoiceActivity}</p>. */ public class VoiceInteractionSession implements KeyEvent.Callback, ComponentCallbacks2 { static final String TAG = "VoiceInteractionSession"; static final boolean DEBUG = false; /** * Flag received in {@link #onShow}: originator requested that the session be started with * assist data from the currently focused activity. */ public static final int SHOW_WITH_ASSIST = 1<<0; /** * Flag received in {@link #onShow}: originator requested that the session be started with * a screen shot of the currently focused activity. */ public static final int SHOW_WITH_SCREENSHOT = 1<<1; /** * Flag for use with {@link #onShow}: indicates that the session has been started from the * system assist gesture. */ public static final int SHOW_SOURCE_ASSIST_GESTURE = 1<<2; /** * Flag for use with {@link #onShow}: indicates that the application itself has invoked * the assistant. */ public static final int SHOW_SOURCE_APPLICATION = 1<<3; final Context mContext; final HandlerCaller mHandlerCaller; final KeyEvent.DispatcherState mDispatcherState = new KeyEvent.DispatcherState(); IVoiceInteractionManagerService mSystemService; IBinder mToken; int mTheme = 0; LayoutInflater mInflater; TypedArray mThemeAttrs; View mRootView; FrameLayout mContentFrame; SoftInputWindow mWindow; boolean mInitialized; boolean mWindowAdded; boolean mWindowVisible; boolean mWindowWasVisible; boolean mInShowWindow; final ArrayMap<IBinder, Request> mActiveRequests = new ArrayMap<IBinder, Request>(); final Insets mTmpInsets = new Insets(); final WeakReference<VoiceInteractionSession> mWeakRef = new WeakReference<VoiceInteractionSession>(this); final IVoiceInteractor mInteractor = new IVoiceInteractor.Stub() { @Override public IVoiceInteractorRequest startConfirmation(String callingPackage, IVoiceInteractorCallback callback, VoiceInteractor.Prompt prompt, Bundle extras) { ConfirmationRequest request = new ConfirmationRequest(callingPackage, Binder.getCallingUid(), callback, VoiceInteractionSession.this, prompt, extras); addRequest(request); mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_CONFIRMATION, request)); return request.mInterface; } @Override public IVoiceInteractorRequest startPickOption(String callingPackage, IVoiceInteractorCallback callback, VoiceInteractor.Prompt prompt, VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) { PickOptionRequest request = new PickOptionRequest(callingPackage, Binder.getCallingUid(), callback, VoiceInteractionSession.this, prompt, options, extras); addRequest(request); mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_PICK_OPTION, request)); return request.mInterface; } @Override public IVoiceInteractorRequest startCompleteVoice(String callingPackage, IVoiceInteractorCallback callback, VoiceInteractor.Prompt message, Bundle extras) { CompleteVoiceRequest request = new CompleteVoiceRequest(callingPackage, Binder.getCallingUid(), callback, VoiceInteractionSession.this, message, extras); addRequest(request); mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMPLETE_VOICE, request)); return request.mInterface; } @Override public IVoiceInteractorRequest startAbortVoice(String callingPackage, IVoiceInteractorCallback callback, VoiceInteractor.Prompt message, Bundle extras) { AbortVoiceRequest request = new AbortVoiceRequest(callingPackage, Binder.getCallingUid(), callback, VoiceInteractionSession.this, message, extras); addRequest(request); mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_ABORT_VOICE, request)); return request.mInterface; } @Override public IVoiceInteractorRequest startCommand(String callingPackage, IVoiceInteractorCallback callback, String command, Bundle extras) { CommandRequest request = new CommandRequest(callingPackage, Binder.getCallingUid(), callback, VoiceInteractionSession.this, command, extras); addRequest(request); mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMMAND, request)); return request.mInterface; } @Override public boolean[] supportsCommands(String callingPackage, String[] commands) { Message msg = mHandlerCaller.obtainMessageIOO(MSG_SUPPORTS_COMMANDS, 0, commands, null); SomeArgs args = mHandlerCaller.sendMessageAndWait(msg); if (args != null) { boolean[] res = (boolean[])args.arg1; args.recycle(); return res; } return new boolean[commands.length]; } }; final IVoiceInteractionSession mSession = new IVoiceInteractionSession.Stub() { @Override public void show(Bundle sessionArgs, int flags, IVoiceInteractionSessionShowCallback showCallback) { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIOO(MSG_SHOW, flags, sessionArgs, showCallback)); } @Override public void hide() { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_HIDE)); } @Override public void handleAssist(final Bundle data, final AssistStructure structure, final AssistContent content) { // We want to pre-warm the AssistStructure before handing it off to the main // thread. We also want to do this on a separate thread, so that if the app // is for some reason slow (due to slow filling in of async children in the // structure), we don't block other incoming IPCs (such as the screenshot) to // us (since we are a oneway interface, they get serialized). (Okay?) Thread retriever = new Thread("AssistStructure retriever") { @Override public void run() { Throwable failure = null; if (structure != null) { try { structure.ensureData(); } catch (Throwable e) { Log.w(TAG, "Failure retrieving AssistStructure", e); failure = e; } } mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageOOOO(MSG_HANDLE_ASSIST, data, failure == null ? structure : null, failure, content)); } }; retriever.start(); } @Override public void handleScreenshot(Bitmap screenshot) { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_HANDLE_SCREENSHOT, screenshot)); } @Override public void taskStarted(Intent intent, int taskId) { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIO(MSG_TASK_STARTED, taskId, intent)); } @Override public void taskFinished(Intent intent, int taskId) { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIO(MSG_TASK_FINISHED, taskId, intent)); } @Override public void closeSystemDialogs() { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_CLOSE_SYSTEM_DIALOGS)); } @Override public void onLockscreenShown() { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_ON_LOCKSCREEN_SHOWN)); } @Override public void destroy() { mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_DESTROY)); } }; /** * Base class representing a request from a voice-driver app to perform a particular * voice operation with the user. See related subclasses for the types of requests * that are possible. */ public static class Request { final IVoiceInteractorRequest mInterface = new IVoiceInteractorRequest.Stub() { @Override public void cancel() throws RemoteException { VoiceInteractionSession session = mSession.get(); if (session != null) { session.mHandlerCaller.sendMessage( session.mHandlerCaller.obtainMessageO(MSG_CANCEL, Request.this)); } } }; final String mCallingPackage; final int mCallingUid; final IVoiceInteractorCallback mCallback; final WeakReference<VoiceInteractionSession> mSession; final Bundle mExtras; Request(String packageName, int uid, IVoiceInteractorCallback callback, VoiceInteractionSession session, Bundle extras) { mCallingPackage = packageName; mCallingUid = uid; mCallback = callback; mSession = session.mWeakRef; mExtras = extras; } /** * Return the uid of the application that initiated the request. */ public int getCallingUid() { return mCallingUid; } /** * Return the package name of the application that initiated the request. */ public String getCallingPackage() { return mCallingPackage; } /** * Return any additional extra information that was supplied as part of the request. */ public Bundle getExtras() { return mExtras; } /** * Check whether this request is currently active. A request becomes inactive after * calling {@link #cancel} or a final result method that completes the request. After * this point, further interactions with the request will result in * {@link java.lang.IllegalStateException} errors; you should not catch these errors, * but can use this method if you need to determine the state of the request. Returns * true if the request is still active. */ public boolean isActive() { VoiceInteractionSession session = mSession.get(); if (session == null) { return false; } return session.isRequestActive(mInterface.asBinder()); } void finishRequest() { VoiceInteractionSession session = mSession.get(); if (session == null) { throw new IllegalStateException("VoiceInteractionSession has been destroyed"); } Request req = session.removeRequest(mInterface.asBinder()); if (req == null) { throw new IllegalStateException("Request not active: " + this); } else if (req != this) { throw new IllegalStateException("Current active request " + req + " not same as calling request " + this); } } /** * Ask the app to cancel this current request. * This also finishes the request (it is no longer active). */ public void cancel() { try { if (DEBUG) Log.d(TAG, "sendCancelResult: req=" + mInterface); finishRequest(); mCallback.deliverCancel(mInterface); } catch (RemoteException e) { } } @Override public String toString() { StringBuilder sb = new StringBuilder(128); DebugUtils.buildShortClassTag(this, sb); sb.append(" "); sb.append(mInterface.asBinder()); sb.append(" pkg="); sb.append(mCallingPackage); sb.append(" uid="); UserHandle.formatUid(sb, mCallingUid); sb.append('}'); return sb.toString(); } void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { writer.print(prefix); writer.print("mInterface="); writer.println(mInterface.asBinder()); writer.print(prefix); writer.print("mCallingPackage="); writer.print(mCallingPackage); writer.print(" mCallingUid="); UserHandle.formatUid(writer, mCallingUid); writer.println(); writer.print(prefix); writer.print("mCallback="); writer.println(mCallback.asBinder()); if (mExtras != null) { writer.print(prefix); writer.print("mExtras="); writer.println(mExtras); } } } /** * A request for confirmation from the user of an operation, as per * {@link android.app.VoiceInteractor.ConfirmationRequest * VoiceInteractor.ConfirmationRequest}. */ public static final class ConfirmationRequest extends Request { final VoiceInteractor.Prompt mPrompt; ConfirmationRequest(String packageName, int uid, IVoiceInteractorCallback callback, VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) { super(packageName, uid, callback, session, extras); mPrompt = prompt; } /** * Return the prompt informing the user of what will happen, as per * {@link android.app.VoiceInteractor.ConfirmationRequest * VoiceInteractor.ConfirmationRequest}. */ @Nullable public VoiceInteractor.Prompt getVoicePrompt() { return mPrompt; } /** * Return the prompt informing the user of what will happen, as per * {@link android.app.VoiceInteractor.ConfirmationRequest * VoiceInteractor.ConfirmationRequest}. * @deprecated Prefer {@link #getVoicePrompt()} which allows multiple voice prompts. */ @Nullable public CharSequence getPrompt() { return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null); } /** * Report that the voice interactor has confirmed the operation with the user, resulting * in a call to * {@link android.app.VoiceInteractor.ConfirmationRequest#onConfirmationResult * VoiceInteractor.ConfirmationRequest.onConfirmationResult}. * This finishes the request (it is no longer active). */ public void sendConfirmationResult(boolean confirmed, Bundle result) { try { if (DEBUG) Log.d(TAG, "sendConfirmationResult: req=" + mInterface + " confirmed=" + confirmed + " result=" + result); finishRequest(); mCallback.deliverConfirmationResult(mInterface, confirmed, result); } catch (RemoteException e) { } } void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.print(prefix); writer.print("mPrompt="); writer.println(mPrompt); } } /** * A request for the user to pick from a set of option, as per * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. */ public static final class PickOptionRequest extends Request { final VoiceInteractor.Prompt mPrompt; final VoiceInteractor.PickOptionRequest.Option[] mOptions; PickOptionRequest(String packageName, int uid, IVoiceInteractorCallback callback, VoiceInteractionSession session, VoiceInteractor.Prompt prompt, VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) { super(packageName, uid, callback, session, extras); mPrompt = prompt; mOptions = options; } /** * Return the prompt informing the user of what they are picking, as per * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. */ @Nullable public VoiceInteractor.Prompt getVoicePrompt() { return mPrompt; } /** * Return the prompt informing the user of what they are picking, as per * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. * @deprecated Prefer {@link #getVoicePrompt()} which allows multiple voice prompts. */ @Nullable public CharSequence getPrompt() { return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null); } /** * Return the set of options the user is picking from, as per * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. */ public VoiceInteractor.PickOptionRequest.Option[] getOptions() { return mOptions; } void sendPickOptionResult(boolean finished, VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) { try { if (DEBUG) Log.d(TAG, "sendPickOptionResult: req=" + mInterface + " finished=" + finished + " selections=" + selections + " result=" + result); if (finished) { finishRequest(); } mCallback.deliverPickOptionResult(mInterface, finished, selections, result); } catch (RemoteException e) { } } /** * Report an intermediate option selection from the request, without completing it (the * request is still active and the app is waiting for the final option selection), * resulting in a call to * {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult * VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished. */ public void sendIntermediatePickOptionResult( VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) { sendPickOptionResult(false, selections, result); } /** * Report the final option selection for the request, completing the request * and resulting in a call to * {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult * VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished. * This finishes the request (it is no longer active). */ public void sendPickOptionResult( VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) { sendPickOptionResult(true, selections, result); } void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.print(prefix); writer.print("mPrompt="); writer.println(mPrompt); if (mOptions != null) { writer.print(prefix); writer.println("Options:"); for (int i=0; i<mOptions.length; i++) { VoiceInteractor.PickOptionRequest.Option op = mOptions[i]; writer.print(prefix); writer.print(" #"); writer.print(i); writer.println(":"); writer.print(prefix); writer.print(" mLabel="); writer.println(op.getLabel()); writer.print(prefix); writer.print(" mIndex="); writer.println(op.getIndex()); if (op.countSynonyms() > 0) { writer.print(prefix); writer.println(" Synonyms:"); for (int j=0; j<op.countSynonyms(); j++) { writer.print(prefix); writer.print(" #"); writer.print(j); writer.print(": "); writer.println(op.getSynonymAt(j)); } } if (op.getExtras() != null) { writer.print(prefix); writer.print(" mExtras="); writer.println(op.getExtras()); } } } } } /** * A request to simply inform the user that the voice operation has completed, as per * {@link android.app.VoiceInteractor.CompleteVoiceRequest * VoiceInteractor.CompleteVoiceRequest}. */ public static final class CompleteVoiceRequest extends Request { final VoiceInteractor.Prompt mPrompt; CompleteVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback, VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) { super(packageName, uid, callback, session, extras); mPrompt = prompt; } /** * Return the message informing the user of the completion, as per * {@link android.app.VoiceInteractor.CompleteVoiceRequest * VoiceInteractor.CompleteVoiceRequest}. */ @Nullable public VoiceInteractor.Prompt getVoicePrompt() { return mPrompt; } /** * Return the message informing the user of the completion, as per * {@link android.app.VoiceInteractor.CompleteVoiceRequest * VoiceInteractor.CompleteVoiceRequest}. * @deprecated Prefer {@link #getVoicePrompt()} which allows a separate visual message. */ @Nullable public CharSequence getMessage() { return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null); } /** * Report that the voice interactor has finished completing the voice operation, resulting * in a call to * {@link android.app.VoiceInteractor.CompleteVoiceRequest#onCompleteResult * VoiceInteractor.CompleteVoiceRequest.onCompleteResult}. * This finishes the request (it is no longer active). */ public void sendCompleteResult(Bundle result) { try { if (DEBUG) Log.d(TAG, "sendCompleteVoiceResult: req=" + mInterface + " result=" + result); finishRequest(); mCallback.deliverCompleteVoiceResult(mInterface, result); } catch (RemoteException e) { } } void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.print(prefix); writer.print("mPrompt="); writer.println(mPrompt); } } /** * A request to report that the current user interaction can not be completed with voice, as per * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}. */ public static final class AbortVoiceRequest extends Request { final VoiceInteractor.Prompt mPrompt; AbortVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback, VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) { super(packageName, uid, callback, session, extras); mPrompt = prompt; } /** * Return the message informing the user of the problem, as per * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}. */ @Nullable public VoiceInteractor.Prompt getVoicePrompt() { return mPrompt; } /** * Return the message informing the user of the problem, as per * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}. * @deprecated Prefer {@link #getVoicePrompt()} which allows a separate visual message. */ @Nullable public CharSequence getMessage() { return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null); } /** * Report that the voice interactor has finished aborting the voice operation, resulting * in a call to * {@link android.app.VoiceInteractor.AbortVoiceRequest#onAbortResult * VoiceInteractor.AbortVoiceRequest.onAbortResult}. This finishes the request (it * is no longer active). */ public void sendAbortResult(Bundle result) { try { if (DEBUG) Log.d(TAG, "sendConfirmResult: req=" + mInterface + " result=" + result); finishRequest(); mCallback.deliverAbortVoiceResult(mInterface, result); } catch (RemoteException e) { } } void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.print(prefix); writer.print("mPrompt="); writer.println(mPrompt); } } /** * A generic vendor-specific request, as per * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}. */ public static final class CommandRequest extends Request { final String mCommand; CommandRequest(String packageName, int uid, IVoiceInteractorCallback callback, VoiceInteractionSession session, String command, Bundle extras) { super(packageName, uid, callback, session, extras); mCommand = command; } /** * Return the command that is being executed, as per * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}. */ public String getCommand() { return mCommand; } void sendCommandResult(boolean finished, Bundle result) { try { if (DEBUG) Log.d(TAG, "sendCommandResult: req=" + mInterface + " result=" + result); if (finished) { finishRequest(); } mCallback.deliverCommandResult(mInterface, finished, result); } catch (RemoteException e) { } } /** * Report an intermediate result of the request, without completing it (the request * is still active and the app is waiting for the final result), resulting in a call to * {@link android.app.VoiceInteractor.CommandRequest#onCommandResult * VoiceInteractor.CommandRequest.onCommandResult} with false for isCompleted. */ public void sendIntermediateResult(Bundle result) { sendCommandResult(false, result); } /** * Report the final result of the request, completing the request and resulting in a call to * {@link android.app.VoiceInteractor.CommandRequest#onCommandResult * VoiceInteractor.CommandRequest.onCommandResult} with true for isCompleted. * This finishes the request (it is no longer active). */ public void sendResult(Bundle result) { sendCommandResult(true, result); } void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); writer.print(prefix); writer.print("mCommand="); writer.println(mCommand); } } static final int MSG_START_CONFIRMATION = 1; static final int MSG_START_PICK_OPTION = 2; static final int MSG_START_COMPLETE_VOICE = 3; static final int MSG_START_ABORT_VOICE = 4; static final int MSG_START_COMMAND = 5; static final int MSG_SUPPORTS_COMMANDS = 6; static final int MSG_CANCEL = 7; static final int MSG_TASK_STARTED = 100; static final int MSG_TASK_FINISHED = 101; static final int MSG_CLOSE_SYSTEM_DIALOGS = 102; static final int MSG_DESTROY = 103; static final int MSG_HANDLE_ASSIST = 104; static final int MSG_HANDLE_SCREENSHOT = 105; static final int MSG_SHOW = 106; static final int MSG_HIDE = 107; static final int MSG_ON_LOCKSCREEN_SHOWN = 108; class MyCallbacks implements HandlerCaller.Callback, SoftInputWindow.Callback { @Override public void executeMessage(Message msg) { SomeArgs args = null; switch (msg.what) { case MSG_START_CONFIRMATION: if (DEBUG) Log.d(TAG, "onConfirm: req=" + msg.obj); onRequestConfirmation((ConfirmationRequest) msg.obj); break; case MSG_START_PICK_OPTION: if (DEBUG) Log.d(TAG, "onPickOption: req=" + msg.obj); onRequestPickOption((PickOptionRequest) msg.obj); break; case MSG_START_COMPLETE_VOICE: if (DEBUG) Log.d(TAG, "onCompleteVoice: req=" + msg.obj); onRequestCompleteVoice((CompleteVoiceRequest) msg.obj); break; case MSG_START_ABORT_VOICE: if (DEBUG) Log.d(TAG, "onAbortVoice: req=" + msg.obj); onRequestAbortVoice((AbortVoiceRequest) msg.obj); break; case MSG_START_COMMAND: if (DEBUG) Log.d(TAG, "onCommand: req=" + msg.obj); onRequestCommand((CommandRequest) msg.obj); break; case MSG_SUPPORTS_COMMANDS: args = (SomeArgs)msg.obj; if (DEBUG) Log.d(TAG, "onGetSupportedCommands: cmds=" + args.arg1); args.arg1 = onGetSupportedCommands((String[]) args.arg1); args.complete(); args = null; break; case MSG_CANCEL: if (DEBUG) Log.d(TAG, "onCancel: req=" + ((Request)msg.obj)); onCancelRequest((Request) msg.obj); break; case MSG_TASK_STARTED: if (DEBUG) Log.d(TAG, "onTaskStarted: intent=" + msg.obj + " taskId=" + msg.arg1); onTaskStarted((Intent) msg.obj, msg.arg1); break; case MSG_TASK_FINISHED: if (DEBUG) Log.d(TAG, "onTaskFinished: intent=" + msg.obj + " taskId=" + msg.arg1); onTaskFinished((Intent) msg.obj, msg.arg1); break; case MSG_CLOSE_SYSTEM_DIALOGS: if (DEBUG) Log.d(TAG, "onCloseSystemDialogs"); onCloseSystemDialogs(); break; case MSG_DESTROY: if (DEBUG) Log.d(TAG, "doDestroy"); doDestroy(); break; case MSG_HANDLE_ASSIST: args = (SomeArgs)msg.obj; if (DEBUG) Log.d(TAG, "onHandleAssist: data=" + args.arg1 + " structure=" + args.arg2 + " content=" + args.arg3); doOnHandleAssist((Bundle) args.arg1, (AssistStructure) args.arg2, (Throwable) args.arg3, (AssistContent) args.arg4); break; case MSG_HANDLE_SCREENSHOT: if (DEBUG) Log.d(TAG, "onHandleScreenshot: " + msg.obj); onHandleScreenshot((Bitmap) msg.obj); break; case MSG_SHOW: args = (SomeArgs)msg.obj; if (DEBUG) Log.d(TAG, "doShow: args=" + args.arg1 + " flags=" + msg.arg1 + " showCallback=" + args.arg2); doShow((Bundle) args.arg1, msg.arg1, (IVoiceInteractionSessionShowCallback) args.arg2); break; case MSG_HIDE: if (DEBUG) Log.d(TAG, "doHide"); doHide(); break; case MSG_ON_LOCKSCREEN_SHOWN: if (DEBUG) Log.d(TAG, "onLockscreenShown"); onLockscreenShown(); break; } if (args != null) { args.recycle(); } } @Override public void onBackPressed() { VoiceInteractionSession.this.onBackPressed(); } } final MyCallbacks mCallbacks = new MyCallbacks(); /** * Information about where interesting parts of the input method UI appear. */ public static final class Insets { /** * This is the part of the UI that is the main content. It is * used to determine the basic space needed, to resize/pan the * application behind. It is assumed that this inset does not * change very much, since any change will cause a full resize/pan * of the application behind. This value is relative to the top edge * of the input method window. */ public final Rect contentInsets = new Rect(); /** * This is the region of the UI that is touchable. It is used when * {@link #touchableInsets} is set to {@link #TOUCHABLE_INSETS_REGION}. * The region should be specified relative to the origin of the window frame. */ public final Region touchableRegion = new Region(); /** * Option for {@link #touchableInsets}: the entire window frame * can be touched. */ public static final int TOUCHABLE_INSETS_FRAME = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME; /** * Option for {@link #touchableInsets}: the area inside of * the content insets can be touched. */ public static final int TOUCHABLE_INSETS_CONTENT = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT; /** * Option for {@link #touchableInsets}: the region specified by * {@link #touchableRegion} can be touched. */ public static final int TOUCHABLE_INSETS_REGION = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION; /** * Determine which area of the window is touchable by the user. May * be one of: {@link #TOUCHABLE_INSETS_FRAME}, * {@link #TOUCHABLE_INSETS_CONTENT}, or {@link #TOUCHABLE_INSETS_REGION}. */ public int touchableInsets; } final ViewTreeObserver.OnComputeInternalInsetsListener mInsetsComputer = new ViewTreeObserver.OnComputeInternalInsetsListener() { public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo info) { onComputeInsets(mTmpInsets); info.contentInsets.set(mTmpInsets.contentInsets); info.visibleInsets.set(mTmpInsets.contentInsets); info.touchableRegion.set(mTmpInsets.touchableRegion); info.setTouchableInsets(mTmpInsets.touchableInsets); } }; public VoiceInteractionSession(Context context) { this(context, new Handler()); } public VoiceInteractionSession(Context context, Handler handler) { mContext = context; mHandlerCaller = new HandlerCaller(context, handler.getLooper(), mCallbacks, true); } public Context getContext() { return mContext; } void addRequest(Request req) { synchronized (this) { mActiveRequests.put(req.mInterface.asBinder(), req); } } boolean isRequestActive(IBinder reqInterface) { synchronized (this) { return mActiveRequests.containsKey(reqInterface); } } Request removeRequest(IBinder reqInterface) { synchronized (this) { return mActiveRequests.remove(reqInterface); } } void doCreate(IVoiceInteractionManagerService service, IBinder token) { mSystemService = service; mToken = token; onCreate(); } void doShow(Bundle args, int flags, final IVoiceInteractionSessionShowCallback showCallback) { if (DEBUG) Log.v(TAG, "Showing window: mWindowAdded=" + mWindowAdded + " mWindowVisible=" + mWindowVisible); if (mInShowWindow) { Log.w(TAG, "Re-entrance in to showWindow"); return; } try { mInShowWindow = true; if (!mWindowVisible) { if (!mWindowAdded) { mWindowAdded = true; View v = onCreateContentView(); if (v != null) { setContentView(v); } } } onShow(args, flags); if (!mWindowVisible) { mWindowVisible = true; mWindow.show(); } if (showCallback != null) { mRootView.invalidate(); mRootView.getViewTreeObserver().addOnPreDrawListener( new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mRootView.getViewTreeObserver().removeOnPreDrawListener(this); try { showCallback.onShown(); } catch (RemoteException e) { Log.w(TAG, "Error calling onShown", e); } return true; } }); } } finally { mWindowWasVisible = true; mInShowWindow = false; } } void doHide() { if (mWindowVisible) { mWindow.hide(); mWindowVisible = false; onHide(); } } void doDestroy() { onDestroy(); if (mInitialized) { mRootView.getViewTreeObserver().removeOnComputeInternalInsetsListener( mInsetsComputer); if (mWindowAdded) { mWindow.dismiss(); mWindowAdded = false; } mInitialized = false; } } void initViews() { mInitialized = true; mThemeAttrs = mContext.obtainStyledAttributes(android.R.styleable.VoiceInteractionSession); mRootView = mInflater.inflate( com.android.internal.R.layout.voice_interaction_session, null); mRootView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); mWindow.setContentView(mRootView); mRootView.getViewTreeObserver().addOnComputeInternalInsetsListener(mInsetsComputer); mContentFrame = (FrameLayout)mRootView.findViewById(android.R.id.content); } /** * Equivalent to {@link VoiceInteractionService#setDisabledShowContext * VoiceInteractionService.setDisabledShowContext(int)}. */ public void setDisabledShowContext(int flags) { try { mSystemService.setDisabledShowContext(flags); } catch (RemoteException e) { } } /** * Equivalent to {@link VoiceInteractionService#getDisabledShowContext * VoiceInteractionService.getDisabledShowContext}. */ public int getDisabledShowContext() { try { return mSystemService.getDisabledShowContext(); } catch (RemoteException e) { return 0; } } /** * Return which show context flags have been disabled by the user through the system * settings UI, so the session will never get this data. Returned flags are any combination of * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT * VoiceInteractionSession.SHOW_WITH_SCREENSHOT}. Note that this only tells you about * global user settings, not about restrictions that may be applied contextual based on * the current application the user is in or other transient states. */ public int getUserDisabledShowContext() { try { return mSystemService.getUserDisabledShowContext(); } catch (RemoteException e) { return 0; } } /** * Show the UI for this session. This asks the system to go through the process of showing * your UI, which will eventually culminate in {@link #onShow}. This is similar to calling * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}. * @param args Arbitrary arguments that will be propagated {@link #onShow}. * @param flags Indicates additional optional behavior that should be performed. May * be any combination of * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT * VoiceInteractionSession.SHOW_WITH_SCREENSHOT} * to request that the system generate and deliver assist data on the current foreground * app as part of showing the session UI. */ public void show(Bundle args, int flags) { if (mToken == null) { throw new IllegalStateException("Can't call before onCreate()"); } try { mSystemService.showSessionFromSession(mToken, args, flags); } catch (RemoteException e) { } } /** * Hide the session's UI, if currently shown. Call this when you are done with your * user interaction. */ public void hide() { if (mToken == null) { throw new IllegalStateException("Can't call before onCreate()"); } try { mSystemService.hideSessionFromSession(mToken); } catch (RemoteException e) { } } /** * You can call this to customize the theme used by your IME's window. * This must be set before {@link #onCreate}, so you * will typically call it in your constructor with the resource ID * of your custom theme. */ public void setTheme(int theme) { if (mWindow != null) { throw new IllegalStateException("Must be called before onCreate()"); } mTheme = theme; } /** * Ask that a new activity be started for voice interaction. This will create a * new dedicated task in the activity manager for this voice interaction session; * this means that {@link Intent#FLAG_ACTIVITY_NEW_TASK Intent.FLAG_ACTIVITY_NEW_TASK} * will be set for you to make it a new task. * * <p>The newly started activity will be displayed to the user in a special way, as * a layer under the voice interaction UI.</p> * * <p>As the voice activity runs, it can retrieve a {@link android.app.VoiceInteractor} * through which it can perform voice interactions through your session. These requests * for voice interactions will appear as callbacks on {@link #onGetSupportedCommands}, * {@link #onRequestConfirmation}, {@link #onRequestPickOption}, * {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice}, * or {@link #onRequestCommand} * * <p>You will receive a call to {@link #onTaskStarted} when the task starts up * and {@link #onTaskFinished} when the last activity has finished. * * @param intent The Intent to start this voice interaction. The given Intent will * always have {@link Intent#CATEGORY_VOICE Intent.CATEGORY_VOICE} added to it, since * this is part of a voice interaction. */ public void startVoiceActivity(Intent intent) { if (mToken == null) { throw new IllegalStateException("Can't call before onCreate()"); } try { intent.migrateExtraStreamToClipData(); intent.prepareToLeaveProcess(); int res = mSystemService.startVoiceActivity(mToken, intent, intent.resolveType(mContext.getContentResolver())); Instrumentation.checkStartActivityResult(res, intent); } catch (RemoteException e) { } } /** * Set whether this session will keep the device awake while it is running a voice * activity. By default, the system holds a wake lock for it while in this state, * so that it can work even if the screen is off. Setting this to false removes that * wake lock, allowing the CPU to go to sleep. This is typically used if the * session decides it has been waiting too long for a response from the user and * doesn't want to let this continue to drain the battery. * * <p>Passing false here will release the wake lock, and you can call later with * true to re-acquire it. It will also be automatically re-acquired for you each * time you start a new voice activity task -- that is when you call * {@link #startVoiceActivity}.</p> */ public void setKeepAwake(boolean keepAwake) { if (mToken == null) { throw new IllegalStateException("Can't call before onCreate()"); } try { mSystemService.setKeepAwake(mToken, keepAwake); } catch (RemoteException e) { } } /** * Request that all system dialogs (and status bar shade etc) be closed, allowing * access to the session's UI. This will <em>not</em> cause the lock screen to be * dismissed. */ public void closeSystemDialogs() { if (mToken == null) { throw new IllegalStateException("Can't call before onCreate()"); } try { mSystemService.closeSystemDialogs(mToken); } catch (RemoteException e) { } } /** * Convenience for inflating views. */ public LayoutInflater getLayoutInflater() { return mInflater; } /** * Retrieve the window being used to show the session's UI. */ public Dialog getWindow() { return mWindow; } /** * Finish the session. This completely destroys the session -- the next time it is shown, * an entirely new one will be created. You do not normally call this function; instead, * use {@link #hide} and allow the system to destroy your session if it needs its RAM. */ public void finish() { if (mToken == null) { throw new IllegalStateException("Can't call before onCreate()"); } try { mSystemService.finish(mToken); } catch (RemoteException e) { } } /** * Initiatize a new session. At this point you don't know exactly what this * session will be used for; you will find that out in {@link #onShow}. */ public void onCreate() { doOnCreate(); } private void doOnCreate() { mTheme = mTheme != 0 ? mTheme : com.android.internal.R.style.Theme_DeviceDefault_VoiceInteractionSession; mInflater = (LayoutInflater)mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mWindow = new SoftInputWindow(mContext, "VoiceInteractionSession", mTheme, mCallbacks, this, mDispatcherState, WindowManager.LayoutParams.TYPE_VOICE_INTERACTION, Gravity.BOTTOM, true); mWindow.getWindow().addFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); initViews(); mWindow.getWindow().setLayout(MATCH_PARENT, MATCH_PARENT); mWindow.setToken(mToken); } /** * Called when the session UI is going to be shown. This is called after * {@link #onCreateContentView} (if the session's content UI needed to be created) and * immediately prior to the window being shown. This may be called while the window * is already shown, if a show request has come in while it is shown, to allow you to * update the UI to match the new show arguments. * * @param args The arguments that were supplied to * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}. * @param showFlags The show flags originally provided to * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}. */ public void onShow(Bundle args, int showFlags) { } /** * Called immediately after stopping to show the session UI. */ public void onHide() { } /** * Last callback to the session as it is being finished. */ public void onDestroy() { } /** * Hook in which to create the session's UI. */ public View onCreateContentView() { return null; } public void setContentView(View view) { mContentFrame.removeAllViews(); mContentFrame.addView(view, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mContentFrame.requestApplyInsets(); } void doOnHandleAssist(Bundle data, AssistStructure structure, Throwable failure, AssistContent content) { if (failure != null) { onAssistStructureFailure(failure); } onHandleAssist(data, structure, content); } /** * Called when there has been a failure transferring the {@link AssistStructure} to * the assistant. This may happen, for example, if the data is too large and results * in an out of memory exception, or the client has provided corrupt data. This will * be called immediately before {@link #onHandleAssist} and the AssistStructure supplied * there afterwards will be null. * * @param failure The failure exception that was thrown when building the * {@link AssistStructure}. */ public void onAssistStructureFailure(Throwable failure) { } /** * Called to receive data from the application that the user was currently viewing when * an assist session is started. If the original show request did not specify * {@link #SHOW_WITH_ASSIST}, this method will not be called. * * @param data Arbitrary data supplied by the app through * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. * May be null if assist data has been disabled by the user or device policy. * @param structure If available, the structure definition of all windows currently * displayed by the app. May be null if assist data has been disabled by the user * or device policy; will be an empty stub if the application has disabled assist * by marking its window as secure. * @param content Additional content data supplied by the app through * {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}. * May be null if assist data has been disabled by the user or device policy; will * not be automatically filled in with data from the app if the app has marked its * window as secure. */ public void onHandleAssist(@Nullable Bundle data, @Nullable AssistStructure structure, @Nullable AssistContent content) { } /** * Called to receive a screenshot of what the user was currently viewing when an assist * session is started. May be null if screenshots are disabled by the user, policy, * or application. If the original show request did not specify * {@link #SHOW_WITH_SCREENSHOT}, this method will not be called. */ public void onHandleScreenshot(@Nullable Bitmap screenshot) { } public boolean onKeyDown(int keyCode, KeyEvent event) { return false; } public boolean onKeyLongPress(int keyCode, KeyEvent event) { return false; } public boolean onKeyUp(int keyCode, KeyEvent event) { return false; } public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) { return false; } /** * Called when the user presses the back button while focus is in the session UI. Note * that this will only happen if the session UI has requested input focus in its window; * otherwise, the back key will go to whatever window has focus and do whatever behavior * it normally has there. The default implementation simply calls {@link #hide}. */ public void onBackPressed() { hide(); } /** * Sessions automatically watch for requests that all system UI be closed (such as when * the user presses HOME), which will appear here. The default implementation always * calls {@link #hide}. */ public void onCloseSystemDialogs() { hide(); } /** * Called when the lockscreen was shown. */ public void onLockscreenShown() { hide(); } @Override public void onConfigurationChanged(Configuration newConfig) { } @Override public void onLowMemory() { } @Override public void onTrimMemory(int level) { } /** * Compute the interesting insets into your UI. The default implementation * sets {@link Insets#contentInsets outInsets.contentInsets.top} to the height * of the window, meaning it should not adjust content underneath. The default touchable * insets are {@link Insets#TOUCHABLE_INSETS_FRAME}, meaning it consumes all touch * events within its window frame. * * @param outInsets Fill in with the current UI insets. */ public void onComputeInsets(Insets outInsets) { outInsets.contentInsets.left = 0; outInsets.contentInsets.bottom = 0; outInsets.contentInsets.right = 0; View decor = getWindow().getWindow().getDecorView(); outInsets.contentInsets.top = decor.getHeight(); outInsets.touchableInsets = Insets.TOUCHABLE_INSETS_FRAME; outInsets.touchableRegion.setEmpty(); } /** * Called when a task initiated by {@link #startVoiceActivity(android.content.Intent)} * has actually started. * * @param intent The original {@link Intent} supplied to * {@link #startVoiceActivity(android.content.Intent)}. * @param taskId Unique ID of the now running task. */ public void onTaskStarted(Intent intent, int taskId) { } /** * Called when the last activity of a task initiated by * {@link #startVoiceActivity(android.content.Intent)} has finished. The default * implementation calls {@link #finish()} on the assumption that this represents * the completion of a voice action. You can override the implementation if you would * like a different behavior. * * @param intent The original {@link Intent} supplied to * {@link #startVoiceActivity(android.content.Intent)}. * @param taskId Unique ID of the finished task. */ public void onTaskFinished(Intent intent, int taskId) { hide(); } /** * Request to query for what extended commands the session supports. * * @param commands An array of commands that are being queried. * @return Return an array of booleans indicating which of each entry in the * command array is supported. A true entry in the array indicates the command * is supported; false indicates it is not. The default implementation returns * an array of all false entries. */ public boolean[] onGetSupportedCommands(String[] commands) { return new boolean[commands.length]; } /** * Request to confirm with the user before proceeding with an unrecoverable operation, * corresponding to a {@link android.app.VoiceInteractor.ConfirmationRequest * VoiceInteractor.ConfirmationRequest}. * * @param request The active request. */ public void onRequestConfirmation(ConfirmationRequest request) { } /** * Request for the user to pick one of N options, corresponding to a * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. * * @param request The active request. */ public void onRequestPickOption(PickOptionRequest request) { } /** * Request to complete the voice interaction session because the voice activity successfully * completed its interaction using voice. Corresponds to * {@link android.app.VoiceInteractor.CompleteVoiceRequest * VoiceInteractor.CompleteVoiceRequest}. The default implementation just sends an empty * confirmation back to allow the activity to exit. * * @param request The active request. */ public void onRequestCompleteVoice(CompleteVoiceRequest request) { } /** * Request to abort the voice interaction session because the voice activity can not * complete its interaction using voice. Corresponds to * {@link android.app.VoiceInteractor.AbortVoiceRequest * VoiceInteractor.AbortVoiceRequest}. The default implementation just sends an empty * confirmation back to allow the activity to exit. * * @param request The active request. */ public void onRequestAbortVoice(AbortVoiceRequest request) { } /** * Process an arbitrary extended command from the caller, * corresponding to a {@link android.app.VoiceInteractor.CommandRequest * VoiceInteractor.CommandRequest}. * * @param request The active request. */ public void onRequestCommand(CommandRequest request) { } /** * Called when the {@link android.app.VoiceInteractor} has asked to cancel a {@link Request} * that was previously delivered to {@link #onRequestConfirmation}, * {@link #onRequestPickOption}, {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice}, * or {@link #onRequestCommand}. * * @param request The request that is being canceled. */ public void onCancelRequest(Request request) { } /** * Print the Service's state into the given stream. This gets invoked by * {@link VoiceInteractionSessionService} when its Service * {@link android.app.Service#dump} method is called. * * @param prefix Text to print at the front of each line. * @param fd The raw file descriptor that the dump is being sent to. * @param writer The PrintWriter to which you should dump your state. This will be * closed for you after you return. * @param args additional arguments to the dump request. */ public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { writer.print(prefix); writer.print("mToken="); writer.println(mToken); writer.print(prefix); writer.print("mTheme=#"); writer.println(Integer.toHexString(mTheme)); writer.print(prefix); writer.print("mInitialized="); writer.println(mInitialized); writer.print(prefix); writer.print("mWindowAdded="); writer.print(mWindowAdded); writer.print(" mWindowVisible="); writer.println(mWindowVisible); writer.print(prefix); writer.print("mWindowWasVisible="); writer.print(mWindowWasVisible); writer.print(" mInShowWindow="); writer.println(mInShowWindow); if (mActiveRequests.size() > 0) { writer.print(prefix); writer.println("Active requests:"); String innerPrefix = prefix + " "; for (int i=0; i<mActiveRequests.size(); i++) { Request req = mActiveRequests.valueAt(i); writer.print(prefix); writer.print(" #"); writer.print(i); writer.print(": "); writer.println(req); req.dump(innerPrefix, fd, writer, args); } } } }
283843ffe06a94ec271be74b4dcb0395ec96b2a1
fcb39b4d2da453825ea8c1bf091e76103f003752
/Splash_Screen.java
04d7f7f1abf62ea479485cf896879b8754d83ba7
[]
no_license
krunal9797-sk/android-login-register-with-firebase
a23d02e2da3a6742f3492a1d2dea7ef43a19de2f
651da44f7a25b764b45e18d5772b603c40a06672
refs/heads/main
2023-01-01T17:05:20.652228
2020-10-25T15:09:32
2020-10-25T15:09:32
307,076,576
0
0
null
2020-10-25T15:09:34
2020-10-25T10:44:47
Java
UTF-8
Java
false
false
890
java
package clg.brijesh.mohit.coffee_desk; import android.content.Intent; import android.os.Bundle; import android.app.Activity; public class Splash_Screen extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); Thread startTimer = new Thread() { public void run() { try { sleep(1000); Intent intent0 = new Intent(Splash_Screen.this, MainActivity.class); startActivity(intent0); overridePendingTransition(R.anim.fadin, R.anim.fadout); finish(); } catch (InterruptedException e) { e.printStackTrace(); } } }; startTimer.start(); } }
b5ade7213008a1de5f26cc1becd4e4c8360b1afb
6cd8d2cf5e9547449a0bb4b5064e6b5e48bbfd05
/core/ui/src/main/java/org/netbeans/cubeon/ui/taskelemet/MoveToDefault.java
54f8ff55195240a2c535f5ec744180236a281121
[ "Apache-2.0" ]
permissive
theanuradha/cubeon
3a8ca9348f1e8733bfa4e46b2f7559cb613815fd
d55ea42a3cd6eb59884dd0b6f9620629395ee63d
refs/heads/master
2020-12-31T00:17:44.572464
2015-11-10T03:34:34
2015-11-10T03:34:34
45,884,253
0
0
null
null
null
null
UTF-8
Java
false
false
2,888
java
/* * Copyright 2008 Anuradha. * * 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. * under the License. */ package org.netbeans.cubeon.ui.taskelemet; import java.util.HashSet; import java.util.Set; import org.netbeans.cubeon.tasks.core.api.TaskFolder; import org.netbeans.cubeon.tasks.core.api.TaskFolderRefreshable; import org.netbeans.cubeon.tasks.core.api.TasksFileSystem; import org.netbeans.cubeon.tasks.spi.task.TaskElement; import org.openide.nodes.Node; import org.openide.util.HelpCtx; import org.openide.util.Lookup; import org.openide.util.actions.NodeAction; /** * * @author Anuradha G */ public class MoveToDefault extends NodeAction { private MoveToDefault() { putValue(NAME, "Remove Task"); } @Override protected void performAction(Node[] activatedNodes) { Set<TaskFolder> refreshFolders = new HashSet<TaskFolder>(activatedNodes.length); for (Node node : activatedNodes) { TaskElement element = node.getLookup().lookup(TaskElement.class); TaskFolder container = node.getLookup().lookup(TaskFolder.class); if (element != null && container != null) { TasksFileSystem fileSystem = Lookup.getDefault().lookup(TasksFileSystem.class); fileSystem.removeTaskElement(container, element); refreshFolders.add(container); } } for (TaskFolder container : refreshFolders) { TaskFolderRefreshable oldTfr = container.getLookup().lookup(TaskFolderRefreshable.class); if (oldTfr != null) { oldTfr.refreshNode(); } } } @Override protected boolean enable(Node[] activatedNodes) { for (Node node : activatedNodes) { if (node.getLookup().lookup(TaskElement.class) == null || node.getLookup().lookup(TaskFolder.class) == null) { return false; } } return true; } @Override public String getName() { return (String) getValue(NAME); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(MoveToDefault.class); } @Override protected boolean asynchronous() { return false; } }
5646cf23587f347c2f56112c9e1c93a8d4e7089e
6e5a270f4abade7c8f297a84cbfba8d6c8d197c7
/matrixMultiplication.java
e66709bc6405ba795e877433261e23ed12a7bad5
[]
no_license
Helloworldhehe/matrixAddition
f55e7f14eb4a4bf9afec6bddcbb3f66e8e934be7
a00cca38928feb528b3c804f6953f3b2b1a01e46
refs/heads/master
2020-04-03T09:56:26.166030
2016-08-11T01:45:33
2016-08-11T01:45:33
65,365,640
0
0
null
null
null
null
UTF-8
Java
false
false
1,133
java
//Created by Robert Throne //Algorithm to compute multiplication of 2 matrices import java.util.*; public class matrixMultiplication{ public static void main(String[] args){ //Input from user int row1 = new Scanner(System.in).nextInt(); int row2 = new Scanner(System.in).nextInt(); int col1 = new Scanner(System.in).nextInt(); int col2 = new Scanner(System.in).nextInt(); Scanner input = new Scanner(System.in); int i,j,k,sum; //Initialize the array int a[][] = new int[row1][col1]; int b[][] = new int[row2][col2]; int c[][] = new int[row1][col2]; if(col1 != row2) throw new IllegalArgumentException("They must be equal"); //Matrix A for(i = 0; i < row1; i++){ for(j = 0; j < col1; j++){ a[i][j] = input.nextInt(); } } //Matrix B for(i = 0; i < row2; i++){ for(j = 0; j < col2; j++){ b[i][j] = input.nextInt(); } } //Algorithm to multiply 2 matrices for(i = 0; i < row1; i++){ for(j = 0; j < col2; j++){ sum = 0; for(k = 0; k < row2; k++){ sum = sum + (a[i][k] * b[k][j]); } c[i][j] = sum; System.out.println(c[i][j]); } } } }
a9fb64c3242a63d03ed8f152a35b604c2836fbe0
e01767aab13e4a5239d39dc2837b4c5ad574870d
/user/src/main/java/com/tdzx/user/utils/ResultStatus.java
c00d37fb8d96039637116185871f4f6dd77febdd
[]
no_license
boom888/xinhualeyu-tdzx-user
6166ec66f008bf0fad75b2e74c15e33dc6dde25f
bb288afa0cc6f8352f4e0dd1cb3f66e9b4cf3e54
refs/heads/master
2022-11-11T17:23:56.370884
2019-12-02T04:59:50
2019-12-02T04:59:50
225,287,089
0
0
null
2022-10-12T20:34:33
2019-12-02T04:43:24
Java
UTF-8
Java
false
false
910
java
package com.tdzx.user.utils; /** * Author:Joker * Date:2018/7/19 * Description: */ public enum ResultStatus implements BaseEnum { /** * 成功 */ SUCCESS(200, "成功"), /** * 注册失败 */ REGFAILD(300, "注册失败"), /** * 错误 */ ERROR(500, "错误"), /** * 异常 */ EXCEPTION(400, "异常"), /** * 权限校验失败 */ INVALIDSESSION(403, "无权限"), /** * 权限校验失败 */ NOTFOUND(404, "Not Found"); /*NOMORETODAY=;*/ private ResultStatus(int value, String description) { this.value = value; this.description = description; } private int value; private String description; @Override public int getValue() { return value; } @Override public String getDescription() { return description; } }
bcfcacf0ec8f91662520a61967991f7f46e043a5
f5a023db0eff197215b7a93795025bd463d95f3b
/src/main/java/com/edfer/repository/logistica/AjudanteRepository.java
2e1dc57d1b1e3d34672c9a6d05facbb42408a5f3
[]
no_license
sauloddiniz/edfer_api
25a8955960ce31aac8fdc99fecd40edc5b52d79d
e8ffb4a65aa8150d83b2212c0721bc30b1065410
refs/heads/master
2023-02-09T08:56:53.819303
2020-12-31T18:17:20
2020-12-31T18:17:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
352
java
package com.edfer.repository.logistica; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.edfer.model.logistica.Ajudante; @Repository public interface AjudanteRepository extends JpaRepository<Ajudante, Long>{ List<Ajudante> findAllByIsAtivoTrue(); }
fb245c64afa79e4de7e8d827b8e2b96e510d1054
af49433ef9e00dfb2b36b19460264579dacd067f
/src/main/java/no/capraconsulting/endpoints/TimeslotEndpoint.java
a5dfe182e67d30116d76e79cc6ccc4c5fcc42be4
[ "Apache-2.0" ]
permissive
capraconsulting/redcross-digital-leksehjelp-backend
a0509abefea37d903cf465e17a554bb903bfdab9
e33712768190b77f15cf2f316fddd2362f4540ed
refs/heads/master
2020-07-25T08:22:20.937069
2020-05-30T20:02:07
2020-05-30T20:02:07
208,228,913
0
0
Apache-2.0
2020-04-29T08:59:16
2019-09-13T08:54:52
Java
UTF-8
Java
false
false
2,410
java
package no.capraconsulting.endpoints; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import no.capraconsulting.db.Database; import no.capraconsulting.utils.EndpointUtils; import no.capraconsulting.auth.JwtFilter; import javax.sql.RowSet; import java.sql.SQLException; import org.json.JSONArray; import org.json.JSONObject; import static no.capraconsulting.endpoints.TimeslotEndpoint.TIMESLOT_PATH; @Path(TIMESLOT_PATH) public final class TimeslotEndpoint { private static Logger LOG = LoggerFactory.getLogger(TimeslotEndpoint.class); public static final String TIMESLOT_PATH = "/timeslots"; @GET @Path("/subject/{subjectID}") @Produces({MediaType.APPLICATION_JSON}) public Response getTimeslots(@PathParam("subjectID")int subjectID) { String query = "" + "SELECT day, from_time, to_time FROM TIMESLOTS " + "WHERE subject_id = ?"; try { RowSet result = Database.INSTANCE.selectQuery(query, subjectID); JSONArray payload = EndpointUtils.buildPayload(result); return Response.ok(payload.toString()).build(); } catch (SQLException e) { LOG.error(e.getMessage()); return Response.status(422).build(); } } @POST @Path("/subject/{subjectID}") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) @JwtFilter public Response postTimeslots(String payload, @PathParam("subjectID")int subjectID){ JSONObject data = new JSONObject(payload); String query = "INSERT INTO " + "TIMESLOTS (day, from_time, to_time, subject_id) " + "VALUES (?,?,?,?)"; try { Database.INSTANCE.manipulateQuery( query, false, data.getInt("day"), data.getString("from_time"), data.getString("to_time"), subjectID ); return Response.status(200).build(); } catch (SQLException e) { LOG.error(e.getMessage()); return Response.status(422).build(); } } }
ba9da2ee7cc5f2001bac035723bcd72fd92b9f34
9343ec1738f22cfae799e8f8bb5af6d482426c0e
/app/src/main/java/com/example/tm18app/viewModels/OtherUserProfileViewModel.java
d11b0243c7cdb91d739a8d9c467d4d4e63f5f7a1
[]
no_license
sebampuero/android
858114e031c8ad92e8d37e11c5b1594b0d8a03c7
cd5421d61680ca3b63ff78c33df80384736dfbea
refs/heads/master
2020-09-16T22:16:50.520961
2020-02-01T13:10:33
2020-02-01T13:10:33
223,902,095
0
0
null
null
null
null
UTF-8
Java
false
false
893
java
package com.example.tm18app.viewModels; import androidx.lifecycle.LiveData; import com.example.tm18app.constants.Constant; import com.example.tm18app.model.User; import com.example.tm18app.repository.UserRepository; /** * {@link androidx.lifecycle.ViewModel} class for other user's profile UI * * @author Sebastian Ampuero * @version 1.0 * @since 03.12.2019 */ public class OtherUserProfileViewModel extends ProfileViewModel { private LiveData<User> mUserLiveData; public LiveData<User> getUserLiveData() { return mUserLiveData; } /** * Calls the repository to fetch the user's details * @param userId {@link String} */ public void callRepositoryForUser(String userId) { UserRepository repository = new UserRepository(); this.mUserLiveData = repository.getUser(userId, mPrefs.getString(Constant.PUSHY_TOKEN, "")); } }
480589185b9c94f00a26a0ed6c5ea4b45fe2c286
f6c08d25310e07cb163497123b00168773daf228
/direct/io-hbase-bindings/src/main/java/cz/o2/proxima/direct/io/hbase/InternalSerializers.java
be85ef9714f40874408b9fdd7a79c087cbc0882c
[ "Apache-2.0" ]
permissive
O2-Czech-Republic/proxima-platform
91b136865cc5aabd157d08d02045893d8e2e6a87
2d5edad54a200d1d77b9f74e02d1d973ccc51608
refs/heads/master
2023-08-19T00:13:47.760910
2023-08-16T13:53:03
2023-08-16T13:53:03
108,869,877
20
7
Apache-2.0
2023-08-01T14:19:51
2017-10-30T15:26:01
Java
UTF-8
Java
false
false
2,136
java
/* * Copyright 2017-2023 O2 Czech Republic, a.s. * * 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 cz.o2.proxima.direct.io.hbase; import cz.o2.proxima.core.repository.AttributeDescriptor; import cz.o2.proxima.core.repository.EntityDescriptor; import cz.o2.proxima.core.storage.StreamElement; import cz.o2.proxima.direct.core.randomaccess.KeyValue; import cz.o2.proxima.direct.core.randomaccess.RawOffset; import java.nio.charset.StandardCharsets; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.client.Put; class InternalSerializers { static Put toPut(byte[] family, byte[] keyAsBytes, StreamElement element, byte[] rawValue) { String column = element.getAttribute(); Put put = new Put(keyAsBytes, element.getStamp()); put.addColumn(family, column.getBytes(StandardCharsets.UTF_8), element.getStamp(), rawValue); return put; } static <V> KeyValue<V> toKeyValue( EntityDescriptor entity, AttributeDescriptor<V> attrDesc, Cell cell, long seqId, byte[] rawValue) { String key = new String(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()); String attribute = new String(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()); if (seqId > 0) { return KeyValue.of( entity, attrDesc, seqId, key, attribute, new RawOffset(attribute), rawValue, cell.getTimestamp()); } return KeyValue.of( entity, attrDesc, key, attribute, new RawOffset(attribute), rawValue, cell.getTimestamp()); } }
a7b0b9cf58a852248e287c192ff9772a9931e099
c38b4a165e9d2d2099a4e0be252316f75ddfe242
/src/main/java/com/bootcamp/TP/entities/IndicateurPerformance.java
8704a42182919f624a487949bfdd87d51b842d8d
[]
no_license
kikigith/gestionProjetRest
247a77294a5c43e86f97c1049b323f6d750d52ce
06e8d73e6d1ea7ece50049fc5968ee2e3f259305
refs/heads/master
2021-07-20T05:56:46.714698
2017-10-28T14:05:20
2017-10-28T14:05:20
107,785,023
0
0
null
null
null
null
UTF-8
Java
false
false
1,563
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.bootcamp.TP.entities; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * * @author ARESKO */ @Entity @Table(name = "tp_indicateurperformance") public class IndicateurPerformance implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(nullable = false, length = 45) private String libelle; @Column(nullable = false, length = 45) private String nature; @Column(nullable = false, length = 45) private String valeur; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLibelle() { return libelle; } public void setLibelle(String libelle) { this.libelle = libelle; } public String getNature() { return nature; } public void setNature(String nature) { this.nature = nature; } public String getValeur() { return valeur; } public void setValeur(String valeur) { this.valeur = valeur; } }
7bcdba09c70e05c3ed42f2b2a5f73ab8444c8f94
7545a5c84d1edeb90dc636cfcb36e391794bf3ee
/src/test/java/com/revature/services/userFeatures/ProductSelectRunner.java
ffb00d2e3ff9e49e423b5a8e4ef0c72786cc23bc
[]
no_license
210712-Richard/team3.p2
c4b743c5f295190827e7dd7350e6cd5a44083dfb
6dd1ae64d4f33c5e4efdc406bca94ce7a16526ff
refs/heads/main
2023-07-24T02:59:33.862458
2021-09-07T01:43:54
2021-09-07T01:43:54
396,980,264
1
0
null
2021-08-30T00:09:31
2021-08-16T21:32:28
Java
UTF-8
Java
false
false
231
java
package com.revature.services.userFeatures; import com.intuit.karate.junit5.Karate; public class ProductSelectRunner { @Karate.Test Karate testProductSelect() { return Karate.run("ProductSelect").relativeTo(getClass()); } }
db145404113bd1cf2958b4cd62c4f7b5bb933bbf
f136701aa16b2cb33f226ea259c2b807c2dea99c
/src/arrays/reverseArray.java
f6f94f9661188c900904a2b8ac68d7931818fe7c
[ "MIT" ]
permissive
everythingProgrammer/Algorithms
4364de3f0c4bc61290e793bc58a44f9a31a1a2b9
1da043f8b194d487b365f3e247fea02e1e370540
refs/heads/main
2023-04-19T15:15:22.341166
2021-05-01T11:58:19
2021-05-01T11:58:19
315,209,392
0
0
null
null
null
null
UTF-8
Java
false
false
233
java
package arrays; /* https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/ */ public class reverseArray { /*Iterative way and recursive way * initialize loop from 0 to n-1 and keep reversing * */ }
a01f8f14dfba124e32378932c6e26a638bbe7070
604ed3d26c3a501383dc0d3a6cd0db756c7cff7e
/mall-coupon/src/main/java/com/cloud/mall/coupon/service/impl/HomeAdvServiceImpl.java
f027dd96f3575b7d0cc677ceee2d8cf360253889
[ "Apache-2.0" ]
permissive
zhengwilken/mall2021
626ad333ed8697aad5dedbec1d90a7c72d40cf20
210f10c90827348000b586389be56ee11a1dbe9d
refs/heads/main
2023-04-03T15:30:23.888106
2021-04-04T14:25:11
2021-04-04T14:25:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
956
java
package com.cloud.mall.coupon.service.impl; import org.springframework.stereotype.Service; import java.util.Map; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cloud.common.utils.PageUtils; import com.cloud.common.utils.Query; import com.cloud.mall.coupon.dao.HomeAdvDao; import com.cloud.mall.coupon.entity.HomeAdvEntity; import com.cloud.mall.coupon.service.HomeAdvService; @Service("homeAdvService") public class HomeAdvServiceImpl extends ServiceImpl<HomeAdvDao, HomeAdvEntity> implements HomeAdvService { @Override public PageUtils queryPage(Map<String, Object> params) { IPage<HomeAdvEntity> page = this.page( new Query<HomeAdvEntity>().getPage(params), new QueryWrapper<HomeAdvEntity>() ); return new PageUtils(page); } }
21644e070cc6f6ff8d70e06a63cbeada298976c0
ad76bcd04abab79c821c245b4433a3bb2debb6f7
/Cong2so/src/MyBigMain.java
5bb781a1e882da68baf0d9f4dde2cbc3ea243b0c
[]
no_license
hoangvietanh51600003/Project
55a753b3d001d32686c473519a1e4b433100b72c
a8287beaf6bf9973e13280ceaf1126616b22837e
refs/heads/master
2020-04-01T07:35:56.808192
2019-01-03T17:04:38
2019-01-03T17:04:38
152,995,640
0
0
null
null
null
null
UTF-8
Java
false
false
856
java
import java.util.Scanner; public class MyBigMain implements IReceiver { public static void main(String[] args) { String dodai1 = ""; String dodai2 = ""; Scanner sc = new Scanner(System.in); MyBigMain main = new MyBigMain(); MyBigNumber num = new MyBigNumber(main); try { if (args.length > 0) { dodai1 = args[0]; dodai2 = args[1]; } else { dodai1 = "0"; dodai2 = "0"; } System.out.println("Ta duoc ket qua : " + num.sum(dodai1, dodai2) + "\n"); } catch (Exception e) { System.out.println(e.getMessage()); } sc.close(); } public void sendStep(String step) { System.out.println(step); } }
d2259905a4238806c6b6a4c1f5e5fdc51e811a11
a472f2bbc57cfa8c07775434e950e3560707d924
/projeto/src/servers/FileServerClientSocket.java
e17cca95af1aa35ded27b92f9cb297bf4fdee449
[]
no_license
luizmoitinho/sistema-distribuido-arquivos
b13c66a194b665043d5dc6a82ae99f47b8ed26ca
4201d394b9a2fadcb76b051e70207f737a9b7c56
refs/heads/master
2023-07-02T02:49:16.864435
2021-07-17T03:23:36
2021-07-17T03:23:36
386,824,537
1
2
null
null
null
null
UTF-8
Java
false
false
1,674
java
package servers; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.nio.file.Path; import java.nio.file.Paths; public class FileServerClientSocket extends Thread { private Socket s; private int folder; public FileServerClientSocket(Socket s) { this.s = s; } @Override public void run() { try { BufferedReader clientBuffer = new BufferedReader(new InputStreamReader(s.getInputStream())); String path = clientBuffer.readLine(); System.out.println(path); Path currentRelativePath = Paths.get(""); String url = currentRelativePath.toAbsolutePath().toString() + path; //File file = new File(url); //FileInputStream fileInputStream = new FileInputStream(file); FileInputStream fileIn = new FileInputStream(url); OutputStream socketOut = s.getOutputStream(); // Criando tamanho de leitura byte[] cbuffer = new byte[1024]; int bytesRead; // Lendo arquivo criado e enviado para o canal de transferencia while ((bytesRead = fileIn.read(cbuffer)) != -1) { socketOut.write(cbuffer, 0, bytesRead); socketOut.flush(); } fileIn.close(); s.close(); } catch (IOException ex) { System.out.println(ex); System.out.println("Erro"); } } }
e2921b46b7cef0539208d8b54ec779f2a560f37f
83d6b92f2309c5f99ca17d1806e476bc5d8e8625
/src/main/java/org/demo/guicedemo/server/controller/SpringAwareServletModule.java
e16d8255f1f6f6c73f0dd846168994a8f07c7514
[]
no_license
LeoFaye/guicedemo-spring
3ea45e91918c8d2d770c7e0644baa91aa00945dc
e687ec6699817917bef797a47281d162a3ee4d72
refs/heads/master
2020-05-30T16:02:48.009317
2019-06-25T14:53:26
2019-06-25T14:53:26
189,834,032
0
0
null
null
null
null
UTF-8
Java
false
false
654
java
package org.demo.guicedemo.server.controller; import org.demo.guicedemo.server.persistence.SampleDao; import org.springframework.context.ApplicationContext; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.servlet.ServletModule; public class SpringAwareServletModule extends AbstractModule { private final ApplicationContext context; public SpringAwareServletModule(ApplicationContext context) { this.context = context; } @Override protected void configure() { install(new ServletModule()); } @Provides SampleDao getSampleDao() { return context.getBean(SampleDao.class); } }
f5b7c4cb4ec8fb074d5a165998fa9e541945d524
63ada9cff94f06a3131972a3f4f360d9fca95d7b
/BDD/src/test/java/com/epam/szte/bdd/runner/CucumberRunnerTest.java
6a7e1fe26a952eeaec2b8267162e851b57ab79f1
[]
no_license
Norbi1986/szte_university_bdd
42955b9122e7b5bbe32818e647e2052f9acf250e
0ff2552846dc68df47fb040fe0536300dcbee98f
refs/heads/master
2022-05-05T08:19:23.870683
2022-03-26T12:31:25
2022-03-26T12:31:25
177,166,426
0
0
null
2021-03-23T22:26:03
2019-03-22T15:34:54
Java
UTF-8
Java
false
false
447
java
package com.epam.szte.bdd.runner; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) @CucumberOptions( features = {"src/test/resources/features"}, glue = {"com.epam.szte.bdd.hooks", "com.epam.szte.bdd.steps"}, plugin = {"html:target/cucumber", "json:target/cucumber-json-report.json","pretty"} //tags = "@shop" ) public class CucumberRunnerTest { }
1775f8d2c1edbe9ab676b30b7b9cd104d8676e23
57e0bb6df155a54545d9cee8f645a95f3db58fd2
/src/by/it/tsyhanova/at21/beans/User.java
d916cd7a027061fb819f1262e128aca6812f969c
[]
no_license
VitaliShchur/AT2019-03-12
a73d3acd955bc08aac6ab609a7d40ad109edd4ef
3297882ea206173ed39bc496dec04431fa957d0d
refs/heads/master
2020-04-30T23:28:19.377985
2019-08-09T14:11:52
2019-08-09T14:11:52
177,144,769
0
0
null
2019-05-15T21:22:32
2019-03-22T13:26:43
Java
UTF-8
Java
false
false
1,698
java
package by.it.tsyhanova.at21.beans; import java.util.Date; public class User { private long id; private String username; private String password; private String email; private Date date; //we need empty constructor Code>Generate>Constructor>Select None public User() { } //we need constructors for all fields public User(long id, String username, String password, String email, Date date) { this.id = id; this.username = username; this.password = password; this.email = email; this.date = date; } //we need get & set //Code>Generate>Getter and Setter public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } //we need to String //Code>Generate>toString() @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", date=" + date + '}'; } }
0b810595b21eefc410b2a52c851314b895a19829
db9dabca10a859af1930ce9aad733352502b4177
/app/src/main/java/com/centaurs/tmdbapp/util/NetworkConnectionUtil.java
dfdb3afdc79ac3191b2811f6033e0f92bc3b1730
[]
no_license
zaharij/TMDBApp
4ae4c4181ef4de78745fd72cf5332a0e09d899c1
edd07e14ed7e36389af9b832b4035de11755e08a
refs/heads/master
2021-08-19T21:54:31.312337
2017-11-13T13:45:07
2017-11-13T13:45:07
105,163,524
0
0
null
2017-11-13T13:45:57
2017-09-28T15:09:17
Java
UTF-8
Java
false
false
732
java
package com.centaurs.tmdbapp.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import javax.inject.Singleton; @Singleton public class NetworkConnectionUtil { private Context context; public NetworkConnectionUtil(Context context){ this.context = context; } public boolean isNetworkConnected(){ ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null; return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
a8f0e5f3059846b7b2d5893f01a7a5a4eea851a9
27df5f2ae2a3f0d2ec2a1672f48fbacdd7efa888
/src/main/java/io/javavrains/springbootstarter/topic/Topic.java
a57e9f59288dc2e82d9aaafd15a00bf56f606245
[]
no_license
nikitarai1511/course-api
db0099f1635b465b6b9de0dbe26bb0946bf72086
cf08265d1414f44e56470767c8a8e9e234dcdfdc
refs/heads/master
2020-05-20T00:17:10.931355
2019-05-06T23:04:47
2019-05-06T23:04:47
185,283,020
0
0
null
null
null
null
UTF-8
Java
false
false
729
java
package io.javavrains.springbootstarter.topic; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Topic { @Id private String Id; private String name; private String description; public Topic() { } public Topic(String id, String name, String description) { super(); Id = id; this.name = name; this.description = description; } public String getId() { return Id; } public void setId(String id) { Id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
9a08da59ecd3dce77ea409f541b73d1058878345
8f322f02a54dd5e012f901874a4e34c5a70f5775
/src/main/java/PTUCharacterCreator/Moves/Spike_Cannon.java
d6073c2c5480ebdd5db1d6b69c2de0a43d2020b6
[]
no_license
BMorgan460/PTUCharacterCreator
3514a4040eb264dec69aee90d95614cb83cb53d8
e55f159587f2cb8d6d7b456e706f910ba5707b14
refs/heads/main
2023-05-05T08:26:04.277356
2021-05-13T22:11:25
2021-05-13T22:11:25
348,419,608
0
0
null
null
null
null
UTF-8
Java
false
false
333
java
package PTUCharacterCreator.Moves; import PTUCharacterCreator.Move; public class Spike_Cannon extends Move { { name = "Spike Cannon"; effect = "--"; damageBase = 3; mDamageBase = 3; AC = 4; frequency = "EOT"; range = "6, 1 Target, Five Strike"; type = "Normal"; category = "Physical"; } public Spike_Cannon(){} }
cb6ad58a09555367df1ebbe444628fac20615a38
6a21ee4d759e1e224fe1c402368094423c7c77af
/pmp-domain/src/main/java/com/shenxin/core/control/Enum/StatisticalGradEnum.java
595665a974ddfc6f74acf9958605248500d25024
[]
no_license
baozong-gao/bjui_control_template-
19edff3cbdddd316db3a68fbd9b0680df7696311
9ebe4436b2b7c80a36f7499ad634658e12ad2c3f
refs/heads/master
2021-08-31T17:38:41.621556
2017-12-22T08:05:59
2017-12-22T08:05:59
115,091,944
0
0
null
null
null
null
UTF-8
Java
false
false
590
java
package com.shenxin.core.control.Enum; import java.util.Calendar; //0:日 , 1:月 ,2:all(所有) public enum StatisticalGradEnum { DAY(0,"当天"),MONTH(1,"当月"),ALL(2,"全部"); private int grad; private Calendar time; private String legendName; StatisticalGradEnum(int grad,String legendName){ this.grad = grad; this.legendName = legendName; } public int getGrad() { return grad; } public Calendar getTime() { return time; } public void setTime(Calendar time) { this.time = time; } public String getLegendName() { return legendName; } }
bd24bb293fc7b4f8f36a4a4b8625fb9862dff5f4
724dc8749fa3879be920934da8da4427ba2e8dea
/src/main/java/cn/edu/zzia/bookstore/service/IPrivilegeService.java
fdd6b707202903282a8d0d5cbef8e05f3edd73fb
[]
no_license
wangkai93/bookstore
af808a9725c8c47498b4e47c4db9b9a32966ad25
292d87ed014b0609f258e5c5fc19e825c4c54ac4
refs/heads/master
2020-05-24T23:21:19.448852
2017-03-20T07:00:28
2017-03-20T07:00:28
84,890,049
0
0
null
null
null
null
UTF-8
Java
false
false
602
java
package cn.edu.zzia.bookstore.service; import java.util.List; import cn.edu.zzia.bookstore.domain.Page; import cn.edu.zzia.bookstore.domain.Privilege; public interface IPrivilegeService { public static final String SERVICE_NAME = "cn.edu.zzia.bookstore.service.impl.PrivilegeServiceImpl"; /** * 分页查找权限信息 * @param pagenum * @return */ Page findPrivilegesByPage(String pagenum); /** * 保存权限信息 * @param privilege */ void savePrivilege(Privilege privilege); /** * 查找所有的权限信息 * @return */ List<Privilege> findAllPrivilege(); }
98a96f590bab0816f8d855ffb6de41dea18d82f2
6722478e2f6ffc34f4f17ac658e65e72840d2ded
/src/main/java/com/tnt/beer/order/repository/BeerOrderRepository.java
67c2411a91dd52154e2567cad5682b29047650f6
[]
no_license
somnath46/tnt-beer-order-service
a2d7a9946fccd585c7f8f212c504a839d6c176d2
363189d7c0a00f755cfb6e34c6451a1c69b76cf9
refs/heads/master
2022-12-27T19:46:04.421726
2020-10-10T15:10:58
2020-10-10T15:10:58
292,618,945
0
0
null
null
null
null
UTF-8
Java
false
false
788
java
package com.tnt.beer.order.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Lock; import com.tnt.beer.order.domain.BeerOrder; import com.tnt.beer.order.domain.Customer; import com.tnt.beer.order.domain.OrderStatusEnum; import javax.persistence.LockModeType; import java.util.List; import java.util.UUID; public interface BeerOrderRepository extends JpaRepository<BeerOrder, UUID> { Page<BeerOrder> findAllByCustomer(Customer customer, Pageable pageable); List<BeerOrder> findAllByOrderStatus(OrderStatusEnum orderStatusEnum); @Lock(LockModeType.PESSIMISTIC_WRITE) BeerOrder findOneById(UUID id); }
47f7e98ce6ab5b4ebcb1117d3a334947d051bad1
a8577246f305a4b62c04661b20280daf3eeebc7e
/src/main/java/com/cherrysoft/bugtracker/service/dto/PasswordChangeDTO.java
e6f78a7051931b81a4bb3affd96509cbb5f73def
[]
no_license
UKirsche/BugTrackerJHipster
317e4b04ead500964c5dd60aabc8e5706152c734
7adc1016cb87822291797dfae9a0eae7c221637d
refs/heads/master
2022-12-21T22:11:15.985835
2019-07-25T11:45:45
2019-07-25T11:45:45
198,821,978
0
1
null
2022-12-16T05:02:33
2019-07-25T11:52:47
Java
UTF-8
Java
false
false
869
java
package com.cherrysoft.bugtracker.service.dto; /** * A DTO representing a password change required data - current and new password. */ public class PasswordChangeDTO { private String currentPassword; private String newPassword; public PasswordChangeDTO() { // Empty constructor needed for Jackson. } public PasswordChangeDTO(String currentPassword, String newPassword) { this.currentPassword = currentPassword; this.newPassword = newPassword; } public String getCurrentPassword() { return currentPassword; } public void setCurrentPassword(String currentPassword) { this.currentPassword = currentPassword; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } }
61e5970820fbf813ee445402d41e6875b0fad23c
dc916f0e5579abfb4d6602d35f3d14cf459d3f6c
/src/main/java/com/volunteer/utils/ExcelUtil.java
3cd816ebde87a97d1e964e2dd6324b2830bd6ddb
[]
no_license
TOmANDJerryz/volunteer
a51264c7836b61b6b2746a6a6a363e64950ab847
ed9fa1aeb7c97d8de4bd6c3a8f4fa9158e41a6ec
refs/heads/master
2020-04-25T01:58:31.517153
2019-02-25T03:35:34
2019-02-25T03:35:34
172,423,811
1
0
null
null
null
null
UTF-8
Java
false
false
9,674
java
package com.volunteer.utils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.http.HttpServletResponse; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; public class ExcelUtil { //显示的导出表的标题 private String title; //导出表的列名 private String[] rowName ; private List<Object[]> dataList = new ArrayList<Object[]>(); HttpServletResponse response; //构造方法,传入要导出的数据 public ExcelUtil(String title,String[] rowName,List<Object[]> dataList){ this.dataList = dataList; this.rowName = rowName; this.title = title; } /* * 导出数据 * */ public void export() throws Exception{ try{ HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象 HSSFSheet sheet = workbook.createSheet(title); // 创建工作表 // 产生表格标题行 HSSFRow rowm = sheet.createRow(0); HSSFCell cellTiltle = rowm.createCell(0); rowm.setHeight((short) (25 * 30)); //设置高度 //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象 HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1))); cellTiltle.setCellStyle(columnTopStyle); cellTiltle.setCellValue(title); // 定义所需列数 int columnNum = rowName.length; HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行) rowRowName.setHeight((short) (25 * 30)); //设置高度 // 将列头设置到sheet的单元格中 for(int n=0;n<columnNum;n++){ HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格 cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型 HSSFRichTextString text = new HSSFRichTextString(rowName[n]); cellRowName.setCellValue(text); //设置列头单元格的值 cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式 } //将查询出的数据设置到sheet对应的单元格中 for(int i=0;i<dataList.size();i++){ Object[] obj = dataList.get(i);//遍历每个对象 HSSFRow row = sheet.createRow(i+3);//创建所需的行数 row.setHeight((short) (25 * 20)); //设置高度 for(int j=0; j<obj.length; j++){ HSSFCell cell = null; //设置单元格的数据类型 if(j == 0){ cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC); cell.setCellValue(i+1); }else{ cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING); if(!"".equals(obj[j]) && obj[j] != null){ cell.setCellValue(obj[j].toString()); //设置单元格的值 } } cell.setCellStyle(style); //设置单元格样式 } } //让列宽随着导出的列长自动适应 for (int colNum = 0; colNum < columnNum; colNum++) { int columnWidth = sheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { HSSFRow currentRow; //当前行未被使用过 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { HSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) { int length = currentCell.getStringCellValue().getBytes().length; if (columnWidth < length) { columnWidth = length; } } } } if(colNum == 0){ sheet.setColumnWidth(colNum, (columnWidth-2) * 128); }else{ sheet.setColumnWidth(colNum, (columnWidth+4) * 256); } } if(workbook !=null){ try { // String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls"; // String headStr = "attachment; filename=\"" + fileName + "\""; // response = getResponse(); // response.setContentType("APPLICATION/OCTET-STREAM"); // response.setHeader("Content-Disposition", headStr); // OutputStream out = response.getOutputStream(); // workbook.write(out); FileOutputStream out = new FileOutputStream("D:/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() +".xls"); workbook.write(out); out.close(); } catch (IOException e) { e.printStackTrace(); } } }catch(Exception e){ e.printStackTrace(); } } /* * 列头单元格样式 */ public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { // 设置字体 HSSFFont font = workbook.createFont(); //设置字体大小 font.setFontHeightInPoints((short)11); //字体加粗 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //设置字体名字 font.setFontName("Courier New"); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //设置底边框颜色; style.setBottomBorderColor(HSSFColor.BLACK.index); //设置左边框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); //设置左边框颜色; style.setLeftBorderColor(HSSFColor.BLACK.index); //设置右边框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); //设置右边框颜色; style.setRightBorderColor(HSSFColor.BLACK.index); //设置顶边框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); //设置顶边框颜色; style.setTopBorderColor(HSSFColor.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //设置单元格背景颜色 style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); return style; } /* * 列数据信息单元格样式 */ public HSSFCellStyle getStyle(HSSFWorkbook workbook) { // 设置字体 HSSFFont font = workbook.createFont(); //设置字体大小 //font.setFontHeightInPoints((short)10); //字体加粗 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //设置字体名字 font.setFontName("Courier New"); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //设置底边框颜色; style.setBottomBorderColor(HSSFColor.BLACK.index); //设置左边框; style.setBorderLeft(HSSFCellStyle.BORDER_THIN); //设置左边框颜色; style.setLeftBorderColor(HSSFColor.BLACK.index); //设置右边框; style.setBorderRight(HSSFCellStyle.BORDER_THIN); //设置右边框颜色; style.setRightBorderColor(HSSFColor.BLACK.index); //设置顶边框; style.setBorderTop(HSSFCellStyle.BORDER_THIN); //设置顶边框颜色; style.setTopBorderColor(HSSFColor.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); return style; } }
19564ccd3386dbbfcea9328bbba9db60bc6cb586
e6f0df9c2e1f2d5eb020f75e160bd358933c923b
/homework7-car-database/src/main/java/com/springcourse/homework7cardatabase/model/Car.java
6673e3acfdfd28ecbd4f0dd82566284bbf0aa9f4
[]
no_license
marcinPluciennik/akademia-springa
6decb1a911bb60d7cd108aec2cf0939e08e583ac
8aca9b5a06d88f93ab55a6cc2b460d5657d48ba3
refs/heads/master
2023-04-02T02:50:42.228744
2021-04-15T12:15:39
2021-04-15T12:15:39
309,067,902
0
0
null
null
null
null
UTF-8
Java
false
false
1,259
java
package com.springcourse.homework7cardatabase.model; public class Car { private long carId; private String mark; private String model; private String color; private int year; public Car(long carId, String mark, String model, String color, int year) { this.carId = carId; this.mark = mark; this.model = model; this.color = color; this.year = year; } public Car() { } public long getCarId() { return carId; } public void setCarId(long carId) { this.carId = carId; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } @Override public String toString() { return "Car{" + "carId=" + carId + ", mark='" + mark + '\'' + ", model='" + model + '\'' + ", color='" + color + '\'' + ", year=" + year + '}'; } }
abb1df0400bc6d44f616dd5dca392d3a740fe26a
722d4949660a79e9a58acb887e42908f418996d5
/zookeeper-action/src/main/java/com/chenxi/zookeeper/basic/zkclient/WriteData.java
4ec4005c136068ffe2fcbbf05d2466a29776f7c1
[]
no_license
chenxi-zhao/frameworks4j-maven
2e896c96008c2a12c1b80b863f10693552237357
0b36f5471698014e8063050ac193692abf93e3b5
refs/heads/master
2021-09-20T22:29:30.165580
2018-04-17T08:20:10
2018-04-17T08:20:10
82,508,655
0
0
null
2021-08-09T20:49:07
2017-02-20T02:35:44
JavaScript
UTF-8
Java
false
false
454
java
package com.chenxi.zookeeper.basic.zkclient; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.serialize.SerializableSerializer; public class WriteData { public static void main(String[] args) { ZkClient zc = new ZkClient("192.168.208.128:2181",10000,10000,new SerializableSerializer()); System.out.println("conneted ok!"); User u = new User(); u.setId(2); u.setName("test2"); zc.writeData("/node_1", u, 1); } }
15399474d4ea3a66f8f833966b235f9b61743ccb
bd0d51c6c6e88d39cbf38b7eeb9059632afe5161
/cars/src/main/java/com/lgz/cras/service/impl/UserServiceImpl.java
f353ce1fdb807c026bf6db448f9efb922b7753ab
[]
no_license
18168215586/zhou
c381d869bba85868ce5193a77a124f000f324e89
ce91f4720813dc87998c327a7ff12e092c924554
refs/heads/master
2022-12-24T00:32:15.633181
2019-06-14T09:09:24
2019-06-14T09:09:24
188,986,175
0
0
null
2022-12-16T07:13:59
2019-05-28T08:22:43
HTML
UTF-8
Java
false
false
2,953
java
package com.lgz.cras.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lgz.cras.mapper.UserMapper; import com.lgz.cras.pojo.User; import com.lgz.cras.service.UserService; import com.lgz.cras.util.MD5Util; import com.lgz.cras.util.MyUtils; import com.lgz.cras.util.ResBean; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.List; import java.util.Map; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override/*自动注入注解*/ public User getInfoByid(Integer id) { return userMapper.selectByPrimaryKey(id); } @Override public User login(User user) { return userMapper.login(user); } @Override public ResBean getPage(int page, int limit, User user) { Map<String,Object> map=new HashMap<>(); PageHelper.startPage(page,limit); List<User> list=userMapper.getPage(user); PageInfo<User> pageInfo=new PageInfo<>(list); return new ResBean(0,"暂无数据",pageInfo.getTotal(),list); } @Override public ResBean checkUname(String username) { User user=userMapper.checkUname(username); if (user==null){ return new ResBean(0); } return new ResBean(1); } @Override public ResBean update(User user, HttpSession session) { if (StringUtils.isNotEmpty(user.getPassword())){ user.setPassword(MD5Util.MD5(user.getPassword())); } int result=0; if (user.getId()==null){ user.setCreateDate(MyUtils.getNowTime()); user.setCreateAdmin(MyUtils.getLoginName(session)); result=userMapper.insertSelective(user); }else { user.setUpdateDate(MyUtils.getNowTime()); user.setCreateAdmin(MyUtils.getLoginName(session)); result=userMapper.updateByPrimaryKeySelective(user); } if (result>0){ return new ResBean(1,"更新成功"); }else { return new ResBean(0,"更新失败"); } } @Override public ResBean delete(Integer id) { if (userMapper.deleteByPrimaryKey(id)>0){ return new ResBean(1,"删除成功"); } return new ResBean(0,"删除失败"); } @Override public User getById(Integer id) { return userMapper.selectByPrimaryKey(id); } @Override public ResBean checkPwd(User user) { user.setPassword(MD5Util.MD5(user.getPassword())); if (userMapper.checkPwd(user)!=null){ return new ResBean(0); } return new ResBean(1); } }
d25f9b6dc9c431990cecab4b4f05a0a124689b8d
d9d9d635f25c68cdfe28ee8bd21082b5975f2f61
/review_java/src/main/java/com/unknown/base/io/Practice.java
aed8c685d5b8c2a5f1405e0ca508c89f3a23c7b7
[]
no_license
ArchangelLiang/myHelloWorldProjects
f87b96f29a5b39367e7fb84671612f8bb81b7125
290cb82b417a695c514dfa360d9967400729b8e7
refs/heads/master
2022-12-26T07:03:15.478125
2020-01-30T11:24:58
2020-01-30T11:24:58
235,990,443
0
0
null
2022-12-16T14:52:36
2020-01-24T11:27:50
Java
UTF-8
Java
false
false
1,333
java
package com.unknown.base.io; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class Practice { public static void main(String[] args) { File file = new File("review_jdbc\\test_io\\zio.txt"); FileReader read = null; HashMap<String, Integer> map = new HashMap<>(); try { read = new FileReader(file); char[] chars = new char[5]; int data_num; while ((data_num = read.read(chars)) != -1) { for (int i = 0; i < data_num; i++) { String key = String.valueOf(chars[i]); if (map.containsKey(key)) { Integer num = map.get(key); num++; map.put(key, num); } else { if (!key.equals(" ")) map.put(key, 1); } } } } catch (Exception e) { e.printStackTrace(); } finally { if (read != null) { try { read.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(map); } }
4e084d345eb273119b56f8ba70719c1d64065fc7
4353ca274ab5a587af3856d78fdfcba7d0b44bbb
/javatest/src/main/java/com/netty/Share/ReplyMsg.java
72b50454f68e389e9cfaedb4d68f80b0decd9475
[]
no_license
JackDong520/AndroidAppPro
e6aa165f2d9056dc2a311e0abb1c60f363ded3c7
9599a129210174417d88135490b33cbb1c2b767d
refs/heads/master
2022-01-17T06:04:01.774566
2019-07-23T07:33:57
2019-07-23T07:33:57
198,377,403
0
0
null
null
null
null
UTF-8
Java
false
false
351
java
package com.netty.Share; /** * Created by yaozb on 15-4-11. */ public class ReplyMsg extends BaseMsg { public ReplyMsg() { super(); setType(MsgType.REPLY); } private ReplyBody body; public ReplyBody getBody() { return body; } public void setBody(ReplyBody body) { this.body = body; } }
cd221f09d206e8b70a14799a9de2e0d0c897c5f2
f1198aee5a975bed23255cf82120904bbd8c07ba
/src/test/java/seedu/address/testutil/DatabaseBuilder.java
a3046e7e3aa0fc4283f907199ed48f25cba2070e
[ "MIT" ]
permissive
duyson98/addressbook-level4
5201865b52d078155feedcf43b222f50dd27e884
2844c79056d7dc4eeca66cf6de01b0cc070bec92
refs/heads/master
2021-09-06T20:19:10.621167
2017-11-20T02:57:31
2017-11-20T02:57:31
105,089,282
0
0
null
2017-09-28T01:48:56
2017-09-28T01:48:56
null
UTF-8
Java
false
false
1,030
java
//@@author cqhchan package seedu.address.testutil; import seedu.address.model.Database; import seedu.address.model.account.ReadOnlyAccount; import seedu.address.model.account.exceptions.DuplicateAccountException; /** * */ public class DatabaseBuilder { private Database database; public DatabaseBuilder() { database = new Database(); } public DatabaseBuilder(Database database) { this.database = database; } /** * Adds a new {@code Account} to the {@code Database} that we are building. */ public DatabaseBuilder withAccount(ReadOnlyAccount account) { try { database.addAccount(account); } catch (DuplicateAccountException dpe) { throw new IllegalArgumentException("account is expected to be unique."); } return this; } /** * Parses {@code tagName} into a {@code Tag} and adds it to the {@code Database} that we are building. */ public Database build() { return database; } }
1881d84870f5592d7991a0d5963fa5d0975b8ba2
875055e950b13244a6c624e13c2a9feb227f6695
/src/com/wyh/pattern/Customer.java
ee3c1042f117bd11bed53b39f5eb25eeb40c17bc
[]
no_license
wyhuiii/ChainOfResponsibility
e60d67cf32875c087601c1b7354c9eb3b580f102
7887d60a1c8b758f40055c4d42f42dec28450a0e
refs/heads/master
2020-06-16T06:42:50.910394
2019-07-06T09:38:45
2019-07-06T09:38:45
195,504,827
0
0
null
null
null
null
UTF-8
Java
false
false
655
java
package com.wyh.pattern; /** * <p>Title: Customer</p> * <p>Description: 客户实体 * 属性:想要申请的折扣 * 方法:向审批人提出申请(客户不关心该申请经过了哪些级别,也不关心最后由谁批准了) * </p> * @author wyh * @date Jul 6, 2019 */ public class Customer { private float discount; public void setDiscount(float discount) { this.discount = discount; } //在传入审批人参数时,审批人直接由审批人工厂创建 public void request(PriceHandler proccessor) { //有了审批人之后,调用方法处理具体的审批流程 proccessor.proccessDiscount(discount); } }
5c6110bd12e1a896581d9c46ad02a74545ca6e40
4f085cb2d1f56fb4b01a03efb13e4b36821e50b2
/src/main/java/ChefScheduler.java
34e1ea4bdde63b49afa3463ab9a21823db85bb65
[]
no_license
SankulGarg/Competetive
ed3b9351515bcc71b019a61ab99b438dc8371cd0
b9dcb4abd5d6b790cd90ca67865cd794f0a3df25
refs/heads/main
2023-07-27T11:36:57.896517
2021-09-09T10:22:55
2021-09-09T10:22:55
352,002,005
0
0
null
null
null
null
UTF-8
Java
false
false
2,380
java
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; final public class ChefScheduler { public static boolean schedulable(HashMap<String, ArrayList<String>> requests) { System.out.println(requests); Map<String, List<String>> sorted = new LinkedHashMap<>(); for (Map.Entry<String, ArrayList<String>> entry : requests.entrySet()) { Set<String> allDays = new HashSet<String>(Set.of("mon", "tue", "wed", "thu", "fri", "sat", "sun")); for (String day : entry.getValue()) { allDays.remove(day); } sorted.put(entry.getKey(), allDays.stream().collect(Collectors.toList())); } sorted = sorted.entrySet().stream().sorted(Comparator.comparingInt(e -> e.getValue().size())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> { throw new AssertionError(); }, LinkedHashMap::new)); System.out.println(sorted); Map<String, Integer> days = new HashMap<>(); days.put("mon", 0); days.put("tue", 1); days.put("wed", 2); days.put("thu", 3); days.put("fri", 4); days.put("sat", 5); days.put("sun", 6); int[] chefCount = new int[7]; for (Map.Entry<String, List<String>> entry : sorted.entrySet()) { int employeeShiftCount = 0; for (String day : entry.getValue()) { if (days.size() == 0) return true; if (!days.containsKey(day)) continue; if (employeeShiftCount >= 5) break; chefCount[days.get(day)]++; employeeShiftCount++; if (chefCount[days.get(day)] == 2) days.remove(day); } } System.out.println(Arrays.toString(chefCount)); System.err.println(days); return days.size() == 0; } public static void main(String[] args) { HashMap<String, ArrayList<String>> requests = new HashMap<>(); requests.put("ada", new ArrayList<>(Arrays.asList(new String[] { "mon", "tue", "wed", "fri", "sat", "sun" }))); requests.put("emma", new ArrayList<>(Arrays.asList(new String[] { "mon", "tue", "wed", "thu", "sun" }))); requests.put("remy", new ArrayList<>(Arrays.asList(new String[] { "mon", "thu", "fri", "sat" }))); requests.put("zach", new ArrayList<>(Arrays.asList(new String[] {}))); ChefScheduler.schedulable(requests); } }
6ee9d8b3ab4e5957d20b3aa9128ae1eedb51731a
dd32e80952925832b417c5fb291d6b4c7c8e714d
/materialList/src/main/java/com/dexafree/materialList/view/WelcomeCardItemView.java
d573eaa3c0af0c692fb53a4aa6e76196c31b20e5
[]
no_license
giovannicolonna/PRIMETIME4U-client
eb7f0a6e502a1958d82edf6cbb1e89b2f421e62a
a55d4fa2bfc4187d4640745e9880afb35b28f330
refs/heads/master
2021-01-23T06:50:23.271083
2015-04-30T10:29:11
2015-04-30T10:29:11
27,669,519
0
1
null
null
null
null
UTF-8
Java
false
false
3,814
java
package com.dexafree.materialList.view; import android.content.Context; import android.graphics.PorterDuff; import android.os.Build; import android.support.v7.widget.CardView; import android.support.v7.widget.MyRoundRectDrawableWithShadow; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.dexafree.materialList.R; import com.dexafree.materialList.events.BusProvider; import com.dexafree.materialList.events.DismissEvent; import com.dexafree.materialList.model.WelcomeCard; public class WelcomeCardItemView extends GridItemView<WelcomeCard> { private TextView mTitle; private TextView mSubtitle; private TextView mDescription; private TextView mButton; private View mDivider; private RelativeLayout backgroundView; private ImageView checkMark; public WelcomeCardItemView(Context context) { super(context); } public WelcomeCardItemView(Context context, AttributeSet attrs) { super(context, attrs); } public WelcomeCardItemView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void configureView(WelcomeCard card) { setTitle(card.getTitle()); setSubtitle(card.getSubtitle()); setDescription(card.getDescription()); setButton(card); setColors(card); } public void setTitle(String title){ mTitle = (TextView)findViewById(R.id.titleTextView); mTitle.setText(title); } public void setSubtitle(String subtitle){ mSubtitle = (TextView)findViewById(R.id.subtitleTextView); mSubtitle.setText(subtitle); } public void setDescription(String description){ mDescription = (TextView)findViewById(R.id.descriptionTextView); mDescription.setText(description); } public void setButton(final WelcomeCard card){ mButton = (TextView) findViewById(R.id.ok_button); mButton.setText(card.getButtonText()); mButton.setTextColor(card.getBackgroundColor()); final GridItemView<WelcomeCard> refView = this; mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Log.d("CLICK", "Text clicked"); if(card.getOnButtonPressedListener() != null) { card.getOnButtonPressedListener().onButtonPressedListener(mButton); } BusProvider.getInstance().post(new DismissEvent(card)); } }); } private void setColors(WelcomeCard card){ CardView cardView = (CardView)findViewById(R.id.cardView); int textSize = pxToDp(36); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { MyRoundRectDrawableWithShadow backgroundDrawable = new MyRoundRectDrawableWithShadow( getContext().getResources(), card.getBackgroundColor(), cardView.getRadius(), 6f, 6f ); cardView.setBackgroundDrawable(backgroundDrawable); } else { cardView.setBackgroundColor(card.getBackgroundColor()); cardView.setCardElevation(dpToPx(6)); } checkMark = (ImageView)findViewById(R.id.check_mark); mDivider = findViewById(R.id.cardDivider); mDivider.setBackgroundColor(card.getDividerColor()); mTitle.setTextColor(card.getTitleColor()); mSubtitle.setTextColor(card.getSubtitleColor()); mDescription.setTextColor(card.getDescriptionColor()); mButton.setTextColor(card.getButtonTextColor()); mButton.setTextSize((float) textSize); checkMark.setColorFilter(card.getButtonTextColor(), PorterDuff.Mode.SRC_IN); } }
d23fbabd20ddd81aacf7ae9f13ca4f25843bd061
fbd8937cb8a8f83390b4ee94ca29724dc5699735
/src/main/java/com/example/d2z/entity/DataConsole.java
650b3fbe58ad34275f1d7e86cde83ae875507440
[]
no_license
rafikahamed/JpdGlobalService
681f1056c9d1bec31a0ab286a310d15e168840b7
70483827fb40bbd9ef8179f996364a6844853834
refs/heads/master
2020-03-26T19:54:33.906465
2019-01-14T04:17:08
2019-01-14T04:17:08
145,292,705
0
0
null
null
null
null
UTF-8
Java
false
false
3,990
java
package com.example.d2z.entity; import java.io.Serializable; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * The persistent class for the data_console database table. * */ @Entity @Table(name="data_console") @NamedQuery(name="DataConsole.findAll", query="SELECT d FROM DataConsole d") @NamedStoredProcedureQueries({ @NamedStoredProcedureQuery(name = "delete_gst_data", procedureName = "deleteRecord", parameters = { @StoredProcedureParameter(mode = ParameterMode.IN, name = "reference_no", type = String.class) }) }) public class DataConsole implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private BigDecimal amount; @Column(name="aud_converted_amount") private BigDecimal audConvertedAmount; @Column(name="currency_code") private String currencyCode; @Column(name="file_name") private String fileName; @Column(name="GST_eligible") private String gstEligible; @Column(name="GST_payable") private BigDecimal gstPayable; @Column(name="reference_no") private String referenceNo; @Column(name="report_indicator") private String reportIndicator; @Temporal( TemporalType.DATE ) @Column(name="sale_date") private java.util.Date saleDate; @Temporal( TemporalType.DATE ) @Column(name="txn_date") private Date txnDate; @Temporal( TemporalType.DATE ) @Column(name="upload_date") private Date uploadDate; @Column(name="user_code") private String userCode; @Column(name="company_name") private String companyName; private String username; private String isdeleted; public DataConsole() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public BigDecimal getAudConvertedAmount() { return audConvertedAmount; } public void setAudConvertedAmount(BigDecimal audConvertedAmount) { this.audConvertedAmount = audConvertedAmount; } public String getCurrencyCode() { return this.currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getGstEligible() { return this.gstEligible; } public void setGstEligible(String gstEligible) { this.gstEligible = gstEligible; } public BigDecimal getGstPayable() { return this.gstPayable; } public void setGstPayable(BigDecimal gstPayable) { this.gstPayable = gstPayable; } public String getReferenceNo() { return this.referenceNo; } public void setReferenceNo(String referenceNo) { this.referenceNo = referenceNo; } public String getReportIndicator() { return this.reportIndicator; } public void setReportIndicator(String reportIndicator) { this.reportIndicator = reportIndicator; } public Date getSaleDate() { return saleDate; } public void setSaleDate(Date saleDate) { this.saleDate = saleDate; } public Date getTxnDate() { return txnDate; } public void setTxnDate(Date txnDate) { this.txnDate = txnDate; } public Date getUploadDate() { return uploadDate; } public void setUploadDate(Date uploadDate) { this.uploadDate = uploadDate; } public String getUserCode() { return this.userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getIsdeleted() { return this.isdeleted; } public void setIsdeleted(String isdeleted) { this.isdeleted = isdeleted; } }
[ "“[email protected] git config --global user.email “[email protected]" ]
[email protected] git config --global user.email “[email protected]
890de590f0b9b47002a586690f7652d824a5fb7c
7f300f813bc38d625e48ce03f7b695064a0bd116
/BBDJPA/src/javax/persistence/Entity.java
80521fc6cf3f8e36e14f5f88741d90b447465565
[ "Apache-2.0" ]
permissive
microneering/BBD
7c55c462d6df755d08b26c979051012b5ae74d5a
ead95375216eeab07be30d396eff136033603302
refs/heads/master
2020-03-26T22:38:55.753264
2018-09-01T05:02:40
2018-09-01T05:02:40
145,476,582
0
0
null
null
null
null
UTF-8
Java
false
false
343
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javax.persistence; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * * @author James Gamber */ @Retention(RetentionPolicy.RUNTIME) public @interface Entity { String name() default ""; }
6e9a7dcd96e33cb235c1e055cfac3cefb9209142
173b64b558857daba1f5f11b6f779aaeb1638e71
/src/main/java/ru/butakov/survey/domain/User.java
9af016a97398272c49df9b35c18cb56b757967df
[]
no_license
mello1984/survey
e9aaad582d05908c4f5c4790a1f5cbe5dcf46caf
25f8c30a36cd05761661380769af5300b83684a4
refs/heads/master
2023-06-19T05:46:59.017689
2021-07-07T09:32:56
2021-07-07T09:32:56
378,266,460
0
0
null
null
null
null
UTF-8
Java
false
false
236
java
package ru.butakov.survey.domain; import lombok.*; import lombok.experimental.FieldDefaults; @Data @NoArgsConstructor @AllArgsConstructor @Builder @FieldDefaults(level = AccessLevel.PRIVATE) public class User { String username; }
c85701054bf552566ff6b75b9e94b0789e45e041
a1e49f5edd122b211bace752b5fb1bd5c970696b
/projects/org.springframework.beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java
7c979316666fbfbe276f7e9e63422bc13926702b
[ "Apache-2.0" ]
permissive
savster97/springframework-3.0.5
4f86467e2456e5e0652de9f846f0eaefc3214cfa
34cffc70e25233ed97e2ddd24265ea20f5f88957
refs/heads/master
2020-04-26T08:48:34.978350
2019-01-22T14:45:38
2019-01-22T14:45:38
173,434,995
0
0
Apache-2.0
2019-03-02T10:37:13
2019-03-02T10:37:12
null
UTF-8
Java
false
false
7,613
java
/* * Copyright 2002-2009 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 org.springframework.beans.factory.xml; import junit.framework.Assert; import junit.framework.TestCase; import test.beans.TestBean; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.io.ClassPathResource; /** * @author Rob Harrop * @author Juergen Hoeller */ public class AutowireWithExclusionTests extends TestCase { public void testByTypeAutowireWithAutoSelfExclusion() throws Exception { CountingFactory.reset(); XmlBeanFactory beanFactory = getBeanFactory("autowire-with-exclusion.xml"); beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); TestBean sally = (TestBean) beanFactory.getBean("sally"); assertEquals(sally, rob.getSpouse()); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testByTypeAutowireWithExclusion() throws Exception { CountingFactory.reset(); XmlBeanFactory beanFactory = getBeanFactory("autowire-with-exclusion.xml"); beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); assertEquals("props1", rob.getSomeProperties().getProperty("name")); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testByTypeAutowireWithExclusionInParentFactory() throws Exception { CountingFactory.reset(); XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.preInstantiateSingletons(); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE); robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally")); child.registerBeanDefinition("rob2", robDef); TestBean rob = (TestBean) child.getBean("rob2"); assertEquals("props1", rob.getSomeProperties().getProperty("name")); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testByTypeAutowireWithPrimaryInParentFactory() throws Exception { CountingFactory.reset(); XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.getBeanDefinition("props1").setPrimary(true); parent.preInstantiateSingletons(); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE); robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally")); child.registerBeanDefinition("rob2", robDef); RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class); propsDef.getPropertyValues().add("properties", "name=props3"); child.registerBeanDefinition("props3", propsDef); TestBean rob = (TestBean) child.getBean("rob2"); assertEquals("props1", rob.getSomeProperties().getProperty("name")); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testByTypeAutowireWithPrimaryOverridingParentFactory() throws Exception { CountingFactory.reset(); XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.preInstantiateSingletons(); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE); robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally")); child.registerBeanDefinition("rob2", robDef); RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class); propsDef.getPropertyValues().add("properties", "name=props3"); propsDef.setPrimary(true); child.registerBeanDefinition("props3", propsDef); TestBean rob = (TestBean) child.getBean("rob2"); assertEquals("props3", rob.getSomeProperties().getProperty("name")); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testByTypeAutowireWithPrimaryInParentAndChild() throws Exception { CountingFactory.reset(); XmlBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.getBeanDefinition("props1").setPrimary(true); parent.preInstantiateSingletons(); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); RootBeanDefinition robDef = new RootBeanDefinition(TestBean.class, RootBeanDefinition.AUTOWIRE_BY_TYPE); robDef.getPropertyValues().add("spouse", new RuntimeBeanReference("sally")); child.registerBeanDefinition("rob2", robDef); RootBeanDefinition propsDef = new RootBeanDefinition(PropertiesFactoryBean.class); propsDef.getPropertyValues().add("properties", "name=props3"); propsDef.setPrimary(true); child.registerBeanDefinition("props3", propsDef); TestBean rob = (TestBean) child.getBean("rob2"); assertEquals("props3", rob.getSomeProperties().getProperty("name")); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testByTypeAutowireWithInclusion() throws Exception { CountingFactory.reset(); XmlBeanFactory beanFactory = getBeanFactory("autowire-with-inclusion.xml"); beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); assertEquals("props1", rob.getSomeProperties().getProperty("name")); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testByTypeAutowireWithSelectiveInclusion() throws Exception { CountingFactory.reset(); XmlBeanFactory beanFactory = getBeanFactory("autowire-with-selective-inclusion.xml"); beanFactory.preInstantiateSingletons(); TestBean rob = (TestBean) beanFactory.getBean("rob"); assertEquals("props1", rob.getSomeProperties().getProperty("name")); Assert.assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } public void testConstructorAutowireWithAutoSelfExclusion() throws Exception { XmlBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml"); TestBean rob = (TestBean) beanFactory.getBean("rob"); TestBean sally = (TestBean) beanFactory.getBean("sally"); assertEquals(sally, rob.getSpouse()); TestBean rob2 = (TestBean) beanFactory.getBean("rob"); assertEquals(rob, rob2); assertNotSame(rob, rob2); assertEquals(rob.getSpouse(), rob2.getSpouse()); assertNotSame(rob.getSpouse(), rob2.getSpouse()); } public void testConstructorAutowireWithExclusion() throws Exception { XmlBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml"); TestBean rob = (TestBean) beanFactory.getBean("rob"); assertEquals("props1", rob.getSomeProperties().getProperty("name")); } private XmlBeanFactory getBeanFactory(String configPath) { return new XmlBeanFactory(new ClassPathResource(configPath, getClass())); } }
04e5fec2162b07e460ac27f81b59e6c3fade69ba
fcd28e246e059e5305ee89931ce7d81edddf8057
/camera/java/camera/logevent_notReadyToTakeImageDataReaderHelper.java
8509bad1f79f815d9fcf26138f200670e6ae84d9
[]
no_license
lsst-ts/ts_sal_runtime
56e396cb42f1204595f9bcdb3a2538007c0befc6
ae918e6f2b73f2ed7a8201bf3a79aca8fb5b36ef
refs/heads/main
2021-12-21T02:40:37.628618
2017-09-14T18:06:48
2017-09-14T18:06:49
145,469,981
0
0
null
null
null
null
UTF-8
Java
false
false
991
java
package camera; import org.opensplice.dds.dcps.Utilities; public final class logevent_notReadyToTakeImageDataReaderHelper { public static camera.logevent_notReadyToTakeImageDataReader narrow(java.lang.Object obj) { if (obj == null) { return null; } else if (obj instanceof camera.logevent_notReadyToTakeImageDataReader) { return (camera.logevent_notReadyToTakeImageDataReader)obj; } else { throw Utilities.createException(Utilities.EXCEPTION_TYPE_BAD_PARAM, null); } } public static camera.logevent_notReadyToTakeImageDataReader unchecked_narrow(java.lang.Object obj) { if (obj == null) { return null; } else if (obj instanceof camera.logevent_notReadyToTakeImageDataReader) { return (camera.logevent_notReadyToTakeImageDataReader)obj; } else { throw Utilities.createException(Utilities.EXCEPTION_TYPE_BAD_PARAM, null); } } }
c673366a04faecab1f2be6e3ae5d20b3bc878051
760f940c21d77760dbe6ead3f504a3246b8c68cf
/app/src/main/java/com/hrsst/housekeeper/mvp/sdcard/SDCardActivity.java
e336ab77a200c7e008f2c4e392487a0a21cbe217
[]
no_license
vidylin/HouseKeeper
441bb888c3c5576a427a45730773fc70121b7d38
c8524253f587d528a2ee9c54ec84730208971b74
refs/heads/master
2020-12-24T12:13:42.487428
2016-12-20T09:40:43
2016-12-20T09:40:43
73,064,440
1
1
null
null
null
null
UTF-8
Java
false
false
12,519
java
package com.hrsst.housekeeper.mvp.sdcard; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.hrsst.housekeeper.R; import com.hrsst.housekeeper.common.data.Contact; import com.hrsst.housekeeper.common.global.Constants; import com.hrsst.housekeeper.common.widget.NormalDialog; import com.hrsst.housekeeper.mvp.apmonitor.ApMonitorActivity; import com.p2p.core.P2PHandler; import com.p2p.core.P2PValue; public class SDCardActivity extends Activity implements View.OnClickListener { private Context mContext; private Contact contact; RelativeLayout sd_format; String command; boolean isRegFilter = false; TextView tv_total_capacity, tv_sd_remainning_capacity,tv_sd_card; ImageView format_icon; ProgressBar progress_format; int SDcardId; int sdId; int usbId; boolean isSDCard; int count = 0; String idOrIp; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_sdcard); mContext = this; contact = (Contact) getIntent().getSerializableExtra("contact"); idOrIp=contact.contactId; if(contact.ipadressAddress!=null){ String mark=contact.ipadressAddress.getHostAddress(); String ip=mark.substring(mark.lastIndexOf(".")+1,mark.length()); if(!ip.equals("")&&ip!=null){ idOrIp=ip; } } initComponent(); showSDProgress(); regFilter(); command=createCommand("80", "0", "00"); P2PHandler.getInstance().getSdCardCapacity(idOrIp, contact.contactPassword,command); } public void initComponent() { tv_sd_card = (TextView) findViewById(R.id.tv_sd_card); tv_total_capacity = (TextView) findViewById(R.id.tv_sd_capacity); tv_sd_remainning_capacity = (TextView)findViewById(R.id.tv_sd_remainning_capacity); sd_format = (RelativeLayout) findViewById(R.id.sd_format); format_icon = (ImageView) findViewById(R.id.format_icon); progress_format = (ProgressBar) findViewById(R.id.progress_format); sd_format.setOnClickListener(this); if (contact.contactType == P2PValue.DeviceType.NPC) { sd_format.setVisibility(RelativeLayout.GONE); } tv_sd_card.setText(contact.contactName); } public void regFilter() { isRegFilter = true; IntentFilter filter = new IntentFilter(); filter.addAction(Constants.P2P.ACK_GET_SD_CARD_CAPACITY); filter.addAction(Constants.P2P.RET_GET_SD_CARD_CAPACITY); filter.addAction(Constants.P2P.ACK_GET_SD_CARD_FORMAT); filter.addAction(Constants.P2P.RET_GET_SD_CARD_FORMAT); filter.addAction(Constants.P2P.RET_GET_USB_CAPACITY); filter.addAction(Constants.P2P.RET_DEVICE_NOT_SUPPORT); mContext.registerReceiver(br, filter); } BroadcastReceiver br = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals( Constants.P2P.ACK_GET_SD_CARD_CAPACITY)) { int result = intent.getIntExtra("result", -1); if (result == Constants.P2P_SET.ACK_RESULT.ACK_PWD_ERROR) { Intent i = new Intent(); i.setAction(Constants.Action.CONTROL_SETTING_PWD_ERROR); mContext.sendBroadcast(i); } else if (result == Constants.P2P_SET.ACK_RESULT.ACK_NET_ERROR) { Log.e("my", "net error resend:get npc time"); P2PHandler.getInstance().getSdCardCapacity(idOrIp, contact.contactPassword, command); } } else if (intent.getAction().equals( Constants.P2P.RET_GET_SD_CARD_CAPACITY)) { int total_capacity = intent.getIntExtra("total_capacity", -1); int remain_capacity = intent.getIntExtra("remain_capacity", -1); int state = intent.getIntExtra("state", -1); SDcardId = intent.getIntExtra("SDcardID", -1); String id = Integer.toBinaryString(SDcardId); Log.e("id", "msga" + id); while (id.length() < 8) { id = "0" + id; } char index = id.charAt(3); Log.e("id", "msgb" + id); Log.e("id", "msgc" + index); if (state == 1) { if (index == '1') { sdId = SDcardId; tv_total_capacity.setText(String .valueOf(total_capacity) + "M"); tv_sd_remainning_capacity.setText(String .valueOf(remain_capacity) + "M"); showSDImg(); } else if (index == '0') { usbId = SDcardId; } } else { Intent back = new Intent(); back.setAction(Constants.Action.REPLACE_MAIN_CONTROL); mContext.sendBroadcast(back); Toast.makeText(mContext, "SD卡不存在", Toast.LENGTH_SHORT).show(); } } else if (intent.getAction().equals( Constants.P2P.ACK_GET_SD_CARD_FORMAT)) { int result = intent.getIntExtra("result", -1); if (result == Constants.P2P_SET.ACK_RESULT.ACK_PWD_ERROR) { Intent i = new Intent(); i.setAction(Constants.Action.CONTROL_SETTING_PWD_ERROR); mContext.sendBroadcast(i); } else if (result == Constants.P2P_SET.ACK_RESULT.ACK_NET_ERROR) { Log.e("my", "net error resend:get npc time"); P2PHandler.getInstance().setSdFormat(idOrIp, contact.contactPassword, sdId); } } else if (intent.getAction().equals( Constants.P2P.RET_GET_SD_CARD_FORMAT)) { int result = intent.getIntExtra("result", -1); if (result == Constants.P2P_SET.SD_FORMAT.SD_CARD_SUCCESS) { Toast.makeText(mContext, "SD卡格式化成功", Toast.LENGTH_SHORT).show(); } else if (result == Constants.P2P_SET.SD_FORMAT.SD_CARD_FAIL) { Toast.makeText(mContext, "SD卡格式化失败", Toast.LENGTH_SHORT).show(); } else if (result == Constants.P2P_SET.SD_FORMAT.SD_NO_EXIST) { Toast.makeText(mContext, "SD卡不存在", Toast.LENGTH_SHORT).show(); } showSDImg(); } else if (intent.getAction().equals( Constants.P2P.RET_GET_USB_CAPACITY)) { int total_capacity = intent.getIntExtra("total_capacity", -1); int remain_capacity = intent.getIntExtra("remain_capacity", -1); int state = intent.getIntExtra("state", -1); SDcardId = intent.getIntExtra("SDcardID", -1); String id = Integer.toBinaryString(SDcardId); Log.e("id", "msga" + id); while (id.length() < 8) { id = "0" + id; } char index = id.charAt(3); Log.e("id", "msgb" + id); Log.e("id", "msgc" + index); if (state == 1) { if (index == '1') { sdId = SDcardId; tv_total_capacity.setText(String .valueOf(total_capacity) + "M"); tv_sd_remainning_capacity.setText(String .valueOf(remain_capacity) + "M"); showSDImg(); } else if (index == '0') { usbId = SDcardId; } } else { count++; if (contact.contactType == P2PValue.DeviceType.IPC) { if (count == 1) { Intent back = new Intent(); back.setAction(Constants.Action.REPLACE_MAIN_CONTROL); mContext.sendBroadcast(back); Toast.makeText(mContext, "SD卡不存在", Toast.LENGTH_SHORT).show(); } } else { if (count == 2) { Intent back = new Intent(); back.setAction(Constants.Action.REPLACE_MAIN_CONTROL); mContext.sendBroadcast(back); Toast.makeText(mContext, "SD卡不存在", Toast.LENGTH_SHORT).show(); } } } } else if (intent.getAction().equals( Constants.P2P.RET_DEVICE_NOT_SUPPORT)) { Intent back = new Intent(); back.setAction(Constants.Action.REPLACE_MAIN_CONTROL); mContext.sendBroadcast(back); Toast.makeText(mContext, "不支持", Toast.LENGTH_SHORT).show(); } } }; public void showSDProgress() { format_icon.setVisibility(ImageView.GONE); progress_format.setVisibility(progress_format.VISIBLE); sd_format.setClickable(false); } public String createCommand(String bCommandType, String bOption, String SDCardCounts) { return bCommandType + bOption + SDCardCounts; } public void showSDImg() { format_icon.setVisibility(ImageView.VISIBLE); progress_format.setVisibility(progress_format.GONE); sd_format.setClickable(true); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch (arg0.getId()) { case R.id.sd_format: final NormalDialog dialog = new NormalDialog(mContext, mContext .getResources().getString(R.string.sd_formatting), mContext .getResources().getString(R.string.delete_sd_remind), mContext.getResources().getString(R.string.ensure), mContext.getResources().getString(R.string.cancel)); dialog.setOnButtonOkListener(new NormalDialog.OnButtonOkListener() { @Override public void onClick() { // TODO Auto-generated method stub P2PHandler.getInstance().setSdFormat(idOrIp, contact.contactPassword, sdId); Log.e("SDcardId", "SDcardId" + SDcardId); } }); dialog.setOnButtonCancelListener(new NormalDialog.OnButtonCancelListener() { @Override public void onClick() { // TODO Auto-generated method stub showSDImg(); dialog.dismiss(); } }); dialog.showNormalDialog(); dialog.setCanceledOnTouchOutside(false); showSDProgress(); break; default: break; } } @Override public void onDestroy() { super.onDestroy(); if (isRegFilter == true) { mContext.unregisterReceiver(br); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK){ Intent i = new Intent(mContext,ApMonitorActivity.class); i.putExtra("contact",contact); startActivity(i); finish(); } return super.onKeyDown(keyCode, event); } }
4ca90d62144219a7bdd88ddb0bed3e3b841fdad8
fca85957a02111c5313ca7acb6b6e6c7a26749ed
/src/main/java/pers/jess/template/common/util/StringRandomUtil.java
671dcb2d991fd9d8767cec0b4668bc1a621611b0
[]
no_license
beginsto/jxwx
8bb0b466c6ceb5eb67c5946b547e055567be5b35
9db169a845c15755bf89364de6c566d5f9495f3a
refs/heads/master
2021-09-09T05:27:35.213588
2018-03-14T00:55:59
2018-03-14T00:55:59
125,134,303
0
0
null
null
null
null
UTF-8
Java
false
false
2,593
java
package pers.jess.template.common.util; import java.util.Random; public class StringRandomUtil { private static Random random = new Random(); /** * 随机 纯数字字符串 * @param length 自定义长度 * @return */ public static String numberRandom(int length){ String val = ""; for(int i = 0; i < length; i++) { val += String.valueOf(random.nextInt(10)); } return val; } /** * 随机小写字符串 * @param length 自定义长度 * @return */ public static String charLowercaseRandom(int length){ String val = ""; for(int i = 0; i < length; i++) { val += (char)(random.nextInt(26) + 97); } return val; } /** * 随机大写字符串 * @param length 自定义长度 * @return */ public static String charCapitalRandom(int length){ String val = ""; for(int i = 0; i < length; i++) { val += (char)(random.nextInt(26) + 65); } return val; } /** * 随机大小写混合字符串 * @param length 自定义长度 * @return */ public static String charCapitalAndLowercaseRandom(int length){ String val = ""; for(int i = 0; i < length; i++) { //输出是大写字母还是小写字母 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; val += (char)(random.nextInt(26) + temp); } return val; } /** * 随机 数字 大小写 字符串 * @param length 自定义长度 * @return */ public static String stringRandom(int length) { String val = ""; for(int i = 0; i < length; i++) { String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; //输出字母还是数字 if( "char".equalsIgnoreCase(charOrNum) ) { //输出是大写字母还是小写字母 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97; val += (char)(random.nextInt(26) + temp); } else if( "num".equalsIgnoreCase(charOrNum) ) { val += String.valueOf(random.nextInt(10)); } } return val; } public static void main(String[] args){ System.out.println(numberRandom(26)); System.out.println(charLowercaseRandom(26)); System.out.println(charCapitalRandom(26)); System.out.println(charCapitalAndLowercaseRandom(26)); System.out.println(stringRandom(26)); } }
8382257ca580dc90546606dab3b2feb84f9d02fa
27835b326965575e47e91e7089b918b642a91247
/src/by/it/malishevskiy/jd01_02/Test_jd01_02.java
2b159efae6081f8abe841d108f30dfc034fe4b66
[]
no_license
s-karpovich/JD2018-11-13
c3bc03dc6268d52fd8372641b12c341aa3a3e11f
5f5be48cb1619810950a629c47e46d186bf1ad93
refs/heads/master
2020-04-07T19:54:15.964875
2019-04-01T00:37:29
2019-04-01T00:37:29
158,667,895
2
0
null
2018-11-22T08:40:16
2018-11-22T08:40:16
null
UTF-8
Java
false
false
18,071
java
package by.it.malishevskiy.jd01_02; import org.junit.Test; import java.io.*; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import static org.junit.Assert.*; @SuppressWarnings("all") //поставьте курсор на следующую строку и нажмите Ctrl+Shift+F10 public class Test_jd01_02 { @Test(timeout = 5000) public void testTaskA() throws Exception { System.out.println("\n\nПроверка на минимум и максимум"); checkMethod("TaskA", "static step1", int[].class); run("-1 2 3 4 567 567 4 3 2 -1 4 4").include("-1 567"); System.out.println("\n\nПроверка на вывод значений меньше среднего"); checkMethod("TaskA", "static step2", int[].class); run("-1 22 33 44 567 567 44 33 22 -1 4 4") .include("-1").include("22").include("33").include("44"); System.out.println("\n\nПроверка на индексы минимума"); checkMethod("TaskA", "static step3", int[].class); run("-1 22 33 44 567 567 44 33 22 -1 4 4").include("9 0"); } @Test(timeout = 5000) public void testTaskAstep1_MinMax__TaskA() throws Exception { Test_jd01_02 ok = run("", false); Method m = checkMethod(ok.aClass.getSimpleName(), "static step1", int[].class); System.out.println("Проверка на массиве -1, 2, 3, 4, 567, 567, 4, 3, 2, -1, 4, 4"); m.invoke(null, new int[]{-1, 2, 3, 4, 567, 567, 4, 3, 2, -1, 4, 4}); ok.include("").include("-1 567"); } @Test(timeout = 5000) public void testTaskAstep2_Avg__TaskA() throws Exception { Test_jd01_02 ok = run("", false); Method m = checkMethod(ok.aClass.getSimpleName(), "static step2", int[].class); System.out.println("Проверка на массиве -1, 22, 30+3, 44, 500+67, 500+67, 44, 30+3, 22, -1, 4, 4"); m.invoke(null, new int[]{-1, 22, 33, 44, 567, 567, 44, 33, 22, -1, 4, 4}); ok.include("").include("-1") .include("1").include("2").include("3").include("4") .include("22").include("33").include("44").exclude("567"); } @Test(timeout = 5000) public void testTaskAstep3_IndexMinMax__TaskA() throws Exception { Test_jd01_02 ok = run("", false); Method m = checkMethod(ok.aClass.getSimpleName(), "static step3", int[].class); System.out.println("Проверка на массиве -1, 22, 33, 44, 567, 567, 44, 33, 22, -1, 4, 4"); m.invoke(null, new int[]{-1, 22, 33, 44, 567, 567, 44, 33, 22, -1, 4, 4}); ok.include("").include("9 0"); } @Test(timeout = 5000) public void testTaskB() throws Exception { System.out.println("\n\nПроверка на вывод матрицы 5 x 5"); checkMethod("TaskB", "step1"); run("0 1 2 3") .include("11 12 13 14 15").include("16 17 18 19 20") .include("21 22 23 24 25"); ; System.out.println("\n\nПроверка на ввод номера месяца"); checkMethod("TaskB", "step2", int.class); run("0 2 3 4").include("нет такого месяца"); run("1 2 3 4").include("январь"); run("2 2 3 4").include("февраль"); run("3 2 3 4").include("март"); run("4 2 3 4").include("апрель"); run("5 2 3 4").include("май"); run("6 2 3 4").include("июнь"); run("7 2 3 4").include("июль"); run("8 2 3 4").include("август"); run("9 2 3 4").include("сентябрь"); run("10 2 3 4").include("октябрь"); run("11 2 3 4").include("ноябрь"); run("12 2 3 4").include("декабрь"); run("13 2 3 4").include("нет такого месяца"); System.out.println("\n\nПроверка на решение квадратного уравнения"); checkMethod("TaskB", "step3", double.class, double.class, double.class); run("0 2 4 2").include("-1"); run("0 2 4 0").include("0.0").include("-2.0"); run("0 2 4 4").include("корней нет"); } @Test(timeout = 5000) public void testTaskBstep1_Loop__TaskB() throws Exception { Test_jd01_02 ok = run("", false); Method m = checkMethod(ok.aClass.getSimpleName(), "static step1"); m.invoke(null); ok.include("11 12 13 14 15").include("16 17 18 19 20").include("21 22 23 24 25"); } @Test(timeout = 5000) public void testTaskBstep2_Switch__TaskB() throws Exception { Test_jd01_02 ok = run("", false); Method m = checkMethod(ok.aClass.getSimpleName(), "static step2", int.class); m.invoke(null, 0); ok.include("нет такого месяца"); m.invoke(null, 1); ok.include("январь"); m.invoke(null, 2); ok.include("февраль"); m.invoke(null, 3); ok.include("март"); m.invoke(null, 4); ok.include("апрель"); m.invoke(null, 5); ok.include("май"); m.invoke(null, 6); ok.include("июнь"); m.invoke(null, 7); ok.include("июль"); m.invoke(null, 8); ok.include("август"); m.invoke(null, 9); ok.include("сентябрь"); m.invoke(null, 10); ok.include("октябрь"); m.invoke(null, 11); ok.include("ноябрь"); m.invoke(null, 12); ok.include("декабрь"); m.invoke(null, 13); ok.include("нет такого месяца"); } @Test(timeout = 5000) public void testTaskBstep3_QEquation__TaskB() throws Exception { Test_jd01_02 ok = run("", false); Method m = checkMethod(ok.aClass.getSimpleName(), "static step3", double.class, double.class, double.class); System.out.println("Квадратное уравление:"); System.out.println("для a=2, для b=4, для c=2, ожидается один корень: минус 1"); m.invoke(null, 2, 4, 2); ok.include("-1"); System.out.println("для a=1, для b=-1, для c=-2, ожидается два корня: минус один и два "); m.invoke(null, 1, -1, -2); ok.include("-1").include("2"); System.out.println("для a=2, для b=4, для c=4, ожидается решение без корней"); m.invoke(null, 2, 4, 4); ok.include("корней нет"); } @Test(timeout = 5000) public void testTaskC() throws Exception { System.out.println("\n\nПроверка на создание массива TaskC.step1"); checkMethod("TaskC", "step1", int.class); run("3").include("-3").include("3"); run("4").include("-4").include("4"); Test_jd01_02 ok = run("5").include("-5").include("5"); System.out.println("\nПроверка на сумму элементов TaskC.step2"); checkMethod("TaskC", "step2", int[][].class); int[][] m4 = {{1, -2, -2, 6}, {-1, 2, -2, 2}, {-2, -2, -6, -2}, {1, 2, -2, 6}}; Method m = ok.aClass.getDeclaredMethod("step2", m4.getClass()); int sum = (int) ok.invoke(m, null, new Object[]{m4}); assertEquals("Неверная сумма в step2", -6, sum); System.out.println("\nПроверка на удаление максимума TaskC.step3"); checkMethod("TaskC", "step3", int[][].class); m = ok.aClass.getDeclaredMethod("step3", int[][].class); int[][] res = (int[][]) ok.invoke(m, null, new Object[]{m4}); int[][] expectmas = {{-1, 2, -2}, {-2, -2, -6}}; assertArrayEquals("Не найден ожидаемый массив {{-1,2,-2},{-2,-2,-6}}", expectmas, res); } @Test(timeout = 5000) public void testTaskCstep1_IndexMinMax__TaskC() throws Exception { Test_jd01_02 ok = run("", false); Method m = checkMethod(ok.aClass.getSimpleName(), "static step1", int.class); int[][] mas = (int[][]) m.invoke(null, 5); boolean min = false; boolean max = false; for (int[] row : mas) for (int i : row) { if (i == -5) min = true; if (i == 5) max = true; } if (!max || !min) { fail("В массиве нет максимума 5 или минимума -5"); } } @Test(timeout = 5000) public void testTaskCstep2_Sum__TaskC() throws Exception { Test_jd01_02 ok = run("", false); int[][] m4 = {{1, -2, -2, 6}, {-1, 2, -2, 2}, {-2, -2, -6, -2}, {1, 2, -2, 6}}; Method m = checkMethod(ok.aClass.getSimpleName(), "static step2", int[][].class); int sum = (int) ok.invoke(m, null, new Object[]{m4}); assertEquals("Неверная сумма в step2", -6, sum); } @Test(timeout = 5000) public void testTaskCstep3_DeleteMax__TaskC() throws Exception { Test_jd01_02 ok = run("", false); int[][] m4 = {{1, -2, -2, 6}, {-1, 2, -2, 2}, {-2, -2, -6, -2}, {1, 2, -2, 6}}; Method m = checkMethod(ok.aClass.getSimpleName(), "static step3", int[][].class); int[][] actualmas = (int[][]) ok.invoke(m, null, new Object[]{m4}); int[][] expectmas = {{-1, 2, -2}, {-2, -2, -6}}; for (int i = 0; i < actualmas.length; i++) { System.out.println("Проверка строки " + i); System.out.println(" Ожидается: " + Arrays.toString(expectmas[i])); System.out.println("Из метода получено: " + Arrays.toString(actualmas[i])); assertArrayEquals("Метод работает некорректно", expectmas[i], actualmas[i]); } System.out.println("Проверка завершена успешно!"); } /* =========================================================================================================== НИЖЕ ВСПОМОГАТЕЛЬНЫЙ КОД ТЕСТОВ. НЕ МЕНЯЙТЕ В ЭТОМ ФАЙЛЕ НИЧЕГО. Но изучить как он работает - можно, это всегда будет полезно. =========================================================================================================== */ //------------------------------- методы ---------------------------------------------------------- private Class findClass(String SimpleName) { String full = this.getClass().getName(); String dogPath = full.replace(this.getClass().getSimpleName(), SimpleName); try { return Class.forName(dogPath); } catch (ClassNotFoundException e) { fail("\nERROR:Тест не пройден. Класс " + SimpleName + " не найден."); } return null; } private Method checkMethod(String className, String methodName, Class<?>... parameters) throws Exception { Class aClass = this.findClass(className); try { methodName = methodName.trim(); Method m; if (methodName.startsWith("static")) { methodName = methodName.replace("static", "").trim(); m = aClass.getDeclaredMethod(methodName, parameters); if ((m.getModifiers() & Modifier.STATIC) != Modifier.STATIC) { fail("\nERROR:Метод " + m.getName() + " должен быть статическим"); } } else m = aClass.getDeclaredMethod(methodName, parameters); m.setAccessible(true); return m; } catch (NoSuchMethodException e) { System.err.println("\nERROR:Не найден метод " + methodName + " либо у него неверная сигнатура"); System.err.println("ERROR:Ожидаемый класс: " + className); System.err.println("ERROR:Ожидаемый метод: " + methodName); return null; } } private Method findMethod(Class<?> cl, String name, Class... param) { try { return cl.getDeclaredMethod(name, param); } catch (NoSuchMethodException e) { fail("\nERROR:Тест не пройден. Метод " + cl.getName() + "." + name + " не найден\n"); } return null; } private Object invoke(Method method, Object o, Object... value) { try { method.setAccessible(true); return method.invoke(o, value); } catch (Exception e) { System.out.println(e.toString()); fail("\nERROR:Не удалось вызвать метод " + method.getName() + "\n"); } return null; } //метод находит и создает класс для тестирования //по имени вызывающего его метода, testTaskA1 будет работать с TaskA1 private static Test_jd01_02 run(String in) { return run(in, true); } private static Test_jd01_02 run(String in, boolean runMain) { Throwable t = new Throwable(); StackTraceElement trace[] = t.getStackTrace(); StackTraceElement element; int i = 0; do { element = trace[i++]; } while (!element.getMethodName().contains("test")); String[] path = element.getClassName().split("\\."); String nameTestMethod = element.getMethodName(); String clName = nameTestMethod.replace("test", ""); clName = clName.replaceFirst(".+__", ""); clName = element.getClassName().replace(path[path.length - 1], clName); System.out.println("\n---------------------------------------------"); System.out.println("Старт теста для " + clName); if (!in.isEmpty()) System.out.println("input:" + in); System.out.println("---------------------------------------------"); return new Test_jd01_02(clName, in, runMain); } //------------------------------- тест ---------------------------------------------------------- public Test_jd01_02() { //Конструктор тестов } //переменные теста private String className; private Class<?> aClass; private PrintStream oldOut = System.out; //исходный поток вывода private PrintStream newOut; //поле для перехвата потока вывода private StringWriter strOut = new StringWriter(); //накопитель строки вывода //Основной конструктор тестов private Test_jd01_02(String className, String in, boolean runMain) { //this.className = className; aClass = null; try { aClass = Class.forName(className); this.className = className; } catch (ClassNotFoundException e) { fail("ERROR:Не найден класс " + className + "/n"); } InputStream reader = new ByteArrayInputStream(in.getBytes()); System.setIn(reader); //перехват стандартного ввода System.setOut(newOut); //перехват стандартного вывода if (runMain) //если нужно запускать, то запустим, иначе оставим только вывод try { Class[] argTypes = new Class[]{String[].class}; Method main = aClass.getDeclaredMethod("main", argTypes); main.invoke(null, (Object) new String[]{}); System.setOut(oldOut); //возврат вывода, нужен, только если был запуск } catch (Exception x) { x.printStackTrace(); } } //проверка вывода private Test_jd01_02 is(String str) { assertTrue("ERROR:Ожидается такой вывод:\n<---начало---->\n" + str + "<---конец--->", strOut.toString().equals(str)); return this; } private Test_jd01_02 include(String str) { assertTrue("ERROR:Строка не найдена: " + str + "\n", strOut.toString().contains(str)); return this; } private Test_jd01_02 exclude(String str) { assertTrue("ERROR:Лишние данные в выводе: " + str + "\n", !strOut.toString().contains(str)); return this; } //логический блок перехвата вывода { newOut = new PrintStream(new OutputStream() { private byte bytes[] = new byte[1]; private int pos = 0; @Override public void write(int b) throws IOException { if (pos==0 && b=='\r') //пропуск \r (чтобы win mac и linux одинаково работали return; if (pos == 0) { //определим кодировку https://ru.wikipedia.org/wiki/UTF-8 if ((b & 0b11110000) == 0b11110000) bytes = new byte[4]; else if ((b & 0b11100000) == 0b11100000) bytes = new byte[3]; else if ((b & 0b11000000) == 0b11000000) bytes = new byte[2]; else bytes = new byte[1]; } bytes[pos++] = (byte) b; if (pos == bytes.length) { //символ готов String s = new String(bytes); //соберем весь символ strOut.append(s); //запомним вывод для теста oldOut.append(s); //копию в обычный вывод pos = 0; //готовим новый символ } } }); } }
a841eebcf906834fd8e36f7557f03511103dd15e
cd602223060180939d6eb2a02729f1bfa35a4fa5
/app/src/main/java/com/chunsun/redenvelope/app/MainApplication.java
c6a3de38b686b7d72df3834fb4bdb2fdfe47846d
[]
no_license
himon/ChunSunRE
25c351ea2385b9c7c0ef494e5604a09fa315c07e
44cfdec4ad97eaecc9913f48dcec278aba84f963
refs/heads/master
2021-01-18T22:09:20.095786
2016-04-28T14:25:01
2016-04-28T14:25:01
41,711,612
3
0
null
null
null
null
UTF-8
Java
false
false
11,610
java
package com.chunsun.redenvelope.app; import android.app.Application; import android.app.Service; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.Build; import android.os.Vibrator; import android.telephony.TelephonyManager; import android.text.TextUtils; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.chunsun.redenvelope.R; import com.chunsun.redenvelope.app.context.LoginContext; import com.chunsun.redenvelope.app.state.impl.LoginState; import com.chunsun.redenvelope.app.state.impl.LogoutState; import com.chunsun.redenvelope.constants.Constants; import com.chunsun.redenvelope.entities.json.UserInfoEntity; import com.chunsun.redenvelope.event.BaiduMapLocationEvent; import com.chunsun.redenvelope.preference.Preferences; import com.chunsun.redenvelope.utils.AppUtil; import com.chunsun.redenvelope.utils.helper.ImageLoaderHelper; import com.chunsun.redenvelope.utils.manager.AppManager; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import org.json.JSONException; import org.json.JSONObject; import de.greenrobot.event.EventBus; /** * Created by Administrator on 2015/7/16. */ public class MainApplication extends Application { private static MainApplication instance; private UserInfoEntity mUserEntity; private String mImei; private DisplayImageOptions mHeadOptions; private String mShareHost; /** * 百度地图 */ private LocationClient mLocationClient; private MyLocationListener mMyLocationListener; private Vibrator mVibrator; private double mLatitude = 0; private double mLongitude = 0; private String mProvince = "不限"; private String mCity = "不限"; private Preferences mPreferences; /** * app当前版本号 */ private String mAppVersion; public LocationClient getLocationClient() { return mLocationClient; } public String getmShareHost() { return mShareHost; } public void setmShareHost(String mShareHost) { this.mShareHost = mShareHost; } /** * 获取用户信息 * * @return */ public UserInfoEntity getUserEntity() { return mUserEntity; } /** * 设置用户信息 * * @param entity */ public void setmUserEntity(UserInfoEntity entity) { this.mUserEntity = entity; } /** * 获取Imei码 * * @return */ public String getmImei() { return mImei; } public DisplayImageOptions getHeadOptions() { return mHeadOptions; } /** * 获取当前城市 * * @return */ public String getCity() { return mCity; } /** * 获取当前省份 * * @return */ public String getProvince() { return mProvince; } /** * 获取经度 * * @return */ public double getLongitude() { return mLongitude; } /** * 获取纬度 * * @return */ public double getLatitude() { return mLatitude; } public String getmAppVersion() { return mAppVersion; } public void setmAppVersion(String mAppVersion) { this.mAppVersion = mAppVersion; } /** * 获取MainApplication对象 * * @return */ public static MainApplication getContext() { return instance; } public MainApplication() { instance = this; } @Override public void onCreate() { super.onCreate(); initIMEI(); initHeadOptions(); initBaiduMap(); initUserState(); mAppVersion = AppUtil.getVersion(getContext()); ImageLoader.getInstance().init(ImageLoaderHelper.getInstance(this).getImageLoaderConfiguration(Constants.IMAGE_LOADER_CACHE_PATH)); mPreferences = new Preferences(getApplicationContext()); String province = mPreferences.getProvinceData(); String city = mPreferences.getCityData(); String longitude = mPreferences.getLongitude(); String latitude = mPreferences.getLatitude(); if (!TextUtils.isEmpty(province)) { mProvince = province; } if (!TextUtils.isEmpty(city)) { mCity = city; } if (!TextUtils.isEmpty(longitude)) { mLongitude = Double.parseDouble(longitude); } if (!TextUtils.isEmpty(latitude)) { mLatitude = Double.parseDouble(latitude); } // 全局捕获异常 //MyCrashHandler handler = MyCrashHandler.getInstance(); //Thread.currentThread().setUncaughtExceptionHandler(handler); } /** * 初始化登录状态 */ private void initUserState() { if(TextUtils.isEmpty(new Preferences(this).getToken())){ LoginContext.getLoginContext().setState(new LogoutState()); }else{ LoginContext.getLoginContext().setState(new LoginState()); } } private void initHeadOptions() { mHeadOptions = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.img_default_capture) .showImageForEmptyUri(R.drawable.img_default_head) .showImageOnFail(R.drawable.img_default_head) .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).displayer(new RoundedBitmapDisplayer(20))//为图片添加圆角显示在ImageAware中 .bitmapConfig(Bitmap.Config.RGB_565).build(); } /** * 获取手机信息 * * @return */ public String getPhoneInfomation() { PackageManager manager = getPackageManager(); String systemVersion = Build.VERSION.RELEASE;//系统版本号 String version = "";//软件版本 String channelName = Constants.CHANNEL_PACKAGE_NAME;//渠道地址 String mobile = Build.MODEL;//手机型号 JSONObject jsonObject = new JSONObject(); try { PackageInfo info = manager.getPackageInfo(getPackageName(), 0); version = info.versionName; jsonObject.put("version", version); jsonObject.put("system_name", "android"); jsonObject.put("system_version", systemVersion); jsonObject.put("mobile_model", mobile); jsonObject.put("software_download_channel", channelName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return jsonObject.toString(); } /** * 初始化IMEI码 */ public void initIMEI() { TelephonyManager telephonyManager = (TelephonyManager) this .getSystemService(Context.TELEPHONY_SERVICE); mImei = telephonyManager.getDeviceId(); } public void exitApp() { AppManager.getAppManager().finishAllActivityAndExit(); System.gc(); android.os.Process.killProcess(android.os.Process.myPid()); } /*--------------------------------------------------- 百度地图 -----------------------------------------------------------*/ /** * 初始化百度地图所需的信息 */ public void initBaiduMap() { //声明LocationClient类 mLocationClient = new LocationClient(this.getApplicationContext()); mMyLocationListener = new MyLocationListener(); ////注册监听函数 mLocationClient.registerLocationListener(mMyLocationListener); mVibrator = (Vibrator) getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE); initLocation(); mLocationClient.start(); } /** * 实现实时位置回调监听 */ public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); mProvince = location.getProvince() == null ? "不限" : location.getProvince(); mCity = location.getCity() == null ? "不限" : location.getCity(); mPreferences.setProvinceData(mProvince); mPreferences.setCityData(mCity); mPreferences.setLatitude(mLatitude + ""); mPreferences.setLongitude(mLongitude + ""); if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果 System.out.println("GPS定位结果"); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果 System.out.println("网络定位结果"); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 System.out.println("离线定位结果"); } else if (location.getLocType() == BDLocation.TypeServerError) { System.out.println("服务端网络定位失败,可以反馈IMEI号和大体定位时间到[email protected],会有人追查原因"); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { System.out.println("网络不同导致定位失败,请检查网络是否通畅"); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { System.out.println("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机"); } mLocationClient.stop(); EventBus.getDefault().post(new BaiduMapLocationEvent("")); } } private void initLocation() { LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系, int span = 0; option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要 option.setOpenGps(true);//可选,默认false,设置是否使用gps option.setLocationNotify(false);//可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 option.setIgnoreKillProcess(true);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要 option.setIsNeedLocationDescribe(false);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” option.setIsNeedLocationPoiList(false);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 mLocationClient.setLocOption(option); } }
6537d0b6179b9d4882bf4da8feae3658fb36a1c7
e3dc5dd135b3f1a2be1130e97292eea14bb904e7
/src/JavaOOP/Lesson2/encapsulation/_1_without_encapsulation/Person.java
ae9f92df6fa14781c32ba426587a856e75e9b8cd
[]
no_license
AnatoliyDeveloper/JavaProg
51fd1d626d2e0879542905ffa88c548cdef48308
daa7e335471451f9b55a99de79cb29f13c01f4c0
refs/heads/master
2020-07-30T20:28:11.918200
2016-11-19T11:01:49
2016-11-19T11:01:57
73,621,142
0
0
null
null
null
null
UTF-8
Java
false
false
169
java
package ua.kiev.prog.javaoop.encapsulation._1_without_encapsulation; /** * @author Bohdan Vanchuhov */ public class Person { String name; // field int age; }
4de6cb8677e6aa83d722db8a4567a49031e52a21
5eb95c43cdcb69c1c048d66c68cacd14189c8471
/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/WindowCreditManagerTest.java
a285558ffb6737f6b1a0d876b59e339210a1a710
[ "Apache-2.0", "MIT" ]
permissive
moazbaghdadi/qpid-java-old
eae07c3d7f0e50ef155d195d1ac849224a6352db
b266b647c8525d531b1dfbacd56757977dacd38b
refs/heads/master
2021-01-20T08:37:29.177233
2017-05-03T15:38:07
2017-05-03T15:38:07
90,167,309
0
1
null
null
null
null
UTF-8
Java
false
false
4,310
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.qpid.server.protocol.v0_10; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.apache.qpid.server.transport.ProtocolEngine; import org.apache.qpid.test.utils.QpidTestCase; public class WindowCreditManagerTest extends QpidTestCase { private WindowCreditManager _creditManager; private ProtocolEngine _protocolEngine; protected void setUp() throws Exception { super.setUp(); _protocolEngine = mock(ProtocolEngine.class); when(_protocolEngine.isTransportBlockedForWriting()).thenReturn(false); _creditManager = new WindowCreditManager(0l, 0l); } /** * Tests that after the credit limit is cleared (e.g. from a message.stop command), credit is * restored (e.g. from completed MessageTransfer) without increasing the available credit, and * more credit is added, that the 'used' count is correct and the proper values for bytes * and message credit are returned along with appropriate 'hasCredit' results (QPID-3592). */ public void testRestoreCreditDecrementsUsedCountAfterCreditClear() { assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); //give some message credit _creditManager.addCredit(1, 0); assertFalse("Manager should not 'haveCredit' due to having 0 bytes credit", _creditManager.hasCredit()); assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); //give some bytes credit _creditManager.addCredit(0, 1); assertTrue("Manager should 'haveCredit'", _creditManager.hasCredit()); assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); assertEquals("unexpected credit value", 1, _creditManager.getBytesCredit()); //use all the credit _creditManager.useCreditForMessage(1); assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); //clear credit out (eg from a message.stop command) _creditManager.clearCredit(); assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); //restore credit (e.g the original message transfer command got completed) //this should not increase credit, because it is now limited to 0 _creditManager.restoreCredit(1, 1); assertEquals("unexpected credit value", 0, _creditManager.getBytesCredit()); assertEquals("unexpected credit value", 0, _creditManager.getMessageCredit()); assertFalse("Manager should not 'haveCredit'", _creditManager.hasCredit()); //give more credit to open the window again _creditManager.addCredit(1, 1); assertEquals("unexpected credit value", 1, _creditManager.getBytesCredit()); assertEquals("unexpected credit value", 1, _creditManager.getMessageCredit()); assertTrue("Manager should 'haveCredit'", _creditManager.hasCredit()); } }
e0aab5b314621afb0b7f03a3cc97a8a4789aa92e
1c6ad7fb063db2ae20a0accf1d95857ed766f6d2
/src/main/java/com/zxx/demorepository/test/intercept/annotation/CryptField.java
e0e0fb8816690860f5f9c8af77e45ce763a1afb6
[]
no_license
kamjin1996/DemoRepository
b7857cd98871ccfb05dca69092babe99093d5b54
a87680a6710897f39ebfb7b50f03e2062508be70
refs/heads/master
2023-04-07T02:26:31.684768
2022-12-06T06:46:40
2022-12-06T06:46:40
156,940,034
0
0
null
2023-03-27T22:22:16
2018-11-10T02:29:12
Java
UTF-8
Java
false
false
338
java
package com.zxx.demorepository.test.intercept.annotation; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) public @interface CryptField { String value() default ""; boolean encrypt() default true; boolean decrypt() default true; }
fb84fed979c900a0f518d5e798b4611a7ccee1d9
a157f0f34ed886bfc9f25454814ef164062f7498
/nodecore-ucp/src/main/java/nodecore/api/ucp/commands/server/MiningSubscribe.java
e631b0b05077dd0ef2b047998ea1497c0f22c3b0
[ "MIT" ]
permissive
xagau/nodecore
d49ea1e6f4835d2fad39d547dfa119cd98240b3c
282f03b4296e71432b183bdfb38d066bc0f575e0
refs/heads/master
2022-12-11T08:28:23.312115
2020-02-24T19:30:18
2020-02-24T19:30:18
257,342,239
0
0
NOASSERTION
2020-04-20T16:35:11
2020-04-20T16:35:10
null
UTF-8
Java
false
false
2,937
java
// VeriBlock NodeCore // Copyright 2017-2019 Xenios SEZC // All rights reserved. // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. package nodecore.api.ucp.commands.server; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import nodecore.api.ucp.arguments.UCPArgument; import nodecore.api.ucp.arguments.UCPArgumentFrequencyMS; import nodecore.api.ucp.arguments.UCPArgumentRequestID; import nodecore.api.ucp.commands.UCPCommand; import nodecore.api.ucp.commands.UCPServerCommand; import org.veriblock.core.types.Pair; import java.util.ArrayList; public class MiningSubscribe extends UCPServerCommand { private final UCPCommand.Command command = Command.MINING_SUBSCRIBE; // Not static for serialization purposes // Required private final UCPArgumentRequestID request_id; private final UCPArgumentFrequencyMS update_frequency_ms; public MiningSubscribe(UCPArgument ... arguments) { ArrayList<Pair<String, UCPArgument.UCPType>> pattern = command.getPattern(); if (arguments.length != pattern.size()) { throw new IllegalArgumentException(getClass().getCanonicalName() + "'s constructor cannot be called without exactly " + pattern.size() + " UCPArguments!"); } for (int i = 0; i < pattern.size(); i++) { if (arguments[i].getType() != pattern.get(i).getSecond()) { throw new IllegalArgumentException(getClass().getCanonicalName() + "'s constructor cannot be called with a argument at index " + i + " which is a " + arguments[i].getType() + " instead of a " + pattern.get(i).getSecond() + "!"); } } this.request_id = (UCPArgumentRequestID)arguments[0]; this.update_frequency_ms = (UCPArgumentFrequencyMS)arguments[1]; } public MiningSubscribe(int request_id, int update_frequency_ms) { this.request_id = new UCPArgumentRequestID(request_id); this.update_frequency_ms = new UCPArgumentFrequencyMS(update_frequency_ms); } public static MiningSubscribe reconstitute(String commandLine) { if (commandLine == null) { throw new IllegalArgumentException(new Exception().getStackTrace()[0].getClassName() + "'s reconstitute cannot be called with a null commandLine!"); } GsonBuilder deserializer = new GsonBuilder(); deserializer.registerTypeAdapter(MiningSubscribe.class, new MiningSubscribeDeserializer()); return deserializer.create().fromJson(commandLine, MiningSubscribe.class); } public int getRequestId() { return request_id.getData(); } public int getUpdateFrequencyMS() { return update_frequency_ms.getData(); } public String compileCommand() { return new Gson().toJson(this); } }
ff2d4e816349be248f9e504eda471a17c995ab20
4de7d01600423e57ac446d3d04f6762f61381576
/Java_05/src/com/biz/control/For_05.java
0d410e14b2f91824bd01e89fc3b35e1cbb333ec0
[]
no_license
smskit726/Biz_506_2020_05_Java
332112b3bbe762726c7f27e5334d9f69d7c738c9
0a45a6f3d0eee9f0635828321bf9a1573506126e
refs/heads/master
2022-12-08T11:57:24.082378
2020-09-04T05:57:37
2020-09-04T05:57:37
265,504,163
0
0
null
null
null
null
UTF-8
Java
false
false
2,199
java
package com.biz.control; public class For_05 { public static void main(String[] args) { int num = 0; int sum = 0; for(;;) { num++; sum+=num; //sum = sum + num 의 축약형 명령문 if(num >= 10) { break; } } System.out.println("결과 : " + sum); sum = 0; num = 0; for(;;) { num++; sum+=num; //sum = sum + num 의 축약형 명령문 if(num < 10) { } else { break; } } System.out.println("결과 : " + sum); /* * for( ; ;) 명령문의 두번째 세미콜론(;) 앞의 연산식 * for ( ; 조건문; ) * 조건문의 결과값이 true이면 {} 내의 명령문을 실행하고 결과값이 false이면 더이상 반복하지 않고 for명령문을 종료한다. * * 조건문은 * if(조건) { * } else { * break; * } * 와 같은 역할을 수행한다. */ sum = 0; num = 0; for(; num < 10 ;) { num++; sum+=num; //sum = sum + num 의 축약형 명령문 } System.out.println("결과 : " + sum); /* * for( ; ;) 명령문의 첫번째 세미콜론(;) 앞의 명령 * for(초기화코드; 조건문; ) * 초기화 코드는 위에서 선언되어 사용중인 변수값을 clear하는 명령문을 넣을 수 있다. */ // sum = 0; // num = 0; for(num=0, sum=0; num < 10;) { num++; sum+=num; //sum = sum + num 의 축약형 명령문 } System.out.println("결과 : " + sum); /* * for( ; ; ) 명령문의 세번째 명령문 * for( 초기화코드; 조건문; 증감문) * * 1. for()명령을 만나면 * 2. 초기화 명령을 무조건 실행한다. (단, 한번만) * 3. 조건문을 실행하여 결과가 true이면 {} 명령문을 실행한다. * 4. {} 명령문을 실행한 후 for()명령문으로 이동하여 * 5. 증감(num++)명령문을 실행한다. * 6. 다시 조건문을 실행하여 결과가 true인지 검사한다. * * 그리고 계속하여 반복하거나, 중단한다. */ for(num=0, sum=0; num < 10; num++) { sum+=num; //sum = sum + num 의 축약형 명령문 } System.out.println("결과 : " + sum); } }
9b7efde516a04f248243f179817023c1a46c8932
40fffc37c379a71c47e45a10f1884ca0b81a4184
/TellMe/app/src/main/java/com/kutztown/tellme/DisplayGuestMain.java
0d596edbfe6181af23279c9784f1eb05d8cf5710
[]
no_license
zkern870/TellMe
32f7ec4b350fc75ea1b7ed84f4bca8d2c40b489b
b1f30b3cfb1ce784281a6d8abb4ba452acc54b72
refs/heads/master
2021-01-10T01:46:41.147060
2016-02-09T00:23:25
2016-02-09T00:23:25
50,141,363
0
1
null
2016-01-22T02:33:55
2016-01-21T22:34:09
null
UTF-8
Java
false
false
1,203
java
package com.kutztown.tellme; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; public class DisplayGuestMain extends AppCompatActivity { /** * This will be called when the Tell Me button is clicked from the display * guest activity. It will send to a news feed activity. * @param view */ public void sendGuestNewsFeed (View view){ Intent intent = new Intent(this, sendGuestNewsFeed.class); startActivity(intent); } public void sendGuestFoodFeed (View view ) { Intent intent1 = new Intent(this, sendGuestFeedMe.class); startActivity(intent1); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_guest_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } }
b9d8f9a02268823e53a29e7e763f71e4e0c6b506
8e7ec69aa0ba3cd22fea3e909de03c6886aa1f12
/DataShow/src/main/java/com/tr/domain/ShowErrorEnum.java
21b9c8c13f9fe50f0c88dd1f16d35d08f9516bdb
[]
no_license
MOIPA/JavaEE
411ddfe81fe8c9673d374cb3cd125b34fc59b6c9
9e670e95dae29eb874475739a14929c03dd72b6b
refs/heads/master
2020-03-11T08:18:19.653909
2019-05-10T06:00:05
2019-05-10T06:00:05
129,880,351
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package com.tr.domain; public enum ShowErrorEnum { EMPTY_SHOE(10001, "No Shoe Data"), EMPTY_DRESS(20001, "No Dress Data"); private int errorCode; private String errorMessage; ShowErrorEnum(int errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
9574394507dbe50ce14b13d660c74d8dee69065c
2bf18f00081f9701d45313e205251bb93c291bff
/src/main/java/com/mateusz/project/domain/BookDto.java
b77f94aaf60e69b9b8ba66526afbbece65f4b4fb
[]
no_license
MateuszKupiec/project
9d0839e8ffb454093671fd535c347aa3ce422357
0a653c92595b09044daa7ccbf359738b4a3b1cac
refs/heads/master
2023-08-13T00:25:48.356457
2021-10-12T16:37:50
2021-10-12T16:37:50
416,009,105
0
0
null
null
null
null
UTF-8
Java
false
false
567
java
package com.mateusz.project.domain; public class BookDto { private String title; private String author; public BookDto(String title, String author) { this.title = title; this.author = author; } BookDto() { } public String getTitle() { return title; } public String getAuthor() { return author; } @Override public String toString() { return "BookDto{" + "title='" + title + '\'' + ", author='" + author + '\'' + '}'; } }