blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
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
listlengths
1
1
author_id
stringlengths
0
313
083c599516da0bcee63e154e1cbfda41c76fbcaf
bc95261e278f998a677a2b38119918062f11b180
/src/Dao/clienteDao.java
a06c744abf0f59bfcdfe2be5831b95a45b4b6972
[]
no_license
wanosoft/PAPSIS2016
468ca9e9d961b9b93f4c7359db30fc0a89e32c5a
1bd972eed9841a7cf996d0080c5d581754562017
refs/heads/master
2020-04-05T23:14:51.706472
2016-12-11T16:26:30
2016-12-11T16:26:30
65,874,086
0
0
null
null
null
null
UTF-8
Java
false
false
807
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 Dao; import To.clienteTo; import java.sql.CallableStatement; import java.sql.Connection; import sql.conexion; /** * * @author WANOSOFT */ public class clienteDao { Connection connection; public void registrarClienteFactura(clienteTo to) throws Exception { connection = conexion.getInstance().getConnection(); CallableStatement cs = connection.prepareCall("CALL Cliente_insertar(?,?,?)"); cs.setString(1, to.getDni()); cs.setString(2, to.getApellidos()); cs.setString(3, to.getDireccion()); cs.execute(); } }
[ "davic@192.168.1.67" ]
davic@192.168.1.67
456f551d60bec3e627375d699a5088f1d8f43a51
8d8f0ba7fecdffedb6c425f8f3c58457502d4fa1
/src/cz/dat/oots/util/Matrix4.java
1cdcd9d2b0d0451138cb44ee7a742185acdde0ae
[]
no_license
Arayn/blocks
333e9d6ddce3fe4dfd4afe0b086c058ac606a771
20ceb15a9c1ef890ebb6445de0891a58a45e5ec9
refs/heads/master
2021-01-24T00:24:19.409136
2016-06-18T13:14:29
2016-06-18T13:14:29
61,205,286
0
0
null
2016-06-15T12:11:17
2016-06-15T12:11:16
null
UTF-8
Java
false
false
9,157
java
package cz.dat.oots.util; import java.nio.FloatBuffer; public final class Matrix4 { private float[][] m; public Matrix4() { m = new float[4][4]; } public float[][] getM() { return m; } public float get(int x, int y) { return m[x][y]; } public void set(int x, int y, float value) { m[x][y] = value; } public Matrix4 mul(Matrix4 r) { Matrix4 res = new Matrix4(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { res.set(i, j, m[i][0] * r.get(0, j) + m[i][1] * r.get(1, j) + m[i][2] * r.get(2, j) + m[i][3] * r.get(3, j)); } } return res; } public Matrix4 copy() { return new Matrix4().set(m); } public Matrix4 set(Matrix4 m) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { this.m[i][j] = m.get(i, j); } } return this; } public Matrix4 set(float[][] m) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { this.m[i][j] = m[i][j]; } } return this; } public Matrix4 initIdentity() { m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[0][3] = 0; m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[1][3] = 0; m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; m[2][3] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; return this; } public Matrix4 initTranslation(float x, float y, float z) { m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[0][3] = x; m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[1][3] = y; m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; m[2][3] = z; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; return this; } public Matrix4 initRotation(float x, float y, float z) { Matrix4 rx = new Matrix4(); Matrix4 ry = new Matrix4(); Matrix4 rz = new Matrix4(); x = (float) Math.toRadians(x); y = (float) Math.toRadians(y); z = (float) Math.toRadians(z); rz.m[0][0] = (float) Math.cos(z); rz.m[0][1] = (float) -Math.sin(z); rz.m[0][2] = 0; rz.m[0][3] = 0; rz.m[1][0] = (float) Math.sin(z); rz.m[1][1] = (float) Math.cos(z); rz.m[1][2] = 0; rz.m[1][3] = 0; rz.m[2][0] = 0; rz.m[2][1] = 0; rz.m[2][2] = 1; rz.m[2][3] = 0; rz.m[3][0] = 0; rz.m[3][1] = 0; rz.m[3][2] = 0; rz.m[3][3] = 1; rx.m[0][0] = 1; rx.m[0][1] = 0; rx.m[0][2] = 0; rx.m[0][3] = 0; rx.m[1][0] = 0; rx.m[1][1] = (float) Math.cos(x); rx.m[1][2] = (float) -Math.sin(x); rx.m[1][3] = 0; rx.m[2][0] = 0; rx.m[2][1] = (float) Math.sin(x); rx.m[2][2] = (float) Math.cos(x); rx.m[2][3] = 0; rx.m[3][0] = 0; rx.m[3][1] = 0; rx.m[3][2] = 0; rx.m[3][3] = 1; ry.m[0][0] = (float) Math.cos(y); ry.m[0][1] = 0; ry.m[0][2] = (float) -Math.sin(y); ry.m[0][3] = 0; ry.m[1][0] = 0; ry.m[1][1] = 1; ry.m[1][2] = 0; ry.m[1][3] = 0; ry.m[2][0] = (float) Math.sin(y); ry.m[2][1] = 0; ry.m[2][2] = (float) Math.cos(y); ry.m[2][3] = 0; ry.m[3][0] = 0; ry.m[3][1] = 0; ry.m[3][2] = 0; ry.m[3][3] = 1; m = rz.mul(ry.mul(rx)).getM(); return this; } public Matrix4 initScale(float x, float y, float z) { m[0][0] = x; m[0][1] = 0; m[0][2] = 0; m[0][3] = 0; m[1][0] = 0; m[1][1] = y; m[1][2] = 0; m[1][3] = 0; m[2][0] = 0; m[2][1] = 0; m[2][2] = z; m[2][3] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; return this; } public Matrix4 initPerspective(float fov, float aspectRatio, float zNear, float zFar) { float tanHalfFOV = (float) Math.tan(fov / 2); float zRange = zNear - zFar; m[0][0] = 1.0f / (tanHalfFOV * aspectRatio); m[0][1] = 0; m[0][2] = 0; m[0][3] = 0; m[1][0] = 0; m[1][1] = 1.0f / tanHalfFOV; m[1][2] = 0; m[1][3] = 0; m[2][0] = 0; m[2][1] = 0; m[2][2] = (-zNear - zFar) / zRange; m[2][3] = 2 * zFar * zNear / zRange; m[3][0] = 0; m[3][1] = 0; m[3][2] = 1; m[3][3] = 0; return this; } public Matrix4 initOrthographic(float left, float right, float bottom, float top, float near, float far) { float width = right - left; float height = top - bottom; float depth = far - near; m[0][0] = 2 / width; m[0][1] = 0; m[0][2] = 0; m[0][3] = -(right + left) / width; m[1][0] = 0; m[1][1] = 2 / height; m[1][2] = 0; m[1][3] = -(top + bottom) / height; m[2][0] = 0; m[2][1] = 0; m[2][2] = -2 / depth; m[2][3] = -(far + near) / depth; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; return this; } public Matrix4 initRotation(Vector3 forward, Vector3 up) { Vector3 f = forward.normalize(); Vector3 r = f.cross(up).normalize(); Vector3 u = up.normalize(); return initRotation(f, u, r); } public Matrix4 initRotation(Vector3 forward, Vector3 up, Vector3 right) { Vector3 f = forward; Vector3 r = right; Vector3 u = up; m[0][0] = r.getX(); m[0][1] = r.getY(); m[0][2] = r.getZ(); m[0][3] = 0; m[1][0] = u.getX(); m[1][1] = u.getY(); m[1][2] = u.getZ(); m[1][3] = 0; m[2][0] = f.getX(); m[2][1] = f.getY(); m[2][2] = f.getZ(); m[2][3] = 0; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; return this; } public Vector3 transform(Vector3 r) { return new Vector3(m[0][0] * r.getX() + m[0][1] * r.getY() + m[0][2] * r.getZ() + m[0][3], m[1][0] * r.getX() + m[1][1] * r.getY() + m[1][2] * r.getZ() + m[1][3], m[2][0] * r.getX() + m[2][1] * r.getY() + m[2][2] * r.getZ() + m[2][3]); } public Quaternion transform(Quaternion r) { return new Quaternion(m[0][0] * r.getX() + m[0][1] * r.getY() + m[0][2] * r.getZ() + m[0][3] * r.getW(), m[1][0] * r.getX() + m[1][1] * r.getY() + m[1][2] * r.getZ() + m[1][3] * r.getW(), m[2][0] * r.getX() + m[2][1] * r.getY() + m[2][2] * r.getZ() + m[2][3] * r.getW(), m[3][0] * r.getX() + m[3][1] * r.getY() + m[3][2] * r.getZ() + m[3][3] * r.getW()); } public void write(FloatBuffer buffer) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { buffer.put((float) get(i, j)); } } } public int getSize() { return 4 * 4; } public Matrix4 rotate() { Matrix4 result = new Matrix4(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { result.set(j, i, get(i, j)); } } return result; } public void translate(float x, float y, float z) { this.set(add(initTranslation(x, y, z))); } public Matrix4 add(Matrix4 m) { Matrix4 result = new Matrix4(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { result.set(i, j, get(i, j) + m.get(i, j)); } } return result; } public void rotate(Vector3 axis, float radians) { this.set(this.mul(new Quaternion(axis, radians).toRotationMatrix())); } }
[ "bhead551@gmail.com" ]
bhead551@gmail.com
9492e3bd728d1d24a6326fb4a8ae49f1d4a2912b
c6506e4c6206e5b227b5f284f484167c5b2ab345
/tile/domain/src/main/java/com/exercise/tarmag/service/IPropertyChargeRuleService.java
f6e7c08d5de1103079fb952d44a003374d1fff13
[]
no_license
yranibee/exercise
2fd765af9b61eef321605c9ce83b7378a05fcb1d
af1a6bd6626595b22505fd9d11be61639e2812cd
refs/heads/master
2021-07-09T16:28:18.636731
2017-10-10T06:46:49
2017-10-10T06:46:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
844
java
package com.dt.tarmag.service; import java.util.List; import java.util.Map; import com.dt.tarmag.model.PropertyChargeRule; import com.dt.tarmag.vo.PropertyChargeRuleVo; /** * 物业规则service * @author wangfacheng * @date 2015年8月21日13:41:13 * */ public interface IPropertyChargeRuleService { /** * 查询所有物业费规则 * @param searchVo * @return */ public List<Map<String , Object>> findPropertyChargeRules(PropertyChargeRuleVo searchVo); /** * 根据小区期数id查询物业费规则 * @param partitionId * @return */ public PropertyChargeRule getPropertyChargeRuleByPartitionId(Long unitId , Long partitionId); /** * 添加物业规则 */ public boolean saveOrUpdatePropertyChargeRule_tx(PropertyChargeRuleVo vo) throws RuntimeException; }
[ "facheng.wang@otms.cn" ]
facheng.wang@otms.cn
88b909e6235c778d4ce185f300337c36cb9ec4eb
64455b7ce0658de6992bb219d8b150dddb30881c
/DesignPatterns/src/main/java/br/com/bcp/pattern/memento/command/LblDisplay.java
3f66575a611d28eda4b25e124f25c754ad798e91
[]
no_license
bproenca/java
f1fba9f21026a67ec3131fed39692999ef6faed0
0b9a9c9620e60b22a57cc61fa3bd467269e270db
refs/heads/master
2023-01-09T15:34:48.597389
2019-12-21T21:46:42
2019-12-21T21:46:42
202,936,509
0
0
null
2023-01-02T21:58:51
2019-08-17T22:25:25
HTML
UTF-8
Java
false
false
487
java
package br.com.bcp.pattern.memento.command; import java.awt.Color; import java.awt.Font; import javax.swing.JLabel; import javax.swing.border.EtchedBorder; class LblDisplay extends JLabel { Mediator med; LblDisplay(final Mediator m) { super("0", JLabel.CENTER); med = m; med.registerDisplay(this); setBackground(Color.white); setBorder(new EtchedBorder(Color.blue, Color.green)); Font font = new Font("Arial", Font.BOLD, 40); setFont(font); } }
[ "bruno.proenca@synchro.com.br" ]
bruno.proenca@synchro.com.br
25e8d34f960b4cb6c17bf633a2027e07f00a138e
f532b92dc0cbf3c04b93eadc429cc5af36a2f2ea
/src/java/com/wonders/common/authority/util/MenuUtil.java
f18d5a10e32de9c312c5f90d8f92643f91a38c8e
[]
no_license
lilu1984/gittest
82958eebb3bc6c081b055659196f2303c258a72b
7f46ae0ffabd2a47b17fe43edd9c78863cf16333
refs/heads/master
2021-04-27T03:43:40.830826
2018-02-24T09:28:05
2018-02-24T10:15:23
122,718,262
0
0
null
null
null
null
GB18030
Java
false
false
4,036
java
package com.wonders.common.authority.util; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import com.wonders.common.authority.bo.AuthorityTree; import com.wonders.tdsc.common.util.AuthorityCheckUtil; /** * 菜单工具类。 */ public class MenuUtil { /** 日志 */ private static Logger logger = Logger.getLogger(MenuUtil.class); /** * 取得一级菜单下的二级、三级菜单 * * @param menuId * 一级菜单代码 * @param menuList * 菜单列表 * @return 取得的二级、三级菜单代码列表 */ public static Map getSubMenu(String menuId, List menuList) { LinkedHashMap menuMap = new LinkedHashMap(); try { for (Iterator iter1 = menuList.iterator(); iter1.hasNext();) { AuthorityTree menu1 = (AuthorityTree) iter1.next(); if (menu1.getNodePid().equals(menuId)) { String secondMenuId = menu1.getNodeId(); List secondList = new ArrayList(); for (Iterator iter2 = menuList.iterator(); iter2.hasNext();) { AuthorityTree menu2 = (AuthorityTree) iter2.next(); if (menu2.getNodePid().equals(secondMenuId)) { secondList.add(menu2); } } menuMap.put(menu1, secondList); } } } catch (Exception ex) { throw new RuntimeException(ex); } return menuMap; } /** * 过滤掉没有权限的主菜单 * * @param menuList * 待过滤的主菜单列表 * @param request * HttpServletRequest * @return 过滤后的菜单列表 */ public static List filterMainMenuByAuthority(List menuList, HttpServletRequest request) { if (menuList == null || menuList.size() < 1) { return menuList; } try { for (int i = menuList.size() - 1; i >= 0; i--) { AuthorityTree menu2 = (AuthorityTree) menuList.get(i); if (AuthorityCheckUtil.hasMenuPriv(request, menu2.getNodeId()) == false) { menuList.remove(i); } } } catch (Exception ex) { throw new RuntimeException(ex); } return menuList; } /** * 过滤掉没有权限的子菜单 * * @param menuMap * 待过滤的子菜单列表 * @param request * HttpServletRequest * @return 过滤后的菜单列表 */ public static Map filterSubMenuByAuthority(Map menuMap, HttpServletRequest request) { if (menuMap == null || menuMap.size() < 1) { return menuMap; } Map newMap = new LinkedHashMap(); try { for (Iterator iter1 = menuMap.keySet().iterator(); iter1.hasNext();) { AuthorityTree menu1 = (AuthorityTree) iter1.next(); if (AuthorityCheckUtil.hasMenuPriv(request, menu1.getNodeId())) { List menuList = (List) menuMap.get(menu1); for (int j = menuList.size() - 1; j >= 0; j--) { AuthorityTree menu2 = (AuthorityTree) menuList.get(j); if (AuthorityCheckUtil.hasMenuPriv(request, menu2.getNodeId()) == false) { menuList.remove(j); } } newMap.put(menu1, menuList); } } } catch (Exception ex) { throw new RuntimeException(ex); } return newMap; } }
[ "lilu@wondersgroup" ]
lilu@wondersgroup
5c5fec9c4cbe3daf35ee58d5ac1d06f12d3fb541
87d52fccc95609c710f8af47b6a2ad591492455a
/kodilla-spring/src/main/java/com/kodilla/spring/shape/Circle.java
5c5f990ab8a0061e46a8586325bd17a3948ad1f6
[]
no_license
rbarcik/rafal-barcik-kodilla-java
be4ba6c800c93f906904668ec0b1cd5697e1c302
4798c7c7257698f11cb4c306b4fa202cb7ec2340
refs/heads/master
2020-04-05T19:10:33.120415
2019-05-26T19:33:09
2019-05-26T19:33:09
157,122,008
0
0
null
null
null
null
UTF-8
Java
false
false
302
java
package com.kodilla.spring.shape; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("singleton") public class Circle implements Shape { @Override public String getShapeName() { return "This is a circle."; } }
[ "barcik.r@gmail.com" ]
barcik.r@gmail.com
b24f68884d2b52fcbe4cc1bab923ada25ad9b8a2
12487a1971203f175e4a9f405302dbb9f498c96f
/src/main/java/org/ort/school/crm/jooq/model/tables/GroupStudent.java
e9a09ec6ac92ada09d2da57eb51e00148977fff2
[ "Apache-2.0" ]
permissive
barlog-m/school-crm
43959cf604e0110fa9c25fe12e4edce70359c67c
8f0a46d51443784f9e90955e1020603aeef58231
refs/heads/master
2020-04-22T05:29:54.488456
2019-02-11T04:22:50
2019-02-11T04:22:50
170,161,699
0
0
null
2019-02-11T16:25:58
2019-02-11T16:25:57
null
UTF-8
Java
false
true
4,193
java
/* * This file is generated by jOOQ. */ package org.ort.school.crm.jooq.model.tables; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Index; import org.jooq.Name; import org.jooq.Record; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; import org.ort.school.crm.jooq.model.Indexes; import org.ort.school.crm.jooq.model.Keys; import org.ort.school.crm.jooq.model.Public; import org.ort.school.crm.jooq.model.tables.records.GroupStudentRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.11.6" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class GroupStudent extends TableImpl<GroupStudentRecord> { private static final long serialVersionUID = -868030188; /** * The reference instance of <code>public.group_student</code> */ public static final GroupStudent GROUP_STUDENT = new GroupStudent(); /** * The class holding records for this type */ @Override public Class<GroupStudentRecord> getRecordType() { return GroupStudentRecord.class; } /** * The column <code>public.group_student.student_id</code>. */ public final TableField<GroupStudentRecord, Long> STUDENT_ID = createField("student_id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * The column <code>public.group_student.group_id</code>. */ public final TableField<GroupStudentRecord, Long> GROUP_ID = createField("group_id", org.jooq.impl.SQLDataType.BIGINT.nullable(false), this, ""); /** * Create a <code>public.group_student</code> table reference */ public GroupStudent() { this(DSL.name("group_student"), null); } /** * Create an aliased <code>public.group_student</code> table reference */ public GroupStudent(String alias) { this(DSL.name(alias), GROUP_STUDENT); } /** * Create an aliased <code>public.group_student</code> table reference */ public GroupStudent(Name alias) { this(alias, GROUP_STUDENT); } private GroupStudent(Name alias, Table<GroupStudentRecord> aliased) { this(alias, aliased, null); } private GroupStudent(Name alias, Table<GroupStudentRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment("")); } public <O extends Record> GroupStudent(Table<O> child, ForeignKey<O, GroupStudentRecord> key) { super(child, key, GROUP_STUDENT); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return Public.PUBLIC; } /** * {@inheritDoc} */ @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.GR_G, Indexes.GR_S); } /** * {@inheritDoc} */ @Override public List<ForeignKey<GroupStudentRecord, ?>> getReferences() { return Arrays.<ForeignKey<GroupStudentRecord, ?>>asList(Keys.GROUP_STUDENT__GROUP_STUDENT_STUDENT_ID_FKEY, Keys.GROUP_STUDENT__GROUP_STUDENT_GROUP_ID_FKEY); } public Student student() { return new Student(this, Keys.GROUP_STUDENT__GROUP_STUDENT_STUDENT_ID_FKEY); } public Group group() { return new Group(this, Keys.GROUP_STUDENT__GROUP_STUDENT_GROUP_ID_FKEY); } /** * {@inheritDoc} */ @Override public GroupStudent as(String alias) { return new GroupStudent(DSL.name(alias), this); } /** * {@inheritDoc} */ @Override public GroupStudent as(Name alias) { return new GroupStudent(alias, this); } /** * Rename this table */ @Override public GroupStudent rename(String name) { return new GroupStudent(DSL.name(name), null); } /** * Rename this table */ @Override public GroupStudent rename(Name name) { return new GroupStudent(name, null); } }
[ "pavel.finkelshtein@gmail.com" ]
pavel.finkelshtein@gmail.com
c053ed26cccc42d846c5c913e8a79e4918ca44aa
ed6c84f05b170cbea17758ee63159f81b268b5f5
/app/src/main/java/com/jhb/dvt/dvt_store/Models/Location.java
a61b84090585bfc52456026aa1ace81505669ea4
[]
no_license
creed6312/DVT-Store_Android
d77d74f3be1e64d0c3ff7b43221050c9648b67d2
65c24e8cf4074d0f6a7c6624a8bb022aaebd9a7d
refs/heads/master
2016-08-11T14:56:33.936881
2016-03-03T12:43:34
2016-03-03T12:43:34
51,435,722
0
0
null
null
null
null
UTF-8
Java
false
false
745
java
package com.jhb.dvt.dvt_store.Models; /** * Created by CreeD on 2016/02/26. */ public class Location { private String Place ; private double Lat ; private double Long ; private String Address ; public String getPlace() { return Place; } public void setPlace(String place) { this.Place = place; } public double getLat() { return Lat; } public void setLat(double lat) { Lat = lat; } public double getLong() { return Long; } public void setLong(double aLong) { Long = aLong; } public String getAddress() { return Address; } public void setAddress(String address) { Address = address; } }
[ "creed.shane@gmail.com" ]
creed.shane@gmail.com
cac0862010702ea3fffffd58d86994f465f7c0eb
e9b9eaa6532cbf4f8d6b5d037ed8453cc5637166
/A4/Screen.java
35c045664ae32df635a6a26b12ee22b642e2c59e
[]
no_license
VictoriaXY6/CSC22100-Projects
dfc010a6e0288f7b1b339de50caa3def2e271406
612670cf9dc91208cb79b68589dc6efc16d399ba
refs/heads/master
2022-11-08T06:34:00.753614
2020-06-24T16:12:11
2020-06-24T16:12:11
274,574,159
0
0
null
null
null
null
UTF-8
Java
false
false
1,351
java
import java.util.Date; public abstract class Screen { private long id; private double salePrice; private Date makeDate; private String manufacturer; private String model; //non-default constructor public Screen(long id, double salePrice, Date makeDate, String manufacturer, String model) { this.id = id; this.salePrice = salePrice; this.makeDate = makeDate; this.manufacturer = manufacturer; this.model = model; } //abstract method getType public abstract String getType(); //getter and setter methods public long getId() { return id; } public void setId(long id) { this.id = id; } public double getSalePrice() { return salePrice; } public void setSalePrice(double salePrice) { this.salePrice = salePrice; } public Date getMakeDate() { return makeDate; } public void setMakeDate(Date makeDate) { this.makeDate = makeDate; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } //abstract method equals public abstract boolean equals(Object obj); //Override method, output the data of the object @Override public String toString() { return getType() + " " + getId(); } }
[ "noreply@github.com" ]
VictoriaXY6.noreply@github.com
5c10f1927a16cf2d18ff983aae506bd0b0418eb7
13e3c7e5067e70e71e4fd59d5336e0168d78dbaa
/REFACTORING/Anonima/src/Circulo.java
4adc9c3179293cd25c36f729078ad5e8a54d3bc3
[]
no_license
lauriiShii/ENTORNOS-DEL-DESARROLLO
f9bacfdaa7fe6400f5c2042f5b2e59f180799e99
0d650071fb9355b3d69d06b77af5d0789c652e96
refs/heads/master
2020-03-22T06:33:34.492538
2018-07-03T23:14:52
2018-07-03T23:14:52
139,642,639
0
0
null
null
null
null
UTF-8
Java
false
false
543
java
public class Circulo { private Punto punto; private double radio; Circulo(double x, double y, double radio){ this.radio = radio; punto = new Punto(x,y); } public double area(){ return Math.PI*radio*radio; } class Punto{ private double x; private double y; Punto(double x, double y){ this.x = x; this.y = y; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } } }
[ "lauracalventedominguez@gmail.com" ]
lauracalventedominguez@gmail.com
40fdb33b6c295efe17633a868dfd994b91f0b403
6e9b4ed585600a7d6166c25703a708f69efa4691
/Lab_4/src/tutorial/servlet/HelloServlet.java
e394247290b6f18945883d18d5451ad6d2429701
[]
no_license
denisstep99/network-programming
55236733673723b4461f2c9956d18530eaca39ae
ad562b2d2fa43019a0a00d3fdd41b29d37c378c4
refs/heads/master
2020-09-16T11:48:32.194048
2019-11-25T00:10:55
2019-11-25T00:10:55
223,760,298
0
0
null
null
null
null
UTF-8
Java
false
false
1,040
java
package tutorial.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "HelloServlet") public class HelloServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = response.getOutputStream(); out.println("<html>"); out.println("<head><title>Hello Servlet</title></head>"); out.println("<body>"); out.println("<h3>Hello World</h3>"); out.println("This is my first Servlet"); out.println("</body>"); out.println("<html>"); } }
[ "denisstep99@gmail.com" ]
denisstep99@gmail.com
e8385b206d79daa06e5f2171684506d6bc2578b9
7c46a44f1930b7817fb6d26223a78785e1b4d779
/soap/src/java/com/zimbra/soap/mail/type/BulkAction.java
ab72048825ed128d43c5a8d6d3f78084588dc11a
[]
no_license
Zimbra/zm-mailbox
20355a191c7174b1eb74461a6400b0329907fb02
8ef6538e789391813b65d3420097f43fbd2e2bf3
refs/heads/develop
2023-07-20T15:07:30.305312
2023-07-03T06:44:00
2023-07-06T10:09:53
85,609,847
67
128
null
2023-09-14T10:12:10
2017-03-20T18:07:01
Java
UTF-8
Java
false
false
2,606
java
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2017 Synacor, Inc. * * 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, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.soap.mail.type; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlEnum; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.MailConstants; @XmlAccessorType(XmlAccessType.NONE) public class BulkAction { @XmlEnum public static enum Operation { move, read, unread; public static Operation fromString(String s) throws ServiceException { try { return Operation.valueOf(s); } catch (IllegalArgumentException e) { throw ServiceException.INVALID_REQUEST("unknown operation: "+s, e); } } } /** * @zm-api-field-tag operation * @zm-api-field-description Operation to perform * <table> * <tr><td><b>move</b> </td><td>move the search result to specified folder location</td></tr> * <tr><td><b>read</b> </td><td>mark the search result as read</td></tr> * <tr><td><b>unread</b> </td><td>mark the search result as unread</td></tr> * </table> */ @XmlAttribute(name = MailConstants.A_OPERATION /* op */, required = true) private Operation op; /** * @zm-api-field-tag folder-path * @zm-api-field-description Required if op="move". Folder pathname where * all matching items should be moved. */ @XmlAttribute(name = MailConstants.A_FOLDER /* l */, required = false) private String folder; public Operation getOp() { return op; } public void setOp(Operation op) { this.op = op; } public String getFolder() { return folder; } public void setFolder(String folder) { this.folder = folder; } }
[ "sneha.patil@synacor.com" ]
sneha.patil@synacor.com
5073c376fd192036eaec7a4e8ccde82ddd20090b
558b99e5b293fa44fb3db9df37b53cf4d7d8fc65
/app/src/main/java/okki/setyatmoko/guidepess/Home/ViewPagerAdapter.java
90222f303e3434f78192c91071a88cac42d4af5f
[]
no_license
ocekaye/GuidePess2
2477991449d9af8b1b1e2082d213819e91f6d481
7aae15f3cc1cf58cd0413ec6bf539918afc91ecf
refs/heads/master
2021-01-20T23:04:00.611112
2017-08-30T04:05:18
2017-08-30T04:05:18
101,836,650
0
0
null
null
null
null
UTF-8
Java
false
false
1,017
java
package okki.setyatmoko.guidepess.Home; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.ArrayList; import java.util.List; /** * Created by Hinata on 8/10/2017. */ public class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } }
[ "styat_moko@rocketmail.com" ]
styat_moko@rocketmail.com
1db9a271c78956b640e5041ca4fe0fe6d0cb7b81
39872bb8cc325f9bf299a0087b39f684f7ef589c
/app/src/main/java/com/fil/SingleProductViewActivity.java
7012c4b7d0f6589eac8198e047092d2b5300a351
[]
no_license
nuwan94/FIL
f0d6c86fcddb4ddf758c3bf46d0a8e314d2fb87e
e4ef2d871822a7757cb2280ee15eaefff3e53822
refs/heads/master
2021-06-30T11:16:09.583760
2019-04-02T09:51:36
2019-04-02T09:51:36
177,328,570
0
0
null
2020-10-07T10:21:52
2019-03-23T18:56:08
Java
UTF-8
Java
false
false
3,392
java
package com.fil; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import com.fil.Common.Common; import com.fil.Common.FireB; import com.fil.Model.CartItem; import com.fil.Model.Product; import com.google.firebase.auth.FirebaseAuth; import com.squareup.picasso.Picasso; public class SingleProductViewActivity extends AppCompatActivity implements View.OnClickListener { private ImageView image; private Button addToCart, buyNow, goToCart, continueShopping; private LinearLayout choose, added; private Product product; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_product_view); Intent intent = getIntent(); product = (Product) intent.getSerializableExtra("product"); setTitle(product.getName()); image = findViewById(R.id.imgProductView); Picasso.get().load(product.getImage()).into(image); addToCart = findViewById(R.id.btnProductAddToCart); buyNow = findViewById(R.id.btnProductBuyNow); goToCart = findViewById(R.id.btnProductGoToCart); continueShopping = findViewById(R.id.btnProductShopping); choose = findViewById(R.id.layoutProductChoose); added = findViewById(R.id.layoutProductAdded); addToCart.setOnClickListener(this); buyNow.setOnClickListener(this); goToCart.setOnClickListener(this); continueShopping.setOnClickListener(this); } @Override public void onClick(View v) { String sleeveStyle = ((Spinner) findViewById(R.id.spinnerSleeveStyle)).getSelectedItem().toString(); String collarSize = ((Spinner) findViewById(R.id.spinnerCollarSize)).getSelectedItem().toString(); String material = ((Spinner) findViewById(R.id.spinnerMaterial)).getSelectedItem().toString(); String color = ((Spinner) findViewById(R.id.spinnerColor)).getSelectedItem().toString(); String collarType = ((Spinner) findViewById(R.id.spinnerCollarType)).getSelectedItem().toString(); String tailor = ((Spinner) findViewById(R.id.spinnerTailor)).getSelectedItem().toString(); CartItem cartItem = new CartItem(product, sleeveStyle, collarSize, material, color, collarType, tailor); switch (v.getId()) { case R.id.btnProductAddToCart: choose.setVisibility(View.GONE); FireB.getCartReference().child(FirebaseAuth.getInstance().getUid()).push().setValue(cartItem); added.setVisibility(View.VISIBLE); break; case R.id.btnProductBuyNow: FireB.getCartReference().child(FirebaseAuth.getInstance().getUid()).push().setValue(cartItem); Intent iPurchase = new Intent(this,PurchaseActivity.class); startActivity(iPurchase); break; case R.id.btnProductGoToCart: Intent iCart = new Intent(this, CartActivity.class); startActivity(iCart); break; case R.id.btnProductShopping: finish(); break; } } }
[ "nuwansalawatta@gmail.com" ]
nuwansalawatta@gmail.com
83e890dad355d2997b2cf9f20b7828425551effc
fc0887f1438c0d5f7f17d8fa39bb3be5c23b7353
/bootique-tapestry58/src/test/java/io/bootique/tapestry/v58/testapp2/bq/BQEchoService.java
13cdd080107f3f1fb494bc0bafd1a0566e678e16
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
bootique/bootique-tapestry
7726c2afca554cc10064fe63a653f8333ae76257
33f187cbfa903e3264a56ff99003ef31f9241095
refs/heads/master
2023-04-02T08:29:14.704771
2023-03-24T12:26:09
2023-03-24T12:26:09
61,655,245
4
3
Apache-2.0
2018-06-18T07:17:29
2016-06-21T17:57:31
Java
UTF-8
Java
false
false
992
java
/* * Licensed to ObjectStyle LLC under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ObjectStyle LLC 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 io.bootique.tapestry.v58.testapp2.bq; /** * Created by andrus on 6/21/16. */ public class BQEchoService { public String get(String in) { return "{" + in + "}"; } }
[ "andrus@objectstyle.com" ]
andrus@objectstyle.com
6d744a38e5fb6d42b805401c7a991fbc628fa73e
28552d7aeffe70c38960738da05ebea4a0ddff0c
/google-ads/src/main/java/com/google/ads/googleads/v4/services/stub/GrpcAdGroupCriterionSimulationServiceCallableFactory.java
d7df903f3c19cfd6c1c061336f83e0401582e4d8
[ "Apache-2.0" ]
permissive
PierrickVoulet/google-ads-java
6f84a3c542133b892832be8e3520fb26bfdde364
f0a9017f184cad6a979c3048397a944849228277
refs/heads/master
2021-08-22T08:13:52.146440
2020-12-09T17:10:48
2020-12-09T17:10:48
250,642,529
0
0
Apache-2.0
2020-03-27T20:41:26
2020-03-27T20:41:25
null
UTF-8
Java
false
false
822
java
/** * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v4.services.stub; import com.google.ads.googleads.lib.GrpcGoogleAdsCallableFactory; public class GrpcAdGroupCriterionSimulationServiceCallableFactory extends GrpcGoogleAdsCallableFactory { }
[ "noreply@github.com" ]
PierrickVoulet.noreply@github.com
1c0ea1210c55b9fa7662265f634d6c97fa276a81
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/19/19_d3fbad01bd07067ddb11a19949277e0493bbb502/Search/19_d3fbad01bd07067ddb11a19949277e0493bbb502_Search_s.java
9b325f1ac424cdd1998913f2beafada88760533a
[]
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
3,219
java
package de.mpg.jena.search; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.commons.collections.ListUtils; import org.apache.log4j.Logger; import de.mpg.jena.controller.SearchCriterion; import de.mpg.jena.controller.SearchCriterion.Operator; import de.mpg.jena.controller.SortCriterion; import de.mpg.jena.sparql.ImejiSPARQL; import de.mpg.jena.sparql.query.SimpleQueryFactory; import de.mpg.jena.vo.User; public class Search { private String containerURI = null; private String type = "http://imeji.mpdl.mpg.de/image"; private static Logger logger = Logger.getLogger(Search.class); public Search(String type, String containerURI) { this.containerURI = containerURI; if (type != null) { this.type = type; } } public SearchResult search(List<SearchCriterion> scList, SortCriterion sortCri, User user) { return new SearchResult(searchAdvanced(scList, sortCri, user)); } public List<String> searchAdvanced(List<SearchCriterion> scList, SortCriterion sortCri, User user) { LinkedList<String> results = new LinkedList<String>(); if (scList == null) scList = new ArrayList<SearchCriterion>(); if (scList.isEmpty() || containerURI != null) { results = (LinkedList<String>) searchSimple(null, sortCri, user); } for (SearchCriterion sc : scList) { LinkedList<String> subResults = new LinkedList<String>(); if (sc.getChildren().isEmpty()) { subResults = (LinkedList<String>) searchSimple(sc, sortCri, user); } else { subResults = (LinkedList<String>) searchAdvanced(sc.getChildren(), sortCri, user); } if (results.isEmpty()) { results = new LinkedList<String>(subResults); } if (Operator.AND.equals(sc.getOperator()) || Operator.NOTAND.equals(sc.getOperator())) { List<String> inter = ListUtils.intersection(results, subResults); results = new LinkedList<String>(inter); } else { List<String> sum = ListUtils.sum(results, subResults); results = new LinkedList<String>(sum); } } return results; } public List<String> searchSimple(SearchCriterion sc, SortCriterion sortCri, User user) { String sq = SimpleQueryFactory.search(type, sc, sortCri, user, (containerURI != null), getSpecificQuery()); return ImejiSPARQL.exec(sq); } private LinkedList<String> getAllURIs(SortCriterion sortCri, User user) { String sq = SimpleQueryFactory.search(type, null, sortCri, user, (containerURI != null), getSpecificQuery()); return ImejiSPARQL.exec(sq); } private String getSpecificQuery() { String specificQuery = ""; if ("http://imeji.mpdl.mpg.de/image".equals(type)) { specificQuery += ". ?s <http://imeji.mpdl.mpg.de/collection> ?c "; } if (containerURI != null) { specificQuery += " . <" + containerURI + "> <http://imeji.mpdl.mpg.de/images> ?s"; } return specificQuery; } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
5c95ba324ea40219661d8976bbd55bb968d0e018
3344240d52225dbb72d3a999791ca85175f63baf
/src/main/java/com/example/service/IStudentService.java
5cf42973129070cc917ba6b827e9624d12d07fbe
[]
no_license
BanLanGenBei/my-project
bd662275984669e34d34264e543088c147ab78d6
7c1dbbd2574df8d432d74961cc68e43bf63e3d20
refs/heads/master
2023-02-05T20:17:58.993442
2020-12-24T06:50:01
2020-12-24T06:50:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
785
java
package com.example.service; import com.example.model.entity.Student; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * <p> * 服务类 * </p> * * @author ${author} * @since 2020-12-23 */ public interface IStudentService extends IService<Student> { /** * 添加一个学生 * @param student * @return */ int saveOneStudent(Student student); /** * 删除一个学生,根据id进行删除 * @param * @return */ int deleteOneStudent(Integer id); /** * 修改学生 * @param student * @return */ int updateStudent(Student student); /** * 根据id查询学生 * @param id * @return */ Student enquiryStudent(Integer id); }
[ "chenchong@ovopark.com" ]
chenchong@ovopark.com
d97b1cabef6f33f62c81b9265ed467c810d626a2
46719835215b0c92e191a12d6adbbb115fef653d
/src/main/java/omid/springframework/repositories/IngredientRepository.java
cc49f6d7a52583687838d79c1db48d0a82e5c1a8
[]
no_license
omid-joukar/spring5-recipe-app
caba47cefe47f5c62455dc6c3ca32138e6453c41
97786769385f8310c47ba794373fac6e3cdd2e39
refs/heads/master
2023-02-13T20:42:15.289853
2020-12-28T22:58:40
2020-12-28T22:58:40
322,797,075
1
0
null
2020-12-24T10:01:53
2020-12-19T08:01:39
Java
UTF-8
Java
false
false
233
java
package omid.springframework.repositories; import omid.springframework.domain.Ingredient; import org.springframework.data.repository.CrudRepository; public interface IngredientRepository extends CrudRepository<Ingredient,Long> { }
[ "joukaromid6@gmail.com" ]
joukaromid6@gmail.com
6b8897b102bf64966df57168ad19b950f8e18fcb
c53fa8acaed81b2b48eb0d26ce0897ced001fc74
/src/leetcode/_191Numerof1Bits.java
e29e489761ef77290763de901617c7ba16de4940
[]
no_license
mapicccy/Java
efb02228044d2de3786834f6655c21773a16c772
e233ac3de3d329d55b03b7ffdd9d5f448ec32524
refs/heads/master
2021-09-09T16:01:46.581730
2018-03-17T15:56:40
2018-03-17T15:56:40
53,581,554
0
0
null
null
null
null
UTF-8
Java
false
false
289
java
package leetcode; public class _191Numerof1Bits { public static int hammingWeight(int n){ int count = 0; while(n != 0){ n = n & (n - 1); count++; } return count; } public static void main(String[] args) { // TODO Auto-generated method stub } }
[ "zhaoguanjun@172.28.50.35" ]
zhaoguanjun@172.28.50.35
79fe1bfe9afce1f5c2719833157b96ac5ee341d2
ba26af1bfe70673303f39fb34bf83f5c08ed5905
/analysis/src/main/java/org/apache/calcite/plan/RelOptSamplingParameters.java
8361072031a336021152e7e1c3991355c404b7ad
[ "MIT" ]
permissive
GinPonson/Quicksql
5a4a6671e87b3278e2d77eee497a4910ac340617
e31f65fb96ea2f2c373ba3acc43473a48dca10d1
refs/heads/master
2020-07-30T06:23:41.805009
2019-09-22T08:50:18
2019-09-22T08:50:18
210,116,844
0
0
MIT
2019-09-22T08:48:23
2019-09-22T08:48:23
null
UTF-8
Java
false
false
3,649
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.calcite.plan; /** * RelOptSamplingParameters represents the parameters necessary to produce a * sample of a relation. * * <p>It's parameters are derived from the SQL 2003 TABLESAMPLE clause. */ public class RelOptSamplingParameters { //~ Instance fields -------------------------------------------------------- private final boolean isBernoulli; private final float samplingPercentage; private final boolean isRepeatable; private final int repeatableSeed; //~ Constructors ----------------------------------------------------------- public RelOptSamplingParameters( boolean isBernoulli, float samplingPercentage, boolean isRepeatable, int repeatableSeed) { this.isBernoulli = isBernoulli; this.samplingPercentage = samplingPercentage; this.isRepeatable = isRepeatable; this.repeatableSeed = repeatableSeed; } //~ Methods ---------------------------------------------------------------- /** * Indicates whether Bernoulli or system sampling should be performed. * Bernoulli sampling requires the decision whether to include each row in * the the sample to be independent across rows. System sampling allows * implementation-dependent behavior. * * @return true if Bernoulli sampling is configured, false for system * sampling */ public boolean isBernoulli() { return isBernoulli; } /** * Returns the sampling percentage. For Bernoulli sampling, the sampling * percentage is the likelihood that any given row will be included in the * sample. For system sampling, the sampling percentage indicates (roughly) * what percentage of the rows will appear in the sample. * * @return the sampling percentage between 0.0 and 1.0, exclusive */ public float getSamplingPercentage() { return samplingPercentage; } /** * Indicates whether the sample results should be repeatable. Sample results * are only required to repeat if no changes have been made to the * relation's content or structure. If the sample is configured to be * repeatable, then a user-specified seed value can be obtained via * {@link #getRepeatableSeed()}. * * @return true if the sample results should be repeatable */ public boolean isRepeatable() { return isRepeatable; } /** * If {@link #isRepeatable()} returns <code>true</code>, this method returns a * user-specified seed value. Samples of the same, unmodified relation * should be identical if the sampling mode, sampling percentage and * repeatable seed are the same. * * @return seed value for repeatable samples */ public int getRepeatableSeed() { return repeatableSeed; } } // End RelOptSamplingParameters.java
[ "xushengguo-xy@360.cn" ]
xushengguo-xy@360.cn
4f653546aa5a753f387946471122235a2308e83c
071e09826a71758e9e0f595d39a1d04622cf3aad
/Java-Interview-Code/generalQuestions/anagram.java
f50b176119545a22efd3a3f53f274bcaea0fc660
[]
no_license
eyeboah369/Data-Structures-and-Algorithms-
6d75b7137ba1fd2e5c5ebbd2aae73647a25c9cc4
72019cd34b5063d9337f9110168e0e1a632b5bb9
refs/heads/master
2022-06-11T05:09:59.047175
2020-05-07T01:30:16
2020-05-07T01:30:16
261,919,646
0
0
null
null
null
null
UTF-8
Java
false
false
325
java
/*This problem was asked by Robinhood. Given an array of strings, group anagrams together. For example, given the following array: ['eat', 'ate', 'apt', 'pat', 'tea', 'now'] Return: [['eat', 'ate', 'tea'], ['apt', 'pat'], ['now']]*/ public class anagram { public static void main(String[] args){ } }
[ "evansyeboahjr.@client159-61.wireless.newpaltz.edu" ]
evansyeboahjr.@client159-61.wireless.newpaltz.edu
60b7d400b6329bd99fb87ece2f347bf6f4dc6bd7
e442335289fe0f195be6bf65a1226aa077669742
/test/rs/ac/bg/etf/pp1/MJParserTest.java
e74b3f3568be1efdb884cf66119170cca89baa18
[]
no_license
Zejladin/PP_Projekat
957ea360a0a155142a88aa715be964d94219fb1a
766deab5d79c69b275b9640e827831c979f6e058
refs/heads/master
2022-04-05T03:54:23.036045
2020-02-06T03:15:03
2020-02-06T03:15:03
236,203,011
0
0
null
null
null
null
UTF-8
Java
false
false
2,040
java
package rs.ac.bg.etf.pp1; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java_cup.runtime.Symbol; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import rs.ac.bg.etf.pp1.ast.Program; import rs.ac.bg.etf.pp1.util.Log4JUtils; import rs.etf.pp1.mj.runtime.Code; import rs.etf.pp1.symboltable.Tab; public class MJParserTest { static { DOMConfigurator.configure(Log4JUtils.instance().findLoggerConfigFile()); Log4JUtils.instance().prepareLogFile(Logger.getRootLogger()); } public static void main(String[] args) throws Exception { Logger log = Logger.getLogger(MJParserTest.class); Reader br = null; try { File sourceCode = new File("test/program.mj"); log.info("Compiling source file: " + sourceCode.getAbsolutePath()); br = new BufferedReader(new FileReader(sourceCode)); Yylex lexer = new Yylex(br); MJParser p = new MJParser(lexer); Symbol s = p.parse(); //pocetak parsiranja Tab.init(); Program prog = (Program)(s.value); // ispis sintaksnog stabla log.info(prog.toString("")); log.info("==================================="); // ispis prepoznatih programskih konstrukcija SemanticPass v = new SemanticPass(); //RuleVisitor v = new RuleVisitor(); prog.traverseBottomUp(v); if(v.getErrorDetected() == false) { log.info("Pocinjemo sa generisanjem koda!"); Tab.dump(); File file = new File("test/program.obj"); if(file.exists()) file.delete(); CodeGenerator codeGenerator = new CodeGenerator(); prog.traverseBottomUp(codeGenerator); Code.dataSize = v.getVarCount(); Code.mainPc = codeGenerator.getMainPc(); Code.write(new FileOutputStream(file)); } } finally { if (br != null) try { br.close(); } catch (IOException e1) { log.error(e1.getMessage(), e1); } } } }
[ "djuradj.kurepa@gmail.com" ]
djuradj.kurepa@gmail.com
e3c02cedc5c0ef526dae91a77ec9c7d6e84e7455
ab6b5e321f19da88300f700d3f9259f501e30344
/src/main/java/com/will/Ex8.java
526e3aeb56764a2b53cd57f3f247b90c9fa04930
[]
no_license
wbrucesc/codingbattests
56837c99d1e2c54f8e2e91eeaac1d0de2a5aabe9
50ef4418ecad5cc1dcb559f70213b560b581319e
refs/heads/master
2021-05-12T16:37:40.154015
2018-01-13T20:49:42
2018-01-13T20:49:42
117,020,647
0
0
null
null
null
null
UTF-8
Java
false
false
565
java
package com.will; public class Ex8 { /* Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative. */ public static boolean posNeg(int a, int b, boolean negative) { if ((a < 0 && b < 0) && negative) { return true; } else if ((a > 0 && b < 0) && !negative) { return true; } else if ((a < 0 && b > 0) && !negative) { return true; } else { return false; } } }
[ "willtiger13@gmail.com" ]
willtiger13@gmail.com
60eada60c51be54a477a27466e2da0c6e8cfd745
d885e082e223c0566dffc780344ce0dc2824887c
/src/main/java/com/microBusiness/manage/service/StorageFormLogService.java
6dbc7e5d36b481678428a30fc3dd3efccdb6ccdd
[]
no_license
shenqidekobe/eba-manager
1f4b44535f96dc5e8a13a6bf80ba19f83a6f077e
a1c224fc1d2681497977cd3c7342cab4ea26175a
refs/heads/master
2020-04-30T14:24:01.252360
2019-03-21T10:01:46
2019-03-21T10:01:46
176,889,788
0
1
null
null
null
null
UTF-8
Java
false
false
916
java
/* * Copyright 2005-2015 dreamforyou. All rights reserved. * Support: http://www.dreamforyou * License: http://www.dreamforyou/license */ package com.microBusiness.manage.service; import java.util.List; import com.microBusiness.manage.entity.Order; import com.microBusiness.manage.entity.Shop; import com.microBusiness.manage.entity.StorageForm; import com.microBusiness.manage.entity.StorageFormLog; public interface StorageFormLogService extends BaseService<StorageFormLog, Long> { /** * 根据店铺,入库单获取操作记录 * * @param shop * @param inventoryForm * @return */ List<StorageFormLog> query(Shop shop, StorageForm storageForm); /** * 根据订单查询入库操作记录 * * @param shop * @param storageForm * @param order * @return */ List<StorageFormLog> query(Shop shop, Order order, StorageFormLog.Record record); }
[ "xiongshiwei@4ef083ab-0e2f-4864-81e5-8fd49570540e" ]
xiongshiwei@4ef083ab-0e2f-4864-81e5-8fd49570540e
844f6a36f2bb9c9292e58b961804921a57e53a0c
6de9842dab5fdd8a68fe60b12b8eaf19a8096921
/src/main/java/project/board/repository/MemberRepository.java
868c2db4099f4ad053ec1eaf9805a1574050a2af
[]
no_license
g1063114/board_project
fa115ce1d1c33ae85323a11dbeb5bfd4c0a86952
7f18b058d39c1a0c8f18bd9405d9d86394601973
refs/heads/master
2023-08-23T11:41:30.398841
2021-09-15T03:04:00
2021-09-15T03:04:00
398,232,118
0
0
null
null
null
null
UTF-8
Java
false
false
283
java
package project.board.repository; import org.springframework.data.jpa.repository.JpaRepository; import project.board.entity.Member; import java.util.List; public interface MemberRepository extends JpaRepository<Member, Long> { List<Member> findByUsername(String username); }
[ "g1063114@naver.com" ]
g1063114@naver.com
c57c81f4b104fdbd91ada10e660fdf138e40e48f
7784a7fcf7880d325430b1a3152d74a9ce98fdb8
/ES_05.2020-10-16/src/assignment05/SlaveForDir.java
e77a54b8d028da14834450452195ed08d4d100ea
[]
no_license
Wander29/Reti_esercizi.2020
b358509a0e895fe2b48988bcfcc2757b80352416
0c5f9287c65d4044875c382ad89de2ca5ded1e5f
refs/heads/master
2023-02-19T07:54:09.567868
2021-01-21T18:14:35
2021-01-21T18:14:35
298,775,730
1
0
null
null
null
null
UTF-8
Java
false
false
441
java
package assignment05; /** * @author LUDOVICO VENTURI 578033 * @version 1.0 * @date 2020-10-22 */ /** * classe astratta utile per il costruttore e per il Protocollo di chiusura */ public abstract class SlaveForDir { protected static final String CODICE_TERMINAZIONE = "029.TERMINATE"; protected final ManagerQueue<String> coda; public SlaveForDir(ManagerQueue<String> c) { this.coda = c; } }
[ "ludo.venturi@gmail.com" ]
ludo.venturi@gmail.com
4111b7efda7459937f8f79f7c6e5484b4b105a76
0144030fd822ff06d875e4ac2b1201c2cc04c77d
/API/src/main/java/org/sikuli/script/Runner.java
391b40e555dc387f7a39aca742f0c039b299f06e
[ "MIT" ]
permissive
xiaolongWangDev/SikuliX1
56ecffe16f41aad888541328080210f2cb18474d
cad35cdc580ca12762f2410f279e06366c9e7cc2
refs/heads/master
2020-04-20T10:17:38.051534
2019-02-05T06:58:52
2019-02-05T06:58:52
168,786,983
0
0
MIT
2019-02-02T02:46:01
2019-02-02T02:46:00
null
UTF-8
Java
false
false
49,667
java
/* * Copyright (c) 2010-2018, sikuli.org, sikulix.com - MIT license */ package org.sikuli.script; import org.apache.commons.cli.CommandLine; import org.sikuli.basics.Debug; import org.sikuli.basics.FileManager; import org.sikuli.basics.Settings; import org.sikuli.util.CommandArgs; import org.sikuli.util.CommandArgsEnum; import org.sikuli.util.JythonHelper; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.File; import java.io.FileReader; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * INTERNAL USE --- NOT official API<br> * not in version 2 */ public class Runner { static final String me = "Runner: "; static final int lvl = 3; static final RunTime runTime = RunTime.get(); public static Map<String, String> endingTypes = new HashMap<String, String>(); public static Map<String, String> typeEndings = new HashMap<String, String>(); public static Map<String, String> runnerTypes = new HashMap<String, String>(); public static String ERUBY = "rb"; public static String EPYTHON = "py"; public static String EJSCRIPT = "js"; public static String EASCRIPT = "script"; public static String ESSCRIPT = "ps1"; public static String EPLAIN = "txt"; public static String EDEFAULT = EPYTHON; public static String CPYTHON = "text/python"; public static String CRUBY = "text/ruby"; public static String CJSCRIPT = "text/javascript"; public static String CASCRIPT = "text/applescript"; public static String CSSCRIPT = "text/powershell"; public static String CPLAIN = "text/plain"; public static String RPYTHON = "jython"; public static String RRUBY = "jruby"; public static String RJSCRIPT = "JavaScript"; public static String RASCRIPT = "AppleScript"; public static String RSSCRIPT = "PowerShell"; public static String RRSCRIPT = "Robot"; public static String RDEFAULT = RPYTHON; private static String[] runScripts = null; private static String[] testScripts = null; private static int lastReturnCode = 0; private static String beforeJSjava8 = "load(\"nashorn:mozilla_compat.js\");"; private static String beforeJS = "importPackage(Packages.org.sikuli.script); " + "importClass(Packages.org.sikuli.basics.Debug); " + "importClass(Packages.org.sikuli.basics.Settings);"; static { endingTypes.put(EPYTHON, CPYTHON); endingTypes.put(ERUBY, CRUBY); endingTypes.put(EJSCRIPT, CJSCRIPT); endingTypes.put(EPLAIN, CPLAIN); for (String k : endingTypes.keySet()) { typeEndings.put(endingTypes.get(k), k); } runnerTypes.put(EPYTHON, RPYTHON); runnerTypes.put(ERUBY, RRUBY); runnerTypes.put(EJSCRIPT, RJSCRIPT); } static void log(int level, String message, Object... args) { Debug.logx(level, me + message, args); } public static String[] evalArgs(String[] args) { CommandArgs cmdArgs = new CommandArgs("SCRIPT"); CommandLine cmdLine = cmdArgs.getCommandLine(CommandArgs.scanArgs(args)); String cmdValue; if (cmdLine == null || cmdLine.getOptions().length == 0) { log(-1, "Did not find any valid option on command line!"); cmdArgs.printHelp(); System.exit(1); } if (cmdLine.hasOption(CommandArgsEnum.HELP.shortname())) { cmdArgs.printHelp(); System.exit(1); } if (cmdLine.hasOption(CommandArgsEnum.LOGFILE.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.LOGFILE.longname()); if (!Debug.setLogFile(cmdValue == null ? "" : cmdValue)) { System.exit(1); } } if (cmdLine.hasOption(CommandArgsEnum.USERLOGFILE.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.USERLOGFILE.longname()); if (!Debug.setUserLogFile(cmdValue == null ? "" : cmdValue)) { System.exit(1); } } if (cmdLine.hasOption(CommandArgsEnum.DEBUG.shortname())) { cmdValue = cmdLine.getOptionValue(CommandArgsEnum.DEBUG.longname()); if (cmdValue == null) { Debug.setDebugLevel(3); Settings.LogTime = true; if (!Debug.isLogToFile()) { Debug.setLogFile(""); } } else { Debug.setDebugLevel(cmdValue); } } runTime.setArgs(cmdArgs.getUserArgs(), cmdArgs.getSikuliArgs()); log(lvl, "commandline: %s", cmdArgs.getArgsOrg()); if (lvl > 2) { runTime.printArgs(); } // select script runner and/or start interactive session // option is overloaded - might specify runner for -r/-t // if (cmdLine.hasOption(CommandArgsEnum.INTERACTIVE.shortname())) { // if (!cmdLine.hasOption(CommandArgsEnum.RUN.shortname()) // && !cmdLine.hasOption(CommandArgsEnum.TEST.shortname())) { // runTime.interactiveRunner = cmdLine.getOptionValue(CommandArgsEnum.INTERACTIVE.longname()); // runTime.runningInteractive = true; // return null; // } // } String[] runScripts = null; runTime.runningTests = false; if (cmdLine.hasOption(CommandArgsEnum.RUN.shortname())) { runScripts = cmdLine.getOptionValues(CommandArgsEnum.RUN.longname()); } // else if (cmdLine.hasOption(CommandArgsEnum.TEST.shortname())) { // runScripts = cmdLine.getOptionValues(CommandArgsEnum.TEST.longname()); // log(-1, "Command line option -t: not yet supported! %s", Arrays.asList(args).toString()); // runTime.runningTests = true; ////TODO run a script as unittest with HTMLTestRunner // System.exit(1); // } return runScripts; } public static int run(String givenName) { return run(givenName, new String[0]); } public static int run(String givenName, String[] args) { String savePath = ImagePath.getBundlePathSet(); int retVal = new RunBox(givenName, args).run(); if (savePath != null) { ImagePath.setBundlePath(savePath); } lastReturnCode = retVal; return retVal; } public static int getLastReturnCode() { return lastReturnCode; } public static int runScripts(String[] args) { runScripts = Runner.evalArgs(args); String someJS = ""; int exitCode = 0; if (runScripts != null && runScripts.length > 0) { for (String givenScriptName : runScripts) { if (lastReturnCode == -1) { log(lvl, "Exit code -1: Terminating multi-script-run"); break; } someJS = runTime.getOption("runsetup"); if (!someJS.isEmpty()) { log(lvl, "Options.runsetup: %s", someJS); new RunBox().runjs(null, null, someJS, null); } RunBox rb = new RunBox(givenScriptName, runTime.getArgs()); exitCode = rb.run(); someJS = runTime.getOption("runteardown"); if (!someJS.isEmpty()) { log(lvl, "Options.runteardown: %s", someJS); new RunBox().runjs(null, null, someJS, null); } if (exitCode == -999) { exitCode = lastReturnCode; } lastReturnCode = exitCode; } } return exitCode; } public static File getScriptFile(File fScriptFolder) { if (fScriptFolder == null) { return null; } File[] content = FileManager.getScriptFile(fScriptFolder); if (null == content) { return null; } File fScript = null; for (File aFile : content) { for (String suffix : Runner.endingTypes.keySet()) { if (!aFile.getName().endsWith("." + suffix)) { continue; } fScript = aFile; break; } if (fScript != null) { break; } } // try with compiled script if (content.length == 1 && content[0].getName().endsWith("$py.class")) { fScript = content[0]; } return fScript; } static JythonHelper pyRunner = null; static Class cIDE; static Method mShow; static Method mHide; protected static boolean initpy() { if (pyRunner == null) { pyRunner = JythonHelper.get(); if (pyRunner == null) { return false; } pyRunner.exec("# -*- coding: utf-8 -*- "); pyRunner.exec("import org.sikuli.script.SikulixForJython"); pyRunner.exec("from sikuli import *"); } return true; } static Object rbRunner = null; static Object txtRunner = null; static ScriptEngine jsRunner = null; public static ScriptEngine initjs() { ScriptEngineManager jsFactory = new ScriptEngineManager(); ScriptEngine jsr = jsFactory.getEngineByName("JavaScript"); if (jsr != null) { log(lvl, "ScriptingEngine started: JavaScript (ending .js)"); } else { Sikulix.terminate(999, "ScriptingEngine for JavaScript not available"); } if (RunTime.Type.IDE.equals(runTime.runType)) { try { cIDE = Class.forName("org.sikuli.ide.SikuliIDE"); mHide = cIDE.getMethod("hideIDE", new Class[0]); mShow = cIDE.getMethod("showIDE", new Class[0]); } catch (Exception ex) { log(-1, "initjs: getIDE"); } } return jsr; } public static String prologjs(String before) { String after = before; if (after.isEmpty()) { if (runTime.isJava8()) { after += beforeJSjava8; } after += beforeJS; } else { String commands = runTime.extractResourceToString("JavaScript", "commands.js", ""); if (commands != null) { after += commands; } } return after; } public static Object[] runBoxInit(String givenName, File scriptProject, URL uScriptProject) { String gitScripts = "https://github.com/RaiMan/SikuliX-2014/tree/master/TestScripts/"; String givenScriptHost = ""; String givenScriptFolder = ""; String givenScriptName; String givenScriptScript = ""; String givenScriptType = "sikuli"; String givenScriptScriptType = RDEFAULT; Boolean givenScriptExists = true; URL uGivenScript = null; URL uGivenScriptFile = null; givenScriptName = givenName; String[] parts = null; int isNet; boolean isInline = false; givenName = givenName.trim(); if (givenName.toLowerCase().startsWith(RASCRIPT.toLowerCase())) { givenScriptScriptType = RASCRIPT; givenScriptName = null; givenScriptScript = givenName.substring(RASCRIPT.length() + 1); isInline = true; } else if (givenName.toLowerCase().startsWith(RSSCRIPT.toLowerCase())) { givenScriptScriptType = RSSCRIPT; givenScriptName = null; givenScriptScript = givenName.substring(RSSCRIPT.length() + 1); isInline = true; } else if (givenName.toLowerCase().startsWith(RRSCRIPT.toLowerCase())) { givenScriptScriptType = RRSCRIPT; givenScriptName = null; givenScriptScript = givenName.substring(RRSCRIPT.length() + 1); isInline = true; } else if (givenName.toLowerCase().startsWith("git*")) { if (givenName.length() == 4) { givenName = gitScripts + "showcase"; } else { givenName = gitScripts + givenName.substring(4); } } if (!isInline) { boolean fromNet = false; String scriptLocation = givenName; String content = ""; if (-1 < (isNet = givenName.indexOf("://"))) { givenName = givenName.substring(isNet + 3); if (givenName.indexOf(":") == -1) { givenName = givenName.replaceFirst("/", ":"); } } if (givenName.indexOf(":") > 5) { parts = givenName.split(":"); if (parts.length > 1 && !parts[1].isEmpty()) { fromNet = true; givenScriptHost = parts[0]; givenScriptName = new File(parts[1]).getName(); String fpFolder = new File(parts[1]).getParent(); if (null != fpFolder && !fpFolder.isEmpty()) { givenScriptFolder = FileManager.slashify(fpFolder, true); } } scriptLocation = givenName; givenScriptExists = false; } if (fromNet) { if (givenScriptHost.contains("github.com")) { givenScriptHost = "https://raw.githubusercontent.com"; givenScriptFolder = givenScriptFolder.replace("tree/", ""); } else { givenScriptHost = "http://" + givenScriptHost; } if (givenScriptName.endsWith(".zip")) { scriptLocation = givenScriptHost + givenScriptFolder + givenScriptName; if (0 < FileManager.isUrlUseabel(scriptLocation)) { Sikulix.terminate(999, ".zip from net not yet supported\n%s", scriptLocation); } } else { for (String suffix : endingTypes.keySet()) { String dlsuffix = ""; if (suffix != "js") { dlsuffix = ".txt"; } givenScriptScript = givenScriptName + "/" + givenScriptName + "." + suffix; scriptLocation = givenScriptHost + "/" + givenScriptFolder + givenScriptScript; givenScriptScriptType = runnerTypes.get(suffix); if (0 < FileManager.isUrlUseabel(scriptLocation)) { content = FileManager.downloadURLtoString(scriptLocation); break; } else if (!dlsuffix.isEmpty()) { givenScriptScript = givenScriptName + "/" + givenScriptName + "." + suffix + dlsuffix; scriptLocation = givenScriptHost + "/" + givenScriptFolder + givenScriptScript; if (0 < FileManager.isUrlUseabel(scriptLocation)) { content = FileManager.downloadURLtoString(scriptLocation); break; } } scriptLocation = givenScriptHost + "/" + givenScriptFolder + givenScriptName; } if (content != null && !content.isEmpty()) { givenScriptType = "NET"; givenScriptScript = content; givenScriptExists = true; try { uGivenScript = new URL(givenScriptHost + "/" + givenScriptFolder + givenScriptName); } catch (Exception ex) { givenScriptExists = false; } } else { givenScriptExists = false; } } if (!givenScriptExists) { log(-1, "given script location not supported or not valid:\n%s", scriptLocation); } else { String header = "# "; String trailer = "\n"; if (RJSCRIPT.equals(givenScriptScriptType)) { header = "/*\n"; trailer = "*/\n"; } header += scriptLocation + "\n"; if (Debug.is() > 2) { FileManager.writeStringToFile(header + trailer + content, new File(runTime.fSikulixStore, "LastScriptFromNet.txt")); } } } else { boolean sameFolder = givenScriptName.startsWith("./"); if (sameFolder) { givenScriptName = givenScriptName.substring(2); } if (givenScriptName.startsWith("JS*")) { givenScriptName = new File(runTime.fSxProjectTestScriptsJS, givenScriptName.substring(3)).getPath(); } if (givenScriptName.startsWith("TEST*")) { givenScriptName = new File(runTime.fSxProjectTestScripts, givenScriptName.substring(5)).getPath(); } String scriptName = new File(givenScriptName).getName(); if (scriptName.contains(".")) { parts = scriptName.split("\\."); givenScriptScript = parts[0]; givenScriptType = parts[1]; } else { givenScriptScript = scriptName; } if (sameFolder && scriptProject != null) { givenScriptName = new File(scriptProject, givenScriptName).getPath(); } else if (sameFolder && uScriptProject != null) { givenScriptHost = uScriptProject.getHost(); givenScriptFolder = uScriptProject.getPath().substring(1); } else if (scriptProject == null && givenScriptHost.isEmpty()) { String fpParent = new File(givenScriptName).getParent(); if (fpParent == null || fpParent.isEmpty()) { scriptProject = null; } else { scriptProject = new File(givenScriptName).getParentFile(); } } } } Object[] vars = new Object[]{givenScriptHost, givenScriptFolder, givenScriptName, givenScriptScript, givenScriptType, givenScriptScriptType, uGivenScript, uGivenScriptFile, givenScriptExists, scriptProject, uScriptProject}; return vars; } public static void runjsEval(String script) { new RunBox().runjsEval(script); } public static int runjs(File fScript, URL uGivenScript, String givenScriptScript, String[] args) { return new RunBox().runjs(fScript, uGivenScript, givenScriptScript, args); } public static int runas(String givenScriptScript) { return runas(givenScriptScript, false); } public static int runrobot(String code) { if (!JythonHelper.get().prepareRobot()) { return -1; } boolean showReport = true; if (code.length() > 7 && code.substring(0, 7).contains("silent\n")) { code = code.substring(7); showReport = false; } File script = new File(ImagePath.getBundlePath()); File fRobotWork = new File(script.getAbsolutePath() + ".robot"); FileManager.deleteFileOrFolder(fRobotWork); fRobotWork.mkdir(); String sName = script.getName().replace(".sikuli", ""); File fPyCode = new File(script, sName + ".py"); String pyCode = FileManager.readFileToString(fPyCode); int prefix = pyCode.indexOf("\"\"\")"); if (prefix > 0) { pyCode = pyCode.substring(prefix + 4).trim(); int refLib = code.indexOf("./inline/"); String inlineLib = ""; File fInline = null; String fpInline = ""; // Keyword implementations are inline if (!pyCode.isEmpty()) { if (refLib < 0) { log(-1, "runRobot: inline code ignored - no ./inline/"); } inlineLib = code.substring(refLib + 9); inlineLib = inlineLib.substring(0, inlineLib.indexOf("\n")).trim(); fInline = new File(fRobotWork, inlineLib + ".py"); pyCode = "from sikuli import *\n" + pyCode; FileManager.writeStringToFile(pyCode, fInline); fpInline = FileManager.slashify(fInline.getAbsolutePath(), false); code = code.replace("./inline/" + inlineLib, fpInline); } else { if (refLib > -1) { log(-1, "runRobot: having ./inline/, but no inline code found"); return -1; } } } File fRobot = new File(fRobotWork, sName + ".robot"); FileManager.writeStringToFile(code, fRobot); if (!initpy()) { log(-1, "Running Python scripts:init failed"); return -999; } pyRunner.exec("from sikuli import *; from threading import currentThread; currentThread().name = \"MainThread\""); //pyRunner.exec("import robot.run;"); String robotCmd = String.format( "ret = robot.run(\"%s\", " + "outputdir=\"%s\")", fRobot, fRobotWork); File fReport = new File(fRobotWork, "report.html"); String urlReport = fReport.getAbsolutePath(); if (RunTime.get().runningWindows) { robotCmd = robotCmd.replaceAll("\\\\", "\\\\\\\\"); urlReport = "/" + urlReport.replaceAll("\\\\", "/"); } pyRunner.exec(robotCmd + "; print \"robot.run returned:\", ret; " + String.format("print \"robot.run output is here:\\n%s\";", fRobotWork.getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"))); if (showReport && new File(fRobotWork, "report.html").exists()) { App.openLink("file:" + urlReport); } return 0; } //<editor-fold defaultstate="collapsed" desc="robot run options"> // -N --name name Set the name of the top level test suite. Underscores // in the name are converted to spaces. Default name is // created from the name of the executed data source. // -D --doc documentation Set the documentation of the top level test suite. // Underscores in the documentation are converted to // spaces and it may also contain simple HTML formatting // (e.g. *bold* and http://url/). // -M --metadata name:value * Set metadata of the top level suite. Underscores // in the name and value are converted to spaces. Value // can contain same HTML formatting as --doc. // Example: --metadata version:1.2 // -G --settag tag * Sets given tag(s) to all executed test cases. // -t --test name * Select test cases to run by name or long name. Name // is case and space insensitive and it can also be a // simple pattern where `*` matches anything and `?` // matches any char. If using `*` and `?` in the console // is problematic see --escape and --argumentfile. // -s --suite name * Select test suites to run by name. When this option // is used with --test, --include or --exclude, only // test cases in matching suites and also matching other // filtering criteria are selected. Name can be a simple // pattern similarly as with --test and it can contain // parent name separated with a dot. For example // `-s X.Y` selects suite `Y` only if its parent is `X`. // -i --include tag * Select test cases to run by tag. Similarly as name // with --test, tag is case and space insensitive and it // is possible to use patterns with `*` and `?` as // wildcards. Tags and patterns can also be combined // together with `AND`, `OR`, and `NOT` operators. // Examples: --include foo --include bar* // --include fooANDbar* // -e --exclude tag * Select test cases not to run by tag. These tests are // not run even if included with --include. Tags are // matched using the rules explained with --include. // -R --rerunfailed output Select failed tests from an earlier output file to be // re-executed. Equivalent to selecting same tests // individually using --test option. // --runfailed output Deprecated since RF 2.8.4. Use --rerunfailed instead. // -c --critical tag * Tests having given tag are considered critical. If no // critical tags are set, all tags are critical. Tags // can be given as a pattern like with --include. // -n --noncritical tag * Tests with given tag are not critical even if they // have a tag set with --critical. Tag can be a pattern. // -v --variable name:value * Set variables in the test data. Only scalar // variables are supported and name is given without // `${}`. See --escape for how to use special characters // and --variablefile for a more powerful variable // setting mechanism that allows also list variables. // Examples: // --variable str:Hello => ${str} = `Hello` // -v str:Hi_World -E space:_ => ${str} = `Hi World` // -v x: -v y:42 => ${x} = ``, ${y} = `42` // -V --variablefile path * File to read variables from (e.g. `path/vars.py`). // Example file: // | import random // | __all__ = [`scalar`, `LIST__var`, `integer`] // | scalar = `Hello world!` // | LIST__var = [`Hello`, `list`, `world`] // | integer = random.randint(1,10) // => // ${scalar} = `Hello world!` // @{var} = [`Hello`,`list`,`world`] // ${integer} = <random integer from 1 to 10> // -d --outputdir dir Where to create output files. The default is the // directory where tests are run from and the given path // is considered relative to that unless it is absolute. // -o --output file XML output file. Given path, similarly as paths given // to --log, --report, --xunit, and --debugfile, is // relative to --outputdir unless given as an absolute // path. Other output files are created based on XML // output files after the test execution and XML outputs // can also be further processed with Rebot tool. Can be // disabled by giving a special value `NONE`. In this // case, also log and report are automatically disabled. // Default: output.xml // -l --log file HTML log file. Can be disabled by giving a special // value `NONE`. Default: log.html // Examples: `--log mylog.html`, `-l NONE` // -r --report file HTML report file. Can be disabled with `NONE` // similarly as --log. Default: report.html // -x --xunit file xUnit compatible result file. Not created unless this // option is specified. // --xunitfile file Deprecated. Use --xunit instead. // --xunitskipnoncritical Mark non-critical tests on xUnit output as skipped. // -b --debugfile file Debug file written during execution. Not created // unless this option is specified. // -T --timestampoutputs When this option is used, timestamp in a format // `YYYYMMDD-hhmmss` is added to all generated output // files between their basename and extension. For // example `-T -o output.xml -r report.html -l none` // creates files like `output-20070503-154410.xml` and // `report-20070503-154410.html`. // --splitlog Split log file into smaller pieces that open in // browser transparently. // --logtitle title Title for the generated test log. The default title // is `<Name Of The Suite> Test Log`. Underscores in // the title are converted into spaces in all titles. // --reporttitle title Title for the generated test report. The default // title is `<Name Of The Suite> Test Report`. // --reportbackground colors Background colors to use in the report file. // Either `all_passed:critical_passed:failed` or // `passed:failed`. Both color names and codes work. // Examples: --reportbackground green:yellow:red // --reportbackground #00E:#E00 // -L --loglevel level Threshold level for logging. Available levels: TRACE, // DEBUG, INFO (default), WARN, NONE (no logging). Use // syntax `LOGLEVEL:DEFAULT` to define the default // visible log level in log files. // Examples: --loglevel DEBUG // --loglevel DEBUG:INFO // --suitestatlevel level How many levels to show in `Statistics by Suite` // in log and report. By default all suite levels are // shown. Example: --suitestatlevel 3 // --tagstatinclude tag * Include only matching tags in `Statistics by Tag` // and `Test Details` in log and report. By default all // tags set in test cases are shown. Given `tag` can // also be a simple pattern (see e.g. --test). // --tagstatexclude tag * Exclude matching tags from `Statistics by Tag` and // `Test Details`. This option can be used with // --tagstatinclude similarly as --exclude is used with // --include. // --tagstatcombine tags:name * Create combined statistics based on tags. // These statistics are added into `Statistics by Tag` // and matching tests into `Test Details`. If optional // `name` is not given, name of the combined tag is got // from the specified tags. Tags are combined using the // rules explained in --include. // Examples: --tagstatcombine requirement-* // --tagstatcombine tag1ANDtag2:My_name // --tagdoc pattern:doc * Add documentation to tags matching given pattern. // Documentation is shown in `Test Details` and also as // a tooltip in `Statistics by Tag`. Pattern can contain // characters `*` (matches anything) and `?` (matches // any char). Documentation can contain formatting // similarly as with --doc option. // Examples: --tagdoc mytag:My_documentation // --tagdoc regression:*See*_http://info.html // --tagdoc owner-*:Original_author // --tagstatlink pattern:link:title * Add external links into `Statistics by // Tag`. Pattern can contain characters `*` (matches // anything) and `?` (matches any char). Characters // matching to wildcard expressions can be used in link // and title with syntax %N, where N is index of the // match (starting from 1). In title underscores are // automatically converted to spaces. // Examples: --tagstatlink mytag:http://my.domain:Link // --tagstatlink bug-*:http://tracker/id=%1:Bug_Tracker // --removekeywords all|passed|for|wuks|name:<pattern> * Remove keyword data // from the generated log file. Keywords containing // warnings are not removed except in `all` mode. // all: remove data from all keywords // passed: remove data only from keywords in passed // test cases and suites // for: remove passed iterations from for loops // wuks: remove all but the last failing keyword // inside `BuiltIn.Wait Until Keyword Succeeds` // name:<pattern>: remove data from keywords that match // the given pattern. The pattern is matched // against the full name of the keyword (e.g. // 'MyLib.Keyword', 'resource.Second Keyword'), // is case, space, and underscore insensitive, // and may contain `*` and `?` as wildcards. // Examples: --removekeywords name:Lib.HugeKw // --removekeywords name:myresource.* // --flattenkeywords for|foritem|name:<pattern> * Flattens matching keywords // in the generated log file. Matching keywords get all // log messages from their child keywords and children // are discarded otherwise. // for: flatten for loops fully // foritem: flatten individual for loop iterations // name:<pattern>: flatten matched keywords using same // matching rules as with // `--removekeywords name:<pattern>` // --listener class * A class for monitoring test execution. Gets // notifications e.g. when a test case starts and ends. // Arguments to listener class can be given after class // name, using colon as separator. For example: // --listener MyListenerClass:arg1:arg2 // --warnonskippedfiles If this option is used, skipped test data files will // cause a warning that is visible in the console output // and the log file. By default skipped files only cause // an info level syslog message. // --nostatusrc Sets the return code to zero regardless of failures // in test cases. Error codes are returned normally. // --runemptysuite Executes tests also if the top level test suite is // empty. Useful e.g. with --include/--exclude when it // is not an error that no test matches the condition. // --dryrun Verifies test data and runs tests so that library // keywords are not executed. // --exitonfailure Stops test execution if any critical test fails. // --exitonerror Stops test execution if any error occurs when parsing // test data, importing libraries, and so on. // --skipteardownonexit Causes teardowns to be skipped if test execution is // stopped prematurely. // --randomize all|suites|tests|none Randomizes the test execution order. // all: randomizes both suites and tests // suites: randomizes suites // tests: randomizes tests // none: no randomization (default) // Use syntax `VALUE:SEED` to give a custom random seed. // The seed must be an integer. // Examples: --randomize all // --randomize tests:1234 // --runmode mode * Deprecated in version 2.8. Use individual options // --dryrun, --exitonfailure, --skipteardownonexit, or // --randomize instead. // -W --monitorwidth chars Width of the monitor output. Default is 78. // -C --monitorcolors auto|on|ansi|off Use colors on console output or not. // auto: use colors when output not redirected (default) // on: always use colors // ansi: like `on` but use ANSI colors also on Windows // off: disable colors altogether // Note that colors do not work with Jython on Windows. // -K --monitormarkers auto|on|off Show `.` (success) or `F` (failure) on // console when top level keywords in test cases end. // Values have same semantics as with --monitorcolors. // -P --pythonpath path * Additional locations (directories, ZIPs, JARs) where // to search test libraries from when they are imported. // Multiple paths can be given by separating them with a // colon (`:`) or using this option several times. Given // path can also be a glob pattern matching multiple // paths but then it normally must be escaped or quoted. // Examples: // --pythonpath libs/ // --pythonpath /opt/testlibs:mylibs.zip:yourlibs // -E star:STAR -P lib/STAR.jar -P mylib.jar // -E --escape what:with * Escape characters which are problematic in console. // `what` is the name of the character to escape and // `with` is the string to escape it with. Note that // all given arguments, incl. data sources, are escaped // so escape characters ought to be selected carefully. // <--------------------ESCAPES------------------------> // Examples: // --escape space:_ --metadata X:Value_with_spaces // -E space:SP -E quot:Q -v var:QhelloSPworldQ // -A --argumentfile path * Text file to read more arguments from. Use special // path `STDIN` to read contents from the standard input // stream. File can have both options and data sources // one per line. Contents do not need to be escaped but // spaces in the beginning and end of lines are removed. // Empty lines and lines starting with a hash character // (#) are ignored. // Example file: // | --include regression // | --name Regression Tests // | # This is a comment line // | my_tests.html // | path/to/test/directory/ // Examples: // --argumentfile argfile.txt --argumentfile STDIN // -h -? --help Print usage instructions. // --version Print version information. // //Options that are marked with an asterisk (*) can be specified multiple times. //For example, `--test first --test third` selects test cases with name `first` //and `third`. If other options are given multiple times, the last value is used. // //Long option format is case-insensitive. For example, --SuiteStatLevel is //equivalent to but easier to read than --suitestatlevel. Long options can //also be shortened as long as they are unique. For example, `--logti Title` //works while `--lo log.html` does not because the former matches only --logtitle //but the latter matches --log, --loglevel and --logtitle. // //Environment Variables //===================== // //ROBOT_OPTIONS Space separated list of default options to be placed // in front of any explicit options on the command line. //ROBOT_SYSLOG_FILE Path to a file where Robot Framework writes internal // information about parsing test case files and running // tests. Can be useful when debugging problems. If not // set, or set to special value `NONE`, writing to the // syslog file is disabled. //ROBOT_SYSLOG_LEVEL Log level to use when writing to the syslog file. // Available levels are the same as for --loglevel // command line option and the default is INFO. //</editor-fold> public static int runas(String givenScriptScript, boolean silent) { if (!runTime.runningMac) { return -1; } String prefix = silent ? "!" : ""; String osascriptShebang = "#!/usr/bin/osascript\n"; givenScriptScript = osascriptShebang + givenScriptScript; File aFile = FileManager.createTempFile("script"); aFile.setExecutable(true); FileManager.writeStringToFile(givenScriptScript, aFile); String retVal = runTime.runcmd(new String[]{prefix + aFile.getAbsolutePath()}); String[] parts = retVal.split("\n"); int retcode = -1; try { retcode = Integer.parseInt(parts[0]); } catch (Exception ex) { } if (retcode != 0) { if (silent) { log(lvl, "AppleScript:\n%s\nreturned:\n%s", givenScriptScript, runTime.getLastCommandResult()); } else { log(-1, "AppleScript:\n%s\nreturned:\n%s", givenScriptScript, runTime.getLastCommandResult()); } } return retcode; } public static int runps(String givenScriptScript) { if (!runTime.runningWindows) { return -1; } File aFile = FileManager.createTempFile("ps1"); FileManager.writeStringToFile(givenScriptScript, aFile); String[] psDirect = new String[]{ "powershell.exe", "-ExecutionPolicy", "UnRestricted", "-NonInteractive", "-NoLogo", "-NoProfile", "-WindowStyle", "Hidden", "-File", aFile.getAbsolutePath() }; String[] psCmdType = new String[]{ "cmd.exe", "/S", "/C", "type " + aFile.getAbsolutePath() + " | powershell -noprofile -" }; String retVal = runTime.runcmd(psCmdType); String[] parts = retVal.split("\\s"); int retcode = -1; try { retcode = Integer.parseInt(parts[0]); } catch (Exception ex) { } if (retcode != 0) { log(-1, "PowerShell:\n%s\nreturned:\n%s", givenScriptScript, runTime.getLastCommandResult()); } return retcode; } public static int runpy(File fScript, URL uGivenScript, String givenScriptScript, String[] args) { return new RunBox().runpy(fScript, uGivenScript, givenScriptScript, args); } public static int runrb(File fScript, URL uGivenScript, String givenScriptScript, String[] args) { return new RunBox().runrb(fScript, uGivenScript, givenScriptScript, args); } public static int runtxt(File fScript, URL uGivenScript, String givenScriptScript, String[] args) { return new RunBox().runtxt(fScript, uGivenScript, givenScriptScript, args); } static class RunBox { String jsScript; public RunBox() { } public static int runtxt(File fScript, URL script, String scriptName, String[] args) { Runner.log(-1, "Running plain text scripts not yet supported!"); return -999; } public static int runrb(File fScript, URL script, String scriptName, String[] args) { Runner.log(-1, "Running Ruby scripts not yet supported!"); return -999; } public static int runpy(File fScript, URL script, String scriptName, String[] args) { String fpScript; if (fScript == null) { fpScript = script.toExternalForm(); } else { fpScript = fScript.getAbsolutePath(); } if (!Runner.initpy()) { Runner.log(-1, "Running Python scripts:init failed"); return -999; } if (args == null || args.length == 0) { args = RunTime.get().getArgs(); } String[] newArgs = new String[args.length + 1]; for (int i = 0; i < args.length; i++) { newArgs[i + 1] = args[i]; } newArgs[0] = fpScript; Runner.pyRunner.setSysArgv(newArgs); int retval; if (fScript == null) { ImagePath.addHTTP(fpScript); retval = (Runner.pyRunner.exec(scriptName) ? 0 : -1); ImagePath.removeHTTP(fpScript); } else { if (null == ImagePath.getBundlePathSet()) ImagePath.setBundlePath(fScript.getParent()); else { ImagePath.add(fScript.getParent()); } retval = Runner.pyRunner.execfile(fpScript); } return retval; } public void runjsEval(String script) { if (script.isEmpty()) { return; } String initSikulix = ""; if (Runner.jsRunner == null) { Runner.jsRunner = Runner.initjs(); initSikulix = Runner.prologjs(initSikulix); } try { if (!initSikulix.isEmpty()) { initSikulix = Runner.prologjs(initSikulix); Runner.jsRunner.eval(initSikulix); } Runner.log(lvl, "JavaScript: eval: %s", script); jsScript = script; Thread evalThread = new Thread() { @Override public void run() { try { Runner.mHide.invoke(null); Runner.jsRunner.eval(jsScript); Runner.mShow.invoke(null); } catch (Exception ex) { Runner.log(-1, "not possible:\n%s", ex); try { Runner.mShow.invoke(null); } catch (Exception e) { Sikulix.terminate(999, "IDE::showWindow not possible"); } } } }; evalThread.start(); } catch (Exception ex) { Runner.log(-1, "init not possible:\n%s", ex); } } public int runjs(File fScript, URL script, String scriptName, String[] args) { String initSikulix = ""; if (Runner.jsRunner == null) { Runner.jsRunner = Runner.initjs(); initSikulix = Runner.prologjs(initSikulix); } try { if (null != fScript) { File innerBundle = new File(fScript.getParentFile(), scriptName + ".sikuli"); if (innerBundle.exists()) { ImagePath.setBundlePath(innerBundle.getCanonicalPath()); } else { ImagePath.setBundlePath(fScript.getParent()); } } else if (script != null) { ImagePath.addHTTP(script.toExternalForm()); String sname = new File(script.toExternalForm()).getName(); ImagePath.addHTTP(script.toExternalForm() + "/" + sname + ".sikuli"); } if (!initSikulix.isEmpty()) { initSikulix = Runner.prologjs(initSikulix); Runner.jsRunner.eval(initSikulix); initSikulix = ""; } if (null != fScript) { Runner.jsRunner.eval(new FileReader(fScript)); } else { Runner.jsRunner.eval(scriptName); } } catch (Exception ex) { Runner.log(-1, "not possible:\n%s", ex); } return 0; } // static File scriptProject = null; // static URL uScriptProject = null; RunTime runTime = RunTime.get(); boolean asTest = false; String[] args = new String[0]; String givenScriptHost = ""; String givenScriptFolder = ""; String givenScriptName = ""; String givenScriptScript = ""; String givenScriptType = "sikuli"; String givenScriptScriptType = RDEFAULT; URL uGivenScript = null; URL uGivenScriptFile = null; boolean givenScriptExists = true; RunBox(String givenName, String[] givenArgs) { Object[] vars = Runner.runBoxInit(givenName, RunTime.scriptProject, RunTime.uScriptProject); givenScriptHost = (String) vars[0]; givenScriptFolder = (String) vars[1]; givenScriptName = (String) vars[2]; givenScriptScript = (String) vars[3]; givenScriptType = (String) vars[4]; givenScriptScriptType = (String) vars[5]; uGivenScript = (URL) vars[6]; uGivenScriptFile = (URL) vars[7]; givenScriptExists = (Boolean) vars[8]; RunTime.scriptProject = (File) vars[9]; RunTime.uScriptProject = (URL) vars[10]; args = givenArgs; } int run() { if (Runner.RASCRIPT.equals(givenScriptScriptType)) { return Runner.runas(givenScriptScript); } else if (Runner.RSSCRIPT.equals(givenScriptScriptType)) { return Runner.runps(givenScriptScript); } else if (Runner.RRSCRIPT.equals(givenScriptScriptType)) { return Runner.runrobot(givenScriptScript); } int exitCode = 0; log(lvl, "givenScriptName:\n%s", givenScriptName); if (-1 == FileManager.slashify(givenScriptName, false).indexOf("/") && RunTime.scriptProject != null) { givenScriptName = new File(RunTime.scriptProject, givenScriptName).getPath(); } if (givenScriptName.endsWith(".skl")) { log(-1, "RunBox.run: .skl scripts not yet supported."); return -9999; // givenScriptName = FileManager.unzipSKL(givenScriptName); // if (givenScriptName == null) { // log(-1, "not possible to make .skl runnable"); // return -9999; // } } if ("NET".equals(givenScriptType)) { if (Runner.RJSCRIPT.equals(givenScriptScriptType)) { exitCode = runjs(null, uGivenScript, givenScriptScript, args); } else if (Runner.RPYTHON.equals(givenScriptScriptType)) { exitCode = runpy(null, uGivenScript, givenScriptScript, args); } else { log(-1, "running from net not supported for %s\n%s", givenScriptScriptType, uGivenScript); } } else { File fScript = Runner.getScriptFile(new File(givenScriptName)); if (fScript == null) { return -9999; } fScript = new File(FileManager.normalizeAbsolute(fScript.getPath(), true)); if (null == RunTime.scriptProject) { RunTime.scriptProject = fScript.getParentFile().getParentFile(); } log(lvl, "Trying to run script:\n%s", fScript); if (fScript.getName().endsWith(EJSCRIPT)) { exitCode = runjs(fScript, null, givenScriptScript, args); } else if (fScript.getName().endsWith(EPYTHON)) { exitCode = runpy(fScript, null, givenScriptScript, args); } else if (fScript.getName().endsWith(ERUBY)) { exitCode = runrb(fScript, null, givenScriptScript, args); } else if (fScript.getName().endsWith(EPLAIN)) { exitCode = runtxt(fScript, null, givenScriptScript, args); } else { log(-1, "Running not supported currently for:\n%s", fScript); return -9999; } } return exitCode; } } }
[ "rmhdevelop@me.com" ]
rmhdevelop@me.com
9369654928218e66a9c574fb4037c0963e87534f
0c8998fa1d986570acd4037a2e2331a116586be0
/Project5QuickSorter.java
285a77b8bc1260dd05406602d767aa4a10e76472
[]
no_license
stempelmeyer/CS3345---Data-Structures-and-Algorithmic-Analysis
a434a5a117de2734d4ce763698dbe35151b07c51
06784e55219b74ca2d2837f0f2e2ca2b4416eed7
refs/heads/main
2023-01-24T03:54:10.748508
2020-12-15T20:43:26
2020-12-15T20:43:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,202
java
//Author: Sarah G. Tempelmeyer //Course: CS 3345.003 //Date: Semester 1 - 11/17/2019 //Assignment: Project 5 - QuickSort //Compiler: Eclipse 2018_12 //Net ID: sgt170030 //Description: Implements several variations of the in-place QuickSort algorithm, each with a different choice of // pivot. The program also outputs the sorted list, unsorted list, and run time for each pivot selection // to files listed in the command line execution. // An example is "./Main_Class 100000 report.txt unsorted.txt sorted.txt" import java.time.Duration; import java.util.ArrayList; import java.util.Random; public class QuickSorter { /* * This private constructor is optional, but it does help to prevent accidental client instantiation of QuickSorter * via the default constructor. (defining any constructor prevents the compiler from creating a default constructor) * This particular anti-instantiation technique is exactly what {@link java.util.Collections} does. */ // throws null pointer exception // returns time in nanoseconds that it took to sort list // list is either non-empty or null public static <E extends Comparable<E>>Duration timedQuickSort(ArrayList<E> list, PivotStrategy pivotStrategy) { try { if(list == null || pivotStrategy == null) throw new NullPointerException(); long startTime = System.nanoTime(); long endTime; // send to quicksort function to be sorted quickSort(pivotStrategy, list, 0, list.size() - 1); endTime = System.nanoTime(); // return Duration.between(startTime, endTime); when Duration is return type return Duration.ofNanos(endTime - startTime); } catch (NullPointerException e) { System.out.println("Null Pointer Exception thrown in timedQuickSort"); return null; } } // throws illegal argument excetion public static ArrayList<Integer> generateRandomList(int size) { try { if (size <= 0) throw new IllegalArgumentException(); // create random upper bound for array list integers Random random = new Random(); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < size; i++) { // adds to list with an integer between 0 and the random upper bound list.add(random.nextInt(100000-(-100000) + 1) - 100000); } return list; } catch (IllegalArgumentException i) { System.out.println("Illegal Argument Exception thrown in generateRandomList"); return new ArrayList<Integer>(0); } } // this private method prints the list to user console private static <E extends Comparable<E>> void printList(ArrayList<E> list) { // use iterator to print list for(int i = 0; i < list.size(); i++) { System.out.printf("%9s",list.get(i)); } System.out.println(); } // sorts small array (< 20 elements) by using insertion sort and returns sorted array private static <E extends Comparable<E>> ArrayList<E> insertionSort(ArrayList<E> list, int left, int right) { int j; // traverses through array once selecting element to insert for (int i = left+1; i < right+1; i++) { E temp = list.get(i); // traverses through previous elements of array to insert selected element for(j = i; j > left && temp.compareTo(list.get(j-1)) < 0; j--) { // inserts element when at beginning of array (j=0) or when element to insert is less than traversing inner pointer list.set(j, list.get(j-1)); } // will if element to insert is larger than the sorted elements before, do not swap/do not enter inner for loop list.set(j, temp); } return list; } // selects and returns pivot using the median of random three elements strategy private static <E extends Comparable<E>> E pivotMedianOfRandom(ArrayList<E> list, int left, int right) { // select random element three times Random rand = new Random(); E element1 = list.get(rand.nextInt(right-left+1)+left); // what if random element chosen is the same as another?? E element2 = list.get(rand.nextInt(right-left+1)+left); E element3 = list.get(rand.nextInt(right-left+1)+left); // element 1 is the pivot if (element1.compareTo(element2) < 0 && element1.compareTo(element3) > 0) // element 3 < element 1 < element 2 return element1; else if (element1.compareTo(element2) > 0 && element1.compareTo(element3) < 0) // element 2 < element 1 < element 3 return element1; // element 2 is the pivot else if (element2.compareTo(element1) < 0 && element2.compareTo(element3) > 0) // element 3 < element 2 < element 1 return element2; else if (element2.compareTo(element1) > 0 && element2.compareTo(element3) < 0) // element 1 < element 2 < element 3 return element2; // element 3 is the pivot else if (element3.compareTo(element1) < 0 && element3.compareTo(element2) > 0) // element 2 < element 3 < element 1 return element3; else // element 1 < element 3 < element 2 return element3; } // selects and returns pivot using the median of three elements strategy private static <E extends Comparable<E>> E pivotMedianOfThree(ArrayList<E> list, int left, int right) { // assign first, middle,and last elements of the array E element1 = list.get(left); E element2 = list.get((left+right)/2); E element3 = list.get(right); // element 1 is the pivot if (element1.compareTo(element2) < 0 && element1.compareTo(element3) > 0) // element 3 < element 1 < element 2 return element1; else if (element1.compareTo(element2) > 0 && element1.compareTo(element3) < 0) // element 2 < element 1 < element 3 return element1; // element 2 is the pivot else if (element2.compareTo(element1) < 0 && element2.compareTo(element3) > 0) // element 3 < element 2 < element 1 return element2; else if (element2.compareTo(element1) > 0 && element2.compareTo(element3) < 0) // element 1 < element 2 < element 3 return element2; // element 3 is the pivot else if (element3.compareTo(element1) < 0 && element3.compareTo(element2) > 0) // element 2 < element 3 < element 1 return element3; else // element 1 < element 3 < element 2 return element3; } // recursive function for quicksort private static <E extends Comparable <E>> void quickSort(PivotStrategy strategy, ArrayList<E> list, int left, int right) { E pivotElement = null; // also check to make sure in array bounds if (left + 20 < right) { // this switch statement selects the pivot switch (strategy) { case FIRST_ELEMENT: pivotElement = list.get(left); // call pivot selection function for first element // System.out.println("This is the first pivot element selected: " + pivotElement); // send list and pivot element to recursive function break; case RANDOM_ELEMENT: Random rand = new Random(); pivotElement =list.get(rand.nextInt(right-left+1)+left); // call pivot selection function for random element // System.out.println("This is the random pivot element selected: " + pivotElement); break; case MEDIAN_OF_THREE_RANDOM_ELEMENTS: pivotElement = pivotMedianOfRandom(list, left, right); // call pivot selection function for three random element // System.out.println("This is the median random pivot element selected: " + pivotElement); break; case MEDIAN_OF_THREE_ELEMENTS: pivotElement = pivotMedianOfThree(list, left, right); // System.out.println("This is the median of 3 pivot element selected: " + pivotElement); break; default: System.out.println("No pivot strategy was chosen"); } // end switch statement // move pivot to the rightmost element of the array (subarray) int pivotLocation = list.indexOf(pivotElement); E temp = list.get(right); list.set(right, pivotElement); list.set(pivotLocation, temp); // partition based off of pivot int i = left; int j = right - 1; // because pivot is moved to the right position for (;;) { // keep moving i to the right while i < pivotElement while(i < list.indexOf(pivotElement) && list.get(i).compareTo(pivotElement) < 0) { i++; } // keep moving j to the left while j > pivotElement while(j > 0 && list.get(j).compareTo(pivotElement) > 0) { j--; } if (list.get(i) == null || list.get(j) == null) { // if either traversal element is past the array bounds, break System.out.println("i or j pointer is null"); break; } else if (i < j) { // swap elements if i < j E swap = list.get(j); list.set(j, list.get(i)); list.set(i, swap); } else { // traversal elements are not null and i > j break; } } // end for loop if (list.get(i) != pivotElement) { // restore pivot (swap i with the pivot) E swap = list.get(right); list.set(right, list.get(i)); list.set(i, swap); } // recursive call with left and right subarrays to pivot quickSort(strategy, list, left, i-1); quickSort(strategy, list, i+1, right); } // end of if left <= right // insertion sort if array or subarray has 20 elements or less else { insertionSort(list, left, right); } return ; } public static enum PivotStrategy { FIRST_ELEMENT, // first element as pivot RANDOM_ELEMENT, // randomly choose pivot element MEDIAN_OF_THREE_RANDOM_ELEMENTS, // choose median of 3 randomly chosen elements as pivot MEDIAN_OF_THREE_ELEMENTS // median of first, center, and last element (book method) } }
[ "noreply@github.com" ]
stempelmeyer.noreply@github.com
937145b3946d3712a2c09f7ee4a39feb963cdea5
c27bc01c43e2b9f959836fd22754aeeebdaac94d
/191012/RegexMatches.java
157e4ff1e1fcdcc6a07e17d82e9c483220d1353e
[]
no_license
tanlex/java
cfde0a1f0b2f20cddf21af45a66c639a92830f50
c4dc1cfaca64e1f687a307accd5817319faf11ad
refs/heads/master
2020-06-21T15:25:39.133680
2019-10-12T09:55:25
2019-10-12T09:55:25
197,490,664
0
0
null
null
null
null
UTF-8
Java
false
false
2,176
java
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches{ /* private static final String REGEX = "\\bcat\\b"; private static final String INPUT = "cat cat cat cattie cat"; */ /* private static final String REGEX = "foo"; private static final String INPUT = "fooooooooooooooooo"; private static final String INPUT2 = "ooooofoooooooooooo"; private static Pattern pattern; private static Matcher matcher; private static Matcher matcher2; */ /* private static String REGEX = "dog"; private static String INPUT = "The dog says meow. " + "All dogs say meow."; private static String REPLACE = "cat"; */ private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoobkkk"; private static String REPLACE = "-"; public static void main(String args[]){ /* Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); int count = 0; while(m.find()){ count++; System.out.println("Match number " + count); System.out.println("start(): " + m.start()); System.out.println("end(): " + m.end()); } */ /* pattern = Pattern.compile(REGEX); matcher = pattern.matcher(INPUT); matcher2 = pattern.matcher(INPUT2); System.out.println("Current REGEX is:"+REGEX); System.out.println("Current INPUT is:"+INPUT); System.out.println("Current INPUT2 is:"+INPUT2); System.out.println("lookingAt():"+matcher.lookingAt()); System.out.println("matches():"+matcher.matches()); System.out.println("lookingAt():"+matcher2.lookingAt()); */ /* Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); */ Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); StringBuffer sb = new StringBuffer(); while(m.find()){ m.appendReplacement(sb,REPLACE); } m.appendTail(sb); System.out.println(sb.toString()); } }
[ "523249435@qq.com" ]
523249435@qq.com
76ce640a68e695db4103e1de88753ccf990e6b4f
d0ff6cdb489f127f081bfd0682f3366de47b6a34
/UPnPProject/devicelib/src/main/java/com/tpvision/sensormgt/datamodel/SensorChangeListener.java
765e10f1ab5104aa68a04975ec4ca40d33705f94
[]
no_license
yurifariasg/upnp-cloud
2f214f617e86a9fd863e387e7996581bc1645734
b1987f3c4efa949d9ffcb773882c961a5ec7d80b
refs/heads/master
2021-01-17T11:04:54.810042
2016-09-06T02:01:45
2016-09-06T02:01:45
45,313,616
0
0
null
null
null
null
UTF-8
Java
false
false
1,729
java
/* Copyright (c) 2013, TP Vision Holding B.V. * All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of TP Vision nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TP VISION HOLDING B.V. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.tpvision.sensormgt.datamodel; public interface SensorChangeListener { void onSensorChange(String collectionID, String sensorID, boolean valueRead, boolean valueTransported, DataItem dataItem); }
[ "yurifariasg@gmail.com" ]
yurifariasg@gmail.com
d5a69ea7710fde755e4518f3e7e4b18698c174f7
ad9c328aeb5ea617a1c056df45ae9acc3e5c1aad
/projects/projects-spring/projects-spring2.5.6/src/main/java/org/springframework/aop/config/AspectComponentDefinition.java
3a5f9e189c3b4797e7a1cb591ff38fb8c26a3c1b
[]
no_license
tangjiquan/collect
3fa4b3fd5fecc7e0d8d7a6bf89151464bd4e98bb
d059d89ae9899bd43b2f5b7d46b7ba88d5f066d4
refs/heads/master
2022-12-22T19:26:37.599708
2019-08-05T15:00:32
2019-08-05T15:00:48
126,582,519
1
0
null
2022-12-16T08:04:19
2018-03-24T09:03:08
Java
UTF-8
Java
false
false
1,854
java
/* * Copyright 2002-2007 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.aop.config; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanReference; import org.springframework.beans.factory.parsing.CompositeComponentDefinition; /** * {@link org.springframework.beans.factory.parsing.ComponentDefinition} * that holds an aspect definition, including its nested pointcuts. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 * @see #getNestedComponents() * @see PointcutComponentDefinition */ public class AspectComponentDefinition extends CompositeComponentDefinition { private final BeanDefinition[] beanDefinitions; private final BeanReference[] beanReferences; public AspectComponentDefinition( String aspectName, BeanDefinition[] beanDefinitions, BeanReference[] beanReferences, Object source) { super(aspectName, source); this.beanDefinitions = (beanDefinitions != null ? beanDefinitions : new BeanDefinition[0]); this.beanReferences = (beanReferences != null ? beanReferences : new BeanReference[0]); } public BeanDefinition[] getBeanDefinitions() { return this.beanDefinitions; } public BeanReference[] getBeanReferences() { return this.beanReferences; } }
[ "2495527426@qq.com" ]
2495527426@qq.com
f154c1341fb3f71e9a48edd9b9e6c8c263983a6e
a09371f214bf653333352935774d2fd1b6796db6
/app/src/test/java/com/example/r30_a/weatheractivity/ExampleUnitTest.java
059bfbdd3fb049b62ad9c5bd289ca72fec892bee
[]
no_license
LucaLin/WeatherInfoTool
59c60765493f24243f6ecaff4d000cc071559dff
9fe5036781f68c4db60f96867466f2fab2f1bf6b
refs/heads/master
2020-05-07T17:57:21.593144
2019-04-17T08:04:28
2019-04-17T08:04:28
180,748,548
0
0
null
null
null
null
UTF-8
Java
false
false
394
java
package com.example.r30_a.weatheractivity; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "luca.lin@tpinformation.com.tw" ]
luca.lin@tpinformation.com.tw
68b362d6dce271803c2b7533347ff32e857702c4
f321db1ace514d08219cc9ba5089ebcfff13c87a
/generated-tests/dynamosa/tests/s1021/6_re2j/evosuite-tests/com/google/re2j/Unicode_ESTest_scaffolding.java
18fdfc9a9c65a4d577c1ca36d698bb31ec7fa788
[]
no_license
sealuzh/dynamic-performance-replication
01bd512bde9d591ea9afa326968b35123aec6d78
f89b4dd1143de282cd590311f0315f59c9c7143a
refs/heads/master
2021-07-12T06:09:46.990436
2020-06-05T09:44:56
2020-06-05T09:44:56
146,285,168
2
2
null
null
null
null
UTF-8
Java
false
false
3,821
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Thu Jul 04 08:20:40 GMT 2019 */ package com.google.re2j; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.junit.AfterClass; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; @EvoSuiteClassExclude public class Unicode_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "com.google.re2j.Unicode"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); } @AfterClass public static void clearEvoSuiteFramework(){ Sandbox.resetDefaultSecurityManager(); java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); setSystemProperties(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); java.lang.System.setProperty("user.dir", "/home/apaniche/performance/Dataset/gordon_scripts/projects/6_re2j"); java.lang.System.setProperty("java.io.tmpdir", "/tmp"); } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(Unicode_ESTest_scaffolding.class.getClassLoader() , "com.google.re2j.UnicodeTables", "com.google.re2j.Unicode" ); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(Unicode_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "com.google.re2j.Unicode", "com.google.re2j.UnicodeTables" ); } }
[ "granogiovanni90@gmail.com" ]
granogiovanni90@gmail.com
bbb69bab20910d42111301f8de3a4a3ae8a3f2ee
bb7c5b09732817fc9f99cc3f246f450c11853895
/src/main/java/com/kostiuk/something/SomethingApplication.java
db4e862263ac3db2b1a08b755a24e8f38241ec39
[]
no_license
kostiuk-repository/something
b8e995ce26f96949bb61bad49b56f2a22f917f8e
31b77c3a6164d3c3e9049b0ae93134aa6156267d
refs/heads/master
2021-02-03T23:35:29.921735
2020-02-27T17:43:20
2020-02-27T17:43:20
243,575,019
0
0
null
null
null
null
UTF-8
Java
false
false
320
java
package com.kostiuk.something; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SomethingApplication { public static void main(String[] args) { SpringApplication.run(SomethingApplication.class, args); } }
[ "vladyslav.kostiuk@clurgo.com" ]
vladyslav.kostiuk@clurgo.com
5e7fc9c22cb47ed079b0377a693e906bb937baff
3ec63163f60d1d58000c193f44d03d7d175ceea8
/src/sohu/test/annotation/func/MethodType.java
950aab2f9c7d361748081f6cbeda9c9bc040a39a
[]
no_license
gaoqi02/learning
715faad73a23235f9c840e81095c8ead228d2c15
4ffc47b38dc84446614cf91550da638918b406e6
refs/heads/master
2020-05-22T01:39:44.731893
2017-05-11T09:47:24
2017-05-11T09:47:24
65,792,025
1
0
null
null
null
null
UTF-8
Java
false
false
531
java
package sohu.test.annotation.func; import java.lang.annotation.*; /** * 定义到可以作用于方法的注解 * Created by qigao212074 on 2016/8/17. */ @Documented//文档 @Retention(RetentionPolicy.RUNTIME)//在运行时可以获取 @Target({ ElementType.TYPE, ElementType.METHOD })//作用到类,方法,接口上等 public @interface MethodType { //枚举类型 public enum MethodTypeEnum { TYPE1, TYPE2 } //实际的值 public MethodTypeEnum methodType() default MethodTypeEnum.TYPE1; }
[ "qigao212074@sohu-inc.com" ]
qigao212074@sohu-inc.com
8a8757fce437700d78d9ea4e97c6542d391a2993
ec3c2cad7144588110dbdf850ee019994affbc2f
/BoShiXuan/app/src/main/java/www/chendanfeng/com/onekeyshare/themes/classic/EditPage.java
1b46437df97f83ab4ba097db4223d5822703768f
[]
no_license
kobeeeeee/BoshiXuan
e764d736efef6d06b4283beb0c7fad1f00e46880
6d52f6cdfaea92997676ec5e6455af2622a66635
refs/heads/master
2021-01-17T17:02:48.160043
2016-08-03T13:39:37
2016-08-03T13:39:37
62,395,411
0
0
null
null
null
null
UTF-8
Java
false
false
6,971
java
/* * 官网地站:http://www.mob.com * 技术支持QQ: 4006852216 * 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复) * * Copyright (c) 2013年 mob.com. All rights reserved. */ package www.chendanfeng.com.onekeyshare.themes.classic; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.drawable.ColorDrawable; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.Platform.ShareParams; import cn.sharesdk.framework.ShareSDK; import www.chendanfeng.com.onekeyshare.OnekeySharePage; import www.chendanfeng.com.onekeyshare.OnekeyShareThemeImpl; import www.chendanfeng.com.onekeyshare.themes.classic.land.FriendListPageLand; import www.chendanfeng.com.onekeyshare.themes.classic.port.FriendListPagePort; import com.mob.tools.gui.AsyncImageView; import com.mob.tools.utils.DeviceHelper; import com.mob.tools.utils.R; public class EditPage extends OnekeySharePage implements OnClickListener, TextWatcher, Runnable { private OnekeyShareThemeImpl impl; protected Platform platform; protected ShareParams sp; protected LinearLayout llPage; protected RelativeLayout rlTitle; protected ScrollView svContent; protected EditText etContent; protected TextView tvCancel; protected TextView tvShare; protected RelativeLayout rlThumb; /** 异步加载图片的控件 */ protected AsyncImageView aivThumb; protected XView xvRemove; protected LinearLayout llBottom; protected TextView tvAt; protected TextView tvTextCouter; protected Bitmap thumb; protected int maxBodyHeight; public EditPage(OnekeyShareThemeImpl impl) { super(impl); this.impl = impl; } public void setPlatform(Platform platform) { this.platform = platform; } public void setShareParams(ShareParams sp) { this.sp = sp; } public void setActivity(Activity activity) { super.setActivity(activity); if (isDialogMode()) { System.err.println("Theme classic does not support dialog mode!"); // activity.setTheme(android.R.style.Theme_Dialog); // activity.requestWindowFeature(Window.FEATURE_NO_TITLE); // if (Build.VERSION.SDK_INT >= 11) { // try { // ReflectHelper.invokeInstanceMethod(activity, "setFinishOnTouchOutside", false); // } catch (Throwable e) {} // } } activity.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); } public void onCreate() { activity.getWindow().setBackgroundDrawable(new ColorDrawable(0xfff3f3f3)); } /** 取消分享时,执行的方法 */ private void cancelAndFinish() { // 分享失败的统计 ShareSDK.logDemoEvent(5, platform); finish(); } /** 执行分享时的方法 */ private void shareAndFinish() { int resId = R.getStringRes(activity, "ssdk_oks_sharing"); if (resId > 0) { Toast.makeText(activity, resId, Toast.LENGTH_SHORT).show(); } if (isDisableSSO()) { platform.SSOSetting(true); } platform.setPlatformActionListener(getCallback()); platform.share(sp); finish(); } /** 编辑界面,显示的图片 */ private void showThumb(Bitmap pic) { PicViewerPage page = new PicViewerPage(impl); page.setImageBitmap(pic); page.show(activity, null); } private void removeThumb() { sp.setImageArray(null); sp.setImageData(null); sp.setImagePath(null); sp.setImageUrl(null); } /** @ 好友时,展示的好友列表 */ private void showFriendList() { FriendListPage page; int orientation = activity.getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) { page = new FriendListPagePort(impl); } else { page = new FriendListPageLand(impl); } page.setPlatform(platform); page.showForResult(platform.getContext(), null, this); } public void onResult(HashMap<String, Object> data) { String atText = getJoinSelectedUser(data); if(!TextUtils.isEmpty(atText)) { etContent.append(atText); } } private String getJoinSelectedUser(HashMap<String, Object> data) { if (data != null && data.containsKey("selected")) { @SuppressWarnings("unchecked") ArrayList<String> selected = (ArrayList<String>) data.get("selected"); String platform = ((Platform)data.get("platform")).getName(); if("FacebookMessenger".equals(platform)) { return null; } StringBuilder sb = new StringBuilder(); for (String sel : selected) { sb.append('@').append(sel).append(' '); } return sb.toString(); } return null; } protected boolean isShowAtUserLayout(String platformName) { return "SinaWeibo".equals(platformName) || "TencentWeibo".equals(platformName) || "Facebook".equals(platformName) || "Twitter".equals(platformName); } public void onClick(View v) { if (v.equals(tvCancel)) { cancelAndFinish(); } else if (v.equals(tvShare)) { sp.setText(etContent.getText().toString().trim()); shareAndFinish(); } else if (v.equals(aivThumb)) { showThumb(thumb); } else if (v.equals(xvRemove)) { maxBodyHeight = 0; rlThumb.setVisibility(View.GONE); llPage.measure(0, 0); onTextChanged(etContent.getText(), 0, 0, 0); removeThumb(); } else if (v.equals(tvAt)) { showFriendList(); } } public void onTextChanged(CharSequence s, int start, int before, int count) { tvTextCouter.setText(String.valueOf(s.length())); if (maxBodyHeight == 0) { maxBodyHeight = llPage.getHeight() - rlTitle.getHeight() - llBottom.getHeight(); } if (maxBodyHeight > 0) { svContent.post(this); } } /** 动态适配编辑界面的高度 */ public void run() { int height = svContent.getChildAt(0).getHeight(); RelativeLayout.LayoutParams lp = R.forceCast(svContent.getLayoutParams()); if (height > maxBodyHeight && lp.height != maxBodyHeight) { lp.height = maxBodyHeight; svContent.setLayoutParams(lp); } else if (height < maxBodyHeight && lp.height == maxBodyHeight) { lp.height = LayoutParams.WRAP_CONTENT; svContent.setLayoutParams(lp); } } public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onPause() { DeviceHelper.getInstance(activity).hideSoftInput(getContentView()); super.onPause(); } }
[ "386793119@qq.com" ]
386793119@qq.com
bacf443e474eeff5459b75332ab503beb74240bb
12b14b30fcaf3da3f6e9dc3cb3e717346a35870a
/examples/commons-math3/mutations/mutants-Dfp/2204/org/apache/commons/math3/dfp/Dfp.java
541abbe2d9123ba8d1c49c1cfee0b14914719fbc
[ "BSD-3-Clause", "Minpack", "Apache-2.0" ]
permissive
SmartTests/smartTest
b1de326998857e715dcd5075ee322482e4b34fb6
b30e8ec7d571e83e9f38cd003476a6842c06ef39
refs/heads/main
2023-01-03T01:27:05.262904
2020-10-27T20:24:48
2020-10-27T20:24:48
305,502,060
0
0
null
null
null
null
UTF-8
Java
false
false
85,680
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.commons.math3.dfp; import java.util.Arrays; import org.apache.commons.math3.RealFieldElement; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.util.FastMath; /** * Decimal floating point library for Java * * <p>Another floating point class. This one is built using radix 10000 * which is 10<sup>4</sup>, so its almost decimal.</p> * * <p>The design goals here are: * <ol> * <li>Decimal math, or close to it</li> * <li>Settable precision (but no mix between numbers using different settings)</li> * <li>Portability. Code should be kept as portable as possible.</li> * <li>Performance</li> * <li>Accuracy - Results should always be +/- 1 ULP for basic * algebraic operation</li> * <li>Comply with IEEE 854-1987 as much as possible. * (See IEEE 854-1987 notes below)</li> * </ol></p> * * <p>Trade offs: * <ol> * <li>Memory foot print. I'm using more memory than necessary to * represent numbers to get better performance.</li> * <li>Digits are bigger, so rounding is a greater loss. So, if you * really need 12 decimal digits, better use 4 base 10000 digits * there can be one partially filled.</li> * </ol></p> * * <p>Numbers are represented in the following form: * <pre> * n = sign &times; mant &times; (radix)<sup>exp</sup>;</p> * </pre> * where sign is &plusmn;1, mantissa represents a fractional number between * zero and one. mant[0] is the least significant digit. * exp is in the range of -32767 to 32768</p> * * <p>IEEE 854-1987 Notes and differences</p> * * <p>IEEE 854 requires the radix to be either 2 or 10. The radix here is * 10000, so that requirement is not met, but it is possible that a * subclassed can be made to make it behave as a radix 10 * number. It is my opinion that if it looks and behaves as a radix * 10 number then it is one and that requirement would be met.</p> * * <p>The radix of 10000 was chosen because it should be faster to operate * on 4 decimal digits at once instead of one at a time. Radix 10 behavior * can be realized by adding an additional rounding step to ensure that * the number of decimal digits represented is constant.</p> * * <p>The IEEE standard specifically leaves out internal data encoding, * so it is reasonable to conclude that such a subclass of this radix * 10000 system is merely an encoding of a radix 10 system.</p> * * <p>IEEE 854 also specifies the existence of "sub-normal" numbers. This * class does not contain any such entities. The most significant radix * 10000 digit is always non-zero. Instead, we support "gradual underflow" * by raising the underflow flag for numbers less with exponent less than * expMin, but don't flush to zero until the exponent reaches MIN_EXP-digits. * Thus the smallest number we can represent would be: * 1E(-(MIN_EXP-digits-1)*4), eg, for digits=5, MIN_EXP=-32767, that would * be 1e-131092.</p> * * <p>IEEE 854 defines that the implied radix point lies just to the right * of the most significant digit and to the left of the remaining digits. * This implementation puts the implied radix point to the left of all * digits including the most significant one. The most significant digit * here is the one just to the right of the radix point. This is a fine * detail and is really only a matter of definition. Any side effects of * this can be rendered invisible by a subclass.</p> * @see DfpField * @version $Id$ * @since 2.2 */ public class Dfp implements RealFieldElement<Dfp> { /** The radix, or base of this system. Set to 10000 */ public static final int RADIX = 10000; /** The minimum exponent before underflow is signaled. Flush to zero * occurs at minExp-DIGITS */ public static final int MIN_EXP = -32767; /** The maximum exponent before overflow is signaled and results flushed * to infinity */ public static final int MAX_EXP = 32768; /** The amount under/overflows are scaled by before going to trap handler */ public static final int ERR_SCALE = 32760; /** Indicator value for normal finite numbers. */ public static final byte FINITE = 0; /** Indicator value for Infinity. */ public static final byte INFINITE = 1; /** Indicator value for signaling NaN. */ public static final byte SNAN = 2; /** Indicator value for quiet NaN. */ public static final byte QNAN = 3; /** String for NaN representation. */ private static final String NAN_STRING = "NaN"; /** String for positive infinity representation. */ private static final String POS_INFINITY_STRING = "Infinity"; /** String for negative infinity representation. */ private static final String NEG_INFINITY_STRING = "-Infinity"; /** Name for traps triggered by addition. */ private static final String ADD_TRAP = "add"; /** Name for traps triggered by multiplication. */ private static final String MULTIPLY_TRAP = "multiply"; /** Name for traps triggered by division. */ private static final String DIVIDE_TRAP = "divide"; /** Name for traps triggered by square root. */ private static final String SQRT_TRAP = "sqrt"; /** Name for traps triggered by alignment. */ private static final String ALIGN_TRAP = "align"; /** Name for traps triggered by truncation. */ private static final String TRUNC_TRAP = "trunc"; /** Name for traps triggered by nextAfter. */ private static final String NEXT_AFTER_TRAP = "nextAfter"; /** Name for traps triggered by lessThan. */ private static final String LESS_THAN_TRAP = "lessThan"; /** Name for traps triggered by greaterThan. */ private static final String GREATER_THAN_TRAP = "greaterThan"; /** Name for traps triggered by newInstance. */ private static final String NEW_INSTANCE_TRAP = "newInstance"; /** Mantissa. */ protected int[] mant; /** Sign bit: 1 for positive, -1 for negative. */ protected byte sign; /** Exponent. */ protected int exp; /** Indicator for non-finite / non-number values. */ protected byte nans; /** Factory building similar Dfp's. */ private final DfpField field; /** Makes an instance with a value of zero. * @param field field to which this instance belongs */ protected Dfp(final DfpField field) { mant = new int[field.getRadixDigits()]; sign = 1; exp = 0; nans = FINITE; this.field = field; } /** Create an instance from a byte value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, byte x) { this(field, (long) x); } /** Create an instance from an int value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, int x) { this(field, (long) x); } /** Create an instance from a long value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, long x) { // initialize as if 0 mant = new int[field.getRadixDigits()]; nans = FINITE; this.field = field; boolean isLongMin = false; if (x == Long.MIN_VALUE) { // special case for Long.MIN_VALUE (-9223372036854775808) // we must shift it before taking its absolute value isLongMin = true; ++x; } // set the sign if (x < 0) { sign = -1; x = -x; } else { sign = 1; } exp = 0; while (x != 0) { System.arraycopy(mant, mant.length - exp, mant, mant.length - 1 - exp, exp); mant[mant.length - 1] = (int) (x % RADIX); x /= RADIX; exp++; } if (isLongMin) { // remove the shift added for Long.MIN_VALUE // we know in this case that fixing the last digit is sufficient for (int i = 0; i < mant.length - 1; i++) { if (mant[i] != 0) { mant[i]++; break; } } } } /** Create an instance from a double value. * @param field field to which this instance belongs * @param x value to convert to an instance */ protected Dfp(final DfpField field, double x) { // initialize as if 0 mant = new int[field.getRadixDigits()]; sign = 1; exp = 0; nans = FINITE; this.field = field; long bits = Double.doubleToLongBits(x); long mantissa = bits & 0x000fffffffffffffL; int exponent = (int) ((bits & 0x7ff0000000000000L) >> 52) - 1023; if (exponent == -1023) { // Zero or sub-normal if (x == 0) { // make sure 0 has the right sign if ((bits & 0x8000000000000000L) != 0) { sign = -1; } return; } exponent++; // Normalize the subnormal number while ( (mantissa & 0x0010000000000000L) == 0) { exponent--; mantissa <<= 1; } mantissa &= 0x000fffffffffffffL; } if (exponent == 1024) { // infinity or NAN if (x != x) { sign = (byte) 1; nans = QNAN; } else if (x < 0) { sign = (byte) -1; nans = INFINITE; } else { sign = (byte) 1; nans = INFINITE; } return; } Dfp xdfp = new Dfp(field, mantissa); xdfp = xdfp.divide(new Dfp(field, 4503599627370496l)).add(field.getOne()); // Divide by 2^52, then add one xdfp = xdfp.multiply(DfpMath.pow(field.getTwo(), exponent)); if ((bits & 0x8000000000000000L) != 0) { xdfp = xdfp.negate(); } System.arraycopy(xdfp.mant, 0, mant, 0, mant.length); sign = xdfp.sign; exp = xdfp.exp; nans = xdfp.nans; } /** Copy constructor. * @param d instance to copy */ public Dfp(final Dfp d) { mant = d.mant.clone(); sign = d.sign; exp = d.exp; nans = d.nans; field = d.field; } /** Create an instance from a String representation. * @param field field to which this instance belongs * @param s string representation of the instance */ protected Dfp(final DfpField field, final String s) { // initialize as if 0 mant = new int[field.getRadixDigits()]; sign = 1; exp = 0; nans = FINITE; this.field = field; boolean decimalFound = false; final int rsize = 4; // size of radix in decimal digits final int offset = 4; // Starting offset into Striped final char[] striped = new char[getRadixDigits() * rsize + offset * 2]; // Check some special cases if (s.equals(POS_INFINITY_STRING)) { sign = (byte) 1; nans = INFINITE; return; } if (s.equals(NEG_INFINITY_STRING)) { sign = (byte) -1; nans = INFINITE; return; } if (s.equals(NAN_STRING)) { sign = (byte) 1; nans = QNAN; return; } // Check for scientific notation int p = s.indexOf("e"); if (p == -1) { // try upper case? p = s.indexOf("E"); } final String fpdecimal; int sciexp = 0; if (p != -1) { // scientific notation fpdecimal = s.substring(0, p); String fpexp = s.substring(p+1); boolean negative = false; for (int i=0; i<fpexp.length(); i++) { if (fpexp.charAt(i) == '-') { negative = true; continue; } if (fpexp.charAt(i) >= '0' && fpexp.charAt(i) <= '9') { sciexp = sciexp * 10 + fpexp.charAt(i) - '0'; } } if (negative) { sciexp = -sciexp; } } else { // normal case fpdecimal = s; } // If there is a minus sign in the number then it is negative if (fpdecimal.indexOf("-") != -1) { sign = -1; } // First off, find all of the leading zeros, trailing zeros, and significant digits p = 0; // Move p to first significant digit int decimalPos = 0; for (;;) { if (fpdecimal.charAt(p) >= '1' && fpdecimal.charAt(p) <= '9') { break; } if (decimalFound && fpdecimal.charAt(p) == '0') { decimalPos--; } if (fpdecimal.charAt(p) == '.') { decimalFound = true; } p++; if (p == fpdecimal.length()) { break; } } // Copy the string onto Stripped int q = offset; striped[0] = '0'; striped[1] = '0'; striped[2] = '0'; striped[3] = '0'; int significantDigits=0; for(;;) { if (p == (fpdecimal.length())) { break; } // Don't want to run pass the end of the array if (q == mant.length*rsize+offset+1) { break; } if (fpdecimal.charAt(p) == '.') { decimalFound = true; decimalPos = significantDigits; p++; continue; } if (fpdecimal.charAt(p) < '0' || fpdecimal.charAt(p) > '9') { p++; continue; } striped[q] = fpdecimal.charAt(p); q++; p++; significantDigits++; } // If the decimal point has been found then get rid of trailing zeros. if (decimalFound && q != offset) { for (;;) { q--; if (q == offset) { break; } if (striped[q] == '0') { significantDigits--; } else { break; } } } // special case of numbers like "0.00000" if (decimalFound && significantDigits == 0) { decimalPos = 0; } // Implicit decimal point at end of number if not present if (!decimalFound) { decimalPos = q-offset; } // Find the number of significant trailing zeros q = offset; // set q to point to first sig digit p = significantDigits-1+offset; while (p > q) { if (striped[p] != '0') { break; } p--; } // Make sure the decimal is on a mod 10000 boundary int i = ((rsize * 100) - decimalPos - sciexp % rsize) % rsize; q -= i; decimalPos += i; // Make the mantissa length right by adding zeros at the end if necessary while ((p - q) < (mant.length * rsize)) { for ( i = 0; i < rsize; i++) { striped[++p] = '0'; } } // Ok, now we know how many trailing zeros there are, // and where the least significant digit is for (i = mant.length - 1; i >= 0; i--) { mant[i] = (striped[q] - '0') * 1000 + (striped[q+1] - '0') * 100 + (striped[q+2] - '0') * 10 + (striped[q+3] - '0'); q += 4; } exp = (decimalPos+sciexp) / rsize; if (q < striped.length) { // Is there possible another digit? round((striped[q] - '0')*1000); } } /** Creates an instance with a non-finite value. * @param field field to which this instance belongs * @param sign sign of the Dfp to create * @param nans code of the value, must be one of {@link #INFINITE}, * {@link #SNAN}, {@link #QNAN} */ protected Dfp(final DfpField field, final byte sign, final byte nans) { this.field = field; this.mant = new int[field.getRadixDigits()]; this.sign = sign; this.exp = 0; this.nans = nans; } /** Create an instance with a value of 0. * Use this internally in preference to constructors to facilitate subclasses * @return a new instance with a value of 0 */ public Dfp newInstance() { return new Dfp(getField()); } /** Create an instance from a byte value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final byte x) { return new Dfp(getField(), x); } /** Create an instance from an int value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final int x) { return new Dfp(getField(), x); } /** Create an instance from a long value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final long x) { return new Dfp(getField(), x); } /** Create an instance from a double value. * @param x value to convert to an instance * @return a new instance with value x */ public Dfp newInstance(final double x) { return new Dfp(getField(), x); } /** Create an instance by copying an existing one. * Use this internally in preference to constructors to facilitate subclasses. * @param d instance to copy * @return a new instance with the same value as d */ public Dfp newInstance(final Dfp d) { // make sure we don't mix number with different precision if (field.getRadixDigits() != d.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, NEW_INSTANCE_TRAP, d, result); } return new Dfp(d); } /** Create an instance from a String representation. * Use this internally in preference to constructors to facilitate subclasses. * @param s string representation of the instance * @return a new instance parsed from specified string */ public Dfp newInstance(final String s) { return new Dfp(field, s); } /** Creates an instance with a non-finite value. * @param sig sign of the Dfp to create * @param code code of the value, must be one of {@link #INFINITE}, * {@link #SNAN}, {@link #QNAN} * @return a new instance with a non-finite value */ public Dfp newInstance(final byte sig, final byte code) { return field.newDfp(sig, code); } /** Get the {@link org.apache.commons.math3.Field Field} (really a {@link DfpField}) to which the instance belongs. * <p> * The field is linked to the number of digits and acts as a factory * for {@link Dfp} instances. * </p> * @return {@link org.apache.commons.math3.Field Field} (really a {@link DfpField}) to which the instance belongs */ public DfpField getField() { return field; } /** Get the number of radix digits of the instance. * @return number of radix digits */ public int getRadixDigits() { return field.getRadixDigits(); } /** Get the constant 0. * @return a Dfp with value zero */ public Dfp getZero() { return field.getZero(); } /** Get the constant 1. * @return a Dfp with value one */ public Dfp getOne() { return field.getOne(); } /** Get the constant 2. * @return a Dfp with value two */ public Dfp getTwo() { return field.getTwo(); } /** Shift the mantissa left, and adjust the exponent to compensate. */ protected void shiftLeft() { for (int i = mant.length - 1; i > 0; i--) { mant[i] = mant[i-1]; } mant[0] = 0; exp--; } /* Note that shiftRight() does not call round() as that round() itself uses shiftRight() */ /** Shift the mantissa right, and adjust the exponent to compensate. */ protected void shiftRight() { for (int i = 0; i < mant.length - 1; i++) { mant[i] = mant[i+1]; } mant[mant.length - 1] = 0; exp++; } /** Make our exp equal to the supplied one, this may cause rounding. * Also causes de-normalized numbers. These numbers are generally * dangerous because most routines assume normalized numbers. * Align doesn't round, so it will return the last digit destroyed * by shifting right. * @param e desired exponent * @return last digit destroyed by shifting right */ protected int align(int e) { int lostdigit = 0; boolean inexact = false; int diff = exp - e; int adiff = diff; if (adiff < 0) { adiff = -adiff; } if (diff == 0) { return 0; } if (adiff > (mant.length + 1)) { // Special case Arrays.fill(mant, 0); exp = e; field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); dotrap(DfpField.FLAG_INEXACT, ALIGN_TRAP, this, this); return 0; } for (int i = 0; i < adiff; i++) { if (diff < 0) { /* Keep track of loss -- only signal inexact after losing 2 digits. * the first lost digit is returned to add() and may be incorporated * into the result. */ if (lostdigit != 0) { inexact = true; } lostdigit = mant[0]; shiftRight(); } else { shiftLeft(); } } if (inexact) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); dotrap(DfpField.FLAG_INEXACT, ALIGN_TRAP, this, this); } return lostdigit; } /** Check if instance is less than x. * @param x number to check instance against * @return true if instance is less than x and neither are NaN, false otherwise */ public boolean lessThan(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, x, result); return false; } /* if a nan is involved, signal invalid and return false */ if (isNaN() || x.isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, x, newInstance(getZero())); return false; } return compare(this, x) < 0; } /** Check if instance is greater than x. * @param x number to check instance against * @return true if instance is greater than x and neither are NaN, false otherwise */ public boolean greaterThan(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; dotrap(DfpField.FLAG_INVALID, GREATER_THAN_TRAP, x, result); return false; } /* if a nan is involved, signal invalid and return false */ if (isNaN() || x.isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, GREATER_THAN_TRAP, x, newInstance(getZero())); return false; } return compare(this, x) > 0; } /** Check if instance is less than or equal to 0. * @return true if instance is not NaN and less than or equal to 0, false otherwise */ public boolean negativeOrNull() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign < 0) || ((mant[mant.length - 1] == 0) && !isInfinite()); } /** Check if instance is strictly less than 0. * @return true if instance is not NaN and less than or equal to 0, false otherwise */ public boolean strictlyNegative() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign < 0) && ((mant[mant.length - 1] != 0) || isInfinite()); } /** Check if instance is greater than or equal to 0. * @return true if instance is not NaN and greater than or equal to 0, false otherwise */ public boolean positiveOrNull() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign > 0) || ((mant[mant.length - 1] == 0) && !isInfinite()); } /** Check if instance is strictly greater than 0. * @return true if instance is not NaN and greater than or equal to 0, false otherwise */ public boolean strictlyPositive() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (sign > 0) && ((mant[mant.length - 1] != 0) || isInfinite()); } /** Get the absolute value of instance. * @return absolute value of instance * @since 3.2 */ public Dfp abs() { Dfp result = newInstance(this); result.sign = 1; return result; } /** Check if instance is infinite. * @return true if instance is infinite */ public boolean isInfinite() { return nans == INFINITE; } /** Check if instance is not a number. * @return true if instance is not a number */ public boolean isNaN() { return (nans == QNAN) || (nans == SNAN); } /** Check if instance is equal to zero. * @return true if instance is equal to zero */ public boolean isZero() { if (isNaN()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); dotrap(DfpField.FLAG_INVALID, LESS_THAN_TRAP, this, newInstance(getZero())); return false; } return (mant[mant.length - 1] == 0) && !isInfinite(); } /** Check if instance is equal to x. * @param other object to check instance against * @return true if instance is equal to x and neither are NaN, false otherwise */ @Override public boolean equals(final Object other) { if (other instanceof Dfp) { final Dfp x = (Dfp) other; if (isNaN() || x.isNaN() || field.getRadixDigits() != x.field.getRadixDigits()) { return false; } return compare(this, x) == 0; } return false; } /** * Gets a hashCode for the instance. * @return a hash code value for this object */ @Override public int hashCode() { return 17 + (sign << 8) + (nans << 16) + exp + Arrays.hashCode(mant); } /** Check if instance is not equal to x. * @param x number to check instance against * @return true if instance is not equal to x and neither are NaN, false otherwise */ public boolean unequal(final Dfp x) { if (isNaN() || x.isNaN() || field.getRadixDigits() != x.field.getRadixDigits()) { return false; } return greaterThan(x) || lessThan(x); } /** Compare two instances. * @param a first instance in comparison * @param b second instance in comparison * @return -1 if a<b, 1 if a>b and 0 if a==b * Note this method does not properly handle NaNs or numbers with different precision. */ private static int compare(final Dfp a, final Dfp b) { // Ignore the sign of zero if (a.mant[a.mant.length - 1] == 0 && b.mant[b.mant.length - 1] == 0 && a.nans == FINITE && b.nans == FINITE) { return 0; } if (a.sign != b.sign) { if (a.sign == -1) { return -1; } else { return 1; } } // deal with the infinities if (a.nans == INFINITE && b.nans == FINITE) { return a.sign; } if (a.nans == FINITE && b.nans == INFINITE) { return -b.sign; } if (a.nans == INFINITE && b.nans == INFINITE) { return 0; } // Handle special case when a or b is zero, by ignoring the exponents if (b.mant[b.mant.length-1] != 0 && a.mant[b.mant.length-1] != 0) { if (a.exp < b.exp) { return -a.sign; } if (a.exp > b.exp) { return a.sign; } } // compare the mantissas for (int i = a.mant.length - 1; i >= 0; i--) { if (a.mant[i] > b.mant[i]) { return a.sign; } if (a.mant[i] < b.mant[i]) { return -a.sign; } } return 0; } /** Round to nearest integer using the round-half-even method. * That is round to nearest integer unless both are equidistant. * In which case round to the even one. * @return rounded value * @since 3.2 */ public Dfp rint() { return trunc(DfpField.RoundingMode.ROUND_HALF_EVEN); } /** Round to an integer using the round floor mode. * That is, round toward -Infinity * @return rounded value * @since 3.2 */ public Dfp floor() { return trunc(DfpField.RoundingMode.ROUND_FLOOR); } /** Round to an integer using the round ceil mode. * That is, round toward +Infinity * @return rounded value * @since 3.2 */ public Dfp ceil() { return trunc(DfpField.RoundingMode.ROUND_CEIL); } /** Returns the IEEE remainder. * @param d divisor * @return this less n &times; d, where n is the integer closest to this/d * @since 3.2 */ public Dfp remainder(final Dfp d) { final Dfp result = this.subtract(this.divide(d).rint().multiply(d)); // IEEE 854-1987 says that if the result is zero, then it carries the sign of this if (result.mant[mant.length-1] == 0) { result.sign = sign; } return result; } /** Does the integer conversions with the specified rounding. * @param rmode rounding mode to use * @return truncated value */ protected Dfp trunc(final DfpField.RoundingMode rmode) { boolean changed = false; if (isNaN()) { return newInstance(this); } if (nans == INFINITE) { return newInstance(this); } if (mant[mant.length-1] == 0) { // a is zero return newInstance(this); } /* If the exponent is less than zero then we can certainly * return zero */ if (exp < 0) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); Dfp result = newInstance(getZero()); result = dotrap(DfpField.FLAG_INEXACT, TRUNC_TRAP, this, result); return result; } /* If the exponent is greater than or equal to digits, then it * must already be an integer since there is no precision left * for any fractional part */ if (exp >= mant.length) { return newInstance(this); } /* General case: create another dfp, result, that contains the * a with the fractional part lopped off. */ Dfp result = newInstance(this); for (int i = 0; i < mant.length-result.exp; i++) { changed |= result.mant[i] != 0; result.mant[i] = 0; } if (changed) { switch (rmode) { case ROUND_FLOOR: if (result.sign == -1) { // then we must increment the mantissa by one result = result.add(newInstance(-1)); } break; case ROUND_CEIL: if (result.sign == 1) { // then we must increment the mantissa by one result = result.add(getOne()); } break; case ROUND_HALF_EVEN: default: final Dfp half = newInstance("0.5"); Dfp a = subtract(result); // difference between this and result a.sign = 1; // force positive (take abs) if (a.greaterThan(half)) { a = newInstance(getOne()); a.sign = sign; result = result.add(a); } /** If exactly equal to 1/2 and odd then increment */ if (a.equals(half) && result.exp > 0 && (result.mant[mant.length-result.exp]&1) != 0) { a = newInstance(getOne()); a.sign = sign; result = result.add(a); } break; } field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); // signal inexact result = dotrap(DfpField.FLAG_INEXACT, TRUNC_TRAP, this, result); return result; } return result; } /** Convert this to an integer. * If greater than 2147483647, it returns 2147483647. If less than -2147483648 it returns -2147483648. * @return converted number */ public int intValue() { Dfp rounded; int result = 0; rounded = rint(); if (rounded.greaterThan(newInstance(2147483647))) { return 2147483647; } if (rounded.lessThan(newInstance(-2147483648))) { return -2147483648; } for (int i = mant.length - 1; i >= mant.length - rounded.exp; i--) { result = result * RADIX + rounded.mant[i]; } if (rounded.sign == -1) { result = -result; } return result; } /** Get the exponent of the greatest power of 10000 that is * less than or equal to the absolute value of this. I.E. if * this is 10<sup>6</sup> then log10K would return 1. * @return integer base 10000 logarithm */ public int log10K() { return exp - 1; } /** Get the specified power of 10000. * @param e desired power * @return 10000<sup>e</sup> */ public Dfp power10K(final int e) { Dfp d = newInstance(getOne()); d.exp = e + 1; return d; } /** Get the exponent of the greatest power of 10 that is less than or equal to abs(this). * @return integer base 10 logarithm * @since 3.2 */ public int intLog10() { if (mant[mant.length-1] > 1000) { return exp * 4 - 1; } if (mant[mant.length-1] > 100) { return exp * 4 - 2; } if (mant[mant.length-1] > 10) { return exp * 4 - 3; } return exp * 4 - 4; } /** Return the specified power of 10. * @param e desired power * @return 10<sup>e</sup> */ public Dfp power10(final int e) { Dfp d = newInstance(getOne()); if (e >= 0) { d.exp = e / 4 + 1; } else { d.exp = (e + 1) / 4; } switch ((e % 4 + 4) % 4) { case 0: break; case 1: d = d.multiply(10); break; case 2: d = d.multiply(100); break; default: d = d.multiply(1000); } return d; } /** Negate the mantissa of this by computing the complement. * Leaves the sign bit unchanged, used internally by add. * Denormalized numbers are handled properly here. * @param extra ??? * @return ??? */ protected int complement(int extra) { extra = RADIX-extra; for (int i = 0; i < mant.length; i++) { mant[i] = RADIX-mant[i]-1; } int rh = extra / RADIX; extra = extra - rh * RADIX; for (int i = 0; i < mant.length; i++) { final int r = mant[i] + rh; rh = r / RADIX; mant[i] = r - rh * RADIX; } return extra; } /** Add x to this. * @param x number to add * @return sum of this and x */ public Dfp add(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, ADD_TRAP, x, result); } /* handle special cases */ if (nans != FINITE || x.nans != FINITE) { if (isNaN()) { return this; } if (x.isNaN()) { return x; } if (nans == INFINITE && x.nans == FINITE) { return this; } if (x.nans == INFINITE && nans == FINITE) { return x; } if (x.nans == INFINITE && nans == INFINITE && sign == x.sign) { return x; } if (x.nans == INFINITE && nans == INFINITE && sign != x.sign) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); Dfp result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, ADD_TRAP, x, result); return result; } } /* copy this and the arg */ Dfp a = newInstance(this); Dfp b = newInstance(x); /* initialize the result object */ Dfp result = newInstance(getZero()); /* Make all numbers positive, but remember their sign */ final byte asign = a.sign; final byte bsign = b.sign; a.sign = 1; b.sign = 1; /* The result will be signed like the arg with greatest magnitude */ byte rsign = bsign; if (compare(a, b) > 0) { rsign = asign; } /* Handle special case when a or b is zero, by setting the exponent of the zero number equal to the other one. This avoids an alignment which would cause catastropic loss of precision */ if (b.mant[mant.length-1] == 0) { b.exp = a.exp; } if (a.mant[mant.length-1] == 0) { a.exp = b.exp; } /* align number with the smaller exponent */ int aextradigit = 0; int bextradigit = 0; if (a.exp < b.exp) { aextradigit = a.align(b.exp); } else { bextradigit = b.align(a.exp); } /* complement the smaller of the two if the signs are different */ if (asign != bsign) { if (asign == rsign) { bextradigit = b.complement(bextradigit); } else { aextradigit = a.complement(aextradigit); } } /* add the mantissas */ int rh = 0; /* acts as a carry */ for (int i = 0; i < mant.length; i++) { final int r = a.mant[i]+b.mant[i]+rh; rh = r / RADIX; result.mant[i] = r - rh * RADIX; } result.exp = a.exp; result.sign = rsign; /* handle overflow -- note, when asign!=bsign an overflow is * normal and should be ignored. */ if (rh != 0 && (asign == bsign)) { final int lostdigit = result.mant[0]; result.shiftRight(); result.mant[mant.length-1] = rh; final int excp = result.round(lostdigit); if (excp != 0) { result = dotrap(excp, ADD_TRAP, x, result); } } /* normalize the result */ for (int i = 0; i < mant.length; i++) { if (result.mant[mant.length-1] != 0) { break; } result.shiftLeft(); if (i == 0) { result.mant[0] = aextradigit+bextradigit; aextradigit = 0; bextradigit = 0; } } /* result is zero if after normalization the most sig. digit is zero */ if (result.mant[mant.length-1] == 0) { result.exp = 0; if (asign != bsign) { // Unless adding 2 negative zeros, sign is positive result.sign = 1; // Per IEEE 854-1987 Section 6.3 } } /* Call round to test for over/under flows */ final int excp = result.round(aextradigit + bextradigit); if (excp != 0) { result = dotrap(excp, ADD_TRAP, x, result); } return result; } /** Returns a number that is this number with the sign bit reversed. * @return the opposite of this */ public Dfp negate() { Dfp result = newInstance(this); result.sign = (byte) - result.sign; return result; } /** Subtract x from this. * @param x number to subtract * @return difference of this and a */ public Dfp subtract(final Dfp x) { return add(x.negate()); } /** Round this given the next digit n using the current rounding mode. * @param n ??? * @return the IEEE flag if an exception occurred */ protected int round(int n) { boolean inc = false; switch (field.getRoundingMode()) { case ROUND_DOWN: inc = false; break; case ROUND_UP: inc = n != 0; // round up if n!=0 break; case ROUND_HALF_UP: inc = n >= 5000; // round half up break; case ROUND_HALF_DOWN: inc = n > 5000; // round half down break; case ROUND_HALF_EVEN: inc = n > 5000 || (n == 5000 && (mant[0] & 1) == 1); // round half-even break; case ROUND_HALF_ODD: inc = n > 5000 || (n == 5000 && (mant[0] & 1) == 0); // round half-odd break; case ROUND_CEIL: inc = sign == 1 && n != 0; // round ceil break; case ROUND_FLOOR: default: inc = sign == -1 && n != 0; // round floor break; } if (inc) { // increment if necessary int rh = 1; for (int i = 0; i < mant.length; i++) { final int r = mant[i] + rh; rh = r / RADIX; mant[i] = r - rh * RADIX; } if (rh != 0) { shiftRight(); mant[mant.length-1] = rh; } } // check for exceptional cases and raise signals if necessary if (exp < MIN_EXP) { // Gradual Underflow field.setIEEEFlagsBits(DfpField.FLAG_UNDERFLOW); return DfpField.FLAG_UNDERFLOW; } if (exp > MAX_EXP) { // Overflow field.setIEEEFlagsBits(DfpField.FLAG_OVERFLOW); return DfpField.FLAG_OVERFLOW; } if (n != 0) { // Inexact field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); return DfpField.FLAG_INEXACT; } return 0; } /** Multiply this by x. * @param x multiplicand * @return product of this and x */ public Dfp multiply(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, x, result); } Dfp result = newInstance(getZero()); /* handle special cases */ if (nans != FINITE || x.nans != FINITE) { if (isNaN()) { return this; } if (x.isNaN()) { return x; } if (nans == INFINITE && x.nans == FINITE && x.mant[mant.length-1] != 0) { result = newInstance(this); result.sign = (byte) (sign * x.sign); return result; } if (x.nans == INFINITE && nans == FINITE && mant[mant.length-1] != 0) { result = newInstance(x); result.sign = (byte) (sign * x.sign); return result; } if (x.nans == INFINITE && nans == INFINITE) { result = newInstance(this); result.sign = (byte) (sign * x.sign); return result; } if ( (x.nans == INFINITE && nans == FINITE && mant[mant.length - 1] == 0) ) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, x, result); return result; } } int[] product = new int[mant.length*2]; // Big enough to hold even the largest result for (int i = 0; i < mant.length; i++) { int rh = 0; // acts as a carry for (int j=0; j<mant.length; j++) { int r = mant[i] * x.mant[j]; // multiply the 2 digits r = r + product[i+j] + rh; // add to the product digit with carry in rh = r / RADIX; product[i+j] = r - rh * RADIX; } product[i+mant.length] = rh; } // Find the most sig digit int md = mant.length * 2 - 1; // default, in case result is zero for (int i = mant.length * 2 - 1; i >= 0; i--) { if (product[i] != 0) { md = i; break; } } // Copy the digits into the result for (int i = 0; i < mant.length; i++) { result.mant[mant.length - i - 1] = product[md - i]; } // Fixup the exponent. result.exp = exp + x.exp + md - 2 * mant.length + 1; result.sign = (byte)((sign == x.sign)?1:-1); if (result.mant[mant.length-1] == 0) { // if result is zero, set exp to zero result.exp = 0; } final int excp; if (md > (mant.length-1)) { excp = result.round(product[md-mant.length]); } else { excp = result.round(0); // has no effect except to check status } if (excp != 0) { result = dotrap(excp, MULTIPLY_TRAP, x, result); } return result; } /** Multiply this by a single digit x. * @param x multiplicand * @return product of this and x */ public Dfp multiply(final int x) { if (x >= 0 && x < RADIX) { return multiplyFast(x); } else { return multiply(newInstance(x)); } } /** Multiply this by a single digit 0&lt;=x&lt;radix. * There are speed advantages in this special case. * @param x multiplicand * @return product of this and x */ private Dfp multiplyFast(final int x) { Dfp result = newInstance(this); /* handle special cases */ if (nans != FINITE) { if (isNaN()) { return this; } if (nans == INFINITE && x != 0) { result = newInstance(this); return result; } if (nans == INFINITE && x == 0) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, newInstance(getZero()), result); return result; } } /* range check x */ if (x < 0 || x >= RADIX) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, MULTIPLY_TRAP, result, result); return result; } int rh = 0; for (int i = 0; i < mant.length; i++) { final int r = mant[i] * x + rh; rh = r / RADIX; result.mant[i] = r - rh * RADIX; } int lostdigit = 0; if (rh != 0) { lostdigit = result.mant[0]; result.shiftRight(); result.mant[mant.length-1] = rh; } if (result.mant[mant.length-1] == 0) { // if result is zero, set exp to zero result.exp = 0; } final int excp = result.round(lostdigit); if (excp != 0) { result = dotrap(excp, MULTIPLY_TRAP, result, result); } return result; } /** Divide this by divisor. * @param divisor divisor * @return quotient of this by divisor */ public Dfp divide(Dfp divisor) { int dividend[]; // current status of the dividend int quotient[]; // quotient int remainder[];// remainder int qd; // current quotient digit we're working with int nsqd; // number of significant quotient digits we have int trial=0; // trial quotient digit int minadj; // minimum adjustment boolean trialgood; // Flag to indicate a good trail digit int md=0; // most sig digit in result int excp; // exceptions // make sure we don't mix number with different precision if (field.getRadixDigits() != divisor.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, DIVIDE_TRAP, divisor, result); } Dfp result = newInstance(getZero()); /* handle special cases */ if (nans != FINITE || divisor.nans != FINITE) { if (isNaN()) { return this; } if (divisor.isNaN()) { return divisor; } if (nans == INFINITE && divisor.nans == FINITE) { result = newInstance(this); result.sign = (byte) (sign * divisor.sign); return result; } if (divisor.nans == INFINITE && nans == FINITE) { result = newInstance(getZero()); result.sign = (byte) (sign * divisor.sign); return result; } if (divisor.nans == INFINITE && nans == INFINITE) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, DIVIDE_TRAP, divisor, result); return result; } } /* Test for divide by zero */ if (divisor.mant[mant.length-1] == 0) { field.setIEEEFlagsBits(DfpField.FLAG_DIV_ZERO); result = newInstance(getZero()); result.sign = (byte) (sign * divisor.sign); result.nans = INFINITE; result = dotrap(DfpField.FLAG_DIV_ZERO, DIVIDE_TRAP, divisor, result); return result; } dividend = new int[mant.length+1]; // one extra digit needed quotient = new int[mant.length+2]; // two extra digits needed 1 for overflow, 1 for rounding remainder = new int[mant.length+1]; // one extra digit needed /* Initialize our most significant digits to zero */ dividend[mant.length] = 0; quotient[mant.length] = 0; quotient[mant.length+1] = 0; remainder[mant.length] = 0; /* copy our mantissa into the dividend, initialize the quotient while we are at it */ for (int i = 0; i < mant.length; i++) { dividend[i] = mant[i]; quotient[i] = 0; remainder[i] = 0; } /* outer loop. Once per quotient digit */ nsqd = 0; for (qd = mant.length+1; qd >= 0; qd--) { /* Determine outer limits of our quotient digit */ // r = most sig 2 digits of dividend final int divMsb = dividend[mant.length]*RADIX+dividend[mant.length-1]; int min = divMsb / (divisor.mant[mant.length-1]+1); int max = (divMsb + 1) / divisor.mant[mant.length-1]; trialgood = false; while (!trialgood) { // try the mean trial = (min+max)/2; /* Multiply by divisor and store as remainder */ int rh = 0; for (int i = 0; i < mant.length + 1; i++) { int dm = (i<mant.length)?divisor.mant[i]:0; final int r = (dm * trial) + rh; rh = r / RADIX; remainder[i] = r - rh * RADIX; } /* subtract the remainder from the dividend */ rh = 1; // carry in to aid the subtraction for (int i = 0; i < mant.length + 1; i++) { final int r = ((RADIX-1) - remainder[i]) + dividend[i] + rh; rh = r / RADIX; remainder[i] = r - rh * RADIX; } /* Lets analyze what we have here */ if (rh == 0) { // trial is too big -- negative remainder max = trial-1; continue; } /* find out how far off the remainder is telling us we are */ minadj = (remainder[mant.length] * RADIX)+remainder[mant.length-1]; minadj = minadj / (divisor.mant[mant.length-1]+1); if (minadj >= 2) { min = trial+minadj; // update the minimum continue; } /* May have a good one here, check more thoroughly. Basically its a good one if it is less than the divisor */ trialgood = false; // assume false for (int i = mant.length - 1; i >= 0; i--) { if (divisor.mant[i] > remainder[i]) { trialgood = true; } if (divisor.mant[i] < remainder[i]) { break; } } if (remainder[mant.length] != 0) { trialgood = false; } if (trialgood == false) { min = trial+1; } } /* Great we have a digit! */ quotient[qd] = trial; if (trial != 0 || nsqd != 0) { nsqd++; } if (field.getRoundingMode() == DfpField.RoundingMode.ROUND_DOWN && nsqd == mant.length) { // We have enough for this mode break; } if (nsqd > mant.length) { // We have enough digits break; } /* move the remainder into the dividend while left shifting */ dividend[0] = 0; for (int i = 0; i < mant.length; i++) { dividend[i + 1] = remainder[i]; } } /* Find the most sig digit */ md = mant.length; // default for (int i = mant.length + 1; i >= 0; i--) { if (quotient[i] != 0) { md = i; break; } } /* Copy the digits into the result */ for (int i=0; i<mant.length; i++) { result.mant[mant.length-i-1] = quotient[md-i]; } /* Fixup the exponent. */ result.exp = exp - divisor.exp + md - mant.length; result.sign = (byte) ((sign == divisor.sign) ? 1 : -1); if (result.mant[mant.length-1] == 0) { // if result is zero, set exp to zero result.exp = 0; } if (md > (mant.length-1)) { excp = result.round(quotient[md-mant.length]); } else { excp = result.round(0); } if (excp != 0) { result = dotrap(excp, DIVIDE_TRAP, divisor, result); } return result; } /** Divide by a single digit less than radix. * Special case, so there are speed advantages. 0 &lt;= divisor &lt; radix * @param divisor divisor * @return quotient of this by divisor */ public Dfp divide(int divisor) { // Handle special cases if (nans != FINITE) { if (isNaN()) { return this; } if (nans == INFINITE) { return newInstance(this); } } // Test for divide by zero if (divisor == 0) { field.setIEEEFlagsBits(DfpField.FLAG_DIV_ZERO); Dfp result = newInstance(getZero()); result.sign = sign; result.nans = INFINITE; result = dotrap(DfpField.FLAG_DIV_ZERO, DIVIDE_TRAP, getZero(), result); return result; } // range check divisor if (divisor < 0 || divisor >= RADIX) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); Dfp result = newInstance(getZero()); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, DIVIDE_TRAP, result, result); return result; } Dfp result = newInstance(this); int rl = 0; for (int i = mant.length-1; i >= 0; i--) { final int r = rl*RADIX + result.mant[i]; final int rh = r / divisor; rl = r - rh * divisor; result.mant[i] = rh; } if (result.mant[mant.length-1] == 0) { // normalize result.shiftLeft(); final int r = rl * RADIX; // compute the next digit and put it in final int rh = r / divisor; rl = r - rh * divisor; result.mant[0] = rh; } final int excp = result.round(rl * RADIX / divisor); // do the rounding if (excp != 0) { result = dotrap(excp, DIVIDE_TRAP, result, result); } return result; } /** {@inheritDoc} */ public Dfp reciprocal() { return field.getOne().divide(this); } /** Compute the square root. * @return square root of the instance * @since 3.2 */ public Dfp sqrt() { // check for unusual cases if (nans == FINITE && mant[mant.length-1] == 0) { // if zero return newInstance(this); } if (nans != FINITE) { if (nans == INFINITE && sign == 1) { // if positive infinity return newInstance(this); } if (nans == QNAN) { return newInstance(this); } if (nans == SNAN) { Dfp result; field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(this); result = dotrap(DfpField.FLAG_INVALID, SQRT_TRAP, null, result); return result; } } if (sign == -1) { // if negative Dfp result; field.setIEEEFlagsBits(DfpField.FLAG_INVALID); result = newInstance(this); result.nans = QNAN; result = dotrap(DfpField.FLAG_INVALID, SQRT_TRAP, null, result); return result; } Dfp x = newInstance(this); /* Lets make a reasonable guess as to the size of the square root */ if (x.exp < -1 || x.exp > 1) { x.exp = this.exp / 2; } /* Coarsely estimate the mantissa */ switch (x.mant[mant.length-1] / 2000) { case 0: x.mant[mant.length-1] = x.mant[mant.length-1]/2+1; break; case 2: x.mant[mant.length-1] = 1500; break; case 3: x.mant[mant.length-1] = 2200; break; default: x.mant[mant.length-1] = 3000; } Dfp dx = newInstance(x); /* Now that we have the first pass estimate, compute the rest by the formula dx = (y - x*x) / (2x); */ Dfp px = getZero(); Dfp ppx = getZero(); while (x.unequal(px)) { dx = newInstance(x); dx.sign = -1; dx = dx.add(this.divide(x)); dx = dx.divide(2); ppx = px; px = x; x = x.add(dx); if (x.equals(ppx)) { // alternating between two values break; } // if dx is zero, break. Note testing the most sig digit // is a sufficient test since dx is normalized if (dx.mant[mant.length-1] == 0) { break; } } return x; } /** Get a string representation of the instance. * @return string representation of the instance */ @Override public String toString() { if (nans != FINITE) { // if non-finite exceptional cases if (nans == INFINITE) { return (sign < 0) ? NEG_INFINITY_STRING : POS_INFINITY_STRING; } else { return NAN_STRING; } } if (exp > mant.length || exp < -1) { return dfp2sci(); } return dfp2string(); } /** Convert an instance to a string using scientific notation. * @return string representation of the instance in scientific notation */ protected String dfp2sci() { char rawdigits[] = new char[mant.length * 4]; char outputbuffer[] = new char[mant.length * 4 + 20]; int p; int q; int e; int ae; int shf; // Get all the digits p = 0; for (int i = mant.length - 1; i >= 0; i--) { rawdigits[p++] = (char) ((mant[i] / 1000) + '0'); rawdigits[p++] = (char) (((mant[i] / 100) %10) + '0'); rawdigits[p++] = (char) (((mant[i] / 10) % 10) + '0'); rawdigits[p++] = (char) (((mant[i]) % 10) + '0'); } // Find the first non-zero one for (p = 0; p < rawdigits.length; p++) { if (rawdigits[p] != '0') { break; } } shf = p; // Now do the conversion q = 0; if (sign == -1) { outputbuffer[q++] = '-'; } if (p != rawdigits.length) { // there are non zero digits... outputbuffer[q++] = rawdigits[p++]; outputbuffer[q++] = '.'; while (p<rawdigits.length) { outputbuffer[q++] = rawdigits[p++]; } } else { outputbuffer[q++] = '0'; outputbuffer[q++] = '.'; outputbuffer[q++] = '0'; outputbuffer[q++] = 'e'; outputbuffer[q++] = '0'; return new String(outputbuffer, 0, 5); } outputbuffer[q++] = 'e'; // Find the msd of the exponent e = exp * 4 - shf - 1; ae = e; if (e < 0) { ae = -e; } // Find the largest p such that p < e for (p = 1000000000; p > ae; p /= 10) { // nothing to do } if (e < 0) { outputbuffer[q++] = '-'; } while (p > 0) { outputbuffer[q++] = (char)(ae / p + '0'); ae = ae % p; p = p / 10; } return new String(outputbuffer, 0, q); } /** Convert an instance to a string using normal notation. * @return string representation of the instance in normal notation */ protected String dfp2string() { char buffer[] = new char[mant.length*4 + 20]; int p = 1; int q; int e = exp; boolean pointInserted = false; buffer[0] = ' '; if (e <= 0) { buffer[p++] = '0'; buffer[p++] = '.'; pointInserted = true; } while (e < 0) { buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; e++; } for (int i = mant.length - 1; i >= 0; i--) { buffer[p++] = (char) ((mant[i] / 1000) + '0'); buffer[p++] = (char) (((mant[i] / 100) % 10) + '0'); buffer[p++] = (char) (((mant[i] / 10) % 10) + '0'); buffer[p++] = (char) (((mant[i]) % 10) + '0'); if (--e == 0) { buffer[p++] = '.'; pointInserted = true; } } while (e > 0) { buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; buffer[p++] = '0'; e--; } if (!pointInserted) { // Ensure we have a radix point! buffer[p++] = '.'; } // Suppress leading zeros q = 1; while (buffer[q] == '0') { q++; } if (buffer[q] == '.') { q--; } // Suppress trailing zeros while (buffer[p-1] == '0') { p--; } // Insert sign if (sign < 0) { buffer[--q] = '-'; } return new String(buffer, q, p - q); } /** Raises a trap. This does not set the corresponding flag however. * @param type the trap type * @param what - name of routine trap occurred in * @param oper - input operator to function * @param result - the result computed prior to the trap * @return The suggested return value from the trap handler */ public Dfp dotrap(int type, String what, Dfp oper, Dfp result) { Dfp def = result; switch (type) { case DfpField.FLAG_INVALID: def = newInstance(getZero()); def.sign = result.sign; def.nans = QNAN; break; case DfpField.FLAG_DIV_ZERO: if (nans == FINITE && mant[mant.length-1] != 0) { // normal case, we are finite, non-zero def = newInstance(getZero()); def.sign = (byte)(sign*oper.sign); def.nans = INFINITE; } if (nans == FINITE && mant[mant.length-1] == 0) { // 0/0 def = newInstance(getZero()); def.nans = QNAN; } if (nans == INFINITE || nans == QNAN) { def = newInstance(getZero()); def.nans = QNAN; } if (nans == INFINITE || nans == SNAN) { def = newInstance(getZero()); def.nans = QNAN; } break; case DfpField.FLAG_UNDERFLOW: if ( (result.exp+mant.length) < MIN_EXP) { def = newInstance(getZero()); def.sign = result.sign; } else { def = newInstance(result); // gradual underflow } result.exp = result.exp + ERR_SCALE; break; case DfpField.FLAG_OVERFLOW: result.exp = result.exp - ERR_SCALE; def = newInstance(getZero()); def.sign = result.sign; def.nans = INFINITE; break; default: def = result; break; } return trap(type, what, oper, def, result); } /** Trap handler. Subclasses may override this to provide trap * functionality per IEEE 854-1987. * * @param type The exception type - e.g. FLAG_OVERFLOW * @param what The name of the routine we were in e.g. divide() * @param oper An operand to this function if any * @param def The default return value if trap not enabled * @param result The result that is specified to be delivered per * IEEE 854, if any * @return the value that should be return by the operation triggering the trap */ protected Dfp trap(int type, String what, Dfp oper, Dfp def, Dfp result) { return def; } /** Returns the type - one of FINITE, INFINITE, SNAN, QNAN. * @return type of the number */ public int classify() { return nans; } /** Creates an instance that is the same as x except that it has the sign of y. * abs(x) = dfp.copysign(x, dfp.one) * @param x number to get the value from * @param y number to get the sign from * @return a number with the value of x and the sign of y */ public static Dfp copysign(final Dfp x, final Dfp y) { Dfp result = x.newInstance(x); result.sign = y.sign; return result; } /** Returns the next number greater than this one in the direction of x. * If this==x then simply returns this. * @param x direction where to look at * @return closest number next to instance in the direction of x */ public Dfp nextAfter(final Dfp x) { // make sure we don't mix number with different precision if (field.getRadixDigits() != x.field.getRadixDigits()) { field.setIEEEFlagsBits(DfpField.FLAG_INVALID); final Dfp result = newInstance(getZero()); result.nans = QNAN; return dotrap(DfpField.FLAG_INVALID, NEXT_AFTER_TRAP, x, result); } // if this is greater than x boolean up = false; if (this.lessThan(x)) { up = true; } if (compare(this, x) == 0) { return newInstance(x); } if (lessThan(getZero())) { up = !up; } final Dfp inc; Dfp result; if (up) { inc = newInstance(getOne()); inc.exp = this.exp-mant.length+1; inc.sign = this.sign; if (this.equals(getZero())) { inc.exp = MIN_EXP-mant.length; } result = add(inc); } else { inc = newInstance(getOne()); inc.exp = this.exp; inc.sign = this.sign; if (this.equals(inc)) { inc.exp = this.exp-mant.length; } else { inc.exp = this.exp-mant.length+1; } if (this.equals(getZero())) { inc.exp = MIN_EXP-mant.length; } result = this.subtract(inc); } if (result.classify() == INFINITE && this.classify() != INFINITE) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); result = dotrap(DfpField.FLAG_INEXACT, NEXT_AFTER_TRAP, x, result); } if (result.equals(getZero()) && this.equals(getZero()) == false) { field.setIEEEFlagsBits(DfpField.FLAG_INEXACT); result = dotrap(DfpField.FLAG_INEXACT, NEXT_AFTER_TRAP, x, result); } return result; } /** Convert the instance into a double. * @return a double approximating the instance * @see #toSplitDouble() */ public double toDouble() { if (isInfinite()) { if (lessThan(getZero())) { return Double.NEGATIVE_INFINITY; } else { return Double.POSITIVE_INFINITY; } } if (isNaN()) { return Double.NaN; } Dfp y = this; boolean negate = false; int cmp0 = compare(this, getZero()); if (cmp0 == 0) { return sign < 0 ? -0.0 : +0.0; } else if (cmp0 < 0) { y = negate(); negate = true; } /* Find the exponent, first estimate by integer log10, then adjust. Should be faster than doing a natural logarithm. */ int exponent = (int)(y.intLog10() * 3.32); if (exponent < 0) { exponent--; } Dfp tempDfp = DfpMath.pow(getTwo(), exponent); while (tempDfp.lessThan(y) || tempDfp.equals(y)) { tempDfp = tempDfp.multiply(2); exponent++; } exponent--; /* We have the exponent, now work on the mantissa */ y = y.divide(DfpMath.pow(getTwo(), exponent)); if (exponent > -1023) { y = y.subtract(getOne()); } if (exponent < -1074) { return 0; } if (exponent > 1023) { return negate ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } y = y.multiply(newInstance(4503599627370496l)).rint(); String str = y.toString(); str = str.substring(0, str.length()-1); long mantissa = Long.parseLong(str); if (mantissa == 4503599627370496L) { // Handle special case where we round up to next power of two mantissa = 0; exponent++; } /* Its going to be subnormal, so make adjustments */ if (exponent <= -1023) { exponent--; } while (exponent < -1023) { exponent++; mantissa >>>= 1; } long bits = mantissa | ((exponent + 1023L) << 52); double x = Double.longBitsToDouble(bits); if (negate) { x = -x; } return x; } /** Convert the instance into a split double. * @return an array of two doubles which sum represent the instance * @see #toDouble() */ public double[] toSplitDouble() { double split[] = new double[2]; long mask = 0xffffffffc0000000L; split[0] = Double.longBitsToDouble(Double.doubleToLongBits(toDouble()) & mask); split[1] = subtract(newInstance(split[0])).toDouble(); return split; } /** {@inheritDoc} * @since 3.2 */ public double getReal() { return toDouble(); } /** {@inheritDoc} * @since 3.2 */ public Dfp add(final double a) { return add(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp subtract(final double a) { return subtract(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp multiply(final double a) { return multiply(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp divide(final double a) { return divide(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public Dfp remainder(final double a) { return remainder(newInstance(a)); } /** {@inheritDoc} * @since 3.2 */ public long round() { return FastMath.round(toDouble()); } /** {@inheritDoc} * @since 3.2 */ public Dfp signum() { if (isNaN() || isZero()) { return this; } else { return newInstance(sign > 0 ? +1 : -1); } } /** {@inheritDoc} * @since 3.2 */ public Dfp copySign(final Dfp s) { if ((sign >= 0 && s.sign >= 0) || (sign < 0 && s.sign < 0)) { // Sign is currently OK return this; } return negate(); // flip sign } /** {@inheritDoc} * @since 3.2 */ public Dfp copySign(final double s) { long sb = Double.doubleToLongBits(s); if ((sign >= 0 && sb >= 0) || (sign < 0 && sb < 0)) { // Sign is currently OK return this; } return negate(); // flip sign } /** {@inheritDoc} * @since 3.2 */ public Dfp scalb(final int n) { return multiply(DfpMath.pow(getTwo(), n)); } /** {@inheritDoc} * @since 3.2 */ public Dfp hypot(final Dfp y) { return multiply(this).add(y.multiply(y)).sqrt(); } /** {@inheritDoc} * @since 3.2 */ public Dfp cbrt() { return rootN(3); } /** {@inheritDoc} * @since 3.2 */ public Dfp rootN(final int n) { return (sign >= 0) ? DfpMath.pow(this, getOne().divide(n)) : DfpMath.pow(negate(), getOne().divide(n)).negate(); } /** {@inheritDoc} * @since 3.2 */ public Dfp pow(final double p) { return DfpMath.pow(this, newInstance(p)); } /** {@inheritDoc} * @since 3.2 */ public Dfp pow(final int n) { return DfpMath.pow(this, n); } /** {@inheritDoc} * @since 3.2 */ public Dfp pow(final Dfp e) { return DfpMath.pow(this, e); } /** {@inheritDoc} * @since 3.2 */ public Dfp exp() { return DfpMath.exp(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp expm1() { return DfpMath.exp(this).subtract(getOne()); } /** {@inheritDoc} * @since 3.2 */ public Dfp log() { return DfpMath.log(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp log1p() { return DfpMath.log(this.add(getOne())); } // TODO: deactivate this implementation (and return type) in 4.0 /** Get the exponent of the greatest power of 10 that is less than or equal to abs(this). * @return integer base 10 logarithm * @deprecated as of 3.2, replaced by {@link #intLog10()}, in 4.0 the return type * will be changed to Dfp */ @Deprecated public int log10() { return intLog10(); } // TODO: activate this implementation (and return type) in 4.0 // /** {@inheritDoc} // * @since 3.2 // */ // public Dfp log10() { // return DfpMath.log(this).divide(DfpMath.log(newInstance(10))); // } /** {@inheritDoc} * @since 3.2 */ public Dfp cos() { return DfpMath.cos(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp sin() { return DfpMath.sin(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp tan() { return DfpMath.tan(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp acos() { return DfpMath.acos(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp asin() { return DfpMath.asin(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp atan() { return DfpMath.atan(this); } /** {@inheritDoc} * @since 3.2 */ public Dfp atan2(final Dfp x) throws DimensionMismatchException { // compute r = sqrt(x^2+y^2) final Dfp r = x.multiply(x).add(multiply(this)).sqrt(); if (x.sign >= 0) { // compute atan2(y, x) = 2 atan(y / (r + x)) return getTwo().multiply(divide(r.add(x)).atan()); } else { // compute atan2(y, x) = +/- pi - 2 atan(y / (r - x)) final Dfp tmp = getTwo().multiply(divide(r.subtract(x)).atan()); final Dfp pmPi = newInstance((tmp.sign <= 0) ? -FastMath.PI : FastMath.PI); return pmPi.subtract(tmp); } } /** {@inheritDoc} * @since 3.2 */ public Dfp cosh() { return DfpMath.exp(this).add(DfpMath.exp(negate())).divide(2); } /** {@inheritDoc} * @since 3.2 */ public Dfp sinh() { return DfpMath.exp(this).subtract(DfpMath.exp(negate())).divide(2); } /** {@inheritDoc} * @since 3.2 */ public Dfp tanh() { final Dfp ePlus = DfpMath.exp(this); final Dfp eMinus = DfpMath.exp(negate()); return ePlus.subtract(eMinus).divide(ePlus.add(eMinus)); } /** {@inheritDoc} * @since 3.2 */ public Dfp acosh() { return multiply(this).subtract(getOne()).sqrt().add(this).log(); } /** {@inheritDoc} * @since 3.2 */ public Dfp asinh() { return multiply(this).add(getOne()).sqrt().add(this).log(); } /** {@inheritDoc} * @since 3.2 */ public Dfp atanh() { return getOne().add(this).divide(getOne().subtract(this)).log().divide(2); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp[] a, final Dfp[] b) throws DimensionMismatchException { if (a.length != b.length) { throw new DimensionMismatchException(a.length, b.length); } Dfp r = getZero(); for (int i = 0; i < a.length; ++i) { r = r.add(a[i].multiply(b[i])); } return r; } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double[] a, final Dfp[] b) throws DimensionMismatchException { if (a.length != b.length) { throw new DimensionMismatchException(a.length, b.length); } Dfp r = getZero(); for (int i = 0; i < a.length; ++i) { r = r.add(b[i].multiply(a[i])); } return r; } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp a1, final Dfp b1, final Dfp a2, final Dfp b2) { return a1.multiply(b1).add(a2.multiply(b2)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double a1, final Dfp b1, final double a2, final Dfp b2) { return b1.multiply(a1).add(b2.multiply(a2)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp a1, final Dfp b1, final Dfp a2, final Dfp b2, final Dfp a3, final Dfp b3) { return a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double a1, final Dfp b1, final double a2, final Dfp b2, final double a3, final Dfp b3) { return b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final Dfp a1, final Dfp b1, final Dfp a2, final Dfp b2, final Dfp a3, final Dfp b3, final Dfp a4, final Dfp b4) { return a1.multiply(b1).add(a2.multiply(b2)).add(a3.multiply(b3)).add(a4.multiply(b4)); } /** {@inheritDoc} * @since 3.2 */ public Dfp linearCombination(final double a1, final Dfp b1, final double a2, final Dfp b2, final double a3, final Dfp b3, final double a4, final Dfp b4) { return b1.multiply(a1).add(b2.multiply(a2)).add(b3.multiply(a3)).add(b4.multiply(a4)); } }
[ "kesina@Kesinas-MBP.lan" ]
kesina@Kesinas-MBP.lan
564769631313e85d59f0dd3714d77ef1c13c6dd9
4fac81dc0e45aee0bab27ce630b219532f9e5c68
/src/sync/send/Mail.java
650ed25463cdeaa82e0f72655ddd640bdeee8db7
[]
no_license
jiaqi-g/EasySync
21a4f60342e62d6d1837cfee2d31c2639de16060
e918758672daaa823be59389598a261fb8c21ad0
refs/heads/master
2021-05-26T16:59:40.625112
2012-11-12T11:53:01
2012-11-12T11:53:01
null
0
0
null
null
null
null
GB18030
Java
false
false
4,999
java
package sync.send; import it.sauronsoftware.base64.Base64; import java.util.*; import java.io.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class Mail { //define sender, receiver, SMTP server, username, password, subject and content private String displayName; private String to; private String from; private String smtpServer; private String username; private String password; private String subject; private String content; private boolean ifAuth; //if the authentication is needed on the server side private String filename=""; private Vector file = new Vector(); //vector for saving sending attachments' filenames public void setSmtpServer(String smtpServer){ this.smtpServer=smtpServer; } public void setFrom(String from){ this.from=from; } public void setDisplayName(String displayName){ this.displayName=displayName; } public void setIfAuth(boolean ifAuth){ this.ifAuth=ifAuth; } public void setUserName(String username){ this.username=username; } public void setPassword(String password){ this.password=password; } public void setTo(String to){ this.to=to; } public void setSubject(String subject){ this.subject=subject; } public void setContent(String content){ this.content=content; } public void addAttachfile(String fname){ file.addElement(fname); } public Mail(){ } public Mail(String smtpServer,String from,String displayName,String username,String password,String to,String subject,String content){ this.smtpServer=smtpServer; this.from=from; this.displayName=displayName; this.ifAuth=true; this.username=username; this.password=password; this.to=to; this.subject=subject; this.content=content; } public Mail(String smtpServer,String from,String displayName,String to,String subject,String content){ this.smtpServer=smtpServer; this.from=from; this.displayName=displayName; this.ifAuth=false; this.to=to; this.subject=subject; this.content=content; } //send mail public HashMap send(){ HashMap map=new HashMap(); map.put("state", "success"); String message="E-mail sent successfully!"; Session session=null; Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); if(ifAuth){ props.put("mail.smtp.auth","true"); SmtpAuth smtpAuth = new SmtpAuth(username, password); session = Session.getDefaultInstance(props, smtpAuth); }else{ props.put("mail.smtp.auth","false"); session = Session.getDefaultInstance(props, null); } session.setDebug(true); Transport trans = null; try { Message msg = new MimeMessage(session); try{ Address from_address = new InternetAddress(from, displayName); msg.setFrom(from_address); }catch(java.io.UnsupportedEncodingException e){ e.printStackTrace(); } InternetAddress[] address={new InternetAddress(to)}; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); Multipart mp = new MimeMultipart(); MimeBodyPart mbp = new MimeBodyPart(); mbp.setContent(content.toString(), "text/html;charset=gb2312"); mp.addBodyPart(mbp); if(!file.isEmpty()){//有附件 Enumeration efile = file.elements(); while(efile.hasMoreElements()){ mbp = new MimeBodyPart(); filename = efile.nextElement().toString(); //选择出每一个附件名 mbp.attachFile(filename); FileDataSource fds = new FileDataSource(filename); //得到文件数据源 mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart mbp.setFileName("=?GBK?B?" + Base64.encode(fds.getName()) + "?="); //得到文件名同样至入BodyPart //System.err.println(fds.getName()); mp.addBodyPart(mbp); } file.removeAllElements(); } msg.setContent(mp); //Multipart加入到信件 msg.setSentDate(new Date()); //设置信件头的发送日期 //发送信件 msg.saveChanges(); trans = session.getTransport("smtp"); trans.connect(smtpServer, username, password); trans.sendMessage(msg, msg.getAllRecipients()); trans.close(); }catch(AuthenticationFailedException e){ map.put("state", "failed"); message="邮件发送失败!错误原因:\n"+"身份验证错误!"; e.printStackTrace(); }catch (MessagingException e) { message="邮件发送失败!错误原因:\n"+e.getMessage(); map.put("state", "failed"); e.printStackTrace(); Exception ex = null; if ((ex = e.getNextException()) != null) { System.out.println(ex.toString()); ex.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } //System.out.println("\n提示信息:"+message); map.put("message", message); return map; } }
[ "fudanvictor@gmail.com" ]
fudanvictor@gmail.com
eb114b009489b1fc567620d52fb2689cf03e5801
235efd488136304d015d0545725c9b7ebb23f428
/generate-jar/codes/Add.java
470d660f2a1798ba045ddcc26cb9fec2aa1efe44
[]
no_license
kailiangji/java-study
fdfdea2617b219b20c7da8752051b272850d0b21
3cedcf238ebd416f4147eb449c9b5e294f3c2ad6
refs/heads/master
2020-03-25T19:15:37.211176
2018-08-31T08:24:16
2018-08-31T08:24:16
144,073,738
0
0
null
null
null
null
UTF-8
Java
false
false
227
java
package add; import java.util.*; public class Add { public static void main(String[] args) { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); System.out.printf("%d + %d = %d\n",x ,y, x+y); } }
[ "jkl@irif.fr" ]
jkl@irif.fr
c4a7d610cdc19f055cfdc75976f46c5e444f42f6
e28992d82c5a83c3384168739d9413b35d00baae
/MayChallenge/src/ranSomNote.java
dedfe40d3d492eb337cc60c646f35b9177cb8fa2
[]
no_license
talktoresh/MayChallenge
607090d50f8a6a7de63943939f1383b5eba8cc12
eaaca66c38d5b35d12fc613d3cc5a538afc346c7
refs/heads/master
2022-07-17T05:31:54.231594
2020-05-13T18:24:32
2020-05-13T18:24:32
263,708,613
0
0
null
null
null
null
UTF-8
Java
false
false
958
java
import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ranSomNote { public static void main( String args[]) { String ransomNote = "aa", magazine = "ab"; System.out.println(canConstruct(ransomNote,magazine)); } public static boolean canConstruct(String ransomNote, String magazine) { Map<Character,Integer> map = new HashMap<Character, Integer>(); int flag =0; for(int i=0;i<magazine.length();i++) { if(map.get(magazine.charAt(i))!= null) { map.put(magazine.charAt(i), map.get(magazine.charAt(i))+1); } else map.put(magazine.charAt(i),1); } for(int i=0;i<ransomNote.length();i++) { if(map.get(ransomNote.charAt(i))==flag){ map.remove(ransomNote.charAt(i)); } if(map.containsKey(ransomNote.charAt(i))) { map.put(ransomNote.charAt(i),map.get(ransomNote.charAt(i))-1); } else return false; } return true; } }
[ "reshmakn@192.168.0.101" ]
reshmakn@192.168.0.101
28412cc0af7c233375596c19d0a535a8af112bb9
8dbf6af7282396825dd138dcd016af7637cd5fbc
/CIS 263 JAVA/Java2Gui/Java2Lesson6/src/com/company/JScrollDemo.java
9c6e0adda7ea2245d3f795261feb30a30db611a6
[]
no_license
daveminkowski/coursework
2a66d255057b7de7e55bc76210ad2e37a32c3c7c
58a1e702536a803b7f5bacb3eb33c25119938f61
refs/heads/master
2023-03-06T08:49:13.552257
2020-01-30T23:09:53
2020-01-30T23:09:53
237,286,320
0
0
null
2023-03-03T04:37:47
2020-01-30T19:13:36
PowerShell
UTF-8
Java
false
false
1,152
java
package com.company; import javax.swing.*; import java.awt.*; public class JScrollDemo extends JFrame{ private JPanel panel = new JPanel(); private JScrollPane scroll = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); // scroll bars always show when given the constructor arguments to do so private JScrollPane scroll2 = new JScrollPane(panel); // scroll bars will only show as needed when the constructor is given no arguments private JLabel label = new JLabel("Four Score and Seven"); private Font bigFont = new Font("Arial", Font.PLAIN, 20); private Container con; public JScrollDemo() { con = getContentPane(); label.setFont(bigFont); con.add(scroll); panel.add(label); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main (String[] args) { final int WIDTH = 180; final int HEIGHT = 100; JScrollDemo aFrame = new JScrollDemo(); aFrame.setSize(WIDTH, HEIGHT); aFrame.setVisible(true); } }
[ "42705084+daveminkowski@users.noreply.github.com" ]
42705084+daveminkowski@users.noreply.github.com
fbe1ea918ac52fc2ccbd63adb80963a348ff72a5
f291c8ab1102078386db2b23c687505f07a7653e
/IslandsDFS.java
6b8514ae6398c961c1f89fa66dc8d325d4001147
[]
no_license
priyananna/sourceAlgo
c8337060b0649c3a3fca27ff13c8b176f3b54b42
ffd39bd28c6b372ac98553a0de9934df28ea6273
refs/heads/master
2020-04-16T01:46:22.750802
2019-05-30T03:03:35
2019-05-30T03:03:35
165,184,698
0
0
null
null
null
null
UTF-8
Java
false
false
2,710
java
import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by priyankananna on 1/12/19. */ /* program to find the island in an matrix in a sorted order. where 1 is to indicate a land and 0 is to indicate water. First line consists of the input matrix row integer followed by the columns integer. Example --> input 4 5 1 0 0 1 0 1 0 1 0 0 0 0 1 0 1 1 0 1 0 1 output 1 2 2 4 */ class IslandsDFS { private List<Integer> getIslandsList(int[][] arr, int n, int k){ int row=n; int column =k; int result; List<Integer> resultlst = new ArrayList<>(); boolean visited[][] = new boolean[row][column]; for(int i =0;i<arr.length; ++i) { for (int j = 0; j < arr[0].length; ++j) { if (arr[i][j] == 1 && !visited[i][j]) { result =1; result = result + depthFirstSearch(arr, i, j, visited); resultlst.add(result); } } } Collections.sort(resultlst); return resultlst ; } private int depthFirstSearch(int arr[][],int row, int column, boolean visited[][]){ int ROW[] = new int[] {-1, -1, -1, 0, 0, 1, 1 ,1}; int COL[] = new int[] {-1, 0, 1, -1, 1, -1, 0, 1}; int resultcount =0; visited[row][column] = true; // System.out.println("Processing location [" +row+ "]["+column+"]"); for(int i =0; i<8;++i) if(checkOk(arr,row + ROW[i], column + COL[i], visited)) resultcount = depthFirstSearch(arr, row + ROW[i], column + COL[i], visited) + 1; return resultcount; } private boolean checkOk(int[][] arr, int row, int col, boolean[][] visited){ if ((row >= 0) && (col >= 0) && (row < arr.length) && (col < arr[0].length)) { if ((arr[row][col] ==1) && !(visited[row][col])) { return true; } } return false; } public static void main(String args[]){ IslandsDFS island = new IslandsDFS(); /* Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); for(int i=0; i<n;i++){ for(int j=0; j<k; k++){ arr[i][j] = sc.nextInt(); } }*/ int n =4; int k = 5; List<Integer> result; int arr[][] = new int[][]{ {1, 0, 0, 1, 0}, {1, 0, 1, 0, 0}, {0, 0, 1, 0, 1}, {1, 0, 1, 0, 1} }; result = island.getIslandsList(arr, n, k); for(int a : result){ System.out.println(a); } } }
[ "priyanka.m.n@gmail.com" ]
priyanka.m.n@gmail.com
756a4322438852a8f6a0e5d7eb077ce05ab41b76
f705e7ca5dfad23badb79e14ea633aed79acca73
/app/src/main/java/me/cangming/cminitfaster/APP.java
e081b9ff804be1bc913b3d632631f8ecadb09421
[]
no_license
CangMing666/CmInitFaster
b308a4aa496b981d6a48e7cc832775f54a427257
2990b4ca18c9aff4ce4efa0e0f9587b3f18ee1cc
refs/heads/master
2022-09-27T04:51:57.388703
2020-06-09T10:06:26
2020-06-09T10:06:26
270,954,471
0
0
null
null
null
null
UTF-8
Java
false
false
971
java
package me.cangming.cminitfaster; import android.app.Application; import android.content.Context; import me.cangming.cminitfaster.task.InitBugly; import me.cangming.cminitfaster.task.InitBuglyId; import me.cangming.cminitfaster.task.InitFrescoTask; import me.cangming.cminitfaster.task.InitUserInfoTask; import me.cangming.initfaster.TaskDispatcher; public class APP extends Application { @Override public void onCreate() { super.onCreate(); // 初始化 TaskDispatcher.init(this); TaskDispatcher dispatcher = TaskDispatcher.createInstance(); dispatcher.addTask(new InitUserInfoTask()) .addTask(new InitFrescoTask()) .addTask(new InitBuglyId()) .addTask(new InitBugly()) .start(); // Task 等待 dispatcher.await(); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); } }
[ "cfloveyr@gmail.com" ]
cfloveyr@gmail.com
39f7fd443ba805b9d45e36e1085814d92210cb29
4b0bf4787e89bcae7e4759bde6d7f3ab2c81f849
/aliyun-java-sdk-ccc/src/main/java/com/aliyuncs/ccc/transform/v20200701/GetTurnCredentialsResponseUnmarshaller.java
2d378b1d9ba121521bb0f508b9db3782150c83fe
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-java-sdk
a263fa08e261f12d45586d1b3ad8a6609bba0e91
e19239808ad2298d32dda77db29a6d809e4f7add
refs/heads/master
2023-09-03T12:28:09.765286
2023-09-01T09:03:00
2023-09-01T09:03:00
39,555,898
1,542
1,317
NOASSERTION
2023-09-14T07:27:05
2015-07-23T08:41:13
Java
UTF-8
Java
false
false
1,686
java
/* * 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.aliyuncs.ccc.transform.v20200701; import com.aliyuncs.ccc.model.v20200701.GetTurnCredentialsResponse; import com.aliyuncs.ccc.model.v20200701.GetTurnCredentialsResponse.Data; import com.aliyuncs.transform.UnmarshallerContext; public class GetTurnCredentialsResponseUnmarshaller { public static GetTurnCredentialsResponse unmarshall(GetTurnCredentialsResponse getTurnCredentialsResponse, UnmarshallerContext _ctx) { getTurnCredentialsResponse.setRequestId(_ctx.stringValue("GetTurnCredentialsResponse.RequestId")); getTurnCredentialsResponse.setCode(_ctx.stringValue("GetTurnCredentialsResponse.Code")); getTurnCredentialsResponse.setHttpStatusCode(_ctx.integerValue("GetTurnCredentialsResponse.HttpStatusCode")); getTurnCredentialsResponse.setMessage(_ctx.stringValue("GetTurnCredentialsResponse.Message")); Data data = new Data(); data.setUserName(_ctx.stringValue("GetTurnCredentialsResponse.Data.UserName")); data.setPassword(_ctx.stringValue("GetTurnCredentialsResponse.Data.Password")); getTurnCredentialsResponse.setData(data); return getTurnCredentialsResponse; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
2597053e883e065c2cf34619e7aea8b967d78f94
e05cbcb1ff44338dd60e6c8e6e4c55cd0b93374f
/src/main/resources/libs/JAT/jat/alg/opt/test/DFP_test.java
b42619e4afe689eb14f60a4d8d8a54928b574cb5
[ "Apache-2.0" ]
permissive
MaximTar/satellite
6f520d66e879eca938a1ac8dc32476369e6aa435
7b11db72c2fbdb7934b389e784bec2ea2dedb034
refs/heads/master
2021-01-10T16:17:35.039159
2018-03-19T19:28:31
2018-03-19T19:28:31
54,265,410
0
0
null
null
null
null
UTF-8
Java
false
false
1,339
java
/* JAT: Java Astrodynamics Toolkit * * Copyright (c) 2002 The JAT Project. All rights reserved. * * This file is part of JAT. JAT is free software; you can * redistribute it and/or modify it under the terms of the * NASA Open Source Agreement, version 1.3 or later. * * 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 * NASA Open Source Agreement for more details. * * You should have received a copy of the NASA Open Source Agreement * along with this program; if not, write to the NASA Goddard * Space Flight Center at opensource@gsfc.nasa.gov. * */ package jat.alg.opt.test; import jat.alg.opt.*; import jat.alg.opt.test.functions.*; /** * Davidon-Fletcher-Powell variable metric method * @author Tobias Berthold * */ public class DFP_test { public static void main(String argv[]) { double[] x_init=new double[2]; System.out.println("Rosenbrock function, Numerical derivs, DFP"); // create instances of the classes DFP_test dt = new DFP_test(); x_init[0] = -1.2; x_init[1] = 1.; DFP dfp = new DFP(new Rosenbrock(), x_init); dfp.err_ods=1.e-6; dfp.err_dfp=1.e-6; dfp.eps_CD=1.e-5; dfp.max_it=50; double[] x=dfp.find_min_DFP(); } }
[ "max_131092@mail.ru" ]
max_131092@mail.ru
db4fb0949bc2dfa385be7d6679d8ab7973171d48
1dd8f516e62de208efc8230dd50571df6c0edf2b
/generalProblems/src/problems/Pattern14.java
0f3117c1ebffd5e32e8f2fbe8de594152dbc7daa
[]
no_license
Sidharth0609/generalProblems
aa82dfbc471cbdaed7e514af1d20c6a9a2ae433c
eb9fedf7b44266fd636398b0471b8e16b66a7f3a
refs/heads/master
2023-03-21T23:38:19.443431
2021-03-11T06:47:19
2021-03-11T06:47:19
346,604,753
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package problems; import java.util.Scanner; public class Pattern14 { public static void main(String[] args) { Scanner scn= new Scanner(System.in); int n= scn.nextInt(); for(int i=1;i<11;i++) { int mult =n*i; System.out.println(n + "*" + i +"=" + mult); } scn.close(); } }
[ "sid@DESKTOP-U7GQOFS" ]
sid@DESKTOP-U7GQOFS
3a2053a6832643138ea7bc22e64721e3e1808641
ea3e75a78fc625ef8b5a551c7c96d44eccf8883f
/app/src/androidTest/java/com/wang/baseadapternodatabinding/ApplicationTest.java
254f578fd073c92f1cb4fa9ca111d758d9527681
[ "Apache-2.0" ]
permissive
kingwang666/BaseAdapterNoDataBinding
bdd77d6c3045427dd412d94be94c2a54343e0306
9ca5e2ae6af3d18359afc2670f890b397c0ce16b
refs/heads/master
2020-07-03T18:28:49.248335
2020-04-07T02:17:57
2020-04-07T02:17:57
66,620,673
5
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.wang.baseadapternodatabinding; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
[ "wangxj@jiudeng.me" ]
wangxj@jiudeng.me
38f41177962da0537620989f8ade5bba9ba7f322
4d9ac7be58fabd17775d29fafa966a0940eff934
/tests/org/unclesniper/ogdl/ClassInfoTests.java
bf55f4cb3da4552dc28b2c2d9d66e5df2ce422f9
[]
no_license
UncleSniper/jogdl
94eea9cca0efdba11f65fbf22a091dc12235206c
244549cf0b640bca6fc2ad0cc678a9c6062677ca
refs/heads/master
2022-10-27T17:53:18.833797
2022-10-07T18:53:39
2022-10-07T18:53:39
129,455,129
4
0
null
null
null
null
UTF-8
Java
false
false
15,720
java
package org.unclesniper.ogdl; import java.util.Set; import org.junit.Test; import java.util.Iterator; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class ClassInfoTests { private static class Empty {} private static class VariousAccessors { // yes: setter public void setProp0(String foo) {} // no: static public static void setProp1(String foo) {} // no: nilary public void setProp2() {} // no: ternary public void setProp3(String a, String b, String c) {} // no: package visibility void setProp4(String foo) {} // yes: setter (primitive) public void setProp5(int bar) {} // yes: putter public void setProp6(int index, String value) {} // yes: adder public void addProp7(String foo) {} // no: nilary public void addProp8() {} // no: ternary public void addProp9(String a, String b, String c) {} // yes: putter public void putProp10(String key, String value) {} // no: nilary public void putProp11() {} // no: ternary public void putProp12(String a, String b, String c) {} static final Method m_setProp0; static final Method m_setProp5; static final Method m_setProp6; static final Method m_addProp7; static final Method m_putProp10; static { try { m_setProp0 = VariousAccessors.class.getDeclaredMethod("setProp0", String.class); m_setProp5 = VariousAccessors.class.getDeclaredMethod("setProp5", Integer.TYPE); m_setProp6 = VariousAccessors.class.getDeclaredMethod("setProp6", Integer.TYPE, String.class); m_addProp7 = VariousAccessors.class.getDeclaredMethod("addProp7", String.class); m_putProp10 = VariousAccessors.class.getDeclaredMethod("putProp10", String.class, String.class); } catch(NoSuchMethodException nsme) { throw new Error("Cannot retrieve methods: " + nsme.getMessage(), nsme); } } } private static class ClashingAccessors { public void setProp(String foo) {} public void setProp(int bar) {} public void addProp(String foo) {} public void putProp(String key, String value) {} public void setOther(String baz) {} static final Method m_setProp_String; static final Method m_setProp_int; static final Method m_addProp; static final Method m_putProp; static final Method m_setOther; static { try { m_setProp_String = ClashingAccessors.class.getDeclaredMethod("setProp", String.class); m_setProp_int = ClashingAccessors.class.getDeclaredMethod("setProp", Integer.TYPE); m_addProp = ClashingAccessors.class.getDeclaredMethod("addProp", String.class); m_putProp = ClashingAccessors.class.getDeclaredMethod("putProp", String.class, String.class); m_setOther = ClashingAccessors.class.getDeclaredMethod("setOther", String.class); } catch(NoSuchMethodException nsme) { throw new Error("Cannot retrieve methods: " + nsme.getMessage(), nsme); } } } private static class Super {} private static class Sub extends Super {} private static class VariousConstructors { public VariousConstructors() {} public VariousConstructors(String s) {} public VariousConstructors(Super s) {} public VariousConstructors(Sub s) {} public VariousConstructors(Super sup, Sub sub) {} public VariousConstructors(Sub sub, Super sup) {} static final Constructor<VariousConstructors> c_nil; static final Constructor<VariousConstructors> c_String; static final Constructor<VariousConstructors> c_Super; static final Constructor<VariousConstructors> c_Sub; static final Constructor<VariousConstructors> c_Super_Sub; static final Constructor<VariousConstructors> c_Sub_Super; static { try { c_nil = VariousConstructors.class.getConstructor(); c_String = VariousConstructors.class.getConstructor(String.class); c_Super = VariousConstructors.class.getConstructor(Super.class); c_Sub = VariousConstructors.class.getConstructor(Sub.class); c_Super_Sub = VariousConstructors.class.getConstructor(Super.class, Sub.class); c_Sub_Super = VariousConstructors.class.getConstructor(Sub.class, Super.class); } catch(NoSuchMethodException nsme) { throw new Error("Cannot retrieve constructors: " + nsme.getMessage(), nsme); } } } @Test public void ctor() { ClassInfo info = new ClassInfo(Empty.class); assertSame("subject class", Empty.class, info.getSubject()); } @Test public void emptyClass() { ClassInfo info = new ClassInfo(Empty.class); assertEquals("subject class", Empty.class, info.getSubject()); TestUtils.assertSetEquals("property name", new String[0], info.getPropertyNames()); } @Test public void variousAccessors() { ClassInfo info = new ClassInfo(VariousAccessors.class); assertEquals("subject class", VariousAccessors.class, info.getSubject()); TestUtils.assertSetEquals("property name", new String[] { "prop0", "prop5", "prop6", "prop7", "prop10", }, info.getPropertyNames()); Property prop; Set<Accessor> accs; Accessor acc; // prop0 prop = info.getProperty("prop0"); assertNotNull("prop0", prop); assertEquals("prop0 name", "prop0", prop.getName()); assertSame("prop0 owning class", info, prop.getOwningClass()); accs = TestUtils.toSet(prop.getSetters()); assertEquals("prop0 setter set size", 1, accs.size()); assertEquals("prop0 adder set size", 0, TestUtils.toSet(prop.getAdders()).size()); assertEquals("prop0 putter set size", 0, TestUtils.toSet(prop.getPutters()).size()); acc = accs.iterator().next(); assertNotNull("prop0 setter present", acc); assertSame("prop0 setter owning property", prop, acc.getProperty()); assertEquals("prop0 setter method", VariousAccessors.m_setProp0, acc.getMethod()); assertNull("prop0 key type", acc.getKeyType()); assertEquals("prop0 value type", String.class, acc.getValueType()); // prop5 prop = info.getProperty("prop5"); assertNotNull("prop5", prop); assertEquals("prop5 name", "prop5", prop.getName()); assertSame("prop5 owning class", info, prop.getOwningClass()); accs = TestUtils.toSet(prop.getSetters()); assertEquals("prop5 setter set size", 1, accs.size()); assertEquals("prop5 adder set size", 0, TestUtils.toSet(prop.getAdders()).size()); assertEquals("prop5 putter set size", 0, TestUtils.toSet(prop.getPutters()).size()); acc = accs.iterator().next(); assertNotNull("prop5 setter present", acc); assertSame("prop5 setter owning property", prop, acc.getProperty()); assertEquals("prop5 setter method", VariousAccessors.m_setProp5, acc.getMethod()); assertNull("prop5 key type", acc.getKeyType()); assertEquals("prop5 value type", Integer.TYPE, acc.getValueType()); // prop6 prop = info.getProperty("prop6"); assertNotNull("prop6", prop); assertEquals("prop6 name", "prop6", prop.getName()); assertSame("prop6 owning class", info, prop.getOwningClass()); assertEquals("prop6 setter set size", 0, TestUtils.toSet(prop.getSetters()).size()); assertEquals("prop6 adder set size", 0, TestUtils.toSet(prop.getAdders()).size()); accs = TestUtils.toSet(prop.getPutters()); assertEquals("prop6 putter set size", 1, accs.size()); acc = accs.iterator().next(); assertNotNull("prop6 putter present", acc); assertSame("prop6 putter owning property", prop, acc.getProperty()); assertEquals("prop6 putter method", VariousAccessors.m_setProp6, acc.getMethod()); assertEquals("prop6 key type", Integer.TYPE, acc.getKeyType()); assertEquals("prop6 value type", String.class, acc.getValueType()); // prop7 prop = info.getProperty("prop7"); assertNotNull("prop7", prop); assertEquals("prop7 name", "prop7", prop.getName()); assertSame("prop7 owning class", info, prop.getOwningClass()); assertEquals("prop7 setter set size", 0, TestUtils.toSet(prop.getSetters()).size()); accs = TestUtils.toSet(prop.getAdders()); assertEquals("prop7 adder set size", 1, accs.size()); assertEquals("prop7 putter set size", 0, TestUtils.toSet(prop.getPutters()).size()); acc = accs.iterator().next(); assertNotNull("prop7 adder present", acc); assertSame("prop7 adder owning property", prop, acc.getProperty()); assertEquals("prop7 adder method", VariousAccessors.m_addProp7, acc.getMethod()); assertNull("prop7 key type", acc.getKeyType()); assertEquals("prop7 value type", String.class, acc.getValueType()); // prop10 prop = info.getProperty("prop10"); assertNotNull("prop10", prop); assertEquals("prop10 name", "prop10", prop.getName()); assertSame("prop10 owning class", info, prop.getOwningClass()); assertEquals("prop10 setter set size", 0, TestUtils.toSet(prop.getSetters()).size()); assertEquals("prop10 adder set size", 0, TestUtils.toSet(prop.getAdders()).size()); accs = TestUtils.toSet(prop.getPutters()); assertEquals("prop10 putter set size", 1, accs.size()); acc = accs.iterator().next(); assertNotNull("prop10 putter present", acc); assertSame("prop10 putter owning property", prop, acc.getProperty()); assertEquals("prop10 putter method", VariousAccessors.m_putProp10, acc.getMethod()); assertEquals("prop10 key type", String.class, acc.getKeyType()); assertEquals("prop10 value type", String.class, acc.getValueType()); } @Test public void clashingAccessors() { ClassInfo info = new ClassInfo(ClashingAccessors.class); assertEquals("subject class", ClashingAccessors.class, info.getSubject()); TestUtils.assertSetEquals("property name", new String[] { "prop", "other", }, info.getPropertyNames()); Property prop; Set<Accessor> accs; Accessor acc, acc2; Iterator<Accessor> iter; // prop prop = info.getProperty("prop"); assertNotNull("prop", prop); assertEquals("prop name", "prop", prop.getName()); assertSame("prop owning class", info, prop.getOwningClass()); // setters accs = TestUtils.toSet(prop.getSetters()); assertEquals("prop setter set size", 2, accs.size()); iter = accs.iterator(); acc = iter.next(); assertNotNull("prop setter present", acc); acc2 = iter.next(); assertNotNull("prop setter present", acc2); if(ClashingAccessors.m_setProp_int.equals(acc.getMethod())) { // acc = setProp(int), acc2 = setProp(String) Accessor tmp = acc; acc = acc2; acc2 = tmp; } assertSame("prop setter owning property", prop, acc.getProperty()); assertEquals("prop setter method", ClashingAccessors.m_setProp_String, acc.getMethod()); assertNull("prop key type", acc.getKeyType()); assertEquals("prop value type", String.class, acc.getValueType()); assertSame("prop setter owning property", prop, acc2.getProperty()); assertEquals("prop setter method", ClashingAccessors.m_setProp_int, acc2.getMethod()); assertNull("prop key type", acc2.getKeyType()); assertEquals("prop value type", Integer.TYPE, acc2.getValueType()); // adder accs = TestUtils.toSet(prop.getAdders()); assertEquals("prop adder set size", 1, accs.size()); acc = accs.iterator().next(); assertNotNull("prop adder present", acc); assertSame("prop adder owning property", prop, acc.getProperty()); assertEquals("prop adder method", ClashingAccessors.m_addProp, acc.getMethod()); assertNull("prop key type", acc.getKeyType()); assertEquals("prop value type", String.class, acc.getValueType()); // putter accs = TestUtils.toSet(prop.getPutters()); assertEquals("prop putter set size", 1, accs.size()); acc = accs.iterator().next(); assertNotNull("prop putter present", acc); assertSame("prop putter owning property", prop, acc.getProperty()); assertEquals("prop putter method", ClashingAccessors.m_putProp, acc.getMethod()); assertEquals("prop key type", String.class, acc.getKeyType()); assertEquals("prop value type", String.class, acc.getValueType()); // other prop = info.getProperty("other"); assertNotNull("other", prop); assertEquals("other name", "other", prop.getName()); assertSame("other owning class", info, prop.getOwningClass()); accs = TestUtils.toSet(prop.getSetters()); assertEquals("other setter set size", 1, accs.size()); assertEquals("other adder set size", 0, TestUtils.toSet(prop.getAdders()).size()); assertEquals("other putter set size", 0, TestUtils.toSet(prop.getPutters()).size()); acc = accs.iterator().next(); assertNotNull("other setter present", acc); assertSame("other setter owning property", prop, acc.getProperty()); assertEquals("other setter method", ClashingAccessors.m_setOther, acc.getMethod()); assertNull("other key type", acc.getKeyType()); assertEquals("other value type", String.class, acc.getValueType()); } @Test public void forNullClass() { ClassInfo info = new ClassInfo(null); assertNull("subject class", info.getSubject()); TestUtils.assertSetEquals("property name", new String[0], info.getPropertyNames()); } @Test public void getNonexistentProperty() { ClassInfo info = new ClassInfo(VariousAccessors.class); assertEquals("subject class", VariousAccessors.class, info.getSubject()); assertNull("property", info.getProperty("nonexistent")); } @Test public void getNullProperty() { ClassInfo info = new ClassInfo(VariousAccessors.class); assertEquals("subject class", VariousAccessors.class, info.getSubject()); assertNull("property", info.getProperty(null)); } @Test public void findConstructor() { ClassInfo info = new ClassInfo(VariousConstructors.class); assertEquals("subject class", VariousConstructors.class, info.getSubject()); Constructor<?> ctor; // nilary ctor = info.findConstructorForArguments(new Object[0]); assertNotNull("nilary ctor found", ctor); assertEquals("nilary ctor", VariousConstructors.c_nil, ctor); // unary mismatch ctor = info.findConstructorForArguments(new Object[] {new Object()}); assertNull("mismatched ctor found", ctor); // unary unrelated ctor = info.findConstructorForArguments(new Object[] {"foo"}); assertNotNull("unary unrelated ctor found", ctor); assertEquals("unary unrelated ctor", VariousConstructors.c_String, ctor); // unary super ctor = info.findConstructorForArguments(new Object[] {new Super()}); assertNotNull("unary super ctor found", ctor); assertEquals("unary super ctor", VariousConstructors.c_Super, ctor); // unary sub ctor = info.findConstructorForArguments(new Object[] {new Sub()}); assertNotNull("unary sub ctor found", ctor); assertEquals("unary sub ctor", VariousConstructors.c_Sub, ctor); // binary super/super ctor = info.findConstructorForArguments(new Object[] {new Super(), new Super()}); assertNull("binary super/super ctor found", ctor); // binary super/sub ctor = info.findConstructorForArguments(new Object[] {new Super(), new Sub()}); assertNotNull("binary super/sub ctor found", ctor); assertEquals("binary super/sub ctor", VariousConstructors.c_Super_Sub, ctor); // binary sub/super ctor = info.findConstructorForArguments(new Object[] {new Sub(), new Super()}); assertNotNull("binary sub/super ctor found", ctor); assertEquals("binary sub/super ctor", VariousConstructors.c_Sub_Super, ctor); // binary sub/sub ctor = info.findConstructorForArguments(new Object[] {new Sub(), new Sub()}); assertNotNull("binary sub/sub ctor", ctor); assertEquals("binary sub/sub ctor", VariousConstructors.c_Sub_Super, ctor); } @Test public void findConstructorForNullArguments() { ClassInfo info = new ClassInfo(VariousConstructors.class); assertEquals("subject class", VariousConstructors.class, info.getSubject()); Constructor<?> ctor = info.findConstructorForArguments(null); assertNotNull("nilary ctor found", ctor); assertEquals("nilary ctor", VariousConstructors.c_nil, ctor); } }
[ "simon@bausch-alfdorf.de" ]
simon@bausch-alfdorf.de
0df0de6c87f05f2e57ec99c54968206b10f73ff4
349614cb2346e3779933393712b4d1e6c80e5cdc
/adminlogin.java
0f928e678146220f4d9cece0162e4c2f402f0c00
[]
no_license
BhavyaAprajita/Examination-Portal
ff258bc005f401bea42955562d1505cd4578f302
4fe3cd2bb72f3356d22a7daacd8c500363313031
refs/heads/master
2021-01-23T03:16:44.523506
2017-03-24T12:51:46
2017-03-24T12:51:46
86,065,289
0
0
null
null
null
null
UTF-8
Java
false
false
13,449
java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JOptionPane; /* * 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. */ public class adminlogin extends javax.swing.JFrame { public adminlogin() { initComponents(); setTitle("Login to Admin Portal!"); setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); id = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); pswd = new javax.swing.JPasswordField(); jPanel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Admin Login", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Perpetua Titling MT", 1, 24), new java.awt.Color(255, 0, 0))); // NOI18N id.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { idActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setText("Admin ID"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("Password"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(47, 47, 47) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(id, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE) .addComponent(pswd)) .addContainerGap(80, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) .addComponent(pswd)) .addContainerGap(65, Short.MAX_VALUE)) ); jButton1.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.darkShadow")); jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton1.setText("Login"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.darkShadow")); jButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton2.setText("Back"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 135, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/1481770801_Login Manager.png"))); // NOI18N jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/online exm.jpg"))); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(429, 429, 429) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel4))) .addContainerGap(413, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(213, 213, 213) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(88, 88, 88))) .addGap(53, 53, 53) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(217, Short.MAX_VALUE)) ); setSize(new java.awt.Dimension(1382, 807)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void idActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idActionPerformed // TODO add your handling code here: }//GEN-LAST:event_idActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String s1 = id.getText(); String s2 = pswd.getText(); try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","System","rajesh"); PreparedStatement ps = con.prepareStatement("select id from admin_login where id=? and password=?"); ps.setString(1,s1); ps.setString(2,s2); ResultSet rs = ps.executeQuery(); if(rs.next()) { JOptionPane.showMessageDialog(null,"You are successfully logged in! "+"Welcome "+rs.getString(1)); adminportal ap = new adminportal(); ap.setVisible(true); dispose(); con.close(); ps.close(); rs.close(); } else { JOptionPane.showMessageDialog(null,"Incorrect Admin id or password. Try again with correct details"); } } catch(ClassNotFoundException | SQLException e){ JOptionPane.showMessageDialog(null,e); } // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: Index i=new Index(); i.setVisible(true); dispose(); }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(adminlogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(adminlogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(adminlogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(adminlogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new adminlogin().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField id; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPasswordField pswd; // End of variables declaration//GEN-END:variables }
[ "noreply@github.com" ]
BhavyaAprajita.noreply@github.com
0c434c065290e64433cb15eaeaa343869a5545b2
187f37290c1e07a48d0dfe47e04bf13202b6c663
/netcontrol/Node.java
7afbc582f1d8788f6d71a714da92ca81dc470953
[]
no_license
heimohe/designPattern
955af81eb2688a566bff58608f27411a263c730b
f9ff6c1734bab53a5cc62a8fa2fb3a0c7fc5913e
refs/heads/master
2021-03-16T08:29:47.615319
2017-07-13T03:45:00
2017-07-13T03:45:00
97,077,772
0
0
null
null
null
null
GB18030
Java
false
false
999
java
package com.netcontrol; /** * 节点类 */ public class Node { /** * 节点编号 */ public String id; /** * 节点内容 */ public String text; /** * 父节点编号 */ public String parentId; /** * 孩子节点列表 */ private Children children = new Children(); // 先序遍历,拼接JSON字符串 public String toString() { String result = "{" + "id : '" + id + "'" + ", text : '" + text + "'"; if (children != null && children.getSize() != 0) { result += ", children : " + children.toString(); } else { result += ", leaf : true"; } return result + "}"; } // 兄弟节点横向排序 public void sortChildren() { if (children != null && children.getSize() != 0) { children.sortChildren(); } } // 添加孩子节点 public void addChild(Node node) { this.children.addChild(node); } }
[ "1320245251@qq.com" ]
1320245251@qq.com
b28dc32d5a18e2095e20e464e6d7f45b9f04aa5f
836b9d38b9a3e4deeca7e2c87bdb7376c2989d71
/FrontEndCode/src/main/java/Think/XmlWebServices/Payment_add_request.java
c5e0526ed471eeb6e7dce84098f5d923ca22ef82
[]
no_license
alokthink/NewJavaCode
b8af570a316e1388dc73b128b072e7dabefbbb8a
4dfe6ae40ecec74c4455f64d7589b18f4f55f047
refs/heads/master
2023-03-20T05:05:18.968417
2021-03-18T06:34:07
2021-03-18T06:34:07
348,959,225
0
1
null
null
null
null
UTF-8
Java
false
false
16,724
java
/** * Payment_add_request.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package Think.XmlWebServices; import java.util.Arrays; public class Payment_add_request implements java.io.Serializable { private Think.XmlWebServices.User_login_data user_login_data; private Think.XmlWebServices.Customer_identifier customer_identifier; private Think.XmlWebServices.Payment_add_data payment_add_data; private Think.XmlWebServices.Item_payment[] item_payment; private Think.XmlWebServices.ZZPXIdentifier px_identifier; private java.lang.String dsn; // attribute private Think.XmlWebServices.ZZBoolean submit; // attribute private int doc_ref_id; // attribute private Think.XmlWebServices.ZZBoolean check_missing_fields; // attribute private Think.XmlWebServices.ZZBoolean suppress_events; // attribute public Payment_add_request() { } public Payment_add_request( Think.XmlWebServices.User_login_data user_login_data, Think.XmlWebServices.Customer_identifier customer_identifier, Think.XmlWebServices.Payment_add_data payment_add_data, Think.XmlWebServices.Item_payment[] item_payment, Think.XmlWebServices.ZZPXIdentifier px_identifier, java.lang.String dsn, Think.XmlWebServices.ZZBoolean submit, int doc_ref_id, Think.XmlWebServices.ZZBoolean check_missing_fields, Think.XmlWebServices.ZZBoolean suppress_events) { this.user_login_data = user_login_data; this.customer_identifier = customer_identifier; this.payment_add_data = payment_add_data; this.item_payment = item_payment; this.px_identifier = px_identifier; this.dsn = dsn; this.submit = submit; this.doc_ref_id = doc_ref_id; this.check_missing_fields = check_missing_fields; this.suppress_events = suppress_events; } /** * Gets the user_login_data value for this Payment_add_request. * * @return user_login_data */ public Think.XmlWebServices.User_login_data getUser_login_data() { return user_login_data; } /** * Sets the user_login_data value for this Payment_add_request. * * @param user_login_data */ public void setUser_login_data(Think.XmlWebServices.User_login_data user_login_data) { this.user_login_data = user_login_data; } /** * Gets the customer_identifier value for this Payment_add_request. * * @return customer_identifier */ public Think.XmlWebServices.Customer_identifier getCustomer_identifier() { return customer_identifier; } /** * Sets the customer_identifier value for this Payment_add_request. * * @param customer_identifier */ public void setCustomer_identifier(Think.XmlWebServices.Customer_identifier customer_identifier) { this.customer_identifier = customer_identifier; } /** * Gets the payment_add_data value for this Payment_add_request. * * @return payment_add_data */ public Think.XmlWebServices.Payment_add_data getPayment_add_data() { return payment_add_data; } /** * Sets the payment_add_data value for this Payment_add_request. * * @param payment_add_data */ public void setPayment_add_data(Think.XmlWebServices.Payment_add_data payment_add_data) { this.payment_add_data = payment_add_data; } /** * Gets the item_payment value for this Payment_add_request. * * @return item_payment */ public Think.XmlWebServices.Item_payment[] getItem_payment() { return item_payment; } /** * Sets the item_payment value for this Payment_add_request. * * @param item_payment */ public void setItem_payment(Think.XmlWebServices.Item_payment[] item_payment) { this.item_payment = item_payment; } public Think.XmlWebServices.Item_payment getItem_payment(int i) { return this.item_payment[i]; } public void setItem_payment(int i, Think.XmlWebServices.Item_payment _value) { this.item_payment[i] = _value; } /** * Gets the px_identifier value for this Payment_add_request. * * @return px_identifier */ public Think.XmlWebServices.ZZPXIdentifier getPx_identifier() { return px_identifier; } /** * Sets the px_identifier value for this Payment_add_request. * * @param px_identifier */ public void setPx_identifier(Think.XmlWebServices.ZZPXIdentifier px_identifier) { this.px_identifier = px_identifier; } /** * Gets the dsn value for this Payment_add_request. * * @return dsn */ public java.lang.String getDsn() { return dsn; } /** * Sets the dsn value for this Payment_add_request. * * @param dsn */ public void setDsn(java.lang.String dsn) { this.dsn = dsn; } /** * Gets the submit value for this Payment_add_request. * * @return submit */ public Think.XmlWebServices.ZZBoolean getSubmit() { return submit; } /** * Sets the submit value for this Payment_add_request. * * @param submit */ public void setSubmit(Think.XmlWebServices.ZZBoolean submit) { this.submit = submit; } /** * Gets the doc_ref_id value for this Payment_add_request. * * @return doc_ref_id */ public int getDoc_ref_id() { return doc_ref_id; } /** * Sets the doc_ref_id value for this Payment_add_request. * * @param doc_ref_id */ public void setDoc_ref_id(int doc_ref_id) { this.doc_ref_id = doc_ref_id; } /** * Gets the check_missing_fields value for this Payment_add_request. * * @return check_missing_fields */ public Think.XmlWebServices.ZZBoolean getCheck_missing_fields() { return check_missing_fields; } /** * Sets the check_missing_fields value for this Payment_add_request. * * @param check_missing_fields */ public void setCheck_missing_fields(Think.XmlWebServices.ZZBoolean check_missing_fields) { this.check_missing_fields = check_missing_fields; } /** * Gets the suppress_events value for this Payment_add_request. * * @return suppress_events */ public Think.XmlWebServices.ZZBoolean getSuppress_events() { return suppress_events; } /** * Sets the suppress_events value for this Payment_add_request. * * @param suppress_events */ public void setSuppress_events(Think.XmlWebServices.ZZBoolean suppress_events) { this.suppress_events = suppress_events; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof Payment_add_request)) return false; Payment_add_request other = (Payment_add_request) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.user_login_data==null && other.getUser_login_data()==null) || (this.user_login_data!=null && this.user_login_data.equals(other.getUser_login_data()))) && ((this.customer_identifier==null && other.getCustomer_identifier()==null) || (this.customer_identifier!=null && this.customer_identifier.equals(other.getCustomer_identifier()))) && ((this.payment_add_data==null && other.getPayment_add_data()==null) || (this.payment_add_data!=null && this.payment_add_data.equals(other.getPayment_add_data()))) && ((this.item_payment==null && other.getItem_payment()==null) || (this.item_payment!=null && java.util.Arrays.equals(this.item_payment, other.getItem_payment()))) && ((this.px_identifier==null && other.getPx_identifier()==null) || (this.px_identifier!=null && this.px_identifier.equals(other.getPx_identifier()))) && ((this.dsn==null && other.getDsn()==null) || (this.dsn!=null && this.dsn.equals(other.getDsn()))) && ((this.submit==null && other.getSubmit()==null) || (this.submit!=null && this.submit.equals(other.getSubmit()))) && this.doc_ref_id == other.getDoc_ref_id() && ((this.check_missing_fields==null && other.getCheck_missing_fields()==null) || (this.check_missing_fields!=null && this.check_missing_fields.equals(other.getCheck_missing_fields()))) && ((this.suppress_events==null && other.getSuppress_events()==null) || (this.suppress_events!=null && this.suppress_events.equals(other.getSuppress_events()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getUser_login_data() != null) { _hashCode += getUser_login_data().hashCode(); } if (getCustomer_identifier() != null) { _hashCode += getCustomer_identifier().hashCode(); } if (getPayment_add_data() != null) { _hashCode += getPayment_add_data().hashCode(); } if (getItem_payment() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getItem_payment()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getItem_payment(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getPx_identifier() != null) { _hashCode += getPx_identifier().hashCode(); } if (getDsn() != null) { _hashCode += getDsn().hashCode(); } if (getSubmit() != null) { _hashCode += getSubmit().hashCode(); } _hashCode += getDoc_ref_id(); if (getCheck_missing_fields() != null) { _hashCode += getCheck_missing_fields().hashCode(); } if (getSuppress_events() != null) { _hashCode += getSuppress_events().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(Payment_add_request.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", ">payment_add_request")); org.apache.axis.description.AttributeDesc attrField = new org.apache.axis.description.AttributeDesc(); attrField.setFieldName("dsn"); attrField.setXmlName(new javax.xml.namespace.QName("", "dsn")); attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); typeDesc.addFieldDesc(attrField); attrField = new org.apache.axis.description.AttributeDesc(); attrField.setFieldName("submit"); attrField.setXmlName(new javax.xml.namespace.QName("", "submit")); attrField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "ZZBoolean")); typeDesc.addFieldDesc(attrField); attrField = new org.apache.axis.description.AttributeDesc(); attrField.setFieldName("doc_ref_id"); attrField.setXmlName(new javax.xml.namespace.QName("", "doc_ref_id")); attrField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); typeDesc.addFieldDesc(attrField); attrField = new org.apache.axis.description.AttributeDesc(); attrField.setFieldName("check_missing_fields"); attrField.setXmlName(new javax.xml.namespace.QName("", "check_missing_fields")); attrField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "ZZBoolean")); typeDesc.addFieldDesc(attrField); attrField = new org.apache.axis.description.AttributeDesc(); attrField.setFieldName("suppress_events"); attrField.setXmlName(new javax.xml.namespace.QName("", "suppress_events")); attrField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "ZZBoolean")); typeDesc.addFieldDesc(attrField); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("user_login_data"); elemField.setXmlName(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "user_login_data")); elemField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", ">user_login_data")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("customer_identifier"); elemField.setXmlName(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "customer_identifier")); elemField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", ">customer_identifier")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("payment_add_data"); elemField.setXmlName(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "payment_add_data")); elemField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", ">payment_add_data")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("item_payment"); elemField.setXmlName(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "item_payment")); elemField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "item_payment")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("px_identifier"); elemField.setXmlName(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "px_identifier")); elemField.setXmlType(new javax.xml.namespace.QName("http://Think/XmlWebServices/", "ZZPXIdentifier")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } @Override public String toString() { return "Payment_add_request [user_login_data=" + user_login_data + ", customer_identifier=" + customer_identifier + ", payment_add_data=" + payment_add_data + ", item_payment=" + Arrays.toString(item_payment) + ", px_identifier=" + px_identifier + ", dsn=" + dsn + ", submit=" + submit + ", doc_ref_id=" + doc_ref_id + ", check_missing_fields=" + check_missing_fields + ", suppress_events=" + suppress_events + ", __equalsCalc=" + __equalsCalc + ", __hashCodeCalc=" + __hashCodeCalc + "]"; } }
[ "Alok.Mishra@macmill.com" ]
Alok.Mishra@macmill.com
c6843ac8f115accfc470e17faedc36b9bffc885f
0da6c07075d8674d0cdc060e2aad2722e8f5e162
/MLN-Android/mlnservics/src/main/java/com/immomo/mls/fun/weight/BorderRadiusTextView.java
3f16721120b018d911875c4f026e086264a987b5
[ "MIT" ]
permissive
ybhjx1314/MLN
67ace274f0eea3c19ef03dc841a5eca1d4acb605
be858cfae05f82aa8bc421d1cda6c71ef12f15a4
refs/heads/master
2020-09-18T18:25:48.624088
2019-11-05T12:30:37
2019-11-05T12:30:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,635
java
/** * Created by MomoLuaNative. * Copyright (c) 2019, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.immomo.mls.fun.weight; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.MotionEvent; import com.immomo.mls.fun.other.Size; import com.immomo.mls.fun.ud.view.IBorderRadiusView; import com.immomo.mls.fun.ud.view.IClipRadius; import com.immomo.mls.util.LuaViewUtil; import com.immomo.mls.utils.ViewClipHelper; import com.immomo.mls.utils.ViewShadowHelper; import androidx.annotation.NonNull; /** * Created by XiongFangyu on 2018/8/1. * Label 不能切割圆角,文字会不显示 */ public class BorderRadiusTextView extends ForegroundTextView implements IBorderRadiusView, IClipRadius, ViewClipHelper.SuperDrawAction { private final @NonNull BorderBackgroundDrawable backgroundDrawable; private final @NonNull ViewClipHelper viewClipHelper; private final @NonNull ViewShadowHelper viewShadowHelper; public BorderRadiusTextView(Context context) { super(context); backgroundDrawable = new BorderBackgroundDrawable(); viewClipHelper = new ViewClipHelper(); viewShadowHelper = new ViewShadowHelper(); } //<editor-fold desc="IBorderRadiusView"> @Override public void setBgColor(int color) { backgroundDrawable.setBgColor(color); LuaViewUtil.setBackground(this, backgroundDrawable); } @Override public void setBgDrawable(Drawable drawable) { backgroundDrawable.setBgDrawable(drawable); LuaViewUtil.setBackground(this, backgroundDrawable); } @Override public void setDrawRadiusBackground(boolean draw) { viewClipHelper.setDrawRadiusBackground(draw); // backgroundDrawable.setDrawRadiusBackground(draw); } @Override public int getBgColor() { return backgroundDrawable.getBgColor(); } @Override public void setGradientColor(int start, int end, int type) { backgroundDrawable.setGradientColor(start, end, type); LuaViewUtil.setBackground(this, backgroundDrawable); } @Override public void setRadiusColor(int color) { viewClipHelper.setRadiusColor(color); } @Override public void setAddShadow(int color, Size offset, float shadowRadius, float alpha) { if (Build.VERSION.SDK_INT >= 21) { // 这个是加外边框,通过 setRoundRect 添加 viewShadowHelper.setShadowData(color,offset,shadowRadius,alpha); viewShadowHelper.setOutlineProvider(this); } } @Override public void setStrokeWidth(float width) { backgroundDrawable.setStrokeWidth(width); LuaViewUtil.setBackground(this, backgroundDrawable); } @Override public void setStrokeColor(int color) { backgroundDrawable.setStrokeColor(color); LuaViewUtil.setBackground(this, backgroundDrawable); } @Override public void setCornerRadius(float radius) { backgroundDrawable.setCornerRadius(radius); LuaViewUtil.setBackground(this, backgroundDrawable); viewClipHelper.setRadius(radius); viewShadowHelper.setRadius(radius); viewShadowHelper.setError(false); viewClipHelper.setCornerType(TYPE_CORNER_RADIUS); } @Override public void setRadius(float topLeft, float topRight, float bottomLeft, float bottomRight) { backgroundDrawable.setRadius(topLeft, topRight, bottomLeft, bottomRight); LuaViewUtil.setBackground(this, backgroundDrawable); viewClipHelper.setRadius(topLeft, topRight, bottomLeft, bottomRight); viewClipHelper.setCornerType(TYPE_CORNER_RADIUS); } @Override public void setRadius(int direction, float radius) { backgroundDrawable.setRadius(direction, radius); LuaViewUtil.setBackground(this, backgroundDrawable); viewClipHelper.setRadius(backgroundDrawable); viewClipHelper.setCornerType(TYPE_CORNER_DIRECTION); viewShadowHelper.setError(true);//阴影禁止和setCornerRadiusWithDirection()连用 } @Override public void setMaskRadius(int direction, float radius) { backgroundDrawable.setMaskRadius(direction, radius); LuaViewUtil.setBackground(this, backgroundDrawable); viewClipHelper.setRadius(backgroundDrawable); viewShadowHelper.setError(false);//阴影可以和addCornerMask()连用 } @Override public void initCornerManager(boolean open) { viewClipHelper.openDefaultClip(open); } @Override public void forceClipLevel(int clipLevel) { viewClipHelper.setForceClipLevel(clipLevel); } @Override public float getStrokeWidth() { return backgroundDrawable.getStrokeWidth(); } @Override public int getStrokeColor() { return backgroundDrawable.getStrokeColor(); } @Override public float getCornerRadiusWithDirection(int direction) { return backgroundDrawable.getCornerRadiusWithDirection(direction); } @Override public float getRadius(int direction) { return backgroundDrawable.getRadius(direction); } @Override public float[] getRadii() { return backgroundDrawable.getRadii(); } @Override public void drawBorder(Canvas canvas) { backgroundDrawable.drawBorder(canvas); } //</editor-fold> @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); viewClipHelper.updatePath(w, h, backgroundDrawable.getStrokeWidth()); } @Override public void draw(Canvas canvas) { if (viewClipHelper.needClicp()) { viewClipHelper.clip(canvas, this); } else { super.draw(canvas); } drawBorder(canvas); } @Override public void innerDraw(Canvas canvas) { super.draw(canvas); } @Override public boolean onTouchEvent(MotionEvent event) { if (isEnabled()) backgroundDrawable.onRippleTouchEvent(event); return super.onTouchEvent(event); } @Override public void setDrawRipple(boolean drawRipple) { if (drawRipple) setClickable(true); backgroundDrawable.setDrawRipple(drawRipple); LuaViewUtil.setBackground(this, backgroundDrawable); } }
[ "xiong.fangyu@immomo.com" ]
xiong.fangyu@immomo.com
859d7e96a696ae1f7d9d17ac556079294226adf6
1a01d3c61e8f6d5b11022ba177a4faeffda35a84
/src/main/java/Main.java
bef0fdc98fb619834757cc043b190ecc259c5f04
[]
no_license
saha777/MetaModelNC
798793cdaff7939541517f8d5faa94b0ca2138b3
d5d42a5fa6e0d91b4ff332b3da7bc3a144f98cdb
refs/heads/master
2021-09-10T08:14:21.812821
2018-03-22T18:20:03
2018-03-22T18:20:03
113,332,936
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
import config.DaoConfig; import config.MetaModelConfig; import metamodel.dao.ObjectTypesDao; import metamodel.dao.models.ObjectTypes; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DaoConfig.class, MetaModelConfig.class); List<ObjectTypes> objectTypes = context.getBean(ObjectTypesDao.class).findAll(); for (ObjectTypes obj : objectTypes){ System.out.println(obj.toString()); } } }
[ "salexm948@ukr.net" ]
salexm948@ukr.net
2a254f03f717748396ebae8a4b6e431eabbdbdde
72a1db081453016d57db309fa550d445479f047d
/src/cecs429/documents/DirectoryCorpus.java
84ce90775082f563a5e5f88bc42442847be7e78f
[]
no_license
krutikapathak/SearchEngine_Milestone1
20ffdb728e810b9f7ca8cc59a88775a89db2a707
8ff5a0d2990f0ba26838aa36c1cd72fa32f4b691
refs/heads/master
2023-02-05T10:30:44.778502
2020-12-15T06:34:41
2020-12-15T06:34:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,071
java
package cecs429.documents; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.function.Predicate; /** * A DirectoryCorpus represents a corpus found in a single directory on a local * file system. */ public class DirectoryCorpus implements DocumentCorpus { // The map from document ID to document. private HashMap<Integer, Document> mDocuments; // Maintains a map of registered file types that the corpus knows how to load. private HashMap<String, FileDocumentFactory> mFactories = new HashMap<>(); // A filtering function for identifying documents that should get loaded. private Predicate<String> mFileFilter; private Path mDirectoryPath; /** * Constructs a corpus over an absolute directory path. Before calling * GetDocuments(), you must register a FileDocumentFactory with the * RegisterFileDocumentFactory method. Otherwise, the corpus will not know what * to do with the files it finds. The LoadTextDirectory facade method can * simplify this initialization. * * @see */ public DirectoryCorpus(Path directoryPath) { this(directoryPath, s -> true); } /** * Constructs a corpus over an absolute directory path, only loading files whose * file names satisfy the given predicate filter. */ public DirectoryCorpus(Path directoryPath, Predicate<String> fileFilter) { mFileFilter = fileFilter; mDirectoryPath = directoryPath; } /** * Reads all documents in the corpus into a map from ID to document object. */ private HashMap<Integer, Document> readDocuments() throws IOException { Iterable<Path> allFiles = findFiles(); // Next build the mapping from document ID to document. HashMap<Integer, Document> result = new HashMap<>(); int nextId = 0; for (Path file : allFiles) { // Use the registered factory for the file's extension. result.put(nextId, mFactories.get(getFileExtension(file)).createFileDocument(file, nextId)); nextId++; } return result; } /** * Finds all file names that match the corpus filter predicate and have a known * file extension. */ private Iterable<Path> findFiles() throws IOException { List<Path> allFiles = new ArrayList<>(); // First discover all the files in the directory that match the filter. Files.walkFileTree(mDirectoryPath, new SimpleFileVisitor<Path>() { public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { // make sure we only process the current working directory if (mDirectoryPath.equals(dir)) { return FileVisitResult.CONTINUE; } return FileVisitResult.SKIP_SUBTREE; } public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { String extension = getFileExtension(file); if (mFileFilter.test(file.toString()) && mFactories.containsKey(extension)) { allFiles.add(file); } return FileVisitResult.CONTINUE; } // don't throw exceptions if files are locked/other errors occur public FileVisitResult visitFileFailed(Path file, IOException e) { return FileVisitResult.CONTINUE; } }); return allFiles; } // Stupid Java doesn't come with this method? private static String getFileExtension(Path file) { String fileName = file.getFileName().toString(); String extension = fileName.substring(fileName.lastIndexOf('.') + 1); return "." + extension; } @Override public Iterable<Document> getDocuments() { if (mDocuments == null) { try { mDocuments = readDocuments(); } catch (IOException e) { throw new RuntimeException(e); } } return mDocuments.values(); } @Override public int getCorpusSize() { if (mDocuments == null) { try { mDocuments = readDocuments(); } catch (IOException e) { throw new RuntimeException(e); } } return mDocuments.size(); } @Override public Document getDocument(int id) { return mDocuments.get(id); } /** * Registers a factory method for loading documents of the given file extension. * By default, a corpus does not know how to load any files -- this method must * be called prior to getDocuments(). */ public void registerFileDocumentFactory(String fileExtension, FileDocumentFactory factory) { mFactories.put(fileExtension, factory); } /** * Constructs a corpus over a directory of simple text documents. * * @param fileExtension The extension of the text documents to load, e.g., * ".txt". */ public static DirectoryCorpus loadTextDirectory(Path absolutePath, String fileExtension) { DirectoryCorpus corpus = new DirectoryCorpus(absolutePath); corpus.registerFileDocumentFactory(fileExtension, TextFileDocument::loadTextFileDocument); return corpus; } }
[ "krutikapathak084@gmail.com" ]
krutikapathak084@gmail.com
d43be38f80e6267dde42b9e41fef740a324dd733
29b6a856a81a47ebab7bfdba7fe8a7b845123c9e
/dingtalk/java/src/main/java/com/aliyun/dingtalkcontact_1_0/models/ListSeniorSettingsRequest.java
94384ccce655c47d3a501df2d3027701f2488f3b
[ "Apache-2.0" ]
permissive
aliyun/dingtalk-sdk
f2362b6963c4dbacd82a83eeebc223c21f143beb
586874df48466d968adf0441b3086a2841892935
refs/heads/master
2023-08-31T08:21:14.042410
2023-08-30T08:18:22
2023-08-30T08:18:22
290,671,707
22
9
null
2021-08-12T09:55:44
2020-08-27T04:05:39
PHP
UTF-8
Java
false
false
707
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.dingtalkcontact_1_0.models; import com.aliyun.tea.*; public class ListSeniorSettingsRequest extends TeaModel { @NameInMap("seniorStaffId") public String seniorStaffId; public static ListSeniorSettingsRequest build(java.util.Map<String, ?> map) throws Exception { ListSeniorSettingsRequest self = new ListSeniorSettingsRequest(); return TeaModel.build(map, self); } public ListSeniorSettingsRequest setSeniorStaffId(String seniorStaffId) { this.seniorStaffId = seniorStaffId; return this; } public String getSeniorStaffId() { return this.seniorStaffId; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
218018ba2f9c72d42eb940bad4478f5a9ea6d0de
87d61733542716961d353de5d08850961a1203e8
/src/main/java/com/sample/jhipster/domain/User.java
47440bc7c045faf627497d82230d38fea8ac5cdf
[]
no_license
gurpreetsingh2808/jhipster
d444127fbf1bc8c9a450826c93db62534575638a
445ff2901fc91c41175914a10982b5e4dbcdd903
refs/heads/master
2021-08-31T11:38:48.907562
2017-12-06T10:41:11
2017-12-06T10:41:11
114,975,850
0
0
null
null
null
null
UTF-8
Java
false
false
5,637
java
package com.sample.jhipster.domain; import com.sample.jhipster.config.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.validator.constraints.Email; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.HashSet; import java.util.Locale; import java.util.Objects; import java.util.Set; import java.time.Instant; /** * A user. */ @Entity @Table(name = "jhi_user") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class User extends AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Pattern(regexp = Constants.LOGIN_REGEX) @Size(min = 1, max = 50) @Column(length = 50, unique = true, nullable = false) private String login; @JsonIgnore @NotNull @Size(min = 60, max = 60) @Column(name = "password_hash", length = 60) private String password; @Size(max = 50) @Column(name = "first_name", length = 50) private String firstName; @Size(max = 50) @Column(name = "last_name", length = 50) private String lastName; @Email @Size(min = 5, max = 100) @Column(length = 100, unique = true) private String email; @NotNull @Column(nullable = false) private boolean activated = false; @Size(min = 2, max = 6) @Column(name = "lang_key", length = 6) private String langKey; @Size(max = 256) @Column(name = "image_url", length = 256) private String imageUrl; @Size(max = 20) @Column(name = "activation_key", length = 20) @JsonIgnore private String activationKey; @Size(max = 20) @Column(name = "reset_key", length = 20) @JsonIgnore private String resetKey; @Column(name = "reset_date") private Instant resetDate = null; @JsonIgnore @ManyToMany @JoinTable( name = "jhi_user_authority", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @BatchSize(size = 20) private Set<Authority> authorities = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLogin() { return login; } // Lowercase the login before saving it in database public void setLogin(String login) { this.login = StringUtils.lowerCase(login, Locale.ENGLISH); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public boolean getActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getActivationKey() { return activationKey; } public void setActivationKey(String activationKey) { this.activationKey = activationKey; } public String getResetKey() { return resetKey; } public void setResetKey(String resetKey) { this.resetKey = resetKey; } public Instant getResetDate() { return resetDate; } public void setResetDate(Instant resetDate) { this.resetDate = resetDate; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return !(user.getId() == null || getId() == null) && Objects.equals(getId(), user.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
[ "gurpreetsingh2808@gmail.com" ]
gurpreetsingh2808@gmail.com
41b7a4e24ef014b3c8aa77298bc746cea38dcec9
0c823038a912c05554a61181f333ee394173e60c
/src/main/java/org/sgit/manageguest/resources/StatusResource.java
41711fe4cebb29c775635aba2d9e332ccae86f35
[]
no_license
inzi25/TestJSService
98c822e9bf2bba89766351f5628fea63a7888070
b9115424f92e4cee54222d1a54f8a6caebf17c72
refs/heads/master
2021-01-17T17:39:41.063438
2016-07-26T10:41:52
2016-07-26T10:42:57
64,213,671
0
0
null
null
null
null
UTF-8
Java
false
false
950
java
package org.sgit.manageguest.resources; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.sgit.manageguest.model.Status; import org.sgit.manageguest.service.StatusService; @Path("/status") public class StatusResource { StatusService statusService = new StatusService(); @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String insertStatusDetails(Status status) { return statusService.insertStatus(status); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String updateCadenceDetails(Status status) { return statusService.updateStatus(status); } @GET @Produces(MediaType.APPLICATION_JSON) public String getStatusDetails() { return statusService.getStatus(); } }
[ "infaaz007@gmail.com" ]
infaaz007@gmail.com
b472a33cbc007f787670c46ee107321e50e4106a
69aebebb20cb20c0f87d09f4490b5e2c2f9df419
/src/main/java/com/mmtap/trader/bridjapi/ConGatewayMarkup.java
692a8dcefb284b11633be62209d5d566054ac56d
[]
no_license
wtospit/MT4BridJAPI
e00a15af8a4fd31f01d073cff91e5b8857444a9a
4b0392fe486cbb7e0c4442747fffc3ee79953cd3
refs/heads/master
2022-12-13T02:09:24.897907
2020-09-16T10:45:33
2020-09-16T10:45:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,788
java
package com.mmtap.trader.bridjapi; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Array; import org.bridj.ann.Field; import org.bridj.ann.Library; /** * +------------------------------------------------------------------+<br> * <i>native declaration : MT4ManagerAPI.h:690</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> or <a href="http://bridj.googlecode.com/">BridJ</a> . */ @Library("MT4ManagerAPI") public class ConGatewayMarkup extends StructObject { static { BridJ.register(); } /** enable flag 0 - disabled, 1 - enabled */ @Field(0) public int enable() { return this.io.getIntField(this, 0); } /** enable flag 0 - disabled, 1 - enabled */ @Field(0) public ConGatewayMarkup enable(int enable) { this.io.setIntField(this, 0, enable); return this; } /** * source symbol\symbols mask\symbols group name<br> * C type : char[128] */ @Array({128}) @Field(1) public Pointer<Byte > source() { return this.io.getPointerField(this, 1); } /** * local symbol name<br> * C type : char[12] */ @Array({12}) @Field(2) public Pointer<Byte > symbol() { return this.io.getPointerField(this, 2); } /** * account name (obsolete)<br> * C type : char[64] */ @Array({64}) @Field(3) public Pointer<Byte > account_name() { return this.io.getPointerField(this, 3); } /** account internal id (obsolete) */ @Field(4) public int account_id() { return this.io.getIntField(this, 4); } /** account internal id (obsolete) */ @Field(4) public ConGatewayMarkup account_id(int account_id) { this.io.setIntField(this, 4, account_id); return this; } /** bid markup in pips */ @Field(5) public int bid_markup() { return this.io.getIntField(this, 5); } /** bid markup in pips */ @Field(5) public ConGatewayMarkup bid_markup(int bid_markup) { this.io.setIntField(this, 5, bid_markup); return this; } /** ask markup in pips */ @Field(6) public int ask_markup() { return this.io.getIntField(this, 6); } /** ask markup in pips */ @Field(6) public ConGatewayMarkup ask_markup(int ask_markup) { this.io.setIntField(this, 6, ask_markup); return this; } /** * reserved<br> * C type : int[16] */ @Array({16}) @Field(7) public Pointer<Integer > reserved() { return this.io.getPointerField(this, 7); } public ConGatewayMarkup() { super(); } public ConGatewayMarkup(Pointer pointer) { super(pointer); } }
[ "java_khan@126.com" ]
java_khan@126.com
64260cfb5c3a75dd33a4902a3094890fac348776
fbbdb6ae1695e654686bf826944cf3a460318c96
/src/main/java/twilightforest/item/ItemTFEmptyMagicMap.java
dfc17835f415eba654ba2acfbeaedfeb03c828c5
[]
no_license
Bogdan-G/twilightforest
de5fd393fd5ebd9285ebdcd10d1f2b556e67b1d7
1f8da057eaa5323625d1dd5174cc4e66806881c3
refs/heads/master
2020-04-05T06:25:14.411198
2019-01-18T08:01:43
2019-01-18T08:01:43
62,345,724
2
3
null
2016-06-30T22:18:26
2016-06-30T22:18:26
null
UTF-8
Java
false
false
2,396
java
package twilightforest.item; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemMapBase; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraft.world.storage.MapData; import twilightforest.TFAchievementPage; import twilightforest.TFMagicMapData; import twilightforest.TwilightForestMod; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemTFEmptyMagicMap extends ItemMapBase { protected ItemTFEmptyMagicMap() { super(); this.setCreativeTab(TFItems.creativeTab); } /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ @Override public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) { ItemStack mapItem = new ItemStack(TFItems.magicMap, 1, par2World.getUniqueDataId(ItemTFMagicMap.STR_ID)); String mapName = ItemTFMagicMap.STR_ID + "_" + mapItem.getItemDamage(); MapData mapData = new TFMagicMapData(mapName); par2World.setItemData(mapName, mapData); mapData.scale = 4; int step = 128 * (1 << mapData.scale); mapData.xCenter = (int)(Math.round(par3EntityPlayer.posX / step) * step); mapData.zCenter = (int)(Math.round(par3EntityPlayer.posZ / step) * step); mapData.dimension = (byte)par2World.provider.dimensionId; mapData.markDirty(); --par1ItemStack.stackSize; //cheevo if (mapItem.getItem() == TFItems.magicMap) { par3EntityPlayer.triggerAchievement(TFAchievementPage.twilightMagicMap); } if (par1ItemStack.stackSize <= 0) { return mapItem; } else { if (!par3EntityPlayer.inventory.addItemStackToInventory(mapItem.copy())) { par3EntityPlayer.dropPlayerItemWithRandomChoice(mapItem, false); } return par1ItemStack; } } /** * Properly register icon source */ @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.itemIcon = par1IconRegister.registerIcon(TwilightForestMod.ID + ":" + this.getUnlocalizedName().substring(5)); } }
[ "ben.mazur@gmail.com" ]
ben.mazur@gmail.com
d3b3de8db65a5c7ffe5b59ee493cba106755618e
507b470c93e5fdf59cbadcd244bc135cd93f7b36
/de.ars.daojones.runtime/src/main/java/de/ars/daojones/runtime/spi/cache/CacheFactory.java
83ded3e93504c948e2c1824b26ad7045377082d0
[]
no_license
ueberfuhr/daojones
9fb777b5c8dc77777c6812281b789a0867d8bd55
b1799e7b34b9925a9fbd64fad37103f5ea7789e3
refs/heads/master
2023-05-30T13:11:22.098433
2017-06-06T05:05:54
2017-06-06T05:05:54
376,147,622
0
0
null
null
null
null
UTF-8
Java
false
false
590
java
package de.ars.daojones.runtime.spi.cache; /** * A common interface for a factory that creates caches. * * @author Ralf Zahn, ARS Computer und Consulting GmbH, 2013 * @since 2.0 */ public interface CacheFactory { /** * Creates a cache instance. * * @param <K> * the key type * @param <V> * the value type * @param context * the cache context * @return the {@link Cache} * @throws CacheException */ public <K, V> Cache<K, V> createCache( CacheContext<K, V> context ) throws CacheException; }
[ "melanie.reiter@ars.de" ]
melanie.reiter@ars.de
c90a355681ce2d73ce04670dcffcb7a04af6f330
70d9fb40762784dcd417f98240ca5e17d182a6e3
/src/main/java/com/joshua/springboot/MainApplication.java
24d1877b261feede78a75a951d578c7ab04a5e74
[]
no_license
JoshuaThotsana/SPRING-BOOT---PART-1
df1d8b3ed7a3d269717ba08191936791e5e0b2ad
441abd8da77b13837264b898b51768dd7f036024
refs/heads/master
2022-06-05T14:29:38.563587
2020-04-28T02:10:12
2020-04-28T02:10:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
731
java
package com.joshua.springboot; import com.joshua.springboot.controller.Controller; import com.joshua.springboot.controller.UserController; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MainApplication { private static Controller controller; // reference variable public MainApplication(UserController controller) { MainApplication.controller = controller; // Create an instance of Controller interface by injecting a class that implements it. } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); controller.callService(); } }
[ "thotsana.mabotsa@umuzi.org" ]
thotsana.mabotsa@umuzi.org
63d35c9bff072e82d73f15caa6d7771729db7877
99a7db50a02cf9a7ebec2eaa3633b1eedcae33dc
/Launcher/src/com/jidesoft/swing/NullTristateCheckBox.java
a4548d68f0c5d34fe175af534572d8465716f529
[]
no_license
Ren0X1/JavaProject
6406fdac158b52d750ea0a38da91a1211b4f5efc
3c4ba1e9aa56f4628eb5df0972e14b7247ae27a8
refs/heads/master
2023-06-01T05:52:53.703303
2021-06-16T14:46:34
2021-06-16T14:46:34
305,355,892
1
2
null
2020-10-30T17:46:34
2020-10-19T11:06:33
Java
UTF-8
Java
false
false
3,613
java
/* * @(#)NullTristateCheckBox.java 8/11/2005 * * Copyright 2002 - 2005 JIDE Software Inc. All rights reserved. */ package com.jidesoft.swing; import javax.swing.*; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import java.awt.*; /** * This is part of the null-components. A null component doesn't have foreground, background or font value set. In the * other words, the foreground, background and font value of null-component are null. But this doesn't mean * getBackground(), getForeground() or getFont() will return null. According to {@link * java.awt.Component#getBackground()}, {@link java.awt.Component#getForeground()} and {@link * java.awt.Component#getFont()}, if the value is null, it will get the value from its parent. In the other words, if * you add a null-component to JPanel, you can use JPanel to control the background, foreground and font of this * null-component. The feature is very helpful if you want to make sure all components in a JPanel has the same * background, foreground or font. * <p/> * Even in null-components, you can still change the foreground, background or font value if you do want. However, * you'll have to use a font which is not an instance of FontUIResource or a color which is not an instance of * ColorUIResource. * <p/> * We creates a few null-components. It doesn't cover all components. You can always create your own. All you need to do * is this * <pre><code> * public class NullXxxComponent extends XxxComponent { * // invoke clearAttribute() in all the constructors * <p/> * public void setFont(Font font) { * if (font instanceof FontUIResource) { * return; * } * super.setFont(font); * } * <p/> * public void setBackground(Color bg) { * if (bg instanceof ColorUIResource) { * return; * } * super.setBackground(bg); * } * <p/> * public void setForeground(Color fg) { * if (fg instanceof ColorUIResource) { * return; * } * super.setForeground(fg); * } * <p/> * private void clearAttribute() { * setFont(null); * setBackground(null); * // do not do this for JButton since JButton always paints button * // content background. So it'd better to leave the foreground alone * setForeground(null); * } * } * </code></pre> * * @see com.jidesoft.swing.NullButton * @see com.jidesoft.swing.NullCheckBox * @see com.jidesoft.swing.NullJideButton * @see com.jidesoft.swing.NullLabel * @see com.jidesoft.swing.NullRadioButton * @see com.jidesoft.swing.NullPanel */ public class NullTristateCheckBox extends TristateCheckBox { public NullTristateCheckBox() { clearAttribute(); } public NullTristateCheckBox(String text) { super(text); clearAttribute(); } public NullTristateCheckBox(String text, Icon icon) { super(text, icon); clearAttribute(); } private void clearAttribute() { super.setFont(null); super.setBackground(null); super.setForeground(null); } @Override public void setFont(Font font) { if (font instanceof FontUIResource) { return; } super.setFont(font); } @Override public void setBackground(Color bg) { if (bg instanceof ColorUIResource) { return; } super.setBackground(bg); } @Override public void setForeground(Color fg) { if (fg instanceof ColorUIResource) { return; } super.setForeground(fg); } }
[ "alexyanamusicpro@gmail.com" ]
alexyanamusicpro@gmail.com
ddad3a4883b4a043889876ba9ed37213deb9e62a
968779314ddc8065f138d8233ec7f20fdb59000f
/app/src/main/java/com/example/htp/widget/PagerSlidingTabStrip.java
631660c6cc42b7aa538abd32c7497cd801eac8b6
[]
no_license
htp930301/HtpAndroid
be5a80c5f7bcbc0f815f7b69f209fd78ad61b72a
df469fbc0777a3ecf362021fd81694c352643308
refs/heads/20151214
2021-01-10T10:11:43.615444
2015-12-04T03:05:47
2015-12-04T03:05:47
47,962,264
0
1
null
2015-12-14T08:39:43
2015-12-14T08:39:42
null
UTF-8
Java
false
false
16,907
java
/* * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.htp.widget; import java.util.Locale; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Typeface; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.example.htp.htpandroidframe.R; public class PagerSlidingTabStrip extends HorizontalScrollView { public interface IconTabProvider { public int getPageIconResId(int position); } // @formatter:off private static final int[] ATTRS = new int[] { android.R.attr.textSize, android.R.attr.textColor }; // @formatter:on private LinearLayout.LayoutParams defaultTabLayoutParams; private LinearLayout.LayoutParams expandedTabLayoutParams; private final PageListener pageListener = new PageListener(); public OnPageChangeListener delegatePageListener; private LinearLayout tabsContainer; private ViewPager pager; private int tabCount; private int currentPosition = 0; private float currentPositionOffset = 0f; private Paint rectPaint; private Paint dividerPaint; private int indicatorColor = 0xFF666666; private int underlineColor = 0x1A000000; private int dividerColor = 0x1A000000; private boolean shouldExpand = true; private boolean textAllCaps = true; private int scrollOffset = 52; private int indicatorHeight = 5; private int underlineHeight = 2; private int dividerPadding = 12; private int tabPadding = 24; private int dividerWidth = 1; private int tabTextSize = 14; private int tabTextColor = 0xFF666666; private int selectedTabTextColor = 0xFF666666; //选中Tab的颜色 private int selectedPosition = 0; private Typeface tabTypeface = null; private int tabTypefaceStyle = Typeface.NORMAL; private int lastScrollX = 0; private int tabBackgroundResId = R.drawable.background_tab; private Locale locale; public PagerSlidingTabStrip(Context context) { this(context, null); } public PagerSlidingTabStrip(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setFillViewport(true); setWillNotDraw(false); tabsContainer = new LinearLayout(context); tabsContainer.setOrientation(LinearLayout.HORIZONTAL); tabsContainer.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); addView(tabsContainer); DisplayMetrics dm = getResources().getDisplayMetrics(); scrollOffset = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm); indicatorHeight = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm); underlineHeight = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm); dividerPadding = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm); tabPadding = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm); dividerWidth = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm); tabTextSize = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm); // get system attrs (android:textSize and android:textColor) TypedArray a = context.obtainStyledAttributes(attrs, ATTRS); tabTextSize = a.getDimensionPixelSize(0, tabTextSize); tabTextColor = a.getColor(1, tabTextColor); a.recycle(); // get custom attrs a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip); // tab文字选中时的颜色,默认和滑动指示器的颜色一致 selectedTabTextColor = a.getColor( R.styleable.PagerSlidingTabStrip_selectedTabTextColor, indicatorColor); indicatorColor = a.getColor( R.styleable.PagerSlidingTabStrip_pstsIndicatorColor, indicatorColor); underlineColor = a.getColor( R.styleable.PagerSlidingTabStrip_pstsUnderlineColor, underlineColor); dividerColor = a .getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor, dividerColor); indicatorHeight = a.getDimensionPixelSize( R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight, indicatorHeight); underlineHeight = a.getDimensionPixelSize( R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight, underlineHeight); dividerPadding = a.getDimensionPixelSize( R.styleable.PagerSlidingTabStrip_pstsDividerPadding, dividerPadding); tabPadding = a.getDimensionPixelSize( R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight, tabPadding); tabBackgroundResId = a.getResourceId( R.styleable.PagerSlidingTabStrip_pstsTabBackground, tabBackgroundResId); shouldExpand = a .getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand, shouldExpand); scrollOffset = a .getDimensionPixelSize( R.styleable.PagerSlidingTabStrip_pstsScrollOffset, scrollOffset); textAllCaps = a.getBoolean( R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps); a.recycle(); rectPaint = new Paint(); rectPaint.setAntiAlias(true); rectPaint.setStyle(Style.FILL); dividerPaint = new Paint(); dividerPaint.setAntiAlias(true); dividerPaint.setStrokeWidth(dividerWidth); defaultTabLayoutParams = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f); if (locale == null) { locale = getResources().getConfiguration().locale; } } public void setViewPager(ViewPager pager) { this.pager = pager; if (pager.getAdapter() == null) { throw new IllegalStateException( "ViewPager does not have adapter instance."); } pager.setOnPageChangeListener(pageListener); notifyDataSetChanged(); } public void setOnPageChangeListener(OnPageChangeListener listener) { this.delegatePageListener = listener; } public void notifyDataSetChanged() { tabsContainer.removeAllViews(); tabCount = pager.getAdapter().getCount(); for (int i = 0; i < tabCount; i++) { if (pager.getAdapter() instanceof IconTabProvider) { addIconTab(i, ((IconTabProvider) pager.getAdapter()) .getPageIconResId(i)); } else { addTextTab(i, pager.getAdapter().getPageTitle(i).toString()); } } updateTabStyles(); getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public void onGlobalLayout() { // if (Build.VERSION.SDK_INT < // Build.VERSION_CODES.JELLY_BEAN) { getViewTreeObserver() .removeGlobalOnLayoutListener(this); // } else { // getViewTreeObserver().removeOnGlobalLayoutListener(this); // } currentPosition = pager.getCurrentItem(); scrollToChild(currentPosition, 0); } }); } private void addTextTab(final int position, String title) { TextView tab = new TextView(getContext()); tab.setText(title); tab.setGravity(Gravity.CENTER); tab.setSingleLine(); addTab(position, tab); } private void addIconTab(final int position, int resId) { ImageButton tab = new ImageButton(getContext()); tab.setImageResource(resId); addTab(position, tab); } private void addTab(final int position, View tab) { tab.setFocusable(true); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(position); } }); tab.setPadding(tabPadding, 0, tabPadding, 0); tabsContainer .addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams); } private void updateTabStyles() { for (int i = 0; i < tabCount; i++) { View v = tabsContainer.getChildAt(i); v.setBackgroundResource(tabBackgroundResId); if (v instanceof TextView) { TextView tab = (TextView) v; tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize); tab.setTypeface(tabTypeface, tabTypefaceStyle); tab.setTextColor(tabTextColor); // setAllCaps() is only available from API 14, so the upper case // is made manually if we are on a // pre-ICS-build if (textAllCaps) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { tab.setAllCaps(true); } else { tab.setText(tab.getText().toString() .toUpperCase(locale)); } } if (i == selectedPosition) { tab.setTextColor(selectedTabTextColor); } } } } private void scrollToChild(int position, int offset) { if (tabCount == 0) { return; } int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset; if (position > 0 || offset > 0) { newScrollX -= scrollOffset; } if (newScrollX != lastScrollX) { lastScrollX = newScrollX; scrollTo(newScrollX, 0); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isInEditMode() || tabCount == 0) { return; } final int height = getHeight(); // draw indicator line rectPaint.setColor(indicatorColor); // default: line below current tab View currentTab = tabsContainer.getChildAt(currentPosition); float lineLeft = currentTab.getLeft(); float lineRight = currentTab.getRight(); // if there is an offset, start interpolating left and right coordinates // between current and next tab if (currentPositionOffset > 0f && currentPosition < tabCount - 1) { View nextTab = tabsContainer.getChildAt(currentPosition + 1); final float nextTabLeft = nextTab.getLeft(); final float nextTabRight = nextTab.getRight(); lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft); lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight); } canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint); // draw underline rectPaint.setColor(underlineColor); canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint); // draw divider dividerPaint.setColor(dividerColor); for (int i = 0; i < tabCount - 1; i++) { View tab = tabsContainer.getChildAt(i); canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint); } } private class PageListener implements OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { currentPosition = position; currentPositionOffset = positionOffset; scrollToChild(position, (int) (positionOffset * tabsContainer .getChildAt(position).getWidth())); invalidate(); if (delegatePageListener != null) { delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } @Override public void onPageScrollStateChanged(int state) { if (state == ViewPager.SCROLL_STATE_IDLE) { scrollToChild(pager.getCurrentItem(), 0); } if (delegatePageListener != null) { delegatePageListener.onPageScrollStateChanged(state); } } @Override public void onPageSelected(int position) { selectedPosition = position; updateTabStyles(); if (delegatePageListener != null) { delegatePageListener.onPageSelected(position); } } } public void setIndicatorColor(int indicatorColor) { this.indicatorColor = indicatorColor; invalidate(); } public void setIndicatorColorResource(int resId) { this.indicatorColor = getResources().getColor(resId); invalidate(); } public int getIndicatorColor() { return this.indicatorColor; } public void setIndicatorHeight(int indicatorLineHeightPx) { this.indicatorHeight = indicatorLineHeightPx; invalidate(); } public int getIndicatorHeight() { return indicatorHeight; } public void setUnderlineColor(int underlineColor) { this.underlineColor = underlineColor; invalidate(); } public void setUnderlineColorResource(int resId) { this.underlineColor = getResources().getColor(resId); invalidate(); } public int getUnderlineColor() { return underlineColor; } public void setDividerColor(int dividerColor) { this.dividerColor = dividerColor; invalidate(); } public void setDividerColorResource(int resId) { this.dividerColor = getResources().getColor(resId); invalidate(); } public int getDividerColor() { return dividerColor; } public void setUnderlineHeight(int underlineHeightPx) { this.underlineHeight = underlineHeightPx; invalidate(); } public int getUnderlineHeight() { return underlineHeight; } public void setDividerPadding(int dividerPaddingPx) { this.dividerPadding = dividerPaddingPx; invalidate(); } public int getDividerPadding() { return dividerPadding; } public void setScrollOffset(int scrollOffsetPx) { this.scrollOffset = scrollOffsetPx; invalidate(); } public int getScrollOffset() { return scrollOffset; } public void setShouldExpand(boolean shouldExpand) { this.shouldExpand = shouldExpand; requestLayout(); } public boolean getShouldExpand() { return shouldExpand; } public boolean isTextAllCaps() { return textAllCaps; } public void setAllCaps(boolean textAllCaps) { this.textAllCaps = textAllCaps; } public void setTextSize(int textSizePx) { this.tabTextSize = textSizePx; updateTabStyles(); } public int getTextSize() { return tabTextSize; } public void setTextColor(int textColor) { this.tabTextColor = textColor; updateTabStyles(); } public void setTextColorResource(int resId) { this.tabTextColor = getResources().getColor(resId); updateTabStyles(); } public int getTextColor() { return tabTextColor; } public void setSelectedTextColor(int textColor) { this.selectedTabTextColor = textColor; updateTabStyles(); } public void setSelectedTextColorResource(int resId) { this.selectedTabTextColor = getResources().getColor(resId); updateTabStyles(); } public int getSelectedTextColor() { return selectedTabTextColor; } public void setTypeface(Typeface typeface, int style) { this.tabTypeface = typeface; this.tabTypefaceStyle = style; updateTabStyles(); } public void setTabBackground(int resId) { this.tabBackgroundResId = resId; } public int getTabBackground() { return tabBackgroundResId; } public void setTabPaddingLeftRight(int paddingPx) { this.tabPadding = paddingPx; updateTabStyles(); } public int getTabPaddingLeftRight() { return tabPadding; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); currentPosition = savedState.currentPosition; requestLayout(); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.currentPosition = currentPosition; return savedState; } static class SavedState extends BaseSavedState { int currentPosition; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentPosition = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(currentPosition); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
[ "544529563@qq.com" ]
544529563@qq.com
9728fe2983ee11460755d645b6af3c8e2e30566f
8e215ff9c4f4c2db53eca01f1d685a1c11cd3e6a
/ITalk/src/com/zd/italk2/ReceiveExitMsgTask.java
15d34bd87063b59bd03f40d420899a3277fc3d9e
[]
no_license
linzheda/ITalk
b3b8a1a0dde3340029f3305c4f2263ca18234c3f
86277c8891912b254f60efddfa6ef83acdf71c81
refs/heads/master
2021-01-19T23:20:02.695968
2017-04-21T09:00:27
2017-04-21T09:00:27
88,963,683
0
0
null
null
null
null
UTF-8
Java
false
false
1,047
java
package com.zd.italk2; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ReceiveExitMsgTask implements Runnable{ private DatagramPacket dp;//package private DatagramSocket ds;//socket private byte[] buf;//接受用的字节数组 public final static int receivePort=10002;//接受用的端口 private MyNotify myNotify; public ReceiveExitMsgTask(MyNotify myNotify) { this.myNotify = myNotify; } @Override public void run() { buf=new byte[1024]; dp=new DatagramPacket(buf,buf.length); try { ds=new DatagramSocket(iTalk.EXITPORT); while(true){ ds.receive(dp); String s=new String(buf,0,dp.getLength()); if(s.equals("bye")){ InetAddress address=dp.getAddress(); if(myNotify!=null){ TaskResult tr=new TaskResult(); tr.content=s; tr.inetAddress=address; myNotify.notifyResult(tr); } } } } catch (Exception e) { e.printStackTrace(); } } }
[ "717537314@qq.com" ]
717537314@qq.com
e7707f05cff8d2d085f699e36c57b2052e5b9bd1
27b86a5aae9bef94c81a053e9020b72dbbbd7255
/ssh/src/main/java/perf/ssh/stream/LineEmittingStream.java
a0fb4530377917bbc9754fd9adc1b17844355b61
[]
no_license
willr3/perf
435228d30fb77d4956958e3964486dfdfceda05d
95db733f002c96c90d2c170b7d15796b7cfa0adb
refs/heads/master
2021-05-02T17:03:45.091621
2017-11-29T15:15:06
2017-11-29T15:15:06
72,554,530
0
1
null
2018-01-16T09:34:59
2016-11-01T16:25:10
Java
UTF-8
Java
false
false
3,818
java
package perf.ssh.stream; import java.io.IOException; import java.io.OutputStream; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; /** * Created by wreicher * A Stream that emits lines to Consumers */ public class LineEmittingStream extends OutputStream { int index = 0; byte buffered[] = new byte[4*1024]; private List<Consumer<String>> consumers = new LinkedList<>(); public LineEmittingStream(){} public boolean addConsumer(Consumer<String> consumer){ return consumers.add(consumer); } public boolean removeConsumer(Consumer<String> consumer){ return consumers.remove(consumer); } public void reset() { index = 0; } @Override public void write(int i) throws IOException {} @Override public void write(byte b[]) throws IOException { write(b,0,b.length); } @Override public void write(byte b[], int off, int len) { int lineBreak = -1; int next=-1; int lim = off+len; //printB(b,off,len); for(int i = off; i<lim; i++){ if( b[i] == 10 || b[i]==13 ){ // if CR or LR lineBreak=i; if(index==0){ emit(b,off,lineBreak-off);//because we don't want the char @ lineBreak }else{ if(index+lineBreak-off >= buffered.length){ byte newBuf[] = new byte[buffered.length*2]; System.arraycopy(buffered,0,newBuf,0,index); buffered = newBuf; } System.arraycopy(b,off,buffered,index,(lineBreak-off)); index+=(lineBreak-off); emit(buffered,0,index); } if(i+1 < lim && (b[i+1]==10 || b[i+1]==13)){//skip the next CR or LR lineBreak++; i++; } len-=lineBreak-off+1;//because we don't want the char @ lineBreak off=lineBreak+1;//because we don't want the char @ lineBreak //printB(b,off,len); } } if(len>0){ if(index+len>buffered.length){ byte newBuffered[] = new byte[buffered.length*2]; System.arraycopy(buffered,0,newBuffered,0,index); buffered = newBuffered; } System.arraycopy(b,off,buffered,index,len); index+=len; } } public int find(byte[] array,byte[] content,int start,int length){ if(array == null || content == null || array.length < content.length){ return -1; } if(start >=array.length || length == 0 || length+start > array.length){ return -1; } int matched = 0; for(int a=start; a<=start+length-content.length; a++){ matched = 0; for(int c=0; c<content.length; c++){ if( array[a+c] != content[c] ){ break; } else { matched ++; } } if( matched == content.length){ return a; } } return -1; } private void emit(byte content[], int start,int length){ int lim = start+length; //trips out ANSI escape sequences (such as terminal coloring) String toEmit = new String(content,start,length).replaceAll("\u001B\\[[;\\d]*m", ""); if(!consumers.isEmpty()){ for(Consumer<String> consumer : consumers){ consumer.accept(toEmit); } } reset(); } public int getBufferLength() { return buffered.length; } public int getIndex() { return index; } }
[ "willr3@gmail.com" ]
willr3@gmail.com
417a5dd8b61a10987fc097b5c46d7b6be401e1d4
6432dd571421c6148a49adecd754df52e09aff5a
/rest-tests/src/test/java/rest/Issue.java
fb818c075d2749da1e5f50b48b17193e7caa77d4
[ "Apache-2.0" ]
permissive
iganusevich/java_study
bb71e58f9ea541022577a0f3c43ad1c5aae2ac87
f2ab42d99686b8a1e93eea8b97182cd1a5c52e5f
refs/heads/master
2021-04-06T11:45:13.307626
2018-12-19T15:39:15
2018-12-19T15:39:15
125,375,906
0
0
null
null
null
null
UTF-8
Java
false
false
621
java
package rest; public class Issue { private int id; private String subject; private String description; public int getId() { return id; } public Issue withId(int id) { this.id = id; return this; } public String getSubject() { return subject; } public Issue withSubject(String subject) { this.subject = subject; return this; } public String getDescription() { return description; } public Issue withDescription(String description) { this.description = description; return this; } }
[ "irene.ganusevich@gmail.com" ]
irene.ganusevich@gmail.com
1fa5c9793a5b0e0c003ae708711ef70526c81221
2b69d7124ce03cb40c3ee284aa0d3ce0d1814575
/p2p-paychannel/paychannel-web/src/test/java/com/zb/p2p/paychannel/RedisTest.java
c0031572fc73900958110cc990c0daae5c821b90
[]
no_license
hhhcommon/fincore_p2p
6bb7a4c44ebd8ff12a4c1f7ca2cf5cc182b55b44
550e937c1f7d1c6642bda948cd2f3cc9feb7d3eb
refs/heads/master
2021-10-24T12:12:22.322007
2019-03-26T02:17:01
2019-03-26T02:17:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,054
java
package com.zb.p2p.paychannel; import com.zb.p2p.paychannel.service.impl.RedisServiceImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * Created by limingxin on 2018/3/12. */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private RedisServiceImpl redisService; @Test public void testINCR() { String loginKey = "preErr:12345"; redisService.setnx(loginKey, "1");//不存在则写入,初始值=1 redisService.increment(loginKey, 1L, 60 * 5);//每次自增+1,并返回自增后的值 } // @Test public void testINCR2() { String loginKey = "preErr:1234511"; redisService.setIfAbsent(loginKey, "1", 30);//不存在则写入,初始值=1 redisService.increment(loginKey, 1L, 60 * 5);//每次自增+1,并返回自增后的值 } }
[ "kaiyun@zillionfortune.com" ]
kaiyun@zillionfortune.com
b819ce581ca89507f004caf1d97ba548ea06e08f
b4cc7a926b84e81e9377d7c92ff10e5626213c0b
/src/main/java/com/cybertek/mapper/RoleMapper.java
fcf2ee4478a256728beb65f4f8a38833aa60750a
[]
no_license
jova01/jd-tickecting-project-security
26cf2c6bfa27964f9d65fba2d10050426cf28e7c
a419cdb1fe2175566dda35b45c8f9cb4a7ab58ba
refs/heads/main
2023-04-16T01:15:02.849068
2021-05-05T06:09:22
2021-05-05T06:09:22
332,133,458
0
0
null
null
null
null
UTF-8
Java
false
false
548
java
package com.cybertek.mapper; import com.cybertek.dto.RoleDTO; import com.cybertek.entity.Role; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RoleMapper { @Autowired private ModelMapper modelMapper; public Role convertToEntity(RoleDTO dto){ return modelMapper.map(dto, Role.class); } public RoleDTO convertToDto(Role entity){ return modelMapper.map(entity, RoleDTO.class); } }
[ "jova_94@inbox.ru" ]
jova_94@inbox.ru
e889b8b13f406fe11177be10b0d925423dbd81d4
2f678595a00f05cb9627774beb8d28ff94e21cbd
/src/RunItems.java
0ad527ec01421743ab60078c896d507e57d8363f
[]
no_license
steffen25/TextAdventure-version2
7677f290126999044a2c7569fe721531b0cdd4db
215a1cebd415300567d6c6774beccb13030e8ebb
refs/heads/master
2021-01-22T07:10:10.574419
2014-11-27T13:24:57
2014-11-27T13:24:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
567
java
import java.util.*; /* * 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. */ /** * * @author christianhasselstrom */ public class RunItems { public RunItems() { Items item1 = new Items("Item One","Key"); Items item2 = new Items("Item two", "Flash Light"); Items item3 = new Items("Item three", "Sword"); ArrayList<Items> items = new ArrayList<Items>(); } }
[ "christianhasselstrom@10.111.180.90" ]
christianhasselstrom@10.111.180.90
c9b255ed2cef4db6546f115e22937855d8d2f36a
1c08d080efbb3192f47a90665745bb6d31599542
/src/com/example/volt/MainActivity.java
c675a39007f35e653bb22eca6d7f1e0edd614add
[]
no_license
wntmddus/Volt
56f3c49bcf7fbe1b2ce33eb50633dfad198f4b96
f0db2cac863936d4c494ede769a17d7eec4835ac
refs/heads/master
2021-05-16T02:55:39.696952
2017-05-15T16:26:29
2017-05-15T16:26:29
10,865,607
0
0
null
null
null
null
UTF-8
Java
false
false
10,161
java
package com.example.volt; import android.app.Activity; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.RemoteViews; import android.widget.TextView; public class MainActivity extends Activity { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; MenuListAdapter mMenuAdapter; public static DataStore DS; String[] title; boolean on; RemoteViews remoteViews; ScreenWatchReceiver swr; DataToggleReceiver dtr; AnimationDrawable onOffAnimation; AnimationDrawable offOnAnimation; ImageView imageView1; RelativeLayout layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DS = new DataStore(this); setup(); initializeCurrentStatus(); setButtonClickListener(); callImageButton(); title = new String[] { " Wait X minutes before turning off data", "Turn on data every X minutes", "Turn on data for X seconds"}; mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mMenuAdapter = new MenuListAdapter(this, title); mDrawerList.setAdapter(mMenuAdapter); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.setting, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { super.onDrawerClosed(view); } public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); getActionBar().setDisplayShowHomeEnabled(true); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void setup() { //Register ScreenWatchReceiver IntentFilter filter_screen_on = new IntentFilter(Intent.ACTION_SCREEN_ON); filter_screen_on.addAction(Intent.ACTION_SCREEN_OFF); swr = new ScreenWatchReceiver(); registerReceiver(swr, filter_screen_on); //Register DataToggleReceiver IntentFilter dtr_filter = new IntentFilter(DataToggleReceiver.ACTION_FIRST_WAIT); dtr_filter.addAction(DataToggleReceiver.ACTION_TURN_OFF); dtr_filter.addAction(DataToggleReceiver.ACTION_TURN_ON); dtr = new DataToggleReceiver(); registerReceiver(dtr,dtr_filter); imageView1 = (ImageView)findViewById(R.id.button1); layout = (RelativeLayout) findViewById(R.id.content_frame); on = false; DS.setBatterySavingModeEnabled(on); Log.d("MainActivity","Status of on:" + on); } @SuppressWarnings("deprecation") private void togglePictures() { Drawable image0; Drawable image1; if(on) { image0 = getResources().getDrawable(R.drawable.on_1); image1 = getResources().getDrawable(R.drawable.background_on); } else { image0 = getResources().getDrawable(R.drawable.on_8); image1 = getResources().getDrawable(R.drawable.background_off); } imageView1.setBackgroundDrawable(image0); layout.setBackgroundDrawable(image1); } @SuppressWarnings("deprecation") private void initializeCurrentStatus() { Drawable image0; Drawable image1; if(DS.getBatterySavingModeEnabled() == true) { image0 = getResources().getDrawable(R.drawable.on_1); image1 = getResources().getDrawable(R.drawable.background_on); } else { image0 = getResources().getDrawable(R.drawable.on_8); image1 = getResources().getDrawable(R.drawable.background_off); } imageView1.setBackgroundDrawable(image0); layout.setBackgroundDrawable(image1); } private void setButtonClickListener() { final ImageButton threeGonOff = (ImageButton)findViewById(R.id.button1); threeGonOff.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { on = DS.getBatterySavingModeEnabled(); if(on == false) { on = true; // change boolean on to true DS.setBatterySavingModeEnabled(on); // on value saved as true Intent intent = new Intent(MainActivity.this, AppWatcherService.class); startService(intent); AppWatcherService.isSwitchOff = false; //turns on the switch Log.d("MainActivity", "firstClick when on == false"); } else if(on == true) { on = false; // when true is received from on, on is switched to false Log.d("MainActivity", "secondClick when on == true"); // turns off broadcast receiver DS.setBatterySavingModeEnabled(on); // on value saved as false by saving false // in the memory AppWatcherService.list_val.clear(); AppWatcherService.isSwitchOff = true; //turns off the switch } togglePictures(); // toggle turn off and turn on picture } }); } private void callImageButton() { TextView explanation = (TextView) findViewById(R.id.gototutorial); explanation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startNewActivity(); } }); } private void startNewActivity() { Intent intent = new Intent(this, Explain.class); this.startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: if(mDrawerLayout.isDrawerOpen(mDrawerList)) { mDrawerLayout.closeDrawer(mDrawerList); } else { mDrawerLayout.openDrawer(mDrawerList); } } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override protected void onRestart() { super.onRestart(); initializeCurrentStatus(); } protected void onResume(Bundle savedInstanceState) { super.onResume(); initializeCurrentStatus(); } protected void onDestroy() { super.onDestroy(); AppWatcherService.list_val.clear(); AppWatcherService.isSwitchOff = true; //turns off the switch DS.setBatterySavingModeEnabled(false); unregisterReceiver(swr); unregisterReceiver(dtr); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); } }
[ "wntmddussla@hotmail.com" ]
wntmddussla@hotmail.com
a6f51076810c245c1fe2c5f0a7acf03f558c12cf
0d00368765f24624bbc8eb440d22762752d299c5
/src/main/java/cr/ac/ucr/proyectoiaplicada/config/Config.java
571012cc13a79973c00a8a0c0aff587f9c1efd31
[]
no_license
jose-coto/Spring-Proyecto-I-Aplicada
ff05a1915725b72e1a88bca790654ae4f12967b4
73bc2d729e031e6ce055b7409e2938ab984e8065
refs/heads/master
2021-01-15T17:29:09.463620
2017-08-29T21:15:24
2017-08-29T21:15:24
99,756,961
0
0
null
null
null
null
UTF-8
Java
false
false
1,684
java
package cr.ac.ucr.proyectoiaplicada.config; import java.util.Locale; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; @Configuration @ComponentScan(basePackages = "cr.ac.ucr.proyectoiaplicada.config") public class Config extends WebMvcConfigurerAdapter { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.ROOT); return slr; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); lci.setParamName("lang"); return lci; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } /* @Bean(name = "multipartResolver") public CommonsMultipartResolver getCommonsMultipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(20971520); multipartResolver.setMaxInMemorySize(1048576); return multipartResolver; } */ }
[ "gerrall@hotmail.com" ]
gerrall@hotmail.com
bea40cb773d52e7bfc5deaa04292f9bcd01056b8
b63c06363617cb207c32b2ab7f3f7897d29b58fa
/app/src/main/java/com/example/yourecipe/MainActivity.java
c2c8e87e93b2bda097c8106b204f3899fe769d4b
[]
no_license
ahomtsov/YouRecipe
5fed97e26b5ef2c7025826f8b7f90a5ca815a6d1
0dc2dd90f207b4a294d1eedc5e4938302a2d0a89
refs/heads/master
2022-09-17T16:52:47.352780
2020-05-28T18:05:03
2020-05-28T18:05:03
267,539,128
0
0
null
null
null
null
UTF-8
Java
false
false
5,091
java
package com.example.yourecipe; import android.annotation.SuppressLint; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.provider.Settings; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.view.View.OnClickListener; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; public class MainActivity extends AppCompatActivity { public int keyOfButton; int radioButtonSelect = 1; @SuppressLint("SourceLockedOrientationActivity") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BottomNavigationView navView = findViewById(R.id.nav_view); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder( R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration); NavigationUI.setupWithNavController(navView, navController); } public void createRecyclerView(View view) { Intent intent = new Intent(this, DisplayRecyclerView.class); startActivity(intent); } public void createFirstCourseCategory(View view) { Intent intent = new Intent(this, DisplayRecipeCategory.class); keyOfButton = 1; intent.putExtra("keyOfButton", keyOfButton); saveSelectedCategory(keyOfButton); startActivity(intent); } public void createSecondCourseCategory(View view) { Intent intent = new Intent(this, DisplayRecipeCategory.class); keyOfButton = 2; intent.putExtra("keyOfButton", keyOfButton); saveSelectedCategory(keyOfButton); startActivity(intent); } public void createSaladCategory(View view) { Intent intent = new Intent(this, DisplayRecipeCategory.class); keyOfButton = 3; intent.putExtra("keyOfButton", keyOfButton); saveSelectedCategory(keyOfButton); startActivity(intent); } public void createDessertCategory(View view) { Intent intent = new Intent(this, DisplayRecipeCategory.class); keyOfButton = 4; intent.putExtra("keyOfButton", keyOfButton); saveSelectedCategory(keyOfButton); startActivity(intent); } public void createFiltered(View view) { Intent intent = new Intent(this, DisplayRecipeFiltered.class); EditText editCalFrom = (EditText)findViewById(R.id.editTextCaloriesFrom); EditText editCalTo = (EditText)findViewById(R.id.editTextCaloriesTo); String caloriesFrom = editCalFrom.getText().toString(); String caloriesTo = editCalTo.getText().toString(); //System.out.println("Calories" + caloriesFrom+" "+caloriesTo); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroupRecipeCategory); int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId(); RadioButton radioButton = (RadioButton) findViewById(checkedRadioButtonId); String rbText = radioButton.getText().toString(); System.out.println("RadioGroup: " + radioGroup); if (rbText.equals("Первые блюда")) radioButtonSelect = 1; if (rbText.equals("Вторые блюда")) radioButtonSelect = 2; if (rbText.equals("Салаты")) radioButtonSelect = 3; if (rbText.equals("Десерты")) radioButtonSelect = 4; System.out.println(checkedRadioButtonId); //2131230955 4 //2131230956 1 //2131230957 3 //2131230958 2 intent.putExtra("caloriesFrom", caloriesFrom); intent.putExtra("caloriesTo", caloriesTo); intent.putExtra("radioButtonSelect", radioButtonSelect); startActivity(intent); } private void saveSelectedCategory(int category) { String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); dbRef.child("selected").child(androidId).child("category").setValue(category); } }
[ "dandyforwork@gmail.com" ]
dandyforwork@gmail.com
312cd122aea72f1dd622d816c69a34e0a50e2efa
801142591a143f5402bee85f93a2b0208a68b585
/src/dbpackage/DatabaseQuery.java
2b93a5453ff2b5748859823f9d570151c9277060
[]
no_license
KyumKyum/MusicStreamingService
4306c807c747569b1ce322285f684e9bf46dbc1c
0fe62e749e44d17e8c75aaccf788f6b969ec8047
refs/heads/master
2023-01-22T00:54:39.834881
2020-12-06T15:45:41
2020-12-06T15:45:41
315,665,718
0
0
null
null
null
null
UTF-8
Java
false
false
5,610
java
package dbpackage; import java.sql.*; import java.util.ArrayList; public class DatabaseQuery { //FIND public static ResultSet findUser (Connection con, String ssn) { ResultSet rs = null; try{ String query = String.format("SELECT * FROM %s WHERE SSN = %s",DatabaseHandler.USER,"'"+ssn+"'"); Statement stmt = con.prepareStatement(query); rs = stmt.executeQuery(query); stmt.close(); //rs.close(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public static ResultSet findAccount (Connection con, String colNames, String ssn) {//User ResultSet rs = null; try{ String query = String.format("SELECT %s FROM %s WHERE Ussn = %s",colNames,DatabaseHandler.ACCOUNT,"'"+ssn+"'"); Statement stmt = con.prepareStatement(query); rs = stmt.executeQuery(query); stmt.close(); //rs.close(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public static ResultSet findAccount (Connection con, String colNames, String ID, String PW, String SerialNum) {//Admin ResultSet rs = null; try{ String query = String.format("SELECT %s FROM %s WHERE AID = %s AND APW = %s AND SerialNum = %s",colNames,DatabaseHandler.ADMIN,ID,PW,SerialNum); Statement stmt = con.prepareStatement(query); rs = stmt.executeQuery(query); stmt.close(); //rs.close(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public static ResultSet findProfile (Connection con, String ID){ ResultSet rs = null; try{ ID = "'"+ID+"'"; String query = String.format("SELECT * from %s where ID = %s",DatabaseHandler.PROFILE,ID); Statement stmt = con.prepareStatement(query); rs = stmt.executeQuery(query); stmt.close(); }catch (SQLException e){ e.printStackTrace(); } return rs; } //Check public static ResultSet checkAccount(Connection con,String colNames, String id){ //boolean returnVal = false; ResultSet rs = null; try{ String query = String.format("SELECT %s FROM %s WHERE ID = %s",colNames,DatabaseHandler.ACCOUNT,"'"+id+"'"); Statement stmt = con.createStatement(); rs = stmt.executeQuery(query); //returnVal = !(rs.next()); //If the id exist, returns false stmt.close(); //rs.close(); }catch (SQLException e){ e.printStackTrace(); } return rs; } public static ResultSet checkAccount(Connection con,String colNames, String id, String password){ //boolean returnVal = false; ResultSet rs = null; try{ String query = String.format("SELECT %s FROM %s WHERE ID = %s AND PW = %s",colNames,DatabaseHandler.ACCOUNT,"'"+id+"'","'"+password+"'"); Statement stmt = con.createStatement(); rs = stmt.executeQuery(query); //returnVal = !(rs.next()); //If the id exist, returns false stmt.close(); //rs.close(); }catch (SQLException e){ e.printStackTrace(); } return rs; } //Insert public static void insertNewUser(Connection con, ArrayList<String> userInfo){ try{ String query = String.format("INSERT INTO %s VALUES (?,?,?,?)",DatabaseHandler.USER); PreparedStatement pstmt = con.prepareStatement(query); for (int i = 1; i <= 4; i++){ if(i != 3) pstmt.setString(i,userInfo.get(i-1)); else //Age is integer information pstmt.setInt(i,Integer.parseInt(userInfo.get(i-1))); } pstmt.execute(); pstmt.close(); }catch (SQLException e){ e.printStackTrace(); } } public static void insertNewAccount(Connection con, ArrayList<String> accountInfo, String ssn){ try{ String query = String.format("INSERT INTO %s(ID,PW,Nickname,Ussn) VALUES (?,?,?,?)",DatabaseHandler.ACCOUNT); PreparedStatement pstmt = con.prepareStatement(query); for(int i = 1; i <= 3; i++){ pstmt.setString(i,accountInfo.get(i-1)); } pstmt.setString(4,ssn); pstmt.execute(); pstmt.close(); }catch (SQLException e){ e.printStackTrace(); }finally { System.out.println("Success! New Account Generated! :)"); } } //Update public static void updateProfile(Connection con, String from, String target, String info, String ssn){ try{ String query = String.format("UPDATE %s SET %s = %s WHERE %s",from,target,info,ssn); Statement stmt = con.createStatement(); stmt.execute(query); stmt.close(); }catch (SQLException e){ e.printStackTrace(); } } public static void updateProfile(Connection con, String from, String target, int info, String ssn){ try{ String query = String.format("UPDATE %s SET %s = %d WHERE %s",from,target,info,ssn); Statement stmt = con.createStatement(); stmt.execute(query); stmt.close(); }catch (SQLException e){ e.printStackTrace(); } } }
[ "myugyin@hanyang.ac.kr" ]
myugyin@hanyang.ac.kr
c16cb1a025b294f54340745ab67d8a95af1de4c3
81758957530b7e7e7be87ef4a3e48583ffa414ef
/src/com/example/hellojni/HelloJniTest.java
44107c5d49fe66af14092f044ba9e1ef981f761e
[]
no_license
voichitabenea/HelloJni
0a9a7c51a5244c754f08718b9697950a2c8875aa
64d2148816d4a35c4899d430fb7a0be12f783b6c
refs/heads/master
2016-09-05T20:56:36.452939
2014-04-11T11:43:26
2014-04-11T11:43:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
729
java
package com.example.hellojni; import android.test.ActivityInstrumentationTestCase; /** * This is a simple framework for a test of an Application. See * {@link android.test.ApplicationTestCase ApplicationTestCase} for more information on * how to write and extend Application tests. * <p/> * To run this test, you can type: * adb shell am instrument -w \ * -e class com.example.HelloJni.HelloJniTest \ * com.example.HelloJni.tests/android.test.InstrumentationTestRunner * Testing 1,2,3... * This is master!!! */ @SuppressWarnings("deprecation") public class HelloJniTest extends ActivityInstrumentationTestCase<HelloJni> { public HelloJniTest() { super("com.example.HelloJni", HelloJni.class); } }
[ "voichitapopescu@gmail.com" ]
voichitapopescu@gmail.com
f72ecaf74e13d60271473e87e8d363decd078c24
aded997186871db68ebdbf9e1914abec1b8768c6
/src/main/java/com/state/Statemachine/persistance/CoffeeMachinePersister.java
2c7266bacaf1b11a3959ad3a6ca4cbe8dda6ec2d
[]
no_license
DaNkOLULzz/coffee-state-machine
cccfe0752ea2b5347dde5fd72f72bc5decdbe0d5
3b74dbdd05828c8a4eeee1d53b8671a7c6bee2e0
refs/heads/master
2023-07-14T16:46:12.306067
2021-08-25T13:52:39
2021-08-25T13:52:39
395,617,776
0
0
null
null
null
null
UTF-8
Java
false
false
877
java
package com.state.Statemachine.persistance; import com.state.Statemachine.enums.CoffeeMachineEvent; import com.state.Statemachine.enums.CoffeeMachineState; import org.springframework.statemachine.StateMachineContext; import org.springframework.statemachine.StateMachinePersist; import java.util.HashMap; public class CoffeeMachinePersister implements StateMachinePersist<CoffeeMachineState, CoffeeMachineEvent, String> { private final HashMap<String, StateMachineContext<CoffeeMachineState, CoffeeMachineEvent>> database = new HashMap<>(); @Override public void write(StateMachineContext<CoffeeMachineState, CoffeeMachineEvent> stateMachineContext, String id) { database.put(id, stateMachineContext); } @Override public StateMachineContext<CoffeeMachineState, CoffeeMachineEvent> read(String id) { return database.get(id); } }
[ "danylo.lototskyi@ext.mercedes-benz.io" ]
danylo.lototskyi@ext.mercedes-benz.io
0e92bfbc4d24c1ffd37c85cfaf5b04cff5f05f1d
f01792925dfee359eae4c1d10f0d3518f06dc46e
/app/src/main/java/com/example/dell/locationtracker/LOCATION_WithAsyncTask.java
b1b6ef9c6d4d09e6c3a636e749fab91ec74d941d
[]
no_license
royrivnam/LocationTracker
43fa88b9a36c5b3eaf6f8cc88dd419711b07da7f
38a53ddcfa2287e14dd23e0efc9729e96367a164
refs/heads/master
2020-12-30T18:02:28.619845
2017-05-11T07:39:33
2017-05-11T07:39:33
90,942,629
0
0
null
null
null
null
UTF-8
Java
false
false
6,528
java
package com.example.dell.locationtracker; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.Calendar; import java.util.List; import java.util.Locale; /** * Created by DELL on 13-Mar-17. */ public class LOCATION_WithAsyncTask extends Fragment implements View.OnClickListener,RadioGroup.OnCheckedChangeListener { EditText e,ee,a; Button b,bb; ProgressBar p; RadioGroup RR; RadioButton RR1,RR2; TextView t; public static final int USE_ADDRESS_NAME=1; public static final int USE_ADDRESS_LOCATION=2; int fetchType=USE_ADDRESS_LOCATION; private static final String TAG="MAIN_ACTIVITY_ASYNC"; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //returning our layout file //change R.layout.yourlayoutfilename for each of your fragments View view= inflater.inflate(R.layout.ltmain, container, false); e=(EditText)view.findViewById(R.id.e1); ee=(EditText)view.findViewById(R.id.e2); a=(EditText)view.findViewById(R.id.e3); b=(Button)view.findViewById(R.id.b1); bb=(Button)view.findViewById(R.id.b3); p=(ProgressBar)view.findViewById(R.id.p1); RR=(RadioGroup)view.findViewById(R.id.radioGroup); RR1=(RadioButton)view.findViewById(R.id.r1); RR2=(RadioButton)view.findViewById(R.id.r2); t=(TextView)view.findViewById(R.id.t1); b.setOnClickListener(this); bb.setOnClickListener(this); RR.setOnCheckedChangeListener(this); return view; } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch(checkedId) { case R.id.r1: e.setText(""); ee.setText(""); a.setText(""); t.setText(""); fetchType = Constants.USE_ADDRESS_LOCATION; e.setEnabled(true); e.requestFocus(); ee.setEnabled(true); a.setEnabled(false); break; case R.id.r2: e.setText(""); ee.setText(""); a.setText(""); t.setText(""); fetchType = Constants.USE_ADDRESS_NAME; e.setEnabled(false); ee.setEnabled(false); a.setEnabled(true); a.requestFocus(); break; default: break; } } public void onClick(View view) { switch(view.getId()) { case R.id.b1: { new GeocodeAsyncTask().execute(); } break; case R.id.b3: { new GeocodeAsyncTask().execute(); } break; default: break; } } class GeocodeAsyncTask extends AsyncTask<Void, Void, Address> { String errorMessage=""; @Override protected void onPreExecute() { p.setVisibility(View.VISIBLE); } @Override protected Address doInBackground(Void ... none) { Geocoder geocoder = new Geocoder(LOCATION_WithAsyncTask.this.getActivity(), Locale.getDefault()); List<Address> addresses = null; if (fetchType == USE_ADDRESS_NAME) { String name = a.getText().toString(); try { addresses = geocoder.getFromLocationName(name, 1); } catch (IOException e) { errorMessage = "Service not available"; Log.e(TAG, errorMessage, e); } } else if (fetchType == USE_ADDRESS_LOCATION) { double latitude = Double.parseDouble(e.getText().toString()); double longitude = Double.parseDouble(ee.getText().toString()); try { addresses = geocoder.getFromLocation(latitude, longitude, 1); } catch (IOException ioException) { errorMessage = "Service not available"; Log.e(TAG, errorMessage, ioException); } catch (IllegalArgumentException illegalArgumentException) { errorMessage = "Invalid Latitude or Longitude Used"; Log.e(TAG, errorMessage + "." + "Latitude=" + latitude + ",Longitude =" + longitude, illegalArgumentException); } } else { errorMessage = "Unknown Type"; Log.e(TAG, errorMessage); } if (addresses != null && addresses.size() > 0) { return addresses.get(0); } return null; } protected void onPostExecute(Address address) { if(address==null) { p.setVisibility((View.INVISIBLE)); a.setText(errorMessage); } else { String addressName=""; for(int i=0;i<address.getMaxAddressLineIndex();i++) { addressName+="---"+address.getAddressLine(i); } p.setVisibility((View.INVISIBLE)); e.setText("Latitude: "+address.getLatitude()); ee.setText("Longitude: "+address.getLongitude()); a.setText("Address: "+addressName); } } } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //you can set the title for your toolbar here for different fragments different titles getActivity().setTitle("LOCATION_WithAsyncTask"); } }
[ "royray2012@gmail.com" ]
royray2012@gmail.com
078857b5b5d3cb22700b803bd1939ffdb5657688
6b4ccbdb7e0ef5816893f5acc97910a69448cead
/VyntraDemo/src/main/java/com/vyntrademo/dao/AdminRepo.java
85521a6b2af69d40d954efe6683a78f0996f8cc1
[]
no_license
BharathidasanD/Vyntra-back-end
5df79a3a6493539a5f6e9069d43df8446a73720c
5e10c054f14cc776ac8051cb2b324098fb50098c
refs/heads/master
2022-11-17T06:45:29.808155
2020-07-09T08:26:11
2020-07-09T08:26:11
278,010,028
0
0
null
null
null
null
UTF-8
Java
false
false
125
java
package com.vyntrademo.dao; import com.vyntrademo.model.Admin; public interface AdminRepo extends UserBaseRepo<Admin> { }
[ "bharathidasan.d1999@gmail.com" ]
bharathidasan.d1999@gmail.com
3fc2b3b273bea0d63749fe691294e584d7b5d917
e91bf22a3021b8e057e4317b8b7ced87f207a3a4
/SpringCoreDemo/src/Basics/StudentMain.java
553e9f485595bf5c3d28a78ae6207c0a625a00b7
[]
no_license
mohitsalunke/AdvanceJava_Basic
53a0df3e3a091e9320341a40ceb3c32342494c2d
37f92d7e593ce240f99250bd0a4e96ff6cd1f639
refs/heads/master
2023-05-10T03:24:59.358107
2021-06-08T04:15:45
2021-06-08T04:15:45
374,876,236
0
0
null
null
null
null
UTF-8
Java
false
false
428
java
package Basics; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class StudentMain { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ctx=new ClassPathXmlApplicationContext("Springbasic.xml"); Student obj=(Student) ctx.getBean("S3"); System.out.println(obj); } }
[ "mohit@LAPTOP-6JJBRT46" ]
mohit@LAPTOP-6JJBRT46
9cfc60b3e6c84e8fb814d7a0dd3c0a90231437b6
d384e551f3217df3fc238edcdcdb55c8825c36d0
/app/src/main/java/com/huanglong/v3/BaseFragment.java
fe4069364d8753f27cbf009b1cee1b75a4334929
[]
no_license
KqSMea8/V3
b25f5e04b6f54edb5ae7b29167e98a751beea724
ab223a67080be076d8a66279c994b07cfd07645b
refs/heads/master
2020-04-07T11:40:32.504003
2018-11-20T05:24:40
2018-11-20T05:24:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,683
java
package com.huanglong.v3; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.huanglong.v3.view.LoadingDialog; import org.xutils.x; /** * Created by hbb on 2017/6/28. * baseFragment */ public abstract class BaseFragment extends Fragment { private View mParentView; private LoadingDialog loadingDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (mParentView == null) { mParentView = getContentView(inflater, container, savedInstanceState); x.view().inject(this, mParentView); initView(); } // else { // ((ViewGroup) mParentView.getParent()).removeView(mParentView); // } return mParentView; } protected abstract View getContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState); @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); logic(); } protected abstract void initView(); protected abstract void logic(); /** * 显示press */ protected void showDialog() { if (loadingDialog != null) { loadingDialog.showDialog(); } } /** * 隐藏press */ protected void dismissDialog() { if (loadingDialog != null) { loadingDialog.dismissDialog(); } } }
[ "1191200738@qq.com" ]
1191200738@qq.com
3687d87f48852d6ee101bf52a56e58e44c978e83
8b9022dda67a555c3fd70e652fa9159e5b517602
/src/main/java/org/drip/sample/simmcrnq/CreditNonQualifyingVegaMargin21.java
5bafad138be391b2e7ee16310328bfb0ed1d071f
[ "Apache-2.0" ]
permissive
BugHunterPhilosopher/DROP
19b77d184fea32366c4892d7d2ca872a16b10c1c
166c1fc6276045aad97ffacf4226caccfa23ce10
refs/heads/master
2022-07-05T22:13:09.331395
2020-05-04T03:41:08
2020-05-04T03:41:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,577
java
package org.drip.sample.simmcrnq; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.drip.analytics.support.CaseInsensitiveHashMap; import org.drip.numerical.common.FormatUtil; import org.drip.service.env.EnvManager; import org.drip.simm.foundation.MarginEstimationSettings; import org.drip.simm.margin.RiskMeasureAggregateCR; import org.drip.simm.margin.SensitivityAggregateCR; import org.drip.simm.parameters.RiskMeasureSensitivitySettingsCR; import org.drip.simm.product.BucketSensitivityCR; import org.drip.simm.product.RiskFactorTenorSensitivity; import org.drip.simm.product.RiskMeasureSensitivityCR; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2020 Lakshmi Krishnamurthy * Copyright (C) 2019 Lakshmi Krishnamurthy * Copyright (C) 2018 Lakshmi Krishnamurthy * * This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics, * asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment * analytics, and portfolio construction analytics within and across fixed income, credit, commodity, * equity, FX, and structured products. It also includes auxiliary libraries for algorithm support, * numerical analysis, numerical optimization, spline builder, model validation, statistical learning, * and computational support. * * https://lakshmidrip.github.io/DROP/ * * DROP is composed of three modules: * * - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/ * - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/ * - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/ * * DROP Product Core implements libraries for the following: * - Fixed Income Analytics * - Loan Analytics * - Transaction Cost Analytics * * DROP Portfolio Core implements libraries for the following: * - Asset Allocation Analytics * - Asset Liability Management Analytics * - Capital Estimation Analytics * - Exposure Analytics * - Margin Analytics * - XVA Analytics * * DROP Computational Core implements libraries for the following: * - Algorithm Support * - Computation Support * - Function Analysis * - Model Validation * - Numerical Analysis * - Numerical Optimizer * - Spline Builder * - Statistical Learning * * Documentation for DROP is Spread Over: * * - Main => https://lakshmidrip.github.io/DROP/ * - Wiki => https://github.com/lakshmiDRIP/DROP/wiki * - GitHub => https://github.com/lakshmiDRIP/DROP * - Repo Layout Taxonomy => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md * - Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html * - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal * - Release Versions => https://lakshmidrip.github.io/DROP/version.html * - Community Credits => https://lakshmidrip.github.io/DROP/credits.html * - Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues * - JUnit => https://lakshmidrip.github.io/DROP/junit/index.html * - Jacoco => https://lakshmidrip.github.io/DROP/jacoco/index.html * * 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. */ /** * <i>CreditNonQualifyingVegaMargin21</i> illustrates the Computation of the CR SIMM 2.1 Vega Margin for a * Bucket of Non-Qualifying Credit Exposure Sensitivities. The References are: * * <br><br> * <ul> * <li> * Andersen, L. B. G., M. Pykhtin, and A. Sokol (2017): Credit Exposure in the Presence of Initial * Margin https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2806156 <b>eSSRN</b> * </li> * <li> * Albanese, C., S. Caenazzo, and O. Frankel (2017): Regression Sensitivities for Initial Margin * Calculations https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2763488 <b>eSSRN</b> * </li> * <li> * Anfuso, F., D. Aziz, P. Giltinan, and K. Loukopoulus (2017): A Sound Modeling and Back-testing * Framework for Forecasting Initial Margin Requirements * https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2716279 <b>eSSRN</b> * </li> * <li> * Caspers, P., P. Giltinan, R. Lichters, and N. Nowaczyk (2017): Forecasting Initial Margin * Requirements - A Model Evaluation https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2911167 * <b>eSSRN</b> * </li> * <li> * International Swaps and Derivatives Association (2017): SIMM v2.0 Methodology * https://www.isda.org/a/oFiDE/isda-simm-v2.pdf * </li> * </ul> * * <br><br> * <ul> * <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/PortfolioCore.md">Portfolio Core Module</a></li> * <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/MarginAnalyticsLibrary.md">Initial and Variation Margin Analytics</a></li> * <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/README.md">DROP API Construction and Usage</a></li> * <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/sample/simmcrnq/README.md">ISDA SIMM Credit Non-Qualifying Estimates</a></li> * </ul> * <br><br> * * @author Lakshmi Krishnamurthy */ public class CreditNonQualifyingVegaMargin21 { private static final void AddTenorSensitivity ( final Map<String, Double> tenorSensitivityMap, final double notional, final String tenor) throws Exception { if (tenorSensitivityMap.containsKey (tenor)) { tenorSensitivityMap.put ( tenor, tenorSensitivityMap.get (tenor) + notional * (Math.random() - 0.5) ); } else { tenorSensitivityMap.put ( tenor, notional * (Math.random() - 0.5) ); } } private static final RiskFactorTenorSensitivity CurveTenorSensitivityMap ( final double notional) throws Exception { Map<String, Double> tenorSensitivityMap = new HashMap<String, Double>(); AddTenorSensitivity ( tenorSensitivityMap, notional, "1Y" ); AddTenorSensitivity ( tenorSensitivityMap, notional, "2Y" ); AddTenorSensitivity ( tenorSensitivityMap, notional, "3Y" ); AddTenorSensitivity ( tenorSensitivityMap, notional, "5Y" ); AddTenorSensitivity ( tenorSensitivityMap, notional, "10Y" ); return new RiskFactorTenorSensitivity (tenorSensitivityMap); } private static final void DisplayComponentTenorSensitivity ( final String componentName, final RiskFactorTenorSensitivity tenorSensitivityMap) throws Exception { System.out.println(); System.out.println ("\t|--------------||"); System.out.println ("\t| " + componentName + " VEGA ||"); System.out.println ("\t|--------------||"); System.out.println ("\t| ||"); System.out.println ("\t| L -> R: ||"); System.out.println ("\t| - Tenor ||"); System.out.println ("\t| - Delta ||"); System.out.println ("\t|--------------||"); for (Map.Entry<String, Double> tenorSensitivityEntry : tenorSensitivityMap.sensitivityMap().entrySet()) { System.out.println ( "\t| " + tenorSensitivityEntry.getKey() + " => " + FormatUtil.FormatDouble (tenorSensitivityEntry.getValue(), 2, 2, 1.) + " ||" ); } System.out.println ("\t|--------------||"); System.out.println(); } private static final void ComponentRiskFactorTenorSensitivity ( final Map<String, RiskFactorTenorSensitivity> tenorSensitivityMap, final double notional, final String componentName) throws Exception { RiskFactorTenorSensitivity ustRiskFactorSensitivity = CurveTenorSensitivityMap (notional); tenorSensitivityMap.put ( componentName, ustRiskFactorSensitivity ); DisplayComponentTenorSensitivity ( componentName, ustRiskFactorSensitivity ); } private static final void DisplayRiskMeasureAggregate ( final RiskMeasureAggregateCR riskMeasureAggregateCR) throws Exception { System.out.println ("\t||--------------------------------------------||"); System.out.println ("\t|| CR RISK CLASS AGGREGATE MARGIN METRICS ||"); System.out.println ("\t||--------------------------------------------||"); System.out.println ( "\t|| Core Vega SBA Variance => " + FormatUtil.FormatDouble (riskMeasureAggregateCR.coreSBAVariance(), 10, 0, 1.) + " ||" ); System.out.println ( "\t|| Residual Vega SBA Variance => " + FormatUtil.FormatDouble (riskMeasureAggregateCR.residualSBAVariance(), 10, 0, 1.) + " ||" ); System.out.println ( "\t|| Vega SBA => " + FormatUtil.FormatDouble (riskMeasureAggregateCR.sba(), 10, 0, 1.) + " ||" ); System.out.println ("\t||--------------------------------------------||"); System.out.println(); } private static final void VegaMarginCovarianceEntry ( final int bucketIndex, final SensitivityAggregateCR crVegaAggregate) throws Exception { System.out.println ("\t||-------------------------------------||"); System.out.println ( "\t|| " + FormatUtil.FormatDouble (bucketIndex, 2, 0, 1.) + " RISK FACTOR MARGIN COVARIANCE ||" ); System.out.println ("\t||-------------------------------------||"); System.out.println ("\t|| ||"); System.out.println ("\t|| - L -> R: ||"); System.out.println ("\t|| - Component Pair ||"); System.out.println ("\t|| - Covariance ||"); System.out.println ("\t||-------------------------------------||"); Map<String, Double> componentMarginCovarianceMap = crVegaAggregate.componentMarginCovarianceMap(); Set<String> componentPairSet = componentMarginCovarianceMap.keySet(); for (String componentPair : componentPairSet) { System.out.println ( "\t|| " + componentPair + " => " + FormatUtil.FormatDouble (componentMarginCovarianceMap.get (componentPair), 9, 0, 1.) + " ||" ); } System.out.println ("\t||-------------------------------------||"); System.out.println(); } public static final void main ( final String[] argumentArray) throws Exception { EnvManager.InitEnv (""); double notional = 100.; int[] bucketIndexArray = { 1, 2, }; String[][] bucketComponentGrid = { {"01a", "01b", "01c", "01d", "01e", "01f"}, {"02a", "02b", "02c", "02d", "02e", "02f"}, }; Map<String, BucketSensitivityCR> bucketSensitivityMap = new HashMap<String, BucketSensitivityCR>(); for (int bucketIndex : bucketIndexArray) { Map<String, RiskFactorTenorSensitivity> tenorSensitivityMap = new CaseInsensitiveHashMap<RiskFactorTenorSensitivity>(); for (String componentName : bucketComponentGrid[bucketIndex - 1]) { ComponentRiskFactorTenorSensitivity ( tenorSensitivityMap, notional, componentName ); } bucketSensitivityMap.put ( "" + bucketIndex, new BucketSensitivityCR (tenorSensitivityMap) ); } RiskMeasureSensitivityCR riskClassSensitivity = new RiskMeasureSensitivityCR (bucketSensitivityMap); MarginEstimationSettings marginEstimationSettings = MarginEstimationSettings.CornishFischer (MarginEstimationSettings.POSITION_PRINCIPAL_COMPONENT_COVARIANCE_ESTIMATOR_ISDA); RiskMeasureSensitivitySettingsCR riskMeasureSensitivitySettings = RiskMeasureSensitivitySettingsCR.ISDA_CRNQ_VEGA_21(); RiskMeasureAggregateCR riskMeasureAggregate = riskClassSensitivity.linearAggregate ( riskMeasureSensitivitySettings, marginEstimationSettings ); for (int bucketIndex : bucketIndexArray) { VegaMarginCovarianceEntry ( bucketIndex, riskMeasureAggregate.bucketAggregateMap().get ("" + bucketIndex).sensitivityAggregate() ); } DisplayRiskMeasureAggregate (riskMeasureAggregate); EnvManager.TerminateEnv(); } }
[ "lakshmimv7977@gmail.com" ]
lakshmimv7977@gmail.com
6ee2fd763f6f55e733851414cba989ca4d578e56
51ef61cbf16edc471a6fa276d3e797ca899dcc2f
/osgi-portal-core/src/main/java/fr/mby/portal/core/security/ILoginManager.java
0908eaac1244201bd92305cb77814fa73a17ceb7
[]
no_license
mxbossard/osgi-portal
013c5ae77d0fe8a854aacd7b0775bdc4e4dc9fc1
4123b6b0cb96d3a2f72abc999b75c3978de858f2
refs/heads/master
2021-01-10T06:54:12.859481
2013-12-03T20:03:57
2013-12-03T20:03:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,244
java
/** * Copyright 2013 Maxime Bossard * * 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 fr.mby.portal.core.security; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import fr.mby.portal.core.auth.IAuthentication; /** * @author Maxime Bossard - 2013 * */ public interface ILoginManager { /** * Perform a login to the Portal. * * @param request * the request which is the origin of the login. * @param response * the response returned on login action. * @param authentication * the IAuthentication object wich must already be authenticated. * @return the IAuthentication wich allowed the login to be performed. * @throws LoginException * when somethig goes wrong. */ IAuthentication login(HttpServletRequest request, HttpServletResponse response, IAuthentication authentication) throws LoginException; /** * Test if the Http request was sent by a logged user. * * @param request * Http request * @return true if the user is logged. */ boolean isLogged(HttpServletRequest request); /** * Retrieve the IAuthentication build when user authenticated. * * @param request * Http request * @return the logged auth objet or null */ IAuthentication getLoggedAuthentication(HttpServletRequest request); /** * Perform a logout from the Portal. * * @param request * the Http request origin of the logout. * @param response * the response returned on logout action. */ void logout(HttpServletRequest request, HttpServletResponse response); }
[ "mxbossard@gmail.com" ]
mxbossard@gmail.com
f147d540d459ab3a826f1139eab2f80ed6929a81
865f5193a3e097bd51be93984fd2a0c643f6f1e7
/src/main/java/com/green/manegerbean/DespesaDebitoBean.java
4f2fd8065b42c1ac466d4db6acd2e50414e473b0
[]
no_license
leandrorafael10/sistema
c74d301f879e455cb7bbdddf02c43de00e07cbd9
cfdaea3c98ef81a22b62dafb085413b45948ad45
refs/heads/master
2016-09-06T02:50:03.595665
2014-12-09T16:01:23
2014-12-09T16:22:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,563
java
package com.green.manegerbean; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import com.green.modelo.Debito; import com.green.modelo.Despesa; import com.green.modelo.Despesadebito; import com.green.rn.DespesaDebitoRN; @ManagedBean(name = "despesaDebitoBean") @ViewScoped public class DespesaDebitoBean implements Serializable { /** * */ private static final long serialVersionUID = 1L; @ManagedProperty("#{despesaDebitoRN}") private DespesaDebitoRN despesaDebitoRN; private Despesadebito despesadebito; private List<Despesadebito> despesadebitos; private Date dTInicio; private Date dTFim; @PostConstruct private void init() { this.despesadebito = new Despesadebito(); this.despesadebito.setIDDespesa(new Despesa()); this.despesadebito.setIDDebito(new Debito()); } public void listarPeriodo(ActionEvent event) { setDespesadebitos(getDespesaDebitoRN().listaPeriodo(getdTInicio(), getdTFim())); } public void estornarDebito(ActionEvent event){ getDespesaDebitoRN().estornarDebito(getDespesadebito()); setDespesadebitos(getDespesaDebitoRN().listaPeriodo(getdTInicio(), getdTFim())); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Estornado com sucesso!","Estornado com sucesso!")); } public void salvar(ActionEvent event) { getDespesaDebitoRN().salvar(getDespesadebito()); } public DespesaDebitoRN getDespesaDebitoRN() { return despesaDebitoRN; } public void setDespesaDebitoRN(DespesaDebitoRN despesaDebitoRN) { this.despesaDebitoRN = despesaDebitoRN; } public Despesadebito getDespesadebito() { return despesadebito; } public void setDespesadebito(Despesadebito despesadebito) { this.despesadebito = despesadebito; } public Date getdTInicio() { return dTInicio; } public void setdTInicio(Date dTInicio) { this.dTInicio = dTInicio; } public Date getdTFim() { return dTFim; } public void setdTFim(Date dTFim) { this.dTFim = dTFim; } public List<Despesadebito> getDespesadebitos() { return despesadebitos; } public void setDespesadebitos(List<Despesadebito> despesadebitos) { this.despesadebitos = despesadebitos; } }
[ "leandro.silva@PRODUCAO-01.paracatu.externa" ]
leandro.silva@PRODUCAO-01.paracatu.externa
f0b29ea4f503f3b7674243f706daa097759b93df
f949c966cb83e439eca568c097739b1d5cdac753
/siri/siri_retriever/siri-0.1/src/main/java/uk/org/siri/siri/StoppingPositionChangedDepartureStructure.java
3fe7719857ee0aebc919466cd041a1b34a66d480
[]
no_license
hasadna/open-bus
d32bd55680b72ef75022e546e2c58413ae365703
1e972a43ca5141bf42f0662d2e21196fa8ff8438
refs/heads/master
2022-12-13T11:43:43.476402
2021-06-05T13:48:36
2021-06-05T13:48:36
62,209,334
95
44
null
2022-12-09T17:13:43
2016-06-29T08:29:01
Java
UTF-8
Java
false
false
3,638
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.11.14 at 03:28:36 PM PST // package uk.org.siri.siri; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * Type for Change to a Distributor stop position. * * <p>Java class for StoppingPositionChangedDepartureStructure complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="StoppingPositionChangedDepartureStructure"> * &lt;complexContent> * &lt;extension base="{http://www.siri.org.uk/siri}AbstractDistributorItemStructure"> * &lt;sequence> * &lt;element name="ChangeNote" type="{http://www.siri.org.uk/siri}NaturalLanguagePlaceNameStructure" minOccurs="0"/> * &lt;element name="NewLocation" type="{http://www.siri.org.uk/siri}LocationStructure" minOccurs="0"/> * &lt;element ref="{http://www.siri.org.uk/siri}Extensions" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "StoppingPositionChangedDepartureStructure", propOrder = { "changeNote", "newLocation", "extensions" }) public class StoppingPositionChangedDepartureStructure extends AbstractDistributorItemStructure { @XmlElement(name = "ChangeNote") protected NaturalLanguagePlaceNameStructure changeNote; @XmlElement(name = "NewLocation") protected LocationStructure newLocation; @XmlElement(name = "Extensions") protected ExtensionsStructure extensions; /** * Gets the value of the changeNote property. * * @return * possible object is * {@link NaturalLanguagePlaceNameStructure } * */ public NaturalLanguagePlaceNameStructure getChangeNote() { return changeNote; } /** * Sets the value of the changeNote property. * * @param value * allowed object is * {@link NaturalLanguagePlaceNameStructure } * */ public void setChangeNote(NaturalLanguagePlaceNameStructure value) { this.changeNote = value; } /** * Gets the value of the newLocation property. * * @return * possible object is * {@link LocationStructure } * */ public LocationStructure getNewLocation() { return newLocation; } /** * Sets the value of the newLocation property. * * @param value * allowed object is * {@link LocationStructure } * */ public void setNewLocation(LocationStructure value) { this.newLocation = value; } /** * Gets the value of the extensions property. * * @return * possible object is * {@link ExtensionsStructure } * */ public ExtensionsStructure getExtensions() { return extensions; } /** * Sets the value of the extensions property. * * @param value * allowed object is * {@link ExtensionsStructure } * */ public void setExtensions(ExtensionsStructure value) { this.extensions = value; } }
[ "evyatar@tikalk.com" ]
evyatar@tikalk.com
e329ff662b9f6e12472f4f848824057b5d8f42a2
5b4a4868967a46148b028e9fe0eeee5fb182b3a0
/src/listPhotoURLs/ListPhotoURLs.java
1f40eefbccd72307ff613fc3727f4c194413b784
[]
no_license
islam95/Flickr
a059f9d841f3a4f888f0494067d9bfbe70e42cc6
046a1b2d45c80c098ced870bff3d8435cf324d13
refs/heads/master
2020-06-17T09:47:00.877144
2016-11-28T21:07:17
2016-11-28T21:07:17
75,013,049
0
0
null
null
null
null
UTF-8
Java
false
false
4,741
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 listPhotoURLs; import java.util.*; // For collections and properties. import java.io.*; // For file handling. import com.flickr4java.flickr.*; // For Flickr4Java classes. import com.flickr4java.flickr.photos.*; // For photos interface. import com.flickr4java.flickr.people.*; // For people interface. // *************************************************************************** /** * Class that links to the Flickr service and creates a simple web page * containing a set of photos from a given contributor. * * @author Islam Dudaev * @version 2.0, 25th October, 2014 */ // ************************************************************************* public class ListPhotoURLs { // ---------------------------- Starter method -------------------------- /** * Runs the program as an application. * * @param args Command line arguments (ignored). */ public static void main(String[] args) { new ListPhotoURLs(); } // --------------------------- Object variables ------------------------- private Flickr flickr; // Object providing link with Flickr. private ArrayList<String> photoURLs; // Stores a list of photo URLs private String contributor; // Name of photo contributor // ----------------------------- Constructor ---------------------------- /** * Sets up the Flickr connection and performs a simple query. */ public ListPhotoURLs() { if (initFlickrConnection()) { photoURLs = new ArrayList<String>(); // URLs of queried photos. doQuery(); listURLs(); } } // --------------------------- Private methods -------------------------- /** * Initialises the connection with the Flickr service by using API key and * secret stored in a local properties file. * * @return True if Flickr connection successfully established. */ private boolean initFlickrConnection() { // Extract the API key and secret from a local properties file. Properties properties = null; try { properties = new Properties(); properties.load(new FileInputStream("flickr.properties")); } catch (IOException e) { System.err.println("Problem reading flickr properties file."); return false; } // Make connection to the Flickr API. flickr = new Flickr(properties.getProperty("apiKey"), properties.getProperty("secret"), new REST()); return true; } /** * Performs a simple non-authenticated query of the Flickr service. * * @return True if query performed successfully. */ private boolean doQuery() { // Provides access to Flickr's 'photos' API calls. PhotosInterface photos = flickr.getPhotosInterface(); // Handles a collection of photos returned by a query. PhotoList<Photo> photoList = null; SearchParameters criteria = new SearchParameters(); criteria.setSort(SearchParameters.DATE_TAKEN_DESC); // Order query results by date. criteria.setUserId("7539598@N04"); // User's id whose photos to display. try { // Find details about the user. PeopleInterface people = flickr.getPeopleInterface(); User user = people.getInfo(criteria.getUserId()); contributor = user.getRealName(); if (contributor == null) { // If no real name provided, try their user name. contributor = user.getUsername(); } if (contributor == null) { // If no username provided, use their ID contributor = "User " + user.getId(); } // Extract details about the first 20 photos that match search criteria. photoList = photos.search(criteria, 20, 1); } catch (FlickrException e) { System.err.println("Problem performing flickr query: " + e); return false; } // Now we have a list of photos, extract the photo URL from each photo in turn. for (Photo photo : photoList) { // Store the URL pointing to the small version of each photo. photoURLs.add(photo.getSmallUrl()); } return true; } public void listURLs(){ for(String url : photoURLs){ System.out.println(url); } } }
[ "islamwolf23@gmail.com" ]
islamwolf23@gmail.com
f0c8d1e185046db89fe3a9a5d3dc9e5ce49dd07f
85cdb7ddd5632141d5e356b10515659e13b759c5
/tadsstore-web/src/main/java/br/senac/tads4/dswb/tadsstore/web/ListarProdutosServlet.java
a210face1edc16be188f3c4af2e5a78f8a24f792
[ "MIT" ]
permissive
ftsuda-senac/tads4-dswb-2017-2
5723e403ecc1abb4cdfe0a4cd00a6aadbd052148
b2e760a0ad955525845f15a92c273e82da5e6e10
refs/heads/master
2021-01-19T20:30:02.800572
2017-11-01T23:35:16
2017-11-01T23:35:16
101,227,889
0
0
null
null
null
null
UTF-8
Java
false
false
3,069
java
/* * The MIT License * * Copyright 2017 fernando.tsuda. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package br.senac.tads4.dswb.tadsstore.web; import br.senac.tads4.dswb.tadsstore.common.entity.Produto; import br.senac.tads4.dswb.tadsstore.common.service.ProdutoService; import br.senac.tads4.dswb.tadsstore.common.service.fakeimpl.ProdutoServiceFakeImpl; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author fernando.tsuda */ @WebServlet(name = "ListarProdutosServlet", urlPatterns = {"/listar-produtos"}) public class ListarProdutosServlet extends HttpServlet { /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProdutoService service = new ProdutoServiceFakeImpl(); List<Produto> produtos = service.listar(0, 100); request.setAttribute("produtos", produtos); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/lista.jsp"); dispatcher.forward(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
[ "ftsuda.senac@gmail.com" ]
ftsuda.senac@gmail.com
58fe3aad987cfbd761f6224423b0a6bba6087a81
ca15543a5e4d0cfd26b39a303f78de0f6035d917
/app/src/main/java/co/loystar/loystarbusiness/utils/EventBus/CustomerDetailFragmentEventBus.java
53d11790cd38a914e2df987ee36adfbbdd232b71
[]
no_license
pawnjester/loy-commerce
2534fc295b1c8d1dbaa4638a0ca30273302a95db
41d4d2c57b8df2e793ebf27ec44ed7e480cd9132
refs/heads/master
2020-12-02T09:02:13.573722
2019-12-30T17:34:51
2019-12-30T17:34:51
230,954,958
0
0
null
null
null
null
UTF-8
Java
false
false
904
java
package co.loystar.loystarbusiness.utils.EventBus; import android.os.Bundle; import io.reactivex.Observable; import io.reactivex.subjects.PublishSubject; /** * Created by ordgen on 11/28/17. */ public class CustomerDetailFragmentEventBus { public static final int ACTION_START_SALE = 103; private static CustomerDetailFragmentEventBus mInstance; public static CustomerDetailFragmentEventBus getInstance() { if (mInstance == null) { mInstance = new CustomerDetailFragmentEventBus(); } return mInstance; } private CustomerDetailFragmentEventBus() {} private PublishSubject<Bundle> fragmentEventSubject = PublishSubject.create(); public Observable<Bundle> getFragmentEventObservable() { return fragmentEventSubject; } public void postFragmentAction(Bundle data) { fragmentEventSubject.onNext(data); } }
[ "emmanuel_andela@medable.com" ]
emmanuel_andela@medable.com
788ff2cd213346e2f84deba561861407ce316a94
96b959d493ff405729abb5a63b68f83961dfe00e
/src/main/java/com/aria/service/mapper/UserMapper.java
ccaab9de899457fc2d3c1aae56932928528108fd
[]
no_license
ariayudanto/jhipster-sample
c998ac242e262a3284e09d9fe88d4a750827138d
50221907737d7858d6e1749d06f6fb9f30a7352a
refs/heads/master
2021-05-01T03:51:06.403535
2018-02-13T02:42:34
2018-02-13T02:42:34
120,562,829
0
0
null
null
null
null
UTF-8
Java
false
false
2,282
java
package com.aria.service.mapper; import com.aria.domain.Authority; import com.aria.domain.User; import com.aria.service.dto.UserDTO; import org.springframework.stereotype.Service; import java.util.*; import java.util.stream.Collectors; /** * Mapper for the entity User and its DTO called UserDTO. * * Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct * support is still in beta, and requires a manual step with an IDE. */ @Service public class UserMapper { public UserDTO userToUserDTO(User user) { return new UserDTO(user); } public List<UserDTO> usersToUserDTOs(List<User> users) { return users.stream() .filter(Objects::nonNull) .map(this::userToUserDTO) .collect(Collectors.toList()); } public User userDTOToUser(UserDTO userDTO) { if (userDTO == null) { return null; } else { User user = new User(); user.setId(userDTO.getId()); user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); user.setEmail(userDTO.getEmail()); user.setImageUrl(userDTO.getImageUrl()); user.setActivated(userDTO.isActivated()); user.setLangKey(userDTO.getLangKey()); Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities()); if (authorities != null) { user.setAuthorities(authorities); } return user; } } public List<User> userDTOsToUsers(List<UserDTO> userDTOs) { return userDTOs.stream() .filter(Objects::nonNull) .map(this::userDTOToUser) .collect(Collectors.toList()); } public User userFromId(Long id) { if (id == null) { return null; } User user = new User(); user.setId(id); return user; } public Set<Authority> authoritiesFromStrings(Set<String> strings) { return strings.stream().map(string -> { Authority auth = new Authority(); auth.setName(string); return auth; }).collect(Collectors.toSet()); } }
[ "aria.yudanto@gmail.com" ]
aria.yudanto@gmail.com
0e70bb3ab0e1067a9bacd6e170a6535fd226cb98
de03862a20612bf7d676bc3ae738828159058d28
/src/main/java/com/neathorium/framework/selenium/namespaces/EnvironmentUtilities.java
9da934c4f1db5172e789ea3bb58e762a2139934b
[ "MIT" ]
permissive
karsaii/thorium-selenium
471003f70b67b631b4469aae8130a9f3044d47d7
08e27f649c293f5bae2e21ded821c91083b497eb
refs/heads/master
2023-08-18T17:55:16.210046
2021-09-14T04:59:59
2021-09-14T04:59:59
274,799,031
0
0
null
null
null
null
UTF-8
Java
false
false
644
java
package com.neathorium.framework.selenium.namespaces; import com.neathorium.framework.selenium.constants.EnvironmentPropertyConstants; import com.neathorium.core.constants.validators.CoreFormatterConstants; import java.nio.file.Paths; public interface EnvironmentUtilities { static String getUsersProjectRootDirectory() { var rootDir = Paths.get(".").normalize().toAbsolutePath().toString(); if (!rootDir.startsWith(EnvironmentPropertyConstants.USER_DIR)) { throw new RuntimeException("Root directory not found in user directory" + CoreFormatterConstants.END_LINE); } return rootDir; } }
[ "noreply@github.com" ]
karsaii.noreply@github.com
a8343238cd757d5fd593a83e8721c6ef1f41da2c
da573e60435f9c2e06c12ee0d682cf3dc20cebad
/app/src/main/java/com/example/administrator/guessmusicgame/uitl/Util.java
c80bceb53bccfffdef0af06609d1ef30ab7c367e
[]
no_license
scYao/GuessMusicGame
196e4b222d37ea386ff00eb7fcfb4813f0c3c9de
c565009ffcd4ee292f3b542edcb786d46d9d2fc2
refs/heads/master
2021-08-07T02:32:15.169703
2017-11-07T09:43:30
2017-11-07T09:43:30
109,779,528
1
0
null
null
null
null
UTF-8
Java
false
false
441
java
package com.example.administrator.guessmusicgame.uitl; import android.content.Context; import android.view.LayoutInflater; import android.view.View; /** * Created by Administrator on 2017/9/21 0021. */ public class Util { public static View getView(Context context, int layoutId) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(layoutId, null); return view; } }
[ "2247523672@qq.com" ]
2247523672@qq.com
86af5a7968a98e237d88beb321b466a45b52d7bd
9940e6d7053cb0a051ec81d846c945dccc2942d7
/app/src/main/java/me/zhangpu/demo/print/printer/ipPrinter/components/IpOptimizationProcessor.java
e1c384c2454729c3f6665098dc2ae13e9f49c8a0
[]
no_license
zangpuu/PrintDemo
2e9b7a8955362f7c64764a84d28401ba13571b70
23af2e91396464cbe35985ca301ea460ebb47ae8
refs/heads/master
2020-08-27T17:12:22.944438
2019-11-07T13:52:52
2019-11-07T13:52:52
217,441,924
1
0
null
null
null
null
UTF-8
Java
false
false
20,633
java
package me.zhangpu.demo.print.printer.ipPrinter.components; import android.text.TextUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.List; import me.zhangpu.demo.print.printer.PrintLog; import me.zhangpu.demo.print.printer.ipPrinter.model.OptimizationTaskModel; import me.zhangpu.demo.print.printer.ipPrinter.model.ReceiptCmdModel; import me.zhangpu.demo.print.printer.ipPrinter.utils.IpPrinterConts; import me.zhangpu.demo.print.processor.ByteProcessUtil; import me.zhangpu.demo.print.processor.PrintResultCode; public class IpOptimizationProcessor { //Gsrn命令,用来监控内容是否打完 private static final byte[] GSRN_CMD = {0x1d, 0x72, 0x01}; private static final byte[] EPSON_Bill_CONTROL_CMD = {0x1d, 0x28, 0x48, 0x06, 0x00, 0x30, 0x30}; private static final String LOG_TAG = "IpPrinterConfig"; private static final byte BYTE_BILL_CONTROL_1 = 0x37; private static final byte BYTE_BILL_CONTROL_2 = 0x22; private static final byte BYTE_BILL_CONTROL_7 = 0x00; private static final int LENGTH_BYTE_BILL_CONTROL = 7; public static final byte[] REAL_TIME_DETECT = {0x10, 0x04, 0x02}; /** * 得到是否可使用优化模式结果 * 由于优化模式非常依赖打印机类型版本,所以并不作为一般设置对外开放 * * @param model * @param mode * @return */ public static String canUseOptimizationMode(int model, int mode) { String result = IpPrinterConts.RECEIPT_MODE_NO_MATCH; switch (model) { case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_EPSON_TMU220B: if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_GSRN; } break; case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_EPSON_T60_903_901: if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_GSRN; } else if (mode == IpPrinterConts.OPTIMIZATION_MODE_PACKAGE_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL; } break; case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_GPRINTER_GP_L80250II: if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_GSRN; } else if (mode == IpPrinterConts.OPTIMIZATION_MODE_PACKAGE_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL; } break; // case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_GPRINTER_GP_3150TIN: // if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { // result = IpPrinterConts.RECEIPT_MODE_GSRN; // } // break; case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_GPRINTER_GP_L80250: if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_GSRN; } else if (mode == IpPrinterConts.OPTIMIZATION_MODE_PACKAGE_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL; } break; case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_SPRINTER_SP_POS88VM: if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_GSRN; } else if (mode == IpPrinterConts.OPTIMIZATION_MODE_PACKAGE_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL; } break; case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_SPRINTER_SP_POS88VBT_POS88V: if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_GSRN; } else if (mode == IpPrinterConts.OPTIMIZATION_MODE_PACKAGE_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL; } break; case IpPrinterConts.OPTIMIZATION_MODEL_GROUP_IPRT_T801M: if (mode == IpPrinterConts.OPTIMIZATION_MODE_FLOW_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_GSRN; } else if (mode == IpPrinterConts.OPTIMIZATION_MODE_PACKAGE_CONTROL) { result = IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL; } break; default: break; } return result; } /** * 通过优化模式发送数据 * 理论上进入此方法不会进入default,因为config创建之初receiptMode已经确定 * 若没有则会按照常规逻辑运行,不会进入优化流程 * * @param optimizationTaskModel * @param receiptMode * @return */ public static int doOptimizationProcess(OptimizationTaskModel optimizationTaskModel, String receiptMode, int printerModel) { if (optimizationTaskModel == null || TextUtils.isEmpty(receiptMode)) { return PrintResultCode.PRINT_EXCEPTION; } if (IpPrinterConts.OPTIMIZATION_MODEL_GROUP_EPSON_TMU220B == printerModel || IpPrinterConts.OPTIMIZATION_MODEL_GROUP_EPSON_T60_903_901 == printerModel || IpPrinterConts.OPTIMIZATION_MODEL_GROUP_GPRINTER_GP_L80250II == printerModel) { boolean isRealTimeOK = detectRealTime(optimizationTaskModel.getOutputStream(), optimizationTaskModel.getInputStream(), optimizationTaskModel.getTaskUniq(), optimizationTaskModel.getConfigUniq()); if (!isRealTimeOK) { return PrintResultCode.PRINTER_PAPER_END_OR_UNCOVER; } } switch (receiptMode) { case IpPrinterConts.RECEIPT_MODE_GSRN: return doOptimization(optimizationTaskModel, receiptMode, 1000, 20 * 1000); case IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL: return doOptimization(optimizationTaskModel, receiptMode, 3000, 10 * 1000); default: break; } return PrintResultCode.PRINT_EXCEPTION; } /** * 实际优化方法,通过输入输出流来进行数据传输 * 根据返回结果判断执行状态 * * @param optimizationTaskModel * @param receiptMode * @param singleMaxLength * @param timeout * @return */ private static int doOptimization(OptimizationTaskModel optimizationTaskModel, String receiptMode, int singleMaxLength, int timeout) { List<byte[]> cmds = ByteProcessUtil.processCmds(optimizationTaskModel.getData(), singleMaxLength); boolean isTransmitOK = true; int sendTotalCount = cmds.size(); OutputStream outputStream = optimizationTaskModel.getOutputStream(); InputStream inputStream = optimizationTaskModel.getInputStream(); for (int i = 0; i < cmds.size(); i++) { if (outputStream != null) { ReceiptCmdModel currentReceiptCmd = buildReceiptCmd(receiptMode); try { byte[] output = cmds.get(i); byte[] readStatus = currentReceiptCmd.getWholeInstruction(); outputStream.write(output); outputStream.write(readStatus); outputStream.flush(); // if (output.length > singleMaxLength) { // LogUtil.logOnlineDebug("[Model " + receiptMode + "] write byte = \n" + "HUGE DATA(MAYBE IMAGE) OMIT"); // } else { // } } catch (IOException e) { e.printStackTrace(); } if (!readStream(currentReceiptCmd.getId(), receiptMode, inputStream, optimizationTaskModel.getTaskUniq(), sendTotalCount, i, optimizationTaskModel.getConfigUniq(), timeout)) { isTransmitOK = false; break; } } } if (isTransmitOK) { return PrintResultCode.SUCCESS; } else { return PrintResultCode.PRINTER_CHECK_TIME_OUT; } } /** * 构建优化指令 * 根据不同模式构建需要的指令内容 * (可优化) * * @param receiptMode * @return */ private static ReceiptCmdModel buildReceiptCmd(String receiptMode) { ReceiptCmdModel receiptCmdModel = new ReceiptCmdModel(); switch (receiptMode) { case IpPrinterConts.RECEIPT_MODE_GSRN: receiptCmdModel.setBasicInstruction(GSRN_CMD); receiptCmdModel.setWholeInstruction(GSRN_CMD); return receiptCmdModel; case IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL: byte[] wholeCmd = new byte[11]; byte[] id = ByteProcessUtil.createRandomId(); System.arraycopy(EPSON_Bill_CONTROL_CMD, 0, wholeCmd, 0, EPSON_Bill_CONTROL_CMD.length); System.arraycopy(id, 0, wholeCmd, EPSON_Bill_CONTROL_CMD.length, 4); receiptCmdModel.setBasicInstruction(EPSON_Bill_CONTROL_CMD); receiptCmdModel.setWholeInstruction(wholeCmd); receiptCmdModel.setId(id); return receiptCmdModel; default: return null; } } /** * 读取流数据,根据返回判断执行结果 * (可优化,传参太多) * * @param id * @param receiptMode * @param inStream * @param taskUniq * @param totalSendCount * @param currentCount * @param configUniq * @param timeout * @return */ public static boolean readStream(byte[] id, String receiptMode, InputStream inStream, String taskUniq, int totalSendCount, int currentCount, String configUniq, int timeout) { long startTimeStamp = System.currentTimeMillis(); ByteBuffer checkBuffer = ByteBuffer.allocate(64); byte[] receiptByte = null; while (true) { if ((System.currentTimeMillis() - startTimeStamp) > timeout) { break; } try { Thread.sleep(100); } catch (InterruptedException e) { PrintLog.e(LOG_TAG, "", e); } byte[] resultBytes = getReceiptResult(inStream); if (resultBytes == null || resultBytes.length == 0) { continue; } checkBuffer.put(resultBytes); int contentLength = checkBuffer.position(); byte[] validData = new byte[contentLength]; System.arraycopy(checkBuffer.array(), 0, validData, 0, contentLength); byte[] checkResult = checkReceiptMessageValid(validData, receiptMode); if (checkResult != null) { receiptByte = checkResult; break; } } if (receiptByte == null) { recordReceiptResult(taskUniq, "NOT RECEIVED", totalSendCount, currentCount, configUniq); PrintLog.d(LOG_TAG, "Receipt:NOT RECEIVED"); return false; } if (receiptByte != null) { boolean isMessageVaild = buildReceiptProcessResult(id, receiptByte, receiptMode); StringBuilder resultInfo = new StringBuilder(); resultInfo.append("Result Message:[" + ByteProcessUtil.bytes2HexString(receiptByte) + "]"); if (id != null && id.length > 0) { resultInfo.append(" PackageID:[" + ByteProcessUtil.bytes2HexString(id) + "]"); } recordReceiptResult(resultInfo.toString(), taskUniq, "" + isMessageVaild, totalSendCount, currentCount, configUniq); PrintLog.d(LOG_TAG, "Receipt:" + ByteProcessUtil.bytes2HexString(receiptByte)); return isMessageVaild; } else { recordReceiptResult(taskUniq, "READ FAIL", totalSendCount, currentCount, configUniq); PrintLog.d(LOG_TAG, "Receipt:READ FAIL"); return false; } } /** * 构建回执结果 * 感觉不同优化方案的结果返回判断结果 * * @param idBytes * @param receipt * @param receiptMode * @return */ private static boolean buildReceiptProcessResult(byte[] idBytes, byte[] receipt, String receiptMode) { switch (receiptMode) { case IpPrinterConts.RECEIPT_MODE_GSRN: if (receipt != null && receipt.length == 1) { return ((receipt[0] & 0x90) == 0 && (receipt[0] & 0x0c) == 0); } case IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL: if (idBytes != null && idBytes.length == 4 && receipt != null && receipt.length == 4) { if (ByteProcessUtil.isEpsonReceiptVaild(idBytes, receipt)) return true; } return false; default: return false; } } /** * 打印回执记录 * * @param taskUniq * @param status * @param totalCount * @param currentCount * @param configUniq */ private static void recordReceiptResult(String taskUniq, String status, int totalCount, int currentCount, String configUniq) { recordReceiptResult("", taskUniq, status, totalCount, currentCount, configUniq); } /** * 打印回执记录 * * @param resultInfo * @param taskUniq * @param status * @param totalCount * @param currentCount * @param configUniq */ private static void recordReceiptResult(String resultInfo, String taskUniq, String status, int totalCount, int currentCount, String configUniq) { StringBuilder sb = new StringBuilder(); sb.append("网口回执监控:Printer[" + configUniq + "]"); if (!TextUtils.isEmpty(resultInfo)) { sb.append(resultInfo); } sb.append(",taskUniq[").append(taskUniq).append("]"); sb.append("\n"); sb.append("receipt status [" + status + "]," + "total count [" + totalCount + "]" + "current count [" + (currentCount + 1) + "]"); } /** * 串口查找中需要的握手返回检测 * * @param inStream * @return */ private static byte[] getReceiptResult(InputStream inStream) { int count = 0; byte[] result = new byte[0]; if (inStream != null) { try { count = inStream.available(); } catch (IOException e) { PrintLog.e(LOG_TAG, "", e); } result = new byte[count]; if (count > 0) { try { inStream.read(result); } catch (IOException e) { PrintLog.e(LOG_TAG, "", e); } } } return result; } /** * 判断返回数据对应不同模式的合法性 * * @param source * @return */ private static byte[] checkReceiptMessageValid(byte[] source, String receiptMode) { switch (receiptMode) { case IpPrinterConts.RECEIPT_MODE_GSRN: if (source.length < 0) { return null; } return source; case IpPrinterConts.RECEIPT_MODE_COMMON_PACKAGE_CONTROL: if (source.length < LENGTH_BYTE_BILL_CONTROL) { return null; } for (int i = 0; i < (source.length + 1 - LENGTH_BYTE_BILL_CONTROL); i++) { if (source[i] == BYTE_BILL_CONTROL_1 && source[i + 1] == BYTE_BILL_CONTROL_2 && source[i + LENGTH_BYTE_BILL_CONTROL - 1] == BYTE_BILL_CONTROL_7) { byte[] receiptId = {source[i + 2], source[i + 3], source[i + 4], source[i + 5]}; return receiptId; } } break; default: break; } return null; } /** * 判断返回数据对应不同模式的合法性 * * @param source * @return */ private static boolean checkDLEReceiptValid(byte[] source) { for (int i = 0; i < source.length; i++) { if ((source[0] & 0x93) == 0x12) { return true; } } return false; } /** * 实时检测状态 * * @param outputStream * @param inputStream * @return */ private static boolean detectRealTime(OutputStream outputStream, InputStream inputStream, String taskUniq, String configUniq) { if (outputStream != null) { try { outputStream.write(REAL_TIME_DETECT); outputStream.flush(); } catch (IOException e) { PrintLog.e(LOG_TAG, "", e); return false; } } return checkRealTime(inputStream, 2 * 1000, taskUniq, configUniq); } /** * 监听处理实时消息回复 * * @param inputStream * @param timeout * @param taskUniq * @param configUniq * @return */ public static boolean checkRealTime(InputStream inputStream, int timeout, String taskUniq, String configUniq) { int count = 0; boolean isCheckOK = false; long startTimeStamp = System.currentTimeMillis(); ByteBuffer checkBuffer = ByteBuffer.allocate(64); while (true) { if ((System.currentTimeMillis() - startTimeStamp) > timeout) { break; } try { Thread.sleep(100); } catch (InterruptedException e) { PrintLog.e(LOG_TAG, "", e); } byte[] resultBytes = getReceiptResult(inputStream); if (resultBytes == null || resultBytes.length == 0) { continue; } checkBuffer.put(resultBytes); int contentLength = checkBuffer.position(); byte[] validData = new byte[contentLength]; System.arraycopy(checkBuffer.array(), 0, validData, 0, contentLength); isCheckOK = checkDLEReceiptValid(validData); if (isCheckOK) { break; } } StringBuilder resultInfo = new StringBuilder(); resultInfo.append("Check Result Message:[" + isCheckOK + "]"); if (!isCheckOK) { recordCheckResult(resultInfo.toString(), taskUniq, "false", configUniq); PrintLog.d(LOG_TAG, "Receipt:CHECK CONNECT FAIL"); return false; } else { recordCheckResult(resultInfo.toString(), taskUniq, "true", configUniq); PrintLog.d(LOG_TAG, "Receipt:CHECK CONNECT SUCCESS"); return true; } // StringBuilder resultInfo = new StringBuilder(); // resultInfo.append("Check Result Message:[" + isCheckOK + "]"); // // if (receipt != null) { // // if (receipt != null && receipt.length == 1) { // // if ((receipt[0] & 0x93) == 0x12) { // // TODO: 2018/7/17 开盖打印细化 // recordCheckResult(resultInfo.toString(), taskUniq, "true", configUniq); // PrintLog.d(LOG_TAG, "Receipt:" + ByteProcessUtil.bytes2HexString(receipt)); // return true; // } // // } // } // // recordCheckResult(resultInfo.toString(), taskUniq, "false", configUniq); // PrintLog.d(LOG_TAG, "Receipt:" + ByteProcessUtil.bytes2HexString(receipt)); } private static void recordCheckResult(String resultInfo, String taskUniq, String status, String configUniq) { StringBuilder sb = new StringBuilder(); sb.append("网口实时检测:Printer[" + configUniq + "]"); if (!TextUtils.isEmpty(resultInfo)) { sb.append(resultInfo); } sb.append(",taskUniq[").append(taskUniq).append("]"); sb.append("\n"); sb.append("receipt status [" + status + "]"); } }
[ "zhang.pu@puscene.com" ]
zhang.pu@puscene.com
8785b595d407c284c88e9207583db7b208e86962
513d9de13963994c0493f9d68c02657c8250e8ba
/src/Tester3.java
fa20352912eef76a61e8e5255210320e83ce9bbd
[]
no_license
peacetoyo/Project1
08285e9d909ee8990f4eb0d916906bc1de6f1380
fbd9cb06bd615ac5006c1c91dcb55110773a0e01
refs/heads/master
2023-02-09T06:10:31.223906
2020-12-27T18:50:10
2020-12-27T18:50:10
311,380,190
0
0
null
null
null
null
UTF-8
Java
false
false
632
java
import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class Tester3 { public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.ie.driver","C:\\Program Files\\IEDriverServer.exe" ); WebDriver driver=new InternetExplorerDriver(); driver.get("https://www.google.com/"); driver.get("https://www.google.com/"); driver.get("https://www.google.com/"); driver.get("https://www.google.com/"); driver.get("https://www.google.com/"); System.out.println(driver.getTitle()); } }
[ "gabriel.toyo@outlook.com" ]
gabriel.toyo@outlook.com
77c2cb17dc7f16de514aa6a8b27fff8746821ec1
405ea5715e81829b5d8578c2ea955ddc31f91b9e
/dbfacade-testlink-rpc-api/src/testlink/api/java/client/tc/autoexec/annotation/IgnoreAutomatedTest.java
3242768479514c12577fc81bee13ef1c09f971b0
[]
no_license
jebakumar23/dbfacade-testlink-rpc-api
984feef07c61e7e7630eccca6febb04b501145af
ead881d9aeeed812448b04f918cc09c80675c385
refs/heads/master
2021-01-10T08:59:12.058170
2010-09-02T02:51:31
2010-09-02T02:51:31
53,023,475
0
1
null
null
null
null
UTF-8
Java
false
false
1,154
java
/* * Daniel R Padilla * * Copyright (c) 2009, Daniel R Padilla * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package testlink.api.java.client.tc.autoexec.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface IgnoreAutomatedTest { }
[ "danthehorn@yahoo.com" ]
danthehorn@yahoo.com
55176766e27a5e8a1a03be7a6f57eee014ddc3a2
397984903e152fb83a53a5b1015bb190f6ae4c15
/src/main/java/com/tangkuo/cn/chapter2/DisplayUnicode.java
09ea2b42a3ff792c6cc8b445abcf219d5eda5c8d
[ "Apache-2.0" ]
permissive
TANGKUO/JavaEE
4f23b0886dd37bf14c35885101783cbaef7ea8b2
48cbc5f286c58f6698b557d9001938e615502d56
refs/heads/master
2022-12-25T05:42:26.149760
2019-05-23T01:10:43
2019-05-23T01:10:43
181,110,981
0
1
Apache-2.0
2022-12-16T06:52:13
2019-04-13T02:32:13
Java
UTF-8
Java
false
false
291
java
package com.tangkuo.cn.chapter2; import javax.swing.JOptionPane; public class DisplayUnicode { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "\u6B22\u8FCE \u03b1 \u03b2 \u03b3", "\u6B22\u8FCE Welcome", JOptionPane.INFORMATION_MESSAGE); } }
[ "616507752@qq.com" ]
616507752@qq.com
d1be7999ca61d3e68200c00da198a280a0da2ae6
b141568d306cac6ccb7c15bbe89d588b866dd470
/myblog/src/main/java/cn/hj/blog/handler/ControllerExceptionHandler.java
dfcc34cfd74e74905a449189bf5bc5a09084e42e
[]
no_license
learn930/myblog
e3d6514f4a9eeb6c06a4bb7db82a01b77e8bdc74
8615ec23535076c8a552476941c8a2dc5b10b80f
refs/heads/master
2022-04-21T23:49:55.289103
2020-04-24T08:37:43
2020-04-24T08:37:43
258,445,287
0
0
null
null
null
null
UTF-8
Java
false
false
1,333
java
package cn.hj.blog.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class ControllerExceptionHandler { private Logger logger= LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(Exception.class) public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception { // logger.error("Request URL : {},Exception: {}",request.getRequestURL(),e.getMessage()); // if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){ // throw e; // } // ModelAndView mv=new ModelAndView(); // ModelAndView mv1=new ModelAndView(); // mv.addObject("url",request.getRequestURL()); // mv.addObject("exception",e); // mv.setViewName("error/error"); // mv1.addObject("mv",mv); // return mv; return null; } }
[ "19823@qq.com" ]
19823@qq.com
d9f318fc177b0bbc766d311fb9bdb480a1168964
a1c11101a3d60a54e8f692edceca6d1809ffb9c0
/app/src/main/java/com/si/lei/android_sample_features/MainActivity.java
d82fdf3d0e228712a567ab991ad3d603103b4cb5
[]
no_license
sileixinhua/android_sample_features
c1d82adb324d78fee3dfe391813ad538dc6e09e1
2d76aec399641fb7ba7101ca83789ae20d9fa5af
refs/heads/master
2020-04-09T04:21:05.072856
2019-04-07T08:05:42
2019-04-07T08:05:42
160,018,343
0
0
null
null
null
null
UTF-8
Java
false
false
5,577
java
package com.si.lei.android_sample_features; import android.app.ActivityManager; import android.content.Context; import android.graphics.PixelFormat; import android.os.Build; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.TextView; /** * @author lei.si * @date 2019/02/15 * 添加底部导航栏 * https://github.com/yaochangliang159/Android-TabView * * @author lei.si * @data 2019/04/07 * 添加悬浮窗口显示可用CPU * 【Bug】无法移动悬浮窗 * https://github.com/brycegao/GlobalWindow */ public class MainActivity extends AppCompatActivity { TextView floatWindow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View view = LayoutInflater.from(this).inflate(R.layout.layout_window_alert, null, false); floatWindow = (TextView) view.findViewById(R.id.floatWindow); findViewById(R.id.btn_window).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showWindow(); //这里无法执行??? new TimeThread().start(); } }); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.getBooleanExtra("fromBaidu", false)) { finish(); } } private void showWindow() { WindowManager.LayoutParams wmParamsDu = new WindowManager.LayoutParams(); WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE); if (Build.VERSION.SDK_INT > 24) { wmParamsDu.type = WindowManager.LayoutParams.TYPE_PHONE; } else { wmParamsDu.type = WindowManager.LayoutParams.TYPE_TOAST; } wmParamsDu.width = WindowManager.LayoutParams.WRAP_CONTENT; wmParamsDu.height = WindowManager.LayoutParams.WRAP_CONTENT; //初始化坐标 wmParamsDu.x = 0; wmParamsDu.y = 800; //弹窗类型为系统Window //以左上角为基准 wmParamsDu.gravity = Gravity.START | Gravity.TOP; wmParamsDu.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;; //如果不加,背景会是一片黑色。 wmParamsDu.format = PixelFormat.RGBA_8888; View view = LayoutInflater.from(this).inflate(R.layout.layout_window_alert, null, false); windowManager.addView(view, wmParamsDu); } public class TimeThread extends Thread{ @Override public void run() { super.run(); do{ try { Thread.sleep(1000); Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } catch (InterruptedException e) { e.printStackTrace(); } }while (true); } } /** * 转换格式 * * @return resultBuffer.toString() 转换格式 */ public String formatSize(long size) { String suffix = null; float fSize = 0; if (size >= 1024) { suffix = "KB"; fSize = size / 1024; if (fSize >= 1024) { suffix = "MB"; fSize /= 1024; } if (fSize >= 1024) { suffix = "GB"; fSize /= 1024; } } else { fSize = size; } java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00"); StringBuilder resultBuffer = new StringBuilder(df.format(fSize)); if (suffix != null) { resultBuffer.append(suffix); } return resultBuffer.toString(); } /** * 获得系统可用内存大小 * * @return availMemStr 系统可用内存大小 */ private String getSystemAvaialbeMemorySize() { //获得ActivityManager服务的对象 //getSystemService无法在fragment中使用,所以要先getActivity()获得context才可以 ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); //获得MemoryInfo对象 ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); //获得系统可用内存,保存在MemoryInfo对象上 mActivityManager.getMemoryInfo(memoryInfo); long memSize = memoryInfo.availMem; //字符类型转换 String availMemStr = formatSize(memSize); return availMemStr; } private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what){ case 1: floatWindow.setText(getSystemAvaialbeMemorySize()); Log.d("sielixinhua", getSystemAvaialbeMemorySize()); break; default: } return false; } }); public void quick_start(View view) { startActivity(new Intent(this, QuickStartActivity.class)); } }
[ "sileixinhua@163.com" ]
sileixinhua@163.com
41986e3a1b8a495d6c888c8fbf9d7c453631a0c0
7a3772fb4a1b38358b375ee36ce436674308295a
/app/src/main/java/com/mkv/secondnote/MainActivity.java
6c6f78a15d5db9ef4b02e57c151c8e0265945a5c
[]
no_license
abhay-kolhe/AndroidNotee
f5d8ef04de7d4283d37dedcf55f1838e08f1cda0
37ee2bca176559ef232af9907c2dc25509bedd18
refs/heads/master
2020-04-30T14:18:35.577485
2019-04-18T05:54:38
2019-04-18T05:54:38
176,887,154
0
0
null
null
null
null
UTF-8
Java
false
false
16,275
java
package com.mkv.secondnote; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class MainActivity extends AppCompatActivity implements View.OnKeyListener { private NotesAdapter mAdapter; private List<Note> notesList = new ArrayList<>(); private CoordinatorLayout coordinatorLayout; private RecyclerView recyclerView; private TextView noNotesView; private static TextView noteText; private DatabaseHelper db; private static final String TAG="pin"; private ImageView i1,i2,i3,i4; private Button saveButton; private EditText enterPin; private EditText mPin; static String answer; LinearLayout backgroundLayout; static SharedPreferences sharedPreferences; TextView pinTitle; ArrayList<String> savePosition=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); sharedPreferences=this.getSharedPreferences ("com.mkv.pin", Context.MODE_PRIVATE); if(!savePosition.isEmpty()) { HashSet<String> set = new HashSet<>(savePosition); sharedPreferences.edit().putStringSet("hideChildChallenge", set).apply(); } coordinatorLayout = findViewById(R.id.coordinator_layout); recyclerView = findViewById(R.id.recycler_view); noNotesView = findViewById(R.id.empty_notes_view); db = new DatabaseHelper(this); notesList.addAll(db.getAllNotes()); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showNoteDialog(false, null, -1); } }); mAdapter = new NotesAdapter(this, notesList); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16)); recyclerView.setAdapter(mAdapter); toggleEmptyNotes(); /** * On long press on RecyclerView item, open alert dialog * with options to choose * Edit and Delete * */ recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, final int position) { showActionsDialog(position); } @Override public void onLongClick(View view, int position) { noteText = view.findViewById(R.id.note); Toast.makeText(MainActivity.this,String.valueOf(position), Toast.LENGTH_SHORT).show(); hidingDialog(noteText,position); }//end of longClick })); } /** * Inserting new note in db * and refreshing the list */ private void createNote(String note) { // inserting note in db and getting // newly inserted note id long id = db.insertNote(note); // get the newly inserted note from db Note n = db.getNote(id); if (n != null) { // adding new note to array list at 0 position notesList.add(0, n); // refreshing the list mAdapter.notifyDataSetChanged(); // refreshing the list toggleEmptyNotes(); } } /** * Updating note in db and updating * item in the list by its position */ private void updateNote(String note, int position) { Note n = notesList.get(position); // updating note text n.setNote(note); // updating note in db db.updateNote(n); // refreshing the list notesList.set(position, n); mAdapter.notifyItemChanged(position); toggleEmptyNotes(); } /** * Deleting note from SQLite and removing the * item from the list by its position */ private void deleteNote(int position) { // deleting the note from db db.deleteNote(notesList.get(position)); // removing the note from the list notesList.remove(position); mAdapter.notifyItemRemoved(position); toggleEmptyNotes(); } /** * Opens dialog with Edit - Delete options * Edit - 0 * Delete - 0 */ private void showActionsDialog(final int position) { CharSequence colors[] = new CharSequence[]{"Edit", "Delete"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose option"); builder.setItems(colors, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { showNoteDialog(true, notesList.get(position), position); } else { deleteNote(position); } } }); builder.show(); } /** * Shows alert dialog with EditText options to enter / edit * a note. * when shouldUpdate=true, it automatically displays old note and changes the * button text to UPDATE */ private void showNoteDialog(final boolean shouldUpdate, final Note note, final int position) { LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext()); View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null); AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(MainActivity.this); alertDialogBuilderUserInput.setView(view); final EditText inputNote = view.findViewById(R.id.note); TextView dialogTitle = view.findViewById(R.id.dialog_title); dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_note_title) : getString(R.string.lbl_edit_note_title)); if (shouldUpdate && note != null) { inputNote.setText(note.getNote()); } alertDialogBuilderUserInput .setCancelable(false) .setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogBox, int id) { } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogBox, int id) { dialogBox.cancel(); } }); final AlertDialog alertDialog = alertDialogBuilderUserInput.create(); alertDialog.show(); alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Show toast message when no text is entered if (TextUtils.isEmpty(inputNote.getText().toString())) { Toast.makeText(MainActivity.this, "Enter note!", Toast.LENGTH_SHORT).show(); return; } else { alertDialog.dismiss(); } // check if user updating note if (shouldUpdate && note != null) { // update note by it's id updateNote(inputNote.getText().toString(), position); } else { // create new note createNote(inputNote.getText().toString()); } } }); } private void hidingDialog(final TextView noteTexts,int position){ myLock(noteTexts,position); } private void myLock(final TextView noteText, final int position){ LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext()); final View myLockView = layoutInflaterAndroid.inflate(R.layout.activity_my_lock, null); final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this); mPin=(EditText) myLockView.findViewById(R.id.enter_pin); pinTitle=(TextView) myLockView.findViewById(R.id.no_textview_1); i1=(ImageView) myLockView.findViewById(R.id.imageview_circle1); i2=(ImageView) myLockView.findViewById(R.id.imageview_circle2); i3=(ImageView) myLockView.findViewById(R.id.imageview_circle3); i4=(ImageView) myLockView.findViewById(R.id.imageview_circle4); backgroundLayout=(LinearLayout) myLockView.findViewById(R.id.no_linear_1); mBuilder.setView(myLockView); mBuilder.setNegativeButton("No",null) .setPositiveButton("Enter", new DialogInterface.OnClickListener() { @SuppressLint("ResourceType") @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(MainActivity.this,"entered further", Toast.LENGTH_SHORT).show(); String text=mPin.getText().toString(); if (text.length() != 4) { Toast.makeText(MainActivity.this, "Please" + " enter 4 digit pin.", Toast.LENGTH_SHORT).show(); }if (text.length() == 4) { if(example() == null) { Toast.makeText(MainActivity.this, "PIN NOT CREATED INITIALLY" , Toast.LENGTH_SHORT).show(); savePin( text, sharedPreferences); }else{ if(example().equals(text)){ if(noteText.getVisibility()==View.VISIBLE){ savePosition.add(String.valueOf(position)); Toast.makeText(MainActivity.this,String.valueOf(position) , Toast.LENGTH_SHORT).show(); noteText.setVisibility(View.INVISIBLE); }else { Toast.makeText(MainActivity.this,"visibilit RUN" , Toast.LENGTH_SHORT).show(); noteText.setVisibility(View.VISIBLE); } }else{ Toast.makeText(MainActivity.this, "WRONG PIN" , Toast.LENGTH_SHORT).show(); } }//end of else } } }); AlertDialog dialog=mBuilder.create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE) .setTextSize(TypedValue.COMPLEX_UNIT_SP,18.0f); dialog.getButton(AlertDialog.BUTTON_NEGATIVE) .setTextSize(TypedValue.COMPLEX_UNIT_SP,18.0f); mPin.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { switch (editable.length()) { case 4: i4.setImageResource(R.drawable.circle2); break; case 3: i4.setImageResource(R.drawable.circle); i3.setImageResource(R.drawable.circle2); break; case 2: i3.setImageResource(R.drawable.circle); i2.setImageResource(R.drawable.circle2); break; case 1: i2.setImageResource(R.drawable.circle); i1.setImageResource(R.drawable.circle2); break; default: i1.setImageResource(R.drawable.circle); } } }); backgroundLayout.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ if(view.getId()==R.id.no_linear_1 || view.getId()==R.id.no_linear_2 || view.getId()==R.id.no_textview_1 ||view.getId()==R.id.no_linear_main){ InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getCurrentFocus() .getWindowToken(),0); } } }); enterPin=(EditText) myLockView.findViewById(R.id.enter_pin); enterPin.requestFocus(); enterPin.setInputType(InputType.TYPE_CLASS_NUMBER); enterPin.setFocusableInTouchMode(true); enterPin.setOnKeyListener(MainActivity.this); }//abo public void savePin( String myPin,SharedPreferences sharedPreferences){ sharedPreferences.edit().putString("password",myPin).apply(); Toast.makeText(this, myPin, Toast.LENGTH_SHORT).show(); answer=sharedPreferences.getString("password",""); Log.i("ad","da"); Toast.makeText(MainActivity.this,"MyloCK entered", Toast.LENGTH_SHORT).show(); } public String example(){ return answer; } public boolean onKey(View view, int i, KeyEvent keyEvent) { if(i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) { Toast.makeText(MainActivity.this,"On Key Runs", Toast.LENGTH_SHORT).show(); } //write code about what happens on clicking done button return false; } /** * Toggling list and empty notes view */ private void toggleEmptyNotes() { // you can check notesList.size() > 0 if (db.getNotesCount() > 0) { noNotesView.setVisibility(View.GONE); } else { noNotesView.setVisibility(View.VISIBLE); } } }
[ "kolhe71@gmail.com" ]
kolhe71@gmail.com
74fe24e8a02f7ba16f261ddea0cd88e1b52f3f8a
5a076617e29016fe75d6421d235f22cc79f8f157
/百度手机地图 实例集合/BaiduMapApi_Sample_Android_1.3.2/BaiduMapApiDemo/src/com/baidu/mapapi/demo/RoutePlan.java
f408893eb1f27a9a9120df50d2b4556829ad161c
[]
no_license
dddddttttt/androidsourcecodes
516b8c79cae7f4fa71b97a2a470eab52844e1334
3d13ab72163bbeed2ef226a476e29ca79766ea0b
refs/heads/master
2020-08-17T01:38:54.095515
2018-04-08T15:17:24
2018-04-08T15:17:24
null
0
0
null
null
null
null
GB18030
Java
false
false
5,821
java
package com.baidu.mapapi.demo; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.baidu.mapapi.BMapManager; import com.baidu.mapapi.MKAddrInfo; import com.baidu.mapapi.MKBusLineResult; import com.baidu.mapapi.MKDrivingRouteResult; import com.baidu.mapapi.MKPlanNode; import com.baidu.mapapi.MKPoiResult; import com.baidu.mapapi.MKSearch; import com.baidu.mapapi.MKSearchListener; import com.baidu.mapapi.MKTransitRouteResult; import com.baidu.mapapi.MKWalkingRouteResult; import com.baidu.mapapi.MapActivity; import com.baidu.mapapi.MapView; import com.baidu.mapapi.RouteOverlay; import com.baidu.mapapi.TransitOverlay; public class RoutePlan extends MapActivity { Button mBtnDrive = null; // 驾车搜索 Button mBtnTransit = null; // 公交搜索 Button mBtnWalk = null; // 步行搜索 MapView mMapView = null; // 地图View MKSearch mSearch = null; // 搜索模块,也可去掉地图模块独立使用 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.routeplan); BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication(); if (app.mBMapMan == null) { app.mBMapMan = new BMapManager(getApplication()); app.mBMapMan.init(app.mStrKey, new BMapApiDemoApp.MyGeneralListener()); } app.mBMapMan.start(); // 如果使用地图SDK,请初始化地图Activity super.initMapActivity(app.mBMapMan); mMapView = (MapView)findViewById(R.id.bmapView); mMapView.setBuiltInZoomControls(true); //设置在缩放动画过程中也显示overlay,默认为不绘制 mMapView.setDrawOverlayWhenZooming(true); // 初始化搜索模块,注册事件监听 mSearch = new MKSearch(); mSearch.init(app.mBMapMan, new MKSearchListener(){ public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { // 错误号可参考MKEvent中的定义 if (error != 0 || res == null) { Toast.makeText(RoutePlan.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show(); return; } RouteOverlay routeOverlay = new RouteOverlay(RoutePlan.this, mMapView); // 此处仅展示一个方案作为示例 routeOverlay.setData(res.getPlan(0).getRoute(0)); mMapView.getOverlays().clear(); mMapView.getOverlays().add(routeOverlay); mMapView.invalidate(); mMapView.getController().animateTo(res.getStart().pt); } public void onGetTransitRouteResult(MKTransitRouteResult res, int error) { if (error != 0 || res == null) { Toast.makeText(RoutePlan.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show(); return; } TransitOverlay routeOverlay = new TransitOverlay (RoutePlan.this, mMapView); // 此处仅展示一个方案作为示例 routeOverlay.setData(res.getPlan(0)); mMapView.getOverlays().clear(); mMapView.getOverlays().add(routeOverlay); mMapView.invalidate(); mMapView.getController().animateTo(res.getStart().pt); } public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { if (error != 0 || res == null) { Toast.makeText(RoutePlan.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show(); return; } RouteOverlay routeOverlay = new RouteOverlay(RoutePlan.this, mMapView); // 此处仅展示一个方案作为示例 routeOverlay.setData(res.getPlan(0).getRoute(0)); mMapView.getOverlays().clear(); mMapView.getOverlays().add(routeOverlay); mMapView.invalidate(); mMapView.getController().animateTo(res.getStart().pt); } public void onGetAddrResult(MKAddrInfo res, int error) { } public void onGetPoiResult(MKPoiResult res, int arg1, int arg2) { } public void onGetBusDetailResult(MKBusLineResult result, int iError) { } }); // 设定搜索按钮的响应 mBtnDrive = (Button)findViewById(R.id.drive); mBtnTransit = (Button)findViewById(R.id.transit); mBtnWalk = (Button)findViewById(R.id.walk); OnClickListener clickListener = new OnClickListener(){ public void onClick(View v) { SearchButtonProcess(v); } }; mBtnDrive.setOnClickListener(clickListener); mBtnTransit.setOnClickListener(clickListener); mBtnWalk.setOnClickListener(clickListener); } void SearchButtonProcess(View v) { // 处理搜索按钮响应 EditText editSt = (EditText)findViewById(R.id.start); EditText editEn = (EditText)findViewById(R.id.end); // 对起点终点的name进行赋值,也可以直接对坐标赋值,赋值坐标则将根据坐标进行搜索 MKPlanNode stNode = new MKPlanNode(); stNode.name = editSt.getText().toString(); MKPlanNode enNode = new MKPlanNode(); enNode.name = editEn.getText().toString(); // 实际使用中请对起点终点城市进行正确的设定 if (mBtnDrive.equals(v)) { mSearch.drivingSearch("北京", stNode, "上海", enNode); } else if (mBtnTransit.equals(v)) { mSearch.transitSearch("北京", stNode, enNode); } else if (mBtnWalk.equals(v)) { mSearch.walkingSearch("北京", stNode, "北京", enNode); } } @Override protected void onPause() { BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication(); app.mBMapMan.stop(); super.onPause(); } @Override protected void onResume() { BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication(); app.mBMapMan.start(); super.onResume(); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } }
[ "harry.han@gmail.com" ]
harry.han@gmail.com
dfba932aa51fc7bd6a35e8121df09ca073ab8b0f
c039d8bb8657242775367a60acd4f36e2873f4c5
/src/main/java/com/dyny/gms/db/pojo/CacheMethod.java
86e000c0bd9417d02347614111acfea17b07ee3a
[]
no_license
wglbsr/gms
952d43f0c87f3837f8a2fde84eb43e40ea79d2eb
f740d93df75d33f78c6b0c804b9175f87b5a5a8d
refs/heads/master
2020-03-25T07:13:17.121809
2019-01-10T08:15:43
2019-01-10T08:15:43
143,548,480
0
0
null
null
null
null
UTF-8
Java
false
false
1,253
java
package com.dyny.gms.db.pojo; public class CacheMethod { private Integer id; private String pojoName; private String mapperId; private Boolean multiple; private Boolean deleted; private String propertyName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPojoName() { return pojoName; } public void setPojoName(String pojoName) { this.pojoName = pojoName == null ? null : pojoName.trim(); } public String getMapperId() { return mapperId; } public void setMapperId(String mapperId) { this.mapperId = mapperId == null ? null : mapperId.trim(); } public Boolean getMultiple() { return multiple; } public void setMultiple(Boolean multiple) { this.multiple = multiple; } public Boolean getDeleted() { return deleted; } public void setDeleted(Boolean deleted) { this.deleted = deleted; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName == null ? null : propertyName.trim(); } }
[ "wglbsr@163.com" ]
wglbsr@163.com
18d9081f70c606bbbab3ececd84cecb34a9d4dd2
3443aad71cd0e764353963d0faa6b0a27be309bb
/src/main/java/com/chiefmech/service/impl/UserServiceImpl.java
91de5d59e4628922d564eb360389572b505eca44
[ "Apache-2.0" ]
permissive
szpaddy/chiefmechweb
77db01eb68b0af2523ae4b7d3c61edd4cdeb2fc8
9ea5671a294e75b7bbdaee1968e0811e4197b2e2
refs/heads/master
2016-09-06T11:16:38.496145
2014-11-18T02:48:08
2014-11-18T02:48:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
984
java
package com.chiefmech.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.chiefmech.service.UserService; import com.chiefmech.service.dao.UserDao; import com.chiefmech.vo.User; @Service("userService") public class UserServiceImpl implements UserService { @Resource(name = "userDao") private UserDao userDao; @Override public int countAll() { return this.userDao.countAll(); } @Override public User queryUser(int id) { return this.userDao.queryUser(id); } @Override public List<User> selectAll() { return this.userDao.selectAll(); } @Override public List<User> selectPersonsByName(String name) { return this.userDao.selectPersonsByName(name); } @Override public void insert(User user) { this.userDao.insert(user); } @Override public void delete(User user) { this.userDao.delete(user); } @Override public void update(User user) { this.userDao.update(user); } }
[ "sz_paddy@163.com" ]
sz_paddy@163.com