blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
ea3a3253bc8311d3cb7007db2e70068931392e95
|
Java
|
zouxiang123/portal
|
/portal-platform/src/main/java/com/xtt/platform/util/CopyUtil.java
|
UTF-8
| 3,155
| 3.171875
| 3
|
[] |
no_license
|
/**
* @Title: CopyUtil.java
* @Package com.xtt.platform.util
* Copyright: Copyright (c) 2015
* @author: bruce
* @date: 2016年3月17日 上午11:35:25
*
*/
package com.xtt.platform.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
public class CopyUtil {
/**
* 复制源对象和目标对象的属性值
*
*/
public static void copy(Object source, Object target) throws Exception {
Class sourceClass = source.getClass();// 得到对象的Class
Class targetClass = target.getClass();// 得到对象的Class
Field[] sourceFields = sourceClass.getDeclaredFields();// 得到Class对象的所有属性
Field[] targetFields = targetClass.getDeclaredFields();// 得到Class对象的所有属性
for (Field sourceField : sourceFields) {
String name = sourceField.getName();// 属性名
Class type = sourceField.getType();// 属性类型
String methodName = name.substring(0, 1).toUpperCase() + name.substring(1);
Method getMethod = sourceClass.getMethod("get" + methodName);// 得到属性对应get方法
Object value = getMethod.invoke(source);// 执行源对象的get方法得到属性值
for (Field targetField : targetFields) {
String targetName = targetField.getName();// 目标对象的属性名
if (targetName.equals(name)) {
Method setMethod = targetClass.getMethod("set" + methodName, type);// 属性对应的set方法
setMethod.invoke(target, value);// 执行目标对象的set方法
}
}
}
}
public static void main(String[] args) throws Exception {
Source source = new Source();
source.setId(201);
source.setName("小周");
source.setCreateTime(new Date());
Target target = new Target();
copy(source, target);
System.out.println(target.getId());
System.out.println(target.getName());
System.out.println(target.getCreateTime());
}
}
class Source {
private Integer id;
private String name;
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
class Target {
private Integer id;
private String name;
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| true
|
4fab2fe6f5d5a1d698187d027eb7759e0570858f
|
Java
|
onofrimelisa/quality-challenge
|
/src/main/java/com/quality/challenge/utils/CitySearchUtil.java
|
UTF-8
| 2,244
| 2.53125
| 3
|
[] |
no_license
|
package com.quality.challenge.utils;
import com.quality.challenge.dto.FlightDTO;
import com.quality.challenge.dto.HotelDTO;
import com.quality.challenge.dto.StatusCodeDTO;
import com.quality.challenge.exceptions.InvalidDestinationException;
import com.quality.challenge.exceptions.InvalidOriginException;
import org.springframework.http.HttpStatus;
import java.util.List;
import java.util.stream.Collectors;
public class CitySearchUtil {
public static void hotelContainsDestination(List<HotelDTO> hotels, String destination) throws InvalidDestinationException {
if(Boolean.TRUE.equals(
hotels
.stream()
.map(HotelDTO::getCity)
.collect(Collectors.toList())
.stream()
.noneMatch(destination::equalsIgnoreCase))
){
StatusCodeDTO statusCodeDTO = StatusCodeUtil.getCustomStatusCode("The chosen destination does not exist", HttpStatus.NOT_FOUND);
throw new InvalidDestinationException(statusCodeDTO);
}
}
public static void flightContainsDestination(List<FlightDTO> flights, String destination) throws InvalidDestinationException {
if(Boolean.TRUE.equals(
flights
.stream()
.map(FlightDTO::getDestination)
.collect(Collectors.toList())
.stream()
.noneMatch(destination::equalsIgnoreCase))
){
StatusCodeDTO statusCodeDTO = StatusCodeUtil.getCustomStatusCode("The chosen destination does not exist", HttpStatus.NOT_FOUND);
throw new InvalidDestinationException(statusCodeDTO);
}
}
public static void flightContainsOrigin(List<FlightDTO> flights, String origin) throws InvalidOriginException {
if(Boolean.TRUE.equals(
flights
.stream()
.map(FlightDTO::getOrigin)
.collect(Collectors.toList())
.stream()
.noneMatch(origin::equalsIgnoreCase))
){
StatusCodeDTO statusCodeDTO = StatusCodeUtil.getCustomStatusCode("The chosen origin does not exist", HttpStatus.NOT_FOUND);
throw new InvalidOriginException(statusCodeDTO);
}
}
}
| true
|
6081f69f2a7cea55347e97d3ca9fd96cae44f519
|
Java
|
diligentyang/JavaWebLibrary
|
/src/shiyan/User.java
|
UTF-8
| 3,312
| 2.625
| 3
|
[] |
no_license
|
package shiyan;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class User {
private Connection conn;
public boolean checkUser(String username,String password){
conn = DBCon.getConnection();
String listSQL = "select * from user where username='"+username+"' and password= '"+password+"'";
try{
PreparedStatement psmt = (PreparedStatement) conn.prepareStatement(listSQL);
java.sql.ResultSet rs = psmt.executeQuery();
if(rs.next()){
return true;
}
conn.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn!=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
return false;
}
public int getPower(String username){
conn = DBCon.getConnection();
int power = 0;
try {
Statement stmt = (Statement) conn.createStatement();
String sql = "select * from user where username='" + username + "'";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
power = rs.getInt("power");
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return power;
}
public boolean addUser(String username,String password) throws SQLException{
conn = DBCon.getConnection();
String listSQL = "insert into user(username,password) values(?,?)";
java.sql.PreparedStatement pstmt = conn.prepareStatement(listSQL);
try{
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.executeUpdate();
conn.commit();
}catch (SQLException e){
conn.rollback();
e.printStackTrace();
}finally{
conn.close();
}
return false;
}
public boolean borrowBook(String username,int id) throws SQLException{
conn = DBCon.getConnection();
String listSQL = "insert into borrow(username,bookid) values(?,?)";
java.sql.PreparedStatement pstmt = conn.prepareStatement(listSQL);
try{
pstmt.setString(1, username);
pstmt.setInt(2, id);
pstmt.executeUpdate();
conn.commit();
}catch (SQLException e){
conn.rollback();
e.printStackTrace();
}
String sql = "update books set counts = counts-1 where id='" + id + "'";
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}finally{
pstmt.close();
conn.close();
}
return false;
}
public boolean returnBook(int bookid,int id) throws SQLException{
conn = DBCon.getConnection();
String listSQL = "update books set counts=counts+1 where id=?";
try{
PreparedStatement psmt = (PreparedStatement) conn.prepareStatement(listSQL);
psmt.setInt(1,bookid);
int num=psmt.executeUpdate();
conn.commit();
}catch(Exception e){
e.printStackTrace();
}
String listSQL1 = "delete from borrow where id=?";
try{
PreparedStatement psmt = (PreparedStatement) conn.prepareStatement(listSQL1);
psmt.setInt(1,id);
int num=psmt.executeUpdate();
conn.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn!=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
return false;
}
}
| true
|
c3ea74dca8fbd6457d3278a87b9a743abc1fc351
|
Java
|
lovemomia/sogokids-admin
|
/src/main/java/com/sogokids/teacher/service/impl/CourseAssignServiceImpl.java
|
UTF-8
| 5,653
| 2.171875
| 2
|
[] |
no_license
|
package com.sogokids.teacher.service.impl;
import com.sogokids.course.model.Course;
import com.sogokids.course.service.CourseService;
import com.sogokids.system.service.PlaceService;
import com.sogokids.teacher.model.CourseAssign;
import com.sogokids.teacher.service.CourseAssignService;
import com.sogokids.utils.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by hoze on 16/1/7.
*/
@Service
public class CourseAssignServiceImpl implements CourseAssignService {
@Autowired
private PlaceService placeService;
@Autowired
private CourseService courseService;
@Resource
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Map<String,List<CourseAssign>> getCourseAssigns(){
Map<String,List<CourseAssign>> map = new HashMap<String, List<CourseAssign>>();
List<CourseAssign> courseAssigns = new ArrayList<CourseAssign>();
List<CourseAssign> w_courseAssigns = new ArrayList<CourseAssign>();
String startTime = "'"+DateUtil.NowDateStr()+"'";
String sql = "SELECT StartTime,EndTime,PlaceId,Id,CourseId FROM SG_CourseSku where Status > 0 and Status != 3 and ParentId = 0 and StartTime > " + startTime +" order by StartTime desc ";
// String sql = "SELECT a.id,a.title,b.StartTime,b.EndTime,b.PlaceId,b.Id as skuId FROM SG_Course a,SG_CourseSku b where a.ParentId = 0 and a.status > 0 and a.status != 3 and b.status > 0 and b.status != 3 and a.id = b.CourseId and b.StartTime > " + startTime +" order by b.StartTime desc ";
// System.out.print(sql);
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
if(list.size() > 0){
for (int i = 0; i < list.size(); i++) {
CourseAssign entity = new CourseAssign();
int courseId = Integer.parseInt(list.get(i).get("CourseId").toString());
Course course = courseService.get(courseId);
if (course.getStatus() == 0){
continue;
}
entity.setCourseId(courseId);
entity.setCourseTitle(course.getTitle());
int courseSkuId = Integer.parseInt(list.get(i).get("Id").toString());
entity.setSkuId(courseSkuId);
String skuStartTime = list.get(i).get("StartTime").toString();
entity.setSkuStartTime(DateUtil.getDateTimeStr_cn(DateUtil.StrToDate(skuStartTime)));
String skuEndTime = list.get(i).get("EndTime").toString();
entity.setSkuEndTime(DateUtil.getTimeStr_cn(DateUtil.StrToDate(skuEndTime)));
int placeId = Integer.parseInt(list.get(i).get("placeId").toString());
entity.setPlaceId(placeId);
entity.setPlaceAddress(placeService.get(placeId).getAddress());
if (isAssign(courseId, courseSkuId) == 0) {
w_courseAssigns.add(entity);
}else{
courseAssigns.add(entity);
}
}
}
map.put("w_assign",w_courseAssigns);
map.put("y_assign",courseAssigns);
return map;
}
private int isAssign(int courseId, int courseSkuId){
int reDate = 0;
String sql = "SELECT * FROM SG_CourseTeacher where status > 0 and CourseId = "+courseId+" and CourseSkuId = "+courseSkuId;
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
if (list.size() > 0){
reDate = 1;
}
return reDate;
}
@Override
public List<CourseAssign> getTeacherCourses(int teacher_id){
List<CourseAssign> courseAssigns = new ArrayList<CourseAssign>();
String sql = "SELECT a.Id,b.title,b.cover,c.StartTime,c.EndTime,c.PlaceId FROM SG_CourseTeacher a,SG_Course b,SG_CourseSku c where a.status > 0 and b.status > 0 and b.status != 3 and c.status > 0 and c.status != 0 and b.Id = a.CourseId and c.Id = a.CourseSkuId and a.TeacherId = "+teacher_id+" order by c.StartTime desc ";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (int i = 0; i < list.size(); i++) {
CourseAssign entity = new CourseAssign();
// int courseId = Integer.parseInt(list.get(i).get("id").toString());
// entity.setCourseId(courseId);
entity.setCourseTitle(list.get(i).get("title").toString());
entity.setCourseCover(list.get(i).get("cover").toString());
// int courseSkuId = Integer.parseInt(list.get(i).get("skuId").toString());
// entity.setSkuId(courseSkuId);
String skuStartTime = list.get(i).get("StartTime").toString();
entity.setSkuStartTime(DateUtil.getDateTimeStr_cn(DateUtil.StrToDate(skuStartTime)));
String skuEndTime = list.get(i).get("EndTime").toString();
entity.setSkuEndTime(DateUtil.getTimeStr_cn(DateUtil.StrToDate(skuEndTime)));
int placeId = Integer.parseInt(list.get(i).get("placeId").toString());
entity.setPlaceId(placeId);
entity.setPlaceAddress(placeService.get(placeId).getAddress());
courseAssigns.add(entity);
}
return courseAssigns;
}
}
| true
|
10bf54bd5217db4c49a9df20c91c431bee227f2d
|
Java
|
yunusborazan/NeverPuk
|
/NeverPuk/net/nv/p.java
|
UTF-8
| 317
| 1.601563
| 2
|
[] |
no_license
|
package net.nv;
import net.nv.t;
public class p extends t {
public p(String var1) {
this("commands.generic.entity.notFound", new Object[]{var1});
}
public p(String var1, Object... var2) {
super(var1, var2);
}
public synchronized Throwable fillInStackTrace() {
return this;
}
}
| true
|
aca7f4fd686f5f4430b036f71a9414d7c8c09923
|
Java
|
liu13722785488/ProjectStruct
|
/app/src/main/java/com/happyjob/wagesteward/base/BaseFragment.java
|
UTF-8
| 386
| 1.742188
| 2
|
[] |
no_license
|
package com.happyjob.wagesteward.base;
import android.view.View;
import android.view.View.OnClickListener;
import androidx.fragment.app.Fragment;
public abstract class BaseFragment extends Fragment implements OnClickListener {
public abstract void initView(View view);
public abstract void initData();
public abstract void setListener();
// public ImageLoader imageLoader =
}
| true
|
a7787c2eae6ee3b84c6d5460c5e771daad8ba788
|
Java
|
lifes/wtf1
|
/src/main/java/com/hikvision/syncbd/common/FileUtil.java
|
UTF-8
| 678
| 2.640625
| 3
|
[] |
no_license
|
package com.hikvision.syncbd.common;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author chenhuaming 2016-1-11
*
*/
public class FileUtil {
public static File[] getFilesOnDirectoryNotIncludeFolder(
String directoryPath) {
File base = new File(directoryPath);
File[] files = base.listFiles();
List<File> list = new ArrayList<File>();
for (File f : files) {
if (!f.isDirectory()) {
list.add(f);
}
}
return list.toArray(new File[0]);
}
public static boolean del(File file){
return file.delete();
}
public static boolean del(List<File> files){
for(File file:files){
file.delete();
}
return true;
}
}
| true
|
db0dea289cdb8bb9d689903146511ba6f4c71d1c
|
Java
|
Paindar/LambdaLib2
|
/src/main/java/cn/lambdalib2/render/TransformChain.java
|
UTF-8
| 1,081
| 2.375
| 2
|
[
"MIT"
] |
permissive
|
package cn.lambdalib2.render;
import org.lwjgl.util.vector.Matrix4f;
public class TransformChain {
private static final Matrix4f _temp = new Matrix4f();
private final Matrix4f _result = new Matrix4f();
public TransformChain() {
}
public TransformChain(Matrix4f other) {
_result.load(other);
}
public TransformChain translate(float dx, float dy, float dz) {
TransformUtils.translate(dx, dy, dz, _temp);
return applyTemp();
}
public TransformChain rotate(float x, float y, float z) {
TransformUtils.rotateEuler(x, y, z, _temp);
return applyTemp();
}
public TransformChain scale(float sx, float sy, float sz) {
TransformUtils.scale(sx, sy, sz, _temp);
return applyTemp();
}
public TransformChain scale(float s) {
TransformUtils.scale(s, _temp);
return applyTemp();
}
private TransformChain applyTemp() {
Matrix4f.mul(_temp, _result, _result);
return this;
}
public Matrix4f build() {
return _result;
}
}
| true
|
0a9efff386ccd2c2e3efb8bac476648bfdfd0dd3
|
Java
|
OksanaKulbaba/graphs
|
/src/main/java/Lab1/Adjacency.java
|
UTF-8
| 2,414
| 3.40625
| 3
|
[] |
no_license
|
package Lab1;
import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;
public class Adjacency {
public int[][] getMatrix() {
return matrix;
}
private int[][] matrix;
private HashMap<Integer,Integer> verTemp ;
public void initMatrix(){
verTemp = new HashMap<>();
int size = (int)(Math.random()*10)+2;
int chislo;
int[][] tempMatrix = new int[size][size];
for (int i=0; i < size; i++){
for (int j=0; j <= i; j++){
chislo = (int)(Math.random()*2);
if (i==j){tempMatrix[i][j] = chislo;}
else {
tempMatrix[i][j] = chislo;
tempMatrix[j][i] = chislo;}
}
}
this.matrix = tempMatrix;
initInerMatrix();
printMatrix();
}
public void printMatrix(){
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j <matrix.length; j++){
System.out.print(matrix[j][i] + " ");
}
System.out.println("");
}
}
public void initMatrix(int[][] mat){
verTemp = new HashMap<>();
this.matrix = mat;
initInerMatrix();
printMatrix();
}
public void initInerMatrix(){
int temp = 0;
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j <matrix.length; j++){
temp += matrix[j][i];
}
verTemp.put(i,temp);
temp = 0;
}
}
public void verticesGraph(){
SortedSet<Integer> vertices = new ConcurrentSkipListSet<Integer>() {
};
for (int value: verTemp.values()){
vertices.add(value);
}
System.out.println(vertices.toString());
}
public void isolated(){
ArrayList<Integer> isol = new ArrayList<>();
for (Map.Entry entry: verTemp.entrySet()){
if (entry.getValue().equals(0)){
isol.add((Integer) entry.getKey());
}
}
System.out.println(isol.toString());
}
public void finishVertices() {
ArrayList<Integer> isol = new ArrayList<>();
for (Map.Entry entry: verTemp.entrySet()){
if (entry.getValue().equals(1)){
isol.add((Integer) entry.getKey());
}
}
System.out.println(isol.toString());
}
}
| true
|
2aa882949add1d1c2253ab6b1be0df427916711d
|
Java
|
stingpie/Java_group_pproject
|
/group_array_project/src/group_array_project/FileGenerator.java
|
UTF-8
| 1,571
| 4.0625
| 4
|
[] |
no_license
|
package group_array_project;
//import necessary java classes
import java.io.FileWriter;
import java.util.Random;
public class FileGenerator{
//method that generates a file containing an array of numbers with specified width, height, and path
public static void makeTextFile(int width, int height, String path) throws Exception{
FileWriter writeto = new FileWriter(path, false); //instantiate FileWriter class (for writing)
int[][] arr = randomizeArray(width, height); //calls randomizeArray fuction and sets that value as a new array
//write the array to a file with new lines for every row
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++){
writeto.write(arr[i][j] + " ");
}
if (i < arr.length - 1){
writeto.write("\n");
}
}
writeto.close(); //stop writing to the file
}
//method that returns an array of specified dimensions with random values in it
public static int[][] randomizeArray(int width, int height){
int[][] arr = new int[height][width]; //sets up new array of specified dimensions
Random r = new Random(); //instantiates Random class (for random integer generation)
//generates a random int for each index of the array
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++){
arr[i][j] = r.nextInt(100);
}
}
return arr; //return the array of random integers
}
}
| true
|
3971e6d3959388df6940949284ef5e5c375df280
|
Java
|
bijojoseph16/CodingInterview
|
/java/getImportance.java
|
UTF-8
| 940
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
/*
// Employee info
class Employee {
// It's the unique id of each node;
// unique id of this employee
public int id;
// the importance value of this employee
public int importance;
// the id of direct subordinates
public List<Integer> subordinates;
};
*/
class Solution {
public int getImportance(List<Employee> employees, int id) {
int importance = 0;
HashMap<Integer, Employee> map = new HashMap<>();
for(Employee employee : employees)
map.put(employee.id, employee);
Queue<Employee> queue = new LinkedList<>();
queue.offer(map.get(id));
while(!queue.isEmpty())
{
Employee node = queue.poll();
importance += node.importance;
for(int subor: node.subordinates)
queue.offer(map.get(subor));
}
return importance;
}
}
| true
|
2560d0e6a204ac35e57564157ff0be865394bf39
|
Java
|
limboc/sample
|
/app/src/main/java/com/github/limboc/sample/ui/activity/BaseActivity.java
|
UTF-8
| 2,712
| 2.15625
| 2
|
[] |
no_license
|
package com.github.limboc.sample.ui.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import com.github.limboc.sample.App;
import com.github.limboc.sample.R;
import com.github.limboc.sample.ui.widget.LoadingDialog;
import butterknife.ButterKnife;
public abstract class BaseActivity extends AppCompatActivity{
LoadingDialog loadingDialog;
AlertDialog.Builder confirmDialog;
Context context;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(getLayoutId());
context = this;
App.getInstance().addActivity(this);
ButterKnife.bind(this);
initView(savedInstanceState);
initData();
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.left_in, R.anim.left_out);
}
@Override
protected void onDestroy() {
super.onDestroy();
App.getInstance().removeActivity(this);
}
protected abstract int getLayoutId();
protected abstract void initView(Bundle saveInstanceState);
protected abstract void initData();
public void showLoadingDialog(boolean isCancelable){
if(loadingDialog == null){
loadingDialog = new LoadingDialog(context, isCancelable);
}
if(!loadingDialog.isShowing()){
loadingDialog.show();
}
}
public void hideLoadingDialog(){
if(loadingDialog != null && loadingDialog.isShowing()){
loadingDialog.dismiss();
loadingDialog = null;
}
}
public void showConfirmDialog(boolean isCancelable, String message, DialogInterface.OnClickListener onClickListener){
if(confirmDialog == null){
confirmDialog = new AlertDialog.Builder(context)
.setPositiveButton(R.string.ok, onClickListener)
.setNegativeButton(R.string.cancel, null)
.setCancelable(isCancelable)
.setMessage(message);
}
confirmDialog.show();
}
long lastTime;
public void exitApp() {
if (System.currentTimeMillis() - lastTime > 2000) {
com.github.limboc.sample.utils.T.showShort("再按一次退出.");
lastTime = System.currentTimeMillis();
} else {
exit();
}
}
public void exit(){
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
}
| true
|
54e6de4ef02731876ec6429c959df8e36c17df8e
|
Java
|
kva-devops/job4j_design
|
/src/main/java/ru/job4j/collection/SimpleQueue.java
|
UTF-8
| 571
| 3.40625
| 3
|
[] |
no_license
|
package ru.job4j.collection;
import java.util.Iterator;
public class SimpleQueue<T> {
private final SimpleStack<T> in = new SimpleStack<>();
private final SimpleStack<T> out = new SimpleStack<>();
public T poll() {
Iterator<T> itIn = in.iterator();
Iterator<T> itOut = out.iterator();
if (!itOut.hasNext()) {
while (itIn.hasNext()) {
out.push(itIn.next());
in.pop();
}
}
return out.pop();
}
public void push(T value) {
in.push(value);
}
}
| true
|
a4919503e64df8822b6c0497ddc1d178eb466b28
|
Java
|
Ramya9710/hms
|
/src/initialprocess/Bed.java
|
UTF-8
| 798
| 2.796875
| 3
|
[] |
no_license
|
package initialprocess;
public class Bed {
private Long bedId;
private String bedType;
private String roomName;
public Long getBedId() {
return bedId;
}
public void setBedId(Long bedId) {
this.bedId = bedId;
}
public String getBedType() {
return (bedType);
}
public void setBedType(String bedType) {
this.bedType = bedType;
}
public String getRoomName() {
return (roomName);
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
@Override
public String toString() {
return "Bed{" +
"bedId=" + bedId +
", bedType='" + bedType + '\'' +
", roomName='" + roomName + '\'' +
'}';
}
}
| true
|
0ecfb6d8152dee5ed65bed34c434325725d1df18
|
Java
|
645551977/java_test
|
/src/test/java/TestCase/V1_1/IssuePage/WorkLog/RPCMSD1395.java
|
UTF-8
| 2,232
| 1.898438
| 2
|
[] |
no_license
|
package TestCase.V1_1.IssuePage.WorkLog;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import shdsd.selenium.Tools.BaseTest;
import shdsd.selenium.Tools.Entrance;
import shdsd.selenium.Tools.Properties;
import shdsd.selenium.Tools.ScreenshotUntils;
public class RPCMSD1395 extends BaseTest {
@Test
public void RPCMSD1395() throws Exception
{
try {
Entrance.IssuePage();
click(By.id("admin_menu")); //点击齿轮图标
click(By.id("admin_plugins_menu")); //选择插件
Enter(By.id("admin_menu")).sendKeys("123456"); //进入登录模式,输入密码
click(By.id("login-form-submit")); //点击确认
click(By.id("shdsd-timesheet-workday-link")); //点击全局配置
click(By.className("sc-gzVnrw")); //关闭加班模式
click(By.id("header-details-user-fullname")); //点击右上角的切换图像
click(By.id("log_out")); //点击注销
click(By.partialLinkText("登录")); //注销页面,点击登录
Enter(By.id("login-form-username")).sendKeys("admin"); //输入用户名
Enter(By.id("login-form-password")).sendKeys("123456"); //输入密码
click(By.id("login-form-submit")); //点击登录
click(By.id("browse_link")); //点击项目
click(By.id("admin_main_proj_link_lnk")); //选择当前项目
click(By.cssSelector("span[class='aui-nav-item-label'][title='问题']")); //点击issue
click(By.id("issueDetailsWebpanel_Log")); //点击+日志
Enter(By.id("workLogContext_textfield_isWorked")).sendKeys("7h"); //输入耗费时间
Enter(By.name("example-text")).sendKeys("开启加班工作日志"); //输入描述
click(By.id("workLogAndPlan-pendingAudit-button")); //提交工作日志
} catch (Exception e) {
System.err.println("");
String method = Thread.currentThread() .getStackTrace()[1].getMethodName();
ScreenshotUntils.getScreenshot(Properties.filepath + method + ".png");
throw new Exception(e);
}
}
}
| true
|
0f9fb0e5806a31e52463d3c177bbc99189b2c1c6
|
Java
|
Semineces/online-video
|
/service/service_vod/src/main/java/com/hty/vod/controller/VodController.java
|
UTF-8
| 3,445
| 2.25
| 2
|
[] |
no_license
|
package com.hty.vod.controller;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.hty.servicebase.MyException;
import com.hty.utils.R;
import com.hty.utils.ResultCode;
import com.hty.vod.service.VodService;
import com.hty.vod.utils.ConstantVodUtils;
import com.hty.vod.utils.InitVodClient;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* create by Semineces on 2020-08-13
*/
@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {
@Autowired
private VodService vodService;
@ApiOperation(value = "上传视频到阿里云")
@PostMapping("/uploadAliyunVideo")
public R uploadAliyunVideo(MultipartFile file) {
String videoId = vodService.uploadVideo(file);
return R.success().data("videoId", videoId);
}
@ApiOperation(value = "根据视频id删除阿里云的内容")
@DeleteMapping("removeAliyunVideo/{id}")
public R removeAliyunVideo(@PathVariable String id) {
if (!StringUtils.isEmpty(id)) {
try {
//初始化对象
DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
//创建删除视频request对象
DeleteVideoRequest request = new DeleteVideoRequest();
//向request里面设置视频id
request.setVideoIds(id);
//调用初始化对象的方法实现删除
client.getAcsResponse(request);
return R.success();
} catch (Exception e) {
e.printStackTrace();
throw new MyException(ResultCode.ERROR, "删除失败");
}
} else {
return R.error().message("删除失败");
}
}
@ApiOperation(value = "删除多个阿里云视频的方法,参数是多个视频id")
@DeleteMapping("deleteBatch")
public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList) {
vodService.removeBatch(videoIdList);
return R.success();
}
@ApiOperation(value = "根据视频id获取视频凭证")
@GetMapping("/getPlayAuth/{id}")
public R getPlayAuth(@PathVariable String id) {
try {
//创建初始化对象
DefaultAcsClient client =
InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
//创建获取凭证request
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
//向request里面设置视频id
request.setVideoId(id);
//获取response对象 调用方法得到凭证
GetVideoPlayAuthResponse response = client.getAcsResponse(request);
String playAuth = response.getPlayAuth();
return R.success().data("playAuth", playAuth);
} catch (Exception e) {
throw new MyException(ResultCode.ERROR, "获取视频凭证失败");
}
}
}
| true
|
172aafbcc7e803851f5cbb11367bad68cf8328a1
|
Java
|
Blajimir/fake-measures
|
/src/main/java/ru/efko/thermal/fakemeasures/model/Sensor.java
|
UTF-8
| 1,410
| 1.929688
| 2
|
[] |
no_license
|
package ru.efko.thermal.fakemeasures.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Table(name = "sensor")
@Data
@NoArgsConstructor
public class Sensor {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sensor_seq")
@SequenceGenerator(name = "sensor_seq", sequenceName = "sensor_id_seq", allocationSize = 1)
private Long id;
@JoinColumn(name = "station_id", foreignKey = @ForeignKey(name = "sensor_station_id_fkey"))
private Long stationId;
@Column(name = "item_name")
private String itemName;
private Boolean active;
private String comment;
@Column(name = "channel_id")
private Integer channelId;
@Column(name = "measure_type")
private String measureType;
private Boolean fake;
@Column(name = "min_value", precision = 16, scale = 2)
private Double minValue;
@Column(name = "max_value", precision = 16, scale = 2)
private Double maxValue;
@JoinColumn(name = "sensor_group_id", foreignKey = @ForeignKey(name = "sensor_sensor_group_id_fkey"))
private Long sensorGroup;
@Column(name = "absolute_deviation", precision = 8)
private Double absoluteDeviation;
@Column(name = "min_input_threshold", precision = 8)
private Double minInputThreshold;
@Column(name = "max_input_threshold", precision = 8)
private Double maxInputThreshold;
}
| true
|
712196bdb4373c1e01c77a1c4ae9e7e63976dddf
|
Java
|
chrgsoni07/SmartShop
|
/src/main/java/com/rk/smartshop/model/ProductLocation.java
|
UTF-8
| 165
| 1.664063
| 2
|
[] |
no_license
|
package com.rk.smartshop.model;
import lombok.Data;
@Data
public class ProductLocation {
private Long id;
private Long locationId;
private Long productId;
}
| true
|
db3e85734e09291fe981e0b4fdc7540b94f0f0ac
|
Java
|
henridev/City-Assistant
|
/app/src/main/java/smartassist/appreciate/be/smartassist/utils/WeatherHelper.java
|
UTF-8
| 4,935
| 2.328125
| 2
|
[] |
no_license
|
package smartassist.appreciate.be.smartassist.utils;
import smartassist.appreciate.be.smartassist.R;
/**
* Created by Inneke on 24/02/2015.
*/
public class WeatherHelper
{
public static final int COLOR_DARK = 0;
public static final int COLOR_GRAY = 1;
public static final int COLOR_WHITE = 2;
private static final int CODE_STORM = 1;
private static final int CODE_RAIN_CLOUD = 2;
private static final int CODE_PARTLY_RAINY = 3;
private static final int CODE_HAIL = 4;
private static final int CODE_SNOW = 5;
private static final int CODE_FOG = 6;
private static final int CODE_TORNADO = 7;
private static final int CODE_SUN = 8;
private static final int CODE_CLOUD = 9;
private static final int CODE_LOW_TEMP = 10;
private static final int CODE_HIGH_TEMP = 11;
private static final int CODE_WIND = 12;
private static final int CODE_PARTLY_SUNNY = 13;
public static int getWeatherIcon(int code, int color)
{
switch (code)
{
case CODE_STORM:
return color == COLOR_DARK ? R.drawable.storm_dark : color == COLOR_GRAY ? R.drawable.storm_grey : R.drawable.storm_white;
case CODE_RAIN_CLOUD:
return color == COLOR_DARK ? R.drawable.rain_cloud_dark : color == COLOR_GRAY ? R.drawable.rain_cloud_grey : R.drawable.rain_cloud_white;
case CODE_PARTLY_RAINY:
return color == COLOR_DARK ? R.drawable.partly_rainy_dark : color == COLOR_GRAY ? R.drawable.partly_rainy_grey : R.drawable.partly_rainy_white;
case CODE_HAIL:
return color == COLOR_DARK ? R.drawable.hail_dark : color == COLOR_GRAY ? R.drawable.hail_grey : R.drawable.hail_white;
case CODE_SNOW:
return color == COLOR_DARK ? R.drawable.snow_dark : color == COLOR_GRAY ? R.drawable.snow_grey : R.drawable.snow_white;
case CODE_FOG:
return color == COLOR_DARK ? R.drawable.fog_dark : color == COLOR_GRAY ? R.drawable.fog_grey : R.drawable.fog_white;
case CODE_TORNADO:
return color == COLOR_DARK ? R.drawable.tornado_dark : color == COLOR_GRAY ? R.drawable.tornado_grey : R.drawable.tornado_white;
case CODE_SUN:
return color == COLOR_DARK ? R.drawable.sun_dark : color == COLOR_GRAY ? R.drawable.sun_grey : R.drawable.sun_white;
case CODE_CLOUD:
return color == COLOR_DARK ? R.drawable.cloud_dark : color == COLOR_GRAY ? R.drawable.cloud_grey : R.drawable.cloud_white;
case CODE_LOW_TEMP:
return color == COLOR_DARK ? R.drawable.lowtemp_dark : color == COLOR_GRAY ? R.drawable.lowtemp_grey : R.drawable.lowtemp_white;
case CODE_HIGH_TEMP:
return color == COLOR_DARK ? R.drawable.highttemp_dark : color == COLOR_GRAY ? R.drawable.highttemp_grey : R.drawable.highttemp_white;
case CODE_WIND:
return color == COLOR_DARK ? R.drawable.wind_dark : color == COLOR_GRAY ? R.drawable.wind_grey : R.drawable.wind_white;
case CODE_PARTLY_SUNNY:
return color == COLOR_DARK ? R.drawable.partly_sunny_dark : color == COLOR_GRAY ? R.drawable.partly_sunny_grey : R.drawable.partly_sunny_white;
default:
return color == COLOR_DARK ? R.drawable.partly_sunny_dark : color == COLOR_GRAY ? R.drawable.partly_sunny_grey : R.drawable.partly_sunny_white;
}
}
public static int convertWeatherCode(int code)
{
if(code >= 200 && code <= 232)
{
return CODE_STORM;
}
else if((code >= 300 && code <= 321) || (code >= 520 && code <= 531))
{
return CODE_RAIN_CLOUD;
}
else if(code >= 500 && code <= 504)
{
return CODE_PARTLY_RAINY;
}
else if(code == 511 || code == 906)
{
return CODE_HAIL;
}
else if(code >= 600 && code <= 622)
{
return CODE_SNOW;
}
else if(code >= 701 && code <= 771)
{
return CODE_FOG;
}
else if(code == 781 || (code >= 900 && code <= 902) || (code >= 960 && code <= 962))
{
return CODE_TORNADO;
}
else if(code == 800 || code == 951)
{
return CODE_SUN;
}
else if(code == 801)
{
return CODE_PARTLY_SUNNY;
}
else if(code >= 802 && code <= 804)
{
return CODE_CLOUD;
}
else if(code == 903)
{
return CODE_LOW_TEMP;
}
else if(code == 904)
{
return CODE_HIGH_TEMP;
}
else if(code == 905 || (code >= 952 && code <= 959))
{
return CODE_WIND;
}
else
{
return CODE_PARTLY_SUNNY;
}
}
}
| true
|
d8240c9e4c4127d4d55cd6a5af2cb1daa234122f
|
Java
|
LMurphy186232/JavaWrapper
|
/src/sortie/data/simpletypes/DetailedOutputSettings.java
|
UTF-8
| 7,773
| 2.9375
| 3
|
[] |
no_license
|
package sortie.data.simpletypes;
import java.util.ArrayList;
/**
* Base class for detailed output settings.
* <p>Copyright: Copyright (c) Charles D. Canham 2003</p>
* <p>Company: Cary Institute of Ecosystem Studies</p>
* @author Lora E. Murphy
* @version 1.0
*
* <br>Edit history:
* <br>------------------
* <br>April 28, 2004: Submitted in beta version (LEM)
* <br>February 4, 2008: Updated to conform to Java 6 compliance (LEM)
*/
public class DetailedOutputSettings {
/**Vector of DataMembers representing floats*/
protected ArrayList<DataMember> mp_oFloats = new ArrayList<DataMember>(0),
/**Vector of DataMembers representing ints*/
mp_oInts = new ArrayList<DataMember>(0),
/**Vector of DataMembers representing chars*/
mp_oChars = new ArrayList<DataMember>(0),
/**Vector of DataMembers representing bools*/
mp_oBools = new ArrayList<DataMember>(0);
protected int m_iSaveFreq = 0; /**<Save frequency, in timesteps*/
/**
* Gets the save frequency.
* @return Save frequency, in timesteps.
*/
public int getSaveFrequency() {
return m_iSaveFreq;
}
/**
* Sets the save frequency.
* @param i Save frequency, in timesteps.
*/
public void setSaveFrequency(int i) {
m_iSaveFreq = i;
}
/**
* Add a new float data member. If it already exists it won't be added again.
* @param sCodeName Code name.
* @param sDisplayName Display name.
*/
public void addFloat(String sCodeName, String sDisplayName) {
try {
DataMember oNewDataMember = new DataMember(sDisplayName, sCodeName,
DataMember.FLOAT);
int i;
for (i = 0; i < mp_oFloats.size(); i++) {
if (oNewDataMember.equals(mp_oFloats.get(i))) {
return;
}
}
mp_oFloats.add(oNewDataMember);
} catch (ModelException oErr) {
;
}
}
/**
* Add a new int data member. If it already exists it won't be added again.
* @param sCodeName Code name.
* @param sDisplayName Display name.
*/
public void addInt(String sCodeName, String sDisplayName) {
try {
DataMember oNewDataMember = new DataMember(sDisplayName, sCodeName,
DataMember.INTEGER);
int i;
for (i = 0; i < mp_oInts.size(); i++) {
if (oNewDataMember.equals(mp_oInts.get(i))) {
return;
}
}
mp_oInts.add(oNewDataMember);
} catch (ModelException oErr) {
;
}
}
/**
* Add a new bool data member. If it already exists it won't be added again.
* @param sCodeName Code name.
* @param sDisplayName Display name.
*/
public void addBool(String sCodeName, String sDisplayName) {
try {
DataMember oNewDataMember = new DataMember(sDisplayName, sCodeName,
DataMember.BOOLEAN);
int i;
for (i = 0; i < mp_oBools.size(); i++) {
if (oNewDataMember.equals(mp_oBools.get(i))) {
return;
}
}
mp_oBools.add(oNewDataMember);
} catch (ModelException oErr) {
;
}
}
/**
* Add a new char data member. If it already exists it won't be added again.
* @param sCodeName Code name.
* @param sDisplayName Display name.
*/
public void addChar(String sCodeName, String sDisplayName) {
try {
DataMember oNewDataMember = new DataMember(sDisplayName, sCodeName,
DataMember.CHAR);
int i;
for (i = 0; i < mp_oChars.size(); i++) {
if (oNewDataMember.equals(mp_oChars.get(i))) {
return;
}
}
mp_oChars.add(oNewDataMember);
} catch (ModelException oErr) {
;
}
}
/**
* Get the number of float data members.
* @return Number of data members.
*/
public int getNumberOfFloats() {
return mp_oFloats.size();
}
/**
* Get the number of int data members.
* @return Number of data members.
*/
public int getNumberOfInts() {
return mp_oInts.size();
}
/**
* Get the number of char data members.
* @return Number of data members.
*/
public int getNumberOfChars() {
return mp_oChars.size();
}
/**
* Get the number of bool data members.
* @return Number of data members.
*/
public int getNumberOfBools() {
return mp_oBools.size();
}
/**
* Removes an integer data member.
* @param i int Index of data member to remove.
*/
public void removeInt(int i){
if (i < 0 || i > mp_oInts.size() - 1) {
return;
}
mp_oInts.remove(i);
}
/**
* Removes a float data member.
* @param i int Index of data member to remove.
*/
public void removeFloat(int i){
if (i < 0 || i > mp_oFloats.size() - 1) {
return;
}
mp_oFloats.remove(i);
}
/**
* Removes a boolean data member.
* @param i int Index of data member to remove.
*/
public void removeBool(int i){
if (i < 0 || i > mp_oBools.size() - 1) {
return;
}
mp_oBools.remove(i);
}
/**
* Removes a char data member.
* @param i int Index of data member to remove.
*/
public void removeChar(int i){
if (i < 0 || i > mp_oChars.size() - 1) {
return;
}
mp_oChars.remove(i);
}
/**
* Gets a float data member
* @param iIndex of the float data member
* @return The data member
*/
public DataMember getFloat(int iIndex) {
if (iIndex >= mp_oFloats.size() || iIndex < 0) {
return null;
}
return mp_oFloats.get(iIndex);
}
/**
* Get the label of an int data member
* @param iIndex of the int data member
* @return The data member
*/
public DataMember getInt(int iIndex) {
if (iIndex >= mp_oInts.size() || iIndex < 0) {
return null;
}
return mp_oInts.get(iIndex);
}
/**
* Get the label of a char data member
* @param iIndex of the char data member
* @return The data member
*/
public DataMember getChar(int iIndex) {
if (iIndex >= mp_oChars.size() || iIndex < 0) {
return null;
}
return mp_oChars.get(iIndex);
}
/**
* Gets a bool data member
* @param iIndex of the bool data member
* @return The data member
*/
public DataMember getBool(int iIndex) {
if (iIndex >= mp_oBools.size() || iIndex < 0) {
return null;
}
return mp_oBools.get(iIndex);
}
/**
* Copies data members from one DetailedOutputSettings object to another. This
* can be used to create deep clones.
* @param oCopyTarget Object to which to copy settings
* @param oCopySource Object from which to copy settings.
*/
public static void copyData(DetailedOutputSettings oCopyTarget,
DetailedOutputSettings oCopySource) {
if (oCopyTarget == null || oCopySource == null) {
return;
}
int j;
DataMember oMember;
oCopyTarget.setSaveFrequency(oCopySource.getSaveFrequency());
oCopyTarget.mp_oFloats.clear();
oCopyTarget.mp_oBools.clear();
oCopyTarget.mp_oInts.clear();
oCopyTarget.mp_oChars.clear();
for (j = 0; j < oCopySource.mp_oFloats.size(); j++) {
oMember = oCopySource.mp_oFloats.get(j);
oCopyTarget.mp_oFloats.add( (DataMember) oMember.clone());
}
for (j = 0; j < oCopySource.mp_oInts.size(); j++) {
oMember = oCopySource.mp_oInts.get(j);
oCopyTarget.mp_oInts.add( (DataMember) oMember.clone());
}
for (j = 0; j < oCopySource.mp_oChars.size(); j++) {
oMember = oCopySource.mp_oChars.get(j);
oCopyTarget.mp_oChars.add( (DataMember) oMember.clone());
}
for (j = 0; j < oCopySource.mp_oBools.size(); j++) {
oMember = oCopySource.mp_oBools.get(j);
oCopyTarget.mp_oBools.add( (DataMember) oMember.clone());
}
}
}
| true
|
3760707d6303858c328b9d3470600dc54dc5692b
|
Java
|
wh1t3p1g/ysomap
|
/core/src/main/java/ysomap/bullets/groovy/ClosureWithTemplatesImplBullet.java
|
UTF-8
| 1,774
| 2.296875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ysomap.bullets.groovy;
import org.codehaus.groovy.runtime.MethodClosure;
import ysomap.bullets.AbstractBullet;
import ysomap.bullets.Bullet;
import ysomap.bullets.jdk.TemplatesImplBullet;
import ysomap.common.annotation.*;
import ysomap.core.util.DetailHelper;
/**
* @author wh1t3p1g
* @since 2021/8/6
*/
@Bullets
@Dependencies({"org.codehaus.groovy:groovy:2.4.3"})
@Details("任意代码执行")
@Targets({Targets.JDK})
@Authors({Authors.WH1T3P1G})
public class ClosureWithTemplatesImplBullet extends AbstractBullet<Object> {
@NotNull
@Require(name = "body" ,detail = DetailHelper.BODY)
private String body = "";
@NotNull
@Require(name = "effect", type = "string", detail="选择载入payload的效果," +
"可选default、" +
"TomcatEcho、SocketEcho、RemoteFileLoader、WinC2Loader、MSFJavaC2Loader、" +
"RemoteFileHttpLoader、RemoteFileHttpExecutor、DnslogLoader、RunClassLoader")
private String effect = "default";
@Require(name = "exception", type = "boolean", detail = "是否需要以抛异常的方式返回执行结果,默认为false")
private String exception = "false";
@Override
public Object getObject() throws Exception {
Bullet bullet = TemplatesImplBullet.newInstance(body, effect, exception);
return new MethodClosure(bullet.getObject(), "getOutputProperties");
}
public static ClosureWithTemplatesImplBullet newInstance(Object... args) throws Exception {
ClosureWithTemplatesImplBullet bullet = new ClosureWithTemplatesImplBullet();
bullet.set("type", args[0]);
bullet.set("body", args[1]);
bullet.set("effect", args[2]);
bullet.set("exception", args[3]);
return bullet;
}
}
| true
|
7f22848825c2fbfd67b025b556a5b96e04011855
|
Java
|
codemky/uni
|
/src/main/java/edu/uni/userBaseInfo1/service/MySecondLevelDisciplineService.java
|
UTF-8
| 2,185
| 2.03125
| 2
|
[] |
no_license
|
package edu.uni.userBaseInfo1.service;
import com.github.pagehelper.PageInfo;
import edu.uni.professionalcourses.bean.SecondLevelDiscipline;
import java.util.List;
public interface MySecondLevelDisciplineService {
/**
* Author: chenenru 23:59 2019/4/29
* @param
* @return List<SecondLevelDiscipline>
* @apiNote: 查询所有的二级学科
*/
List<SecondLevelDiscipline> selectAllSecondLevelDisciplines();
/**
* Author: chenenru 0:00 2019/4/30
* @param id
* @return SecondLevelDiscipline
* @apiNote: 根据id查询二级学科
*/
SecondLevelDiscipline selectSecondLevelDisciplineById(long id);
/**
* Author: chenenru 0:00 2019/4/30
* @param pageNum
* @return PageInfo<SecondLevelDiscipline>
* @apiNote: 分页查询二级学科
*/
PageInfo<SecondLevelDiscipline> selectSecondLevelDisciplineByPage(int pageNum);
/**
* Author: chenenru 0:00 2019/4/30
* @param SecondLevelDiscipline
* @return boolean
* @apiNote: 二级学科添加SecondLevelDiscipline表的一条记录
*/
boolean insertSecondLevelDiscipline(SecondLevelDiscipline SecondLevelDiscipline);
/**
* Author: chenenru 0:00 2019/4/30
* @param SecondLevelDiscipline
* @return boolean
* @apiNote: 用户更新一个SecondLevelDiscipline表的某个记录(传一个新的对象)
*/
boolean updateSecondLevelDiscipline(SecondLevelDiscipline SecondLevelDiscipline);
/**
* Author: chenenru 0:00 2019/4/30
* @param id
* @return boolean
* @apiNote: 用于删除SecondLevelDiscipline表的某个记录
*/
boolean deleteSecondLevelDiscipline(long id);
/**
* Author: laizhouhao 20:56 2019/5/15
* @param id
* @return SecondLevelDiscipline
* @apiNote: 根据id获取有效的二级学科信息
*/
SecondLevelDiscipline selectValidSecondLevelDisciplineById(Long id);
/**
* Author: mokuanyuan 16:30 2019/6/27
* @param name
* @return List<SecondLevelDiscipline>
* @apiNote 根据名称模糊搜索二级学科
*/
List<SecondLevelDiscipline> selectByName(String name);
}
| true
|
7f832bcf54a9165da7ad9b1eb97dd1076985c7cb
|
Java
|
wnifirami/YtsMovies
|
/app/src/main/java/com/example/macprosam/ytsmovies/DetailActivity.java
|
UTF-8
| 1,950
| 2.09375
| 2
|
[] |
no_license
|
package com.example.macprosam.ytsmovies;
import android.animation.ObjectAnimator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
ProgressBar mprogressBar;
TextView ratevalue,overview,summary,movieyear,moviename,movietag;
Double ratingval = 0.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ImageView mPlace = findViewById(R.id.imageView);
overview = findViewById(R.id.overview);
summary = findViewById(R.id.sum);
moviename = findViewById(R.id.moviename);
movieyear = findViewById(R.id.movieyear);
movietag = findViewById(R.id.tag);
Bundle mBundle = getIntent().getExtras();
if(mBundle != null){
// mPlace.setImageResource(mBundle.getInt("Image"));
Picasso.with(getApplicationContext()).load(mBundle.getString("Image")).into(mPlace);
ratingval = mBundle.getDouble("rate");
}
overview.setText(mBundle.getString("overview"));
summary.setText(mBundle.getString("desc"));
moviename.setText(mBundle.getString("Title"));
movieyear.setText(mBundle.getInt("year")+"");
movietag.setText(mBundle.getString("tags"));
ratevalue=findViewById(R.id.ratevalue);
ratevalue.setText(ratingval+"");
mprogressBar = (ProgressBar) findViewById(R.id.circular_progress_bar);
ObjectAnimator anim = ObjectAnimator.ofInt(mprogressBar, "progress", 0, (int)Math.round(ratingval*10) );
anim.setDuration(1500);
anim.setInterpolator(new DecelerateInterpolator());
anim.start();
}
}
| true
|
1cdee80f96c204c1997e181d6f4abe74a5ef4b88
|
Java
|
SuperLiL/diff
|
/src/main/java/com/web/controller/DiffController.java
|
UTF-8
| 14,029
| 2.15625
| 2
|
[] |
no_license
|
package com.web.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.web.interceptor.Diffintercept;
import com.web.pojo.DiffPostParams;
import com.web.response.ResultGenerator;
import com.web.service.DiffService;
import com.web.util.DiffTools;
import com.web.util.ResponseApi;
import com.web.response.Result;
import com.web.util.SSRFChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/diff")
public class DiffController {
ResponseApi responseApi = new ResponseApi();
SSRFChecker ssrfChecker = new SSRFChecker();
@Autowired
private DiffService diffService;
@Autowired
private DiffTools diffTools;
// 页面请求跳转
@RequestMapping("/diff")
public String requestForward() {
return "test";
}
@RequestMapping("/diffbody")
public String requestForwardbody() {
return "test1";
}
/**
* Get请求- 调用service服务对比结果,将结果标准化输出
*
* @param requestUrl
* @return
* @RequestParam暂时使用两个,分别表示两个已经拼接好的URL请求,若有参数拼接还可以进行分析
*/
@Diffintercept()
@RequestMapping(value = "/check", method = RequestMethod.GET)
@ResponseBody
public Result byJsonMethod(
@RequestParam("requestUrl") String requestUrl,
@RequestParam("requestUrl2") String requestUrl2,
@RequestParam(required = false, defaultValue = "") String params1,
@RequestParam(required = false, defaultValue = "") String params2,
@RequestParam(required = false, defaultValue = "") String headers1,
@RequestParam(required = false, defaultValue = "") String headers2,
@RequestParam(required = false, defaultValue = "") String userCookies1,
@RequestParam(required = false, defaultValue = "") String userCookies2,
HttpServletRequest request) {
/*int error = (int)request.getAttribute("error");
if(error==1){
return ResultGenerator.genFailedResult("疑似请求非法数据,请联系管理员核实");
}*/
Map<String, String> param1;
Map<String, String> param2;
Map<String, String> header1;
Map<String, String> header2;
Map<String, String> userCookie1;
Map<String, String> userCookie2;
try {
param1 = parameterNormalization(params1);
param2 = parameterNormalization(params2);
header1 = parameterNormalization(headers1);
header2 = parameterNormalization(headers2);
userCookie1 = parameterNormalization(userCookies1);
userCookie2 = parameterNormalization(userCookies2);
} catch (Exception e) {
System.out.println(e);
return ResultGenerator.genFailedResult("请求参数数据不合法,请检查后输入");
}
//将前端的复合参数转为map集合封装到对应的request请求。
try {
requestUrl = URLDecoder.decode(requestUrl, "UTF-8");
requestUrl2 = URLDecoder.decode(requestUrl2, "UTF-8");
/*boolean b1 = ssrfChecker.checkURL(requestUrl);
boolean b2 = ssrfChecker.checkURL(requestUrl2);
if(!b1||!b2) {
return ResultGenerator.genFailedResult("Bad IP~ Error");
}*/
String response_body1 = responseApi.Get(requestUrl, param1, header1, userCookie1);
String response_body2 = responseApi.Get(requestUrl2, param2, header2, userCookie2);
return resultByString(response_body1, response_body2);
} catch (Exception e) {
return ResultGenerator.genFailedResult("对比过程中出现错误,请重试");
}
}
public Result illegalDataRequest(){
return ResultGenerator.genFailedResult("疑似请求非法数据,请联系管理员核实");
}
/**
* 接收前端传递的初始数据处理,将处理结果map集合返回。
*
* @param param
* @return
*/
public Map<String, String> parameterNormalization(String param) {
Map<String, String> paramMap = new HashMap<>();
//若为空,初始化为null
if (param.isEmpty()) {
paramMap = null;
} else if (param.charAt(0) == '{') { //在这里判断参数是如何传递到后端的--1、json-{"":"","":""}类型;2、字符串(页面展示key=value;这种类型)
paramMap = JSONObject.parseObject(param, Map.class);
} else {
String[] keyValues = param.split(";");
for (int i = 0; i < keyValues.length; i++) {
String[] key_value = keyValues[i].split("=");
String key = key_value[0];
String value = key_value[1];
paramMap.put(key, value);
}
}
return paramMap;
}
/**
* 传入string的转为JsonObject
*
* @param response_body1
* @param response_body2
* @return
*/
public Result resultByString(String response_body1, String response_body2) {
try {
int status1 = diffTools.verificationBykey(response_body1);
int status2 = diffTools.verificationBykey(response_body2);
if (status1 != 1 && status1 != 2 || status1 != status2 || status2 != 1 && status2 != 2) {
return ResultGenerator.genFailedResult("请求数据中含有不合法数据,请检查后输入");
}
if (status1 == 2) {
/*JSONObject.parseObject(response_body1, SerializerFeature.WRITE_MAP_NULL_FEATURES);
net.sf.json.JSONObject jsonObjectss = net.sf.json.JSONObject.fromObject(response_body2);*/
JSONObject jsonObject1 = JSONObject.parseObject(response_body1);
JSONObject jsonObject2 = JSONObject.parseObject(response_body2);
//2019.8.12
JSONObject resultByJson = diffService.getResultByJson(jsonObject1, jsonObject2);
if (resultByJson.getJSONObject("diff").size() >= 1) {
return ResultGenerator.genOkResult(resultByJson, "两个接口返回值不一致");
} else {
return ResultGenerator.genOkResult(resultByJson);
}
} else {
JSONArray jsonArray1 = JSONArray.parseArray(response_body1);
JSONArray jsonArray2 = JSONArray.parseArray(response_body2);
JSONObject resultByJson = diffService.getResultByJson(jsonArray1, jsonArray2);
if (resultByJson.getJSONObject("diff").size() >= 1) {
return ResultGenerator.genOkResult(resultByJson, "两个接口返回值不一致");
} else {
return ResultGenerator.genOkResult(resultByJson);
}
}
} catch (Exception e) {
return ResultGenerator.genFailedResult("请求数据不合法,请检查后输入");
}
}
/**
* Post请求-调用service服务对比结果,将结果标准化输出
*
* @param requestUrl
* @return
* @RequestParam
*/
@Diffintercept()
@RequestMapping(value = "/check", method = RequestMethod.POST)
@ResponseBody
public Result byJsonMethodPost(
@RequestParam("requestUrl") String requestUrl,
@RequestParam("requestUrl2") String requestUrl2,
@RequestParam(required = false, defaultValue = "") String params1,
@RequestParam(required = false, defaultValue = "") String params2,
@RequestParam(required = false, defaultValue = "") String headers1,
@RequestParam(required = false, defaultValue = "") String headers2,
@RequestParam(required = false, defaultValue = "") String userCookies1,
@RequestParam(required = false, defaultValue = "") String userCookies2,
HttpServletRequest request) {
int error = (int)request.getAttribute("error");
if(error==1){
return ResultGenerator.genFailedResult("疑似请求非法数据,请联系管理员核实");
}
Map<String, String> param1;
Map<String, String> param2;
Map<String, String> header1;
Map<String, String> header2;
Map<String, String> userCookie1;
Map<String, String> userCookie2;
try {
param1 = parameterNormalization(params1);
param2 = parameterNormalization(params2);
header1 = parameterNormalization(headers1);
header2 = parameterNormalization(headers2);
userCookie1 = parameterNormalization(userCookies1);
userCookie2 = parameterNormalization(userCookies2);
} catch (Exception e) {
return ResultGenerator.genFailedResult("请求参数数据不合法,请检查后输入");
}
//将前端的复合参数转为map集合封装到对应的request请求。
try {
requestUrl = URLDecoder.decode(requestUrl, "UTF-8");
requestUrl2 = URLDecoder.decode(requestUrl2, "UTF-8");
/* boolean b1 = ssrfChecker.checkURL(requestUrl);
boolean b2 = ssrfChecker.checkURL(requestUrl2);
if(!b1||!b2) {
return ResultGenerator.genFailedResult("Bad IP~ Error");
}*/
String response_body1 = responseApi.Post(requestUrl, param1, header1, userCookie1);
String response_body2 = responseApi.Post(requestUrl2, param2, header2, userCookie2);
return resultByString(response_body1, response_body2);
} catch (Exception e) {
return ResultGenerator.genFailedResult("请求参数数据不合法,请检查后输入");
}
}
/**
* 直接传入String的情况
* 1、普通字符串""情况
* 2、JsonObject转为String的情况 {"":""}
* 3、JsonArrary转为String情况[ , , ,]。
*
* @param requestBody1
* @return
* @RequestParam
*/
@Diffintercept()
@RequestMapping(value = "/checkByString",method = RequestMethod.GET)
@ResponseBody
public Result byJsonMethodString(
@RequestParam("requestBody1") String requestBody1,
@RequestParam("requestBody2") String requestBody2) {
try {
return resultByString(requestBody1, requestBody2);
} catch (Exception e) {
return ResultGenerator.genFailedResult("请求参数数据不合法,请检查后输入");
}
}
/**
* 直接传入jsonObject的情况。
*
* @param
* @return
*
*/
@RequestMapping(value = "/checkByStringTest",method = RequestMethod.POST)
@ResponseBody
public Result byJsonMethodString(
@RequestBody DiffPostParams diffPostParams) {
try {
JSONObject resultByJson = diffService.getResultByJson(diffPostParams.getRequestBody1(), diffPostParams.getRequestBody2());
if (resultByJson.getJSONObject("diff").size() >= 1) {
return ResultGenerator.genOkResult(resultByJson, "两个接口返回值不一致");
} else {
return ResultGenerator.genOkResult(resultByJson);
}
//return resultByString(diffPostParams.getRequestBody1().toString(), diffPostParams.getRequestBody2().toString());
} catch (Exception e) {
e.printStackTrace();
return ResultGenerator.genFailedResult("请求参数数据不合法,请检查后输入");
}
}
/**
* 直接传入jsonObject的情况。
* 在这里并没有过多的考虑传入是否为JsonObject、JsonArray、普通字符串,主要是考虑到diff主要目的。
* @param
* @return
*
*/
@RequestMapping(value = "/checkByStringPost",method = RequestMethod.POST)
@ResponseBody
public Result byJsonMethodStringss(
@RequestBody DiffPostParams diffPostParams) {
try{
/* JSONObject requestBody2 = diffPostParams.getRequestBody2();
String sq = requestBody2.toString(SerializerFeature.WriteMapNullValue);
String s2 = diffPostParams.getRequestBody2().toString();
System.out.println("s2"+s2+"---"+sq);
System.out.println(diffPostParams.getRequestBody2());*/
//2019.8.12解决了在Json转为String出现的忽视null字段的问题。SerializerFeature.WriteMapNullValue
return resultByString(diffPostParams.getRequestBody1().toString(), diffPostParams.getRequestBody2().toString());
} catch (Exception e) {
return ResultGenerator.genFailedResult("请求参数数据不合法,请检查后输入");
}
}
@RequestMapping(value = "/checkByStringPosttest",method = RequestMethod.POST)
@ResponseBody
public Result byJsonMethodStringss2(
@RequestBody String requestBody1,
@RequestBody String requestBody2) {
try{
/* JSONObject requestBody2 = diffPostParams.getRequestBody2();
String sq = requestBody2.toString(SerializerFeature.WriteMapNullValue);
String s2 = diffPostParams.getRequestBody2().toString();
System.out.println("s2"+s2+"---"+sq);
System.out.println(diffPostParams.getRequestBody2());*/
//2019.8.12解决了在Json转为String出现的忽视null字段的问题。
return resultByString(requestBody1,requestBody2);
} catch (Exception e) {
return ResultGenerator.genFailedResult("请求参数数据不合法,请检查后输入");
}
}
}
| true
|
77301c6afba0135fe75b252aa97e3cae603f477a
|
Java
|
flamestro/openwhisk-devtools
|
/java-local/src/test/java/openwhisk/java/local/test/LauncherTest.java
|
UTF-8
| 3,529
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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 openwhisk.java.local.test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
import com.google.gson.JsonObject;
import openwhisk.java.local.Launcher;
/**
* LauncherTest
*/
public class LauncherTest {
@Test
public void testLauncherParameters(){
Launcher launcher = new Launcher();
final Path binaryPath = Paths.get("/");
assertNull(launcher.getBinaryPath());
launcher.setBinaryPath(binaryPath);
assertTrue(launcher.getBinaryPath().isAbsolute());
final String className = "clazzname";
assertNull(launcher.getEntryClassName());
launcher.setEntryClassName(className);
assertSame(className, launcher.getEntryClassName());
final JsonObject param = new JsonObject();
assertNull(launcher.getParameter());
launcher.setParameter(param);
assertSame(param, launcher.getParameter());
}
@Test(expected=IllegalStateException.class)
public void testLaunchJarNoMain() throws Exception{
Launcher launcher = new Launcher();
Path jarPath = Paths.get("someJar.jar");
System.out.println(jarPath.toAbsolutePath().toString());
launcher.setBinaryPath(jarPath);
launcher.launch();
fail();
}
@Test
public void testRelativePathForJavaFile() throws Exception{
Launcher launcher = new Launcher();
Path filePath = Paths.get("./src/test/resources/aproject/App.java");
launcher.setBinaryPath(filePath);
JsonObject result = launcher.launch();
assertNotNull(result);
}
@Test
public void testAbsolutePathForJavaFile() throws Exception{
Launcher launcher = new Launcher();
Path filePath = Paths.get("./src/test/resources/aproject/App.java");
launcher.setBinaryPath(filePath.toRealPath());
JsonObject result = launcher.launch();
assertNotNull(result);
}
@Test
public void testAbsolutePathForJarLaunch() throws Exception{
Launcher launcher = new Launcher();
Path jarPath = Paths.get("./src/test/resources/serverlessJava.jar");
launcher.setBinaryPath(jarPath.toRealPath());
launcher.setEntryClassName("aproject.App");
JsonObject result = launcher.launch();
assertNotNull(result);
}
@Test
public void testRelativePathForJarLaunch() throws Exception{
Launcher launcher = new Launcher();
Path jarPath = Paths.get("./src/test/resources/serverlessJava.jar");
launcher.setBinaryPath(jarPath);
launcher.setEntryClassName("aproject.App");
JsonObject result = launcher.launch();
assertNotNull(result);
}
}
| true
|
cdcc28781c7e69d7a8d5836269f34419cb072d3f
|
Java
|
ananghanafi/CobMNN
|
/app/src/main/java/com/masbi/cobmnn/Daftar.java
|
UTF-8
| 2,555
| 2.21875
| 2
|
[] |
no_license
|
package com.masbi.cobmnn;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Daftar extends AppCompatActivity {
EditText nama, username, alamat, email, no_hp, password;
String str_nama, str_username, str_alamat, str_email, str_no_hp, str_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daftar);
nama = (EditText) findViewById(R.id.nama);
username = (EditText) findViewById(R.id.username);
alamat = (EditText) findViewById(R.id.alamat);
email = (EditText) findViewById(R.id.email);
no_hp = (EditText) findViewById(R.id.telp);
password = (EditText) findViewById(R.id.password);
}
public void daftarMain(View view) {
str_nama = nama.getText().toString();
str_username = username.getText().toString();
str_alamat = alamat.getText().toString();
str_email = email.getText().toString();
str_no_hp = no_hp.getText().toString();
str_password = password.getText().toString();
String tipe = "daftar";
if (str_nama.equals("") || str_email.equals("") || str_alamat.equals("") || str_no_hp.equals("") || str_username.equals("") || str_password.equals("")) {
Toast.makeText(Daftar.this, "Harus terisi semua", Toast.LENGTH_LONG).show();
return;
} else if (str_username.length() <= 3 || password.length() <= 3) {
Toast.makeText(Daftar.this, "Username atau password harus lebih dari 3 karakter", Toast.LENGTH_LONG).show();
return;
}else{
BackgroundWorkerReg backgroundWorkerReg = new BackgroundWorkerReg(this);
backgroundWorkerReg.execute(tipe, str_nama, str_username, str_alamat, str_email, str_no_hp, str_password);
System.out.println("onDaftar sfldjf;jf;sjfsjf;sjf;sfj;s");
}
}
}
| true
|
cb9845a274444dd81031edd1343e193554191a5e
|
Java
|
rktoledo/KEBA
|
/KEBA_Interface/src/dbObjects/LoadingData.java
|
UTF-8
| 4,158
| 2.40625
| 2
|
[] |
no_license
|
package dbObjects;
import java.io.Serializable;
import java.time.LocalDateTime;
import org.json.simple.JSONObject;
public class LoadingData implements Serializable{
private static final long serialVersionUID = 1L;
private int loadID;
private int sessionID;
private int loadTime;
private int loadedEnergy;
private boolean isComplete;
private boolean isUsable;
private boolean isSessionIDSet;
private boolean isLoadFileAvailable;
private String loadFilePath;
private JSONObject loadFile;
private boolean isStateFileAvailable;
private String stateFilePath;
private JSONObject stateFile;
private LocalDateTime startDateTime;
private LocalDateTime endDateTime;
public LoadingData(){
}
public LoadingData(int loadID, int sessionID, LocalDateTime startDateTime, LocalDateTime endDateTime,
int loadTime, JSONObject loadFile, JSONObject stateFile, boolean isComplete, boolean isUsable, int loadedEnergy,
Boolean isSessionIDSet){
this.loadID= loadID;
this.sessionID= sessionID;
this.loadTime= loadTime;
this.isComplete= isComplete;
this.isUsable= isUsable;
this.loadedEnergy= loadedEnergy;
this.startDateTime= startDateTime;
this.endDateTime= endDateTime;
this.loadFile= loadFile;
this.stateFile= stateFile;
this.setSessionIDSet(isSessionIDSet);
}
public int getLoadID() {
return loadID;
}
public int getSessionID() {
return sessionID;
}
public int getLoadTime() {
return loadTime;
}
public int getLoadedEnergy() {
return loadedEnergy;
}
public boolean isComplete() {
return isComplete;
}
public boolean isUsable() {
return isUsable;
}
public boolean isLoadFileAvailable() {
return isLoadFileAvailable;
}
public JSONObject getLoadFile() {
return loadFile;
}
public boolean isStateFileAvailable() {
return isStateFileAvailable;
}
public JSONObject getStateFile() {
return stateFile;
}
public LocalDateTime getStartDateTime() {
return startDateTime;
}
/*public String getStartDateTimeString() {
return startDateTime;
}*/
public LocalDateTime getEndDateTime() {
return endDateTime;
}
public void setLoadID(int loadID) {
this.loadID = loadID;
}
public void setSessionID(int sessionID) {
this.sessionID = sessionID;
}
public void setLoadTime(int loadTime) {
this.loadTime = loadTime;
}
public void setLoadedEnergy(int loadedEnergy) {
this.loadedEnergy = loadedEnergy;
}
public void setComplete(boolean isComplete) {
this.isComplete = isComplete;
}
public void setUsable(boolean isUsable) {
this.isUsable = isUsable;
}
public void setLoadFileAvailable(boolean isLoadFileAvailable) {
this.isLoadFileAvailable = isLoadFileAvailable;
}
public String getLoadFilePath() {
return loadFilePath;
}
public void setLoadFilePath(String loadFilePath) {
this.loadFilePath = loadFilePath;
}
public void setLoadFile(JSONObject loadFile) {
this.loadFile = loadFile;
}
public void setStateFileAvailable(boolean isStateFileAvailable) {
this.isStateFileAvailable = isStateFileAvailable;
}
public String getStateFilePath() {
return stateFilePath;
}
public void setStateFilePath(String stateFilePath) {
this.stateFilePath = stateFilePath;
}
public void setStateFile(JSONObject stateFile) {
this.stateFile = stateFile;
}
public void setStartDateTime(LocalDateTime startDateTime) {
this.startDateTime = startDateTime;
}
public void setStartDateTime(String startDateTime) {
this.startDateTime = null;
}
public void setEndDateTime(LocalDateTime endDateTime) {
this.endDateTime = endDateTime;
}
public void setEndDateTime(String endDateTime) {
this.endDateTime = null;
}
public boolean isSessionIDSet() {
return isSessionIDSet;
}
public void setSessionIDSet(boolean isSessionIDSet) {
this.isSessionIDSet = isSessionIDSet;
}
public String toString(int seconds){
int days= seconds/(24*60*60);
seconds= seconds-days*(24*60*60);
int hours= seconds/(60*60);
seconds= seconds-hours*(60*60);
int min= seconds/60;
seconds= seconds-min*60;
String str= days + " days, " + hours + " hours " + min + " minutes " + seconds + " seconds";
return str;
}
}
| true
|
46038bbe1ad74125fd6ab97b33fde73308e32e29
|
Java
|
org-PhoenixFairy/JavaTeachRepostiory
|
/Teach/src/NoteMaker/LibMain.java
|
GB18030
| 1,275
| 3.5
| 4
|
[] |
no_license
|
package NoteMaker;
import java.util.Scanner;
public class LibMain {
/**
*
* @param msg
* StringıʼǣһַԪռһУһнٰͣ
* @param prog
* һRunnableij
*/
public static void NoteMake(String[] msg,Runnable prog){
Scanner sc= new Scanner(System.in);
int i=0;
System.out.println("----ʼӡʼ----");
for(int j=0;j<msg.length;j++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(msg[i]);
}
System.out.println("----ʼǴӡ----");
System.out.println("");
while(true){
System.out.println("Ƿг");
System.out.println("1 ");
System.out.println("0 ");
String sel = sc.nextLine();
try{
i = Integer.parseInt(sel);
if(i == 1){
new Thread(prog).start();;
break;
}else if(i == 0){
System.out.println("--------");
System.exit(0);
}
}catch(Exception e){
System.out.println("10");
continue;
}
}
sc.close();
}
}
| true
|
dc57af0e54ffa1d0a5bffe8e5eed839cac44a0e6
|
Java
|
agaveplatform/science-apis
|
/agave-profiles/profiles-core/src/main/java/org/iplantc/service/profile/model/ProfileSerializer.java
|
UTF-8
| 785
| 2.21875
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package org.iplantc.service.profile.model;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.iplantc.service.profile.exceptions.ProfileException;
import java.io.IOException;
@JsonSerialize(using = ProfileSerializer.class)
public class ProfileSerializer extends JsonSerializer<Profile> {
@Override
public void serialize(Profile profile, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
try {
jsonGenerator.writeRaw(profile.toJSON());
} catch (ProfileException e) {
throw new IOException(e);
}
}
}
| true
|
6a53c14dc129b127df477350ae64ae1788047b86
|
Java
|
subaruwrx/Activity
|
/app/src/main/java/cput/za/ac/ecommerce_clothingapp/factory/DatasourceDAO.java
|
UTF-8
| 444
| 2.09375
| 2
|
[] |
no_license
|
package cput.za.ac.ecommerce_clothingapp.factory;
import java.util.ArrayList;
import cput.za.ac.ecommerce_clothingapp.domain.Address;
/**
* Created by Admin on 2016-06-06.
*/
public interface DatasourceDAO {
public void createAddress(Address address);
public void updateAddress(Address address);
public Address findAddress(Long id);
public void deleteAddress(Address address);
public ArrayList<Address> getAddress();
}
| true
|
227d6a36266f91168668a2d24c81bedf8cd52cb9
|
Java
|
AbhijeetDhillon/Design-1
|
/MinStack.java
|
UTF-8
| 949
| 3.375
| 3
|
[] |
no_license
|
import java.util.Stack;
// Time Complexity :O(n)
// Space Complexity :O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
class MinStack {
Stack<Integer> stack,stack2;
int min;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
stack2 = new Stack<>();
min = Integer.MAX_VALUE;
stack2.push(min);
}
public void push(int x) {
stack.push(x);
if(min>x)
{
min = x;
}
stack2.push(min);
}
public void pop() {
stack.pop();
stack2.pop();
min = stack2.peek();
}
public int top() {
return stack.peek();
}
public int getMin() {
if(!stack2.isEmpty())
{
return min;
}
return -1;
}
}
| true
|
088b3151e1b7e69e3c4c6196fcabffcd43325117
|
Java
|
pentaho/pentaho-chartbeans
|
/src/main/java/org/pentaho/chart/plugin/xml/XmlChartOutput.java
|
UTF-8
| 5,022
| 1.976563
| 2
|
[] |
no_license
|
/*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.chart.plugin.xml;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.pentaho.chart.core.ChartDocument;
import org.pentaho.chart.core.ChartElement;
import org.pentaho.chart.plugin.api.IOutput;
import org.pentaho.chart.plugin.api.PersistenceException;
import org.pentaho.reporting.libraries.xmlns.common.AttributeList;
import org.pentaho.reporting.libraries.xmlns.common.AttributeMap;
import org.pentaho.reporting.libraries.xmlns.writer.XmlWriter;
/**
* Todo: Document Me
*
* @author Thomas Morgner
*/
public class XmlChartOutput implements IOutput
{
private ChartDocument document;
public XmlChartOutput(final ChartDocument document)
{
if (document == null)
{
throw new NullPointerException();
}
this.document = document;
}
public OutputStream persistChart(final OutputStream outputStream,
final OutputTypes fileType, int width, int height) throws PersistenceException
{
try
{
final XmlWriter writer = new XmlWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.writeXmlDeclaration("UTF-8");
final ChartElement chartElement = document.getRootElement();
writeElement(writer, chartElement);
writer.flush();
}
catch (IOException e)
{
throw new PersistenceException(e);
}
return outputStream;
}
private void writeElement(final XmlWriter writer, final ChartElement chartElement)
throws IOException
{
final AttributeList list = createMainAttributes(chartElement, writer, new AttributeList());
writer.writeTag(chartElement.getNamespace(), chartElement.getTagName(), list, XmlWriter.OPEN);
ChartElement child = chartElement.getFirstChildItem();
while (child != null)
{
writeElement(writer, child);
child = child.getNextItem();
}
if (isEmpty(chartElement.getText(), true) == false)
{
writer.writeTextNormalized(chartElement.getText(), false);
}
writer.writeCloseTag();
}
public static boolean isEmpty(final String source, final boolean trim)
{
if (source == null)
{
return true;
}
if (source.length() == 0)
{
return true;
}
if (trim == false)
{
return false;
}
final char[] chars = source.toCharArray();
for (int i = 0; i < chars.length; i++)
{
final char c = chars[i];
if (c > ' ')
{
return false;
}
}
return true;
}
protected AttributeList createMainAttributes(final ChartElement element,
final XmlWriter writer,
final AttributeList attList)
{
if (element == null)
{
throw new NullPointerException();
}
if (writer == null)
{
throw new NullPointerException();
}
if (attList == null)
{
throw new NullPointerException();
}
final AttributeMap map = element.getAttributeMap();
final String[] attributeNamespaces = map.getNameSpaces();
for (int i = 0; i < attributeNamespaces.length; i++)
{
final String namespace = attributeNamespaces[i];
final String[] attributeNames = map.getNames(namespace);
for (int j = 0; j < attributeNames.length; j++)
{
final String name = attributeNames[j];
final Object value = element.getAttribute(namespace, name);
if (value == null)
{
continue;
}
ensureNamespaceDefined(writer, attList, namespace);
attList.setAttribute(namespace, name, String.valueOf(value));
}
}
return attList;
}
private void ensureNamespaceDefined(final XmlWriter writer, final AttributeList attList, final String namespace)
{
if (writer.isNamespaceDefined(namespace) == false &&
attList.isNamespaceUriDefined(namespace) == false)
{
attList.addNamespaceDeclaration("autoGenNs", namespace);
}
}
public Writer persistMap(final Writer outputStream, final String mapName) throws PersistenceException
{
return outputStream;
}
public Object getDrawable()
{
return null;
}
}
| true
|
ad542bfda79466350cd56c0c1e2d29b100a16316
|
Java
|
jonabacke/programieren-1
|
/Blatt_6/Blatt06_1_NeuronaleNetzwerke/Zug.java
|
UTF-8
| 1,732
| 3.75
| 4
|
[] |
no_license
|
/**
* Mit dieser Klasse wird eine Liste (Zug) erstellt die aus mehreren
* Elementen (Wagen ) bestehen kann
*
* @author Jonathan Backes
* @version 31.05.2018
*/
public class Zug
{
private Wagen _lock;
/**
* Im Konstruktor wird das erste Element der Liste erstellt (Lock)
*
* @param string string der im ersten Element gespeichert werden soll
*/
public Zug (String string){
_lock = new Wagen(string);
}
/**
* Mit dieser Methode wird das letzte Elemen t der Liste herausgefunden
*
* @return Wagen letztes Element der Liste
*/
public Wagen getLastWagen(){
Wagen schaffner = _lock;
while (schaffner.getNextWagen() != null){
schaffner = schaffner.getNextWagen();
}
return schaffner;
}
/**
* Diese Methode gibt das erste Element zurück
*
* @return Wagen erstes Element
*/
public Wagen getLock(){
return _lock;
}
/**
* Mit dieser Methode kann ein Element in die Liste hinzugefügt werden
*
* @param string String den das Element beinhalten soll
*/
public void addLast(String string){
Wagen wagon = new Wagen(string);
Wagen lastWagon = getLastWagen();
lastWagon.setNextWagen(wagon);
}
/**
* Mit dieser Methode kann ein Element in die Liste hinzugefügt werden
*
* @param string String den das Element beinhalten soll
* @param bool Booleanwert dass das Element haben soll
*/
public void addLast(String string, boolean bool){
Wagen wagon = new Wagen(string, bool);
Wagen lastWagon = getLastWagen();
lastWagon.setNextWagen(wagon);
}
}
| true
|
61da49e44653ecba420b178872bb33255e0e0f3f
|
Java
|
fx247562340/opscloud-demo
|
/opscloud-common/src/main/java/com/baiyi/opscloud/common/util/RedisKeyUtils.java
|
UTF-8
| 341
| 1.953125
| 2
|
[] |
no_license
|
package com.baiyi.opscloud.common.util;
import com.google.common.base.Joiner;
/**
* @Author baiyi
* @Date 2020/4/7 6:55 下午
* @Version 1.0
*/
public class RedisKeyUtils {
public static String getMyServerTreeKey(int userId,String uuid){
return Joiner.on(":").join("serverTree", "userId", userId, "uuid", uuid);
}
}
| true
|
7f2891b5eb42f59e257e69afd7a9e69273db0691
|
Java
|
bryanwhho/Java-algorithms
|
/LSEMA407/src/LongestMirrorSequence.java
|
UTF-8
| 3,599
| 3.109375
| 3
|
[] |
no_license
|
/*----------------------------------------------------------------
* Author: Bryan Ho
* Written: 09/12/2013
* Last updated: 09/12/2013
*
* Compilation: javac LongestMirrorSequence.java
* Execution: java LongestMirror Sequence [string of char values]
*
*
* % java LongestMirrorSequence ACAGTGTC
*
* Finds the longest mirror sequence in the user-input sequence, prints
* its length, and prints the corresponding mirror sequence.
*----------------------------------------------------------------*/
// PROBLEM: how to find the longest mirror sequence?
// SUB-PROBLEM: how to find the longest mirror sequence for pairs x[i], x[j]?
// ANSWER AND RELATION: find sequence of pairs such that x[i] = x[j], i.e. let
// mirror[i][j] = LMS of x[i]...x[j], i<j.
// Base case: i = j, then mirror[i][i] = 1
// General cases, i != j:
// Case 1: x[i] == x[j], then mirror[i][j] = 2 + mirror[i+1][j-1]
// Case 2: x[i] != x[j], then mirror[i][j] = max{mirror[i+1][j], mirror[i][j-1]}
// RUNNING TIME: since the sub-problems are structured as a matrix-filling
// problem, the running time to fill the matrix is O(n^2).
class LongestMirrorSequence {
public static void main (String[] args) {
if (args.length == 0) {
return;
}
int n = args[0].length();
char[] x = new char[n]; // sequence of characters
for (int i=0; i<n; i++) {
x[i] = args[0].charAt(i);
}
int[][] mirror = new int[n][n];
int[] marker = new int[n]; // record which pairs x[i] = x[j]
for (int i=0; i<n; i++) {
mirror[i][i] = 1; // base case
}
// Subproblems:
for (int j=1; j<n; j++) {
for (int i=j-1; i>=0; i--) {
if (x[i] == x[j]) {
mirror[j][i] = 2 + mirror[j-1][i+1];
} else if(x[i] != x[j]) {
if (mirror[j-1][i] < mirror[j][i+1]) {
mirror[j][i] = mirror[j][i+1];
} else {
mirror[j][i] = mirror[j-1][i];
}
}
}
}
int maxmirror=0;
int start=0;
int end=0;
for (int j=0; j<n; j++) {
for (int i=0; i<n; i++) {
if (maxmirror <= mirror[j][i]) {
maxmirror = mirror[j][i];
start = i;
end = j;
}
}
}
// for (int i=0; i<n; i++) { // matrix printer to check results
// for (int j=0; j<n; j++) {
// System.out.print(mirror[i][j] + " ");
// }
// System.out.println();
// }
outerloop:
for (int i=start; i<end; i++) {
for (int j=end; j>i; j--) {
if (x[i] == x[j]) {
marker[i] = 1;
marker[j] = 1;
if (i+2==j) { // check if x[i] is 2 away from x[j];
marker[i+1]=1; // then there is one element in between
break outerloop;// which should be included
}
}
}
}
System.out.println("length of longest mirror sequence: " + maxmirror);
System.out.print("corresponding sequence: ");
for(int i=start; i<=end; i++) {
if (marker[i] == 1) {
System.out.print(x[i] + " ");
}
}
}
}
| true
|
dd0804b14cbd8041e251929d9f55503a81ff599f
|
Java
|
amrendrabagga/LeetcodeChallenge21
|
/src/main/java/april/week3/Day4_RemoveNthNodeFromEndOfList.java
|
UTF-8
| 1,294
| 3.25
| 3
|
[] |
no_license
|
package april.week3;
import utils.ListNode;
public class Day4_RemoveNthNodeFromEndOfList {
public ListNode removeNthFromEnd(ListNode head, int n) {
int len = 0;
ListNode tmp = head;
while (tmp != null) {
len++;
tmp = tmp.next;
}
if (len == 1) {
return null;
}
int d = len - n + 1;
ListNode prev = null;
tmp = head;
int i = 1;
while (tmp != null) {
if (i == d) {
if (prev == null) {
head = tmp.next;
}
else {
prev.next = tmp.next;
}
break;
}
i++;
prev = tmp;
tmp = tmp.next;
}
return head;
}
public ListNode removeNthFromEndEfficient(ListNode head, int n) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode slow = dummyNode;
ListNode fast = dummyNode;
for (int i=1; i<=n+1; i++) {
fast = fast.next;
}
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyNode.next;
}
}
| true
|
f01ffb5d2e9a602fa04551f936522079300c72bd
|
Java
|
veffhz/library-web-app
|
/library-batch/src/main/java/ru/otus/dao/jpa/BookJpaRepository.java
|
UTF-8
| 349
| 1.867188
| 2
|
[] |
no_license
|
package ru.otus.dao.jpa;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.otus.domain.Book;
import java.util.List;
public interface BookJpaRepository extends JpaRepository<Book, String>, FindAllSupport {
@EntityGraph("bookGraph")
List<Book> findAll();
}
| true
|
a2b523d3700d84ad7b81d8643a9811569ddbed75
|
Java
|
diego1198/ServicioGruas
|
/final/Gruas/src/java/ec/edu/espe/gruasService/service/ServiceResource.java
|
UTF-8
| 6,804
| 2.484375
| 2
|
[] |
no_license
|
/*
* 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 ec.edu.espe.gruasService.service;
import ec.edu.espe.gruasService.model.DBConnect;
import ec.edu.espe.gruasService.model.Service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* @author diego
*/
@Path("Service")
public class ServiceResource {
@Context
private UriInfo context;
/**
* Creates a new instance of ServiceResource
*/
public ServiceResource() {
}
/**
* Retrieves representation of an instance of ec.edu.espe.gruasService.service.ServiceResource
* @return an instance of ec.edu.espe.gruasService.model.Service
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<Service> getJson() {
ArrayList<Service> listServices = new ArrayList<>();
listServices = getall();
return listServices;
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Service byId(@PathParam("id") String id){
Service service = new Service();
service = getById(id);
return service;
}
@GET
@Path("maxId")
@Produces(MediaType.TEXT_PLAIN)
public String byId(){
return getMaxId();
}
@GET
@Path("total/{from}/{to}")
@Produces(MediaType.APPLICATION_JSON)
public String getTotal(@PathParam("from") String from,@PathParam("to") String to){
return String.valueOf(total(from,to));
}
/**
* PUT method for updating or creating an instance of ServiceResource
* @param content representation for the resource
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public void putJson(Service content) {
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String postJson(Service content){
return setService(content);
}
public ArrayList<Service> getall(){
ArrayList<Service> listServices = new ArrayList<>();
DBConnect connect = new DBConnect();
PreparedStatement state;
Service service;
try {
state = connect.getConnection().prepareStatement("SELECT * from service");
ResultSet rs = state.executeQuery();
while (rs.next()) {
service = new Service(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4), rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getFloat(9),rs.getString(11),rs.getString(10));
listServices.add(service);
}
rs.close();
state.close();
} catch (SQLException ex) {
Logger.getLogger(ServiceResource.class.getName()).log(Level.SEVERE, null, ex);
}
return listServices;
}
public Service getById(String id){
Service service = null;
DBConnect connect = new DBConnect();
PreparedStatement state;
try {
state = connect.getConnection().prepareStatement("SELECT * from service where servid = ?");
state.setString(1, id);
ResultSet rs = state.executeQuery();
while (rs.next()) {
service = new Service(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4), rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getFloat(9),rs.getString(11),rs.getString(10));
}
} catch (SQLException ex) {
Logger.getLogger(ServiceResource.class.getName()).log(Level.SEVERE, null, ex);
}
return service;
}
public float total(String from,String to){
float total = 0.0f;
DBConnect connect = new DBConnect();
PreparedStatement state;
try {
state = connect.getConnection().prepareStatement("select sum(servcost) from service where service_date >= ? and service_date <= ?");
state.setString(1, from);
state.setString(2, to);
ResultSet rs = state.executeQuery();
if(rs.next()){
total = rs.getFloat(1);
}
} catch (SQLException ex) {
Logger.getLogger(ServiceResource.class.getName()).log(Level.SEVERE, null, ex);
}
return total;
}
public String setService(Service service){
DBConnect conec = new DBConnect();
String response = "";
try {
Connection con = null;
con = conec.getConnection();
PreparedStatement ps;
ResultSet rs;
ps = con.prepareStatement("INSERT INTO service values(?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, getNextId());
ps.setString(2, service.getServiceDate());
ps.setString(3, service.getServBrand());
ps.setString(4, service.getServModel());
ps.setString(5, service.getServColor());
ps.setString(6, service.getServPlate());
ps.setString(7, service.getServOrig());
ps.setString(8, service.getServDest());
ps.setFloat(9, service.getServCost());
ps.setString(10, service.getServUnity());
ps.setString(11, service.getServDistance());
ps.executeUpdate();
response="Succesfull Save Service";
} catch (Exception e) {
System.out.println(e);
response="Error Save Service";
}
conec.finished();
return response;
}
public String getMaxId(){
DBConnect conec = new DBConnect();
String response = "";
try {
Connection con = null;
con = conec.getConnection();
PreparedStatement ps;
ResultSet rs;
ps = con.prepareStatement("Select max(servid) as maxId from service");
rs = ps.executeQuery();
if(rs.next()){
response = rs.getString(1);
}
} catch (Exception e) {
System.out.println(e);
}
return response;
}
public String getNextId(){
String maxId = getMaxId();
int id = Integer.parseInt(maxId);
id++;
return String.valueOf(id);
}
}
| true
|
a8ff76122df89bc460e476f4ff8b0907ec07bd18
|
Java
|
John-Sawicki/TSI
|
/PowerLoadsActivity.java
|
UTF-8
| 17,843
| 1.726563
| 2
|
[] |
no_license
|
package com.john.android.tsi;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.john.android.tsi.SqliteSum.SumDbHelper;
import com.john.android.tsi.SqliteSum.SumTaskContract;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.john.android.tsi.SqliteSum.SumTaskContract.SummaryEntry;
import com.john.android.tsi.Widget.SummaryService;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
public class PowerLoadsActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private TextView tv_line_total_1, tv_line_total_2,tv_line_total_3, tv_line_total_4,tv_line_total_5, tv_line_total_6,
tv_line_total_7, tv_line_total_8,tv_line_total_9, tv_line_total_10,
tv_total_power_result, tv_total_pdu_result, tv_total_ups_result,tv_breaker_result, tv_total_ups_title;
private EditText et_qty_1, et_watt_1, et_qty_2, et_watt_2, et_qty_3, et_watt_3, et_qty_4, et_watt_4, et_qty_5,
et_watt_5, et_qty_6, et_watt_6, et_qty_7, et_watt_7, et_qty_8, et_watt_8, et_qty_9, et_watt_9, et_qty_10, et_watt_10;
private String pfString ="0.9", pfTitle;
private Button btn_calculate;
private int voltage = 120,spinnerVoltage, powerTotal,intPduSize, breakerSize;
private SQLiteDatabase mDb;
private boolean imperial = true;
@BindView(R.id.adViewBanner) AdView adViewBanner;
@BindView(R.id.sp_source_voltage)Spinner sp_source_voltage;
private static String ACTIVITY = "Power_Loads_Activity";
private double upsSize;
private float powerFactor =0.9f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_power_loads);
ButterKnife.bind(this);
View viewLoads = findViewById(R.id.lo_top_left);
View viewResults = findViewById(R.id.lo_bottom_right);
MobileAds.initialize(this, "ca-app-pub-8686454969066832~6147856904");
AdRequest adRequest = new AdRequest.Builder().build();
adViewBanner.loadAd(adRequest);
tv_total_ups_title = viewResults.findViewById(R.id.tv_total_ups_title);
setUpPreferences();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.voltages,android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_source_voltage.setAdapter(adapter);
sp_source_voltage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinnerVoltage = determineVoltage(i); Log.d(ACTIVITY,"voltage "+voltage);
calculate();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
et_qty_1 = viewLoads.findViewById(R.id.et_qty_1);
et_watt_1 = viewLoads.findViewById(R.id.et_watt_1);
tv_line_total_1 = viewLoads.findViewById(R.id.tv_line_total_1);
et_qty_2 = viewLoads.findViewById(R.id.et_qty_2);
et_watt_2 = viewLoads.findViewById(R.id.et_watt_2);
tv_line_total_2 = viewLoads.findViewById(R.id.tv_line_total_2);
et_qty_3 = viewLoads.findViewById(R.id.et_qty_3);
et_watt_3 = viewLoads.findViewById(R.id.et_watt_3);
tv_line_total_3 = viewLoads.findViewById(R.id.tv_line_total_3);
et_qty_4 = viewLoads.findViewById(R.id.et_qty_4);
et_watt_4 = viewLoads.findViewById(R.id.et_watt_4);
tv_line_total_4 = viewLoads.findViewById(R.id.tv_line_total_4);
et_qty_5 = viewLoads.findViewById(R.id.et_qty_5);
et_watt_5 = viewLoads.findViewById(R.id.et_watt_5);
tv_line_total_5 = viewLoads.findViewById(R.id.tv_line_total_5);
et_qty_6 = viewLoads.findViewById(R.id.et_qty_6);
et_watt_6 = viewLoads.findViewById(R.id.et_watt_6);
tv_line_total_6 = viewLoads.findViewById(R.id.tv_line_total_6);
et_qty_7 = viewLoads.findViewById(R.id.et_qty_7);
et_watt_7 = viewLoads.findViewById(R.id.et_watt_7);
tv_line_total_7 = viewLoads.findViewById(R.id.tv_line_total_7);
et_qty_8 = viewLoads.findViewById(R.id.et_qty_8);
et_watt_8 = viewLoads.findViewById(R.id.et_watt_8);
tv_line_total_8 = viewLoads.findViewById(R.id.tv_line_total_8);
et_qty_9 = viewLoads.findViewById(R.id.et_qty_9);
et_watt_9 = viewLoads.findViewById(R.id.et_watt_9);
tv_line_total_9 = viewLoads.findViewById(R.id.tv_line_total_9);
et_qty_10 = viewLoads.findViewById(R.id.et_qty_10);
et_watt_10 = viewLoads.findViewById(R.id.et_watt_10);
tv_line_total_10 = viewLoads.findViewById(R.id.tv_line_total_10);
tv_total_power_result = viewResults.findViewById(R.id.tv_total_power_result);
tv_total_pdu_result = viewResults.findViewById(R.id.tv_total_pdu_result);
tv_total_ups_result = viewResults.findViewById(R.id.tv_total_ups_result);
tv_breaker_result = viewResults.findViewById(R.id.tv_breaker_result);
btn_calculate = viewResults.findViewById(R.id.btn_calculate);
if(savedInstanceState!=null){
powerTotal =savedInstanceState.getInt("powerTotal",0);
String saveIntText =powerTotal+"W"; tv_total_power_result.setText(saveIntText);
intPduSize = savedInstanceState.getInt("intPduSize",0);
saveIntText =intPduSize+"W"; tv_total_pdu_result.setText(saveIntText);
upsSize =savedInstanceState.getDouble("upsSize",0);
if(upsSize>(int)upsSize) upsSize+=1;//round decimal up
saveIntText= (int)upsSize+"W";
tv_total_ups_result.setText(saveIntText);
breakerSize =savedInstanceState.getInt("breakerSize",0);
if(breakerSize==0) {
tv_breaker_result.setText(R.string.breaker_greater_than_50);
}else{
saveIntText = breakerSize+"A";
tv_breaker_result.setText(saveIntText);
}
}
btn_calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
calculate();
}
});
}
private void calculate(){
int qty1=0, qty2=0, qty3=0, qty4=0, qty5=0, qty6=0, qty7=0, qty8=0, qty9=0, qty10=0,
watt1=0, watt2=0, watt3=0, watt4=0, watt5=0, watt6=0, watt7=0, watt8=0, watt9=0, watt10=0;
if (!TextUtils.isEmpty(et_qty_1.getText().toString())) qty1 = Integer.parseInt(et_qty_1.getText().toString());
if (!TextUtils.isEmpty(et_watt_1.getText().toString())) watt1 = Integer.parseInt(et_watt_1.getText().toString());
if (!TextUtils.isEmpty(et_qty_2.getText().toString())) qty2 = Integer.parseInt(et_qty_2.getText().toString());
if (!TextUtils.isEmpty(et_watt_2.getText().toString())) watt2 = Integer.parseInt(et_watt_2.getText().toString());
if (!TextUtils.isEmpty(et_qty_3.getText().toString())) qty3 = Integer.parseInt(et_qty_3.getText().toString());
if (!TextUtils.isEmpty(et_watt_3.getText().toString())) watt3 = Integer.parseInt(et_watt_3.getText().toString());
if (!TextUtils.isEmpty(et_qty_4.getText().toString())) qty4 = Integer.parseInt(et_qty_4.getText().toString());
if (!TextUtils.isEmpty(et_watt_4.getText().toString())) watt4 = Integer.parseInt(et_watt_4.getText().toString());
if (!TextUtils.isEmpty(et_qty_5.getText().toString())) qty5 = Integer.parseInt(et_qty_5.getText().toString());
if (!TextUtils.isEmpty(et_watt_5.getText().toString())) watt5 = Integer.parseInt(et_watt_5.getText().toString());
if (!TextUtils.isEmpty(et_qty_6.getText().toString())) qty6 = Integer.parseInt(et_qty_6.getText().toString());
if (!TextUtils.isEmpty(et_watt_6.getText().toString())) watt6 = Integer.parseInt(et_watt_6.getText().toString());
if (!TextUtils.isEmpty(et_qty_7.getText().toString())) qty7 = Integer.parseInt(et_qty_7.getText().toString());
if (!TextUtils.isEmpty(et_watt_7.getText().toString())) watt7 = Integer.parseInt(et_watt_7.getText().toString());
if (!TextUtils.isEmpty(et_qty_8.getText().toString())) qty8 = Integer.parseInt(et_qty_8.getText().toString());
if (!TextUtils.isEmpty(et_watt_8.getText().toString())) watt8 = Integer.parseInt(et_watt_8.getText().toString());
if (!TextUtils.isEmpty(et_qty_9.getText().toString())) qty9 = Integer.parseInt(et_qty_9.getText().toString());
if (!TextUtils.isEmpty(et_watt_9.getText().toString())) watt9 = Integer.parseInt(et_watt_9.getText().toString());
if (!TextUtils.isEmpty(et_qty_10.getText().toString())) qty10 = Integer.parseInt(et_qty_10.getText().toString());
if (!TextUtils.isEmpty(et_watt_10.getText().toString())) watt10 = Integer.parseInt(et_watt_10.getText().toString());
int line1 = qty1 *watt1;
String line1String =line1+"W"; tv_line_total_1.setText(line1String);
int line2 = qty2 *watt2;
String line2String =line2+"W"; tv_line_total_2.setText(line2String);
int line3 = qty3 *watt3;
String line3String =line3+"W"; tv_line_total_3.setText(line3String);
int line4 = qty4 *watt4;
String line4String =line4+"W"; tv_line_total_4.setText(line4String);
int line5 = qty5 *watt5;
String line5String =line5+"W"; tv_line_total_5.setText(line5String);
int line6 = qty6 *watt6;
String line6String =line6+"W"; tv_line_total_6.setText(line6String);
int line7 = qty7 *watt7;
String line7String =line7+"W"; tv_line_total_7.setText(line7String);
int line8 = qty8 *watt8;
String line8String =line8+"W"; tv_line_total_8.setText(line8String);
int line9 = qty9 *watt9;
String line9String =line9+"W"; tv_line_total_9.setText(line9String);
int line10 = qty10 *watt10;
String line10String =line10+"W"; tv_line_total_10.setText(line10String);
powerTotal = line1+line2+line3+line4+line5+line6+line7+line8+line9+line10;//save on rotate
String totalPowerResults = powerTotal+"W";
tv_total_power_result.setText(totalPowerResults);
double pduSize = powerTotal/.8;
intPduSize = (int)pduSize+1;//save on rotate
String pduResults = intPduSize+"W";
tv_total_pdu_result.setText(pduResults);
if(powerFactor<0&& powerFactor>1){//check for limits for the power factor entered in preference activity
upsSize = powerTotal/0.9f;//save on rotate
}else{
upsSize = powerTotal/powerFactor;//save on rotate
}
if(upsSize>(int)upsSize){//if there is a decimal value, round up to the next integer
Log.d("Widget PwrLoads", upsSize+"");
upsSize+=1; //round up the the next int
Log.d("Widget PwrLoads", upsSize+"");
}
String upsResults = (int)upsSize+"VA";
tv_total_ups_result.setText(upsResults);
breakerSize = breakerSize(powerTotal);//save on rotate
Log.d("Widget PwrLoads", "breakerSize "+breakerSize);
if(breakerSize==0){
tv_breaker_result.setText(R.string.breaker_greater_than_50);
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, R.string.max_breaker_size_error, Toast.LENGTH_LONG);
toast.show();
}else{
String breakerResults = breakerSize+"A";
tv_breaker_result.setText(breakerResults);
}
SumDbHelper dbHelper = new SumDbHelper(getApplicationContext());
mDb = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SumTaskContract.SummaryEntry.COLUMN_SYSTEM, "Power Loads");
contentValues.put(SumTaskContract.SummaryEntry.COLUMN_SUMMARY, "UPS Size "+(int)upsSize+"W");
Cursor cursor = mDb.query(SummaryEntry.TABLE_NAME, null, null,null,null,null,null);
if(cursor.moveToFirst()){
mDb.update(SummaryEntry.TABLE_NAME, contentValues,null, null);
Log.d("Widget PwrLoads", "update");
}else {
long insert =mDb.insert(SummaryEntry.TABLE_NAME, null, contentValues);
Log.d("Widget PwrLoads", "insert");
}cursor.close();
SummaryService.startActionUpdateSum(getApplicationContext());
}
private int breakerSize(double bsPowerTotal){
int ZERO = 0, ONE = 1, TWO = 2, FIVE = 5, TEN = 10, FIFTEEN = 15, TWENTY =20, TWENTY_FIVE = 25, THIRTY = 30, FORTY = 40, FIFTY = 50;
double mBsTotalPower = bsPowerTotal;
double bsCurrent = mBsTotalPower/spinnerVoltage;//ex 500W load /120V = ~4.2A
double breakerSize = bsCurrent/0.8;//20% margin
if(breakerSize<1) return ONE;
if(breakerSize<2) return TWO;
if(breakerSize<5) return FIVE;
if(breakerSize<10) return TEN;
if(breakerSize<15) return FIFTEEN;
if(breakerSize<20) return TWENTY;
if(breakerSize<25) return TWENTY_FIVE;
if(breakerSize<30) return THIRTY;
if(breakerSize<40) return FORTY;
if(breakerSize<50) return FIFTY;
return ZERO;
}
private int determineVoltage(int voltageIndex){
int TWELVE= 12, TWENTY_FOUR =24, FORTY_EIGHT = 48, ONE_HUNDRED_TWENTY = 120, TWO_HUNDRED_THIRTY = 230;
switch(voltageIndex){
case 0: return TWELVE;
case 1: return TWENTY_FOUR;
case 2: return FORTY_EIGHT;
case 3: return ONE_HUNDRED_TWENTY;
case 4: return TWO_HUNDRED_THIRTY;
default: return ONE_HUNDRED_TWENTY;
}
}
private void setUpPreferences() {//sets up preferences when the user reopens the activity
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.registerOnSharedPreferenceChangeListener(this);
imperial = sharedPref.getBoolean(getResources().getString(R.string.pref_units_key), true);
pfString = sharedPref.getString(getResources().getString(R.string.pref_pf_key), "0.9");
pfTitle = getResources().getString(R.string.min_ups_size_0_9pf)+" "+pfString+"pf";
tv_total_ups_title.setText(pfTitle);
powerFactor = Float.parseFloat(pfString);
Log.d("pref_fragment", imperial+" setup"+pfString+" "+powerFactor);
}
@Override//updates the activity once the units system has changed
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(getResources().getString(R.string.pref_units_key))){
imperial = sharedPreferences.getBoolean(getResources().getString(R.string.pref_units_key), true);
Log.d("pref fragment", imperial+" changed");
}else if(key.equals(getResources().getString(R.string.pref_pf_key))){
pfString = sharedPreferences.getString(getResources().getString(R.string.pref_pf_key), "0.9");
powerFactor = Float.parseFloat(pfString);
if(powerFactor>1){
Toast toast = Toast.makeText(getApplicationContext(), "Power factor can't be greater than 1. The value is set to the default value of 0.9.", Toast.LENGTH_LONG);
toast.show();
powerFactor=0.9f;
}pfTitle = getResources().getString(R.string.min_ups_size_0_9pf)+" "+pfString+"pf";
tv_total_ups_title.setText(pfTitle);
calculate();//will calculate valid user input or default 0.9
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemClicked = item.getItemId();
if(itemClicked==R.id.shared_pref){
Log.d("menu", "menu clicked");
startActivity(new Intent(PowerLoadsActivity.this, SettingsActivity.class));
return true;
}else if (itemClicked==R.id.menu_go_to_main){
startActivity(new Intent(PowerLoadsActivity.this, MainActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("powerTotal",powerTotal);
outState.putInt("intPduSize",intPduSize);
outState.putDouble("upsSize",upsSize);
outState.putInt("breakerSize",breakerSize);
}
@Override
public void onPause() {
if (adViewBanner != null) adViewBanner.pause();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
if (adViewBanner != null) adViewBanner.resume();
}
@Override
public void onDestroy() {
if (adViewBanner != null) adViewBanner.destroy();
super.onDestroy();
}
}
| true
|
34edb393d8df93efd7dc39876d214e6ec1079a53
|
Java
|
Suresh918/mySpringbootMicroServices
|
/MYCHANGE/java/review-service/src/test/java/com/example/mirai/mychange/reviewservice/json/ReviewCaseStatusJson.java
|
UTF-8
| 421
| 2.140625
| 2
|
[] |
no_license
|
package com.example.mirai.projectname.reviewservice.json;
public class ReviewCaseStatusJson extends Content {
public ReviewCaseStatusJson(String content) {
super(content);
}
public Long getId() {
return Long.valueOf("" + documentContext.read("id"));
}
public Integer getStatus() {
return Integer.valueOf("" + documentContext.read("$.review_case_status.status"));
}
}
| true
|
f4355fbefa5565d3bad8ebfef4f85b6601fa5ce8
|
Java
|
dostermeier/mbuddy
|
/mail-rest-server/src/main/java/com/zutubi/services/mail/rest/server/RestLifecycleComponent.java
|
UTF-8
| 3,757
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.zutubi.services.mail.rest.server;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import com.yammer.metrics.jetty.InstrumentedHandler;
import com.yammer.metrics.jetty.InstrumentedQueuedThreadPool;
import com.yammer.metrics.jetty.InstrumentedSelectChannelConnector;
import com.zutubi.services.mail.core.lifecycle.Environment;
import com.zutubi.services.mail.core.lifecycle.LifecycleComponent;
import ch.qos.logback.access.jetty.RequestLogImpl;
/**
* The RestLifecycleComponent is responsible for managing the embedded jetty server
* that runs the REST API.
*/
public class RestLifecycleComponent extends LifecycleComponent {
private static final Logger LOGGER = LoggerFactory.getLogger(RestLifecycleComponent.class);
private static final String ACCESS_LOG_CONFIGURATION_RESOURCE = "/logback-rest-access.xml";
/**
* Indicates whether or not this component is currently running.
*/
private boolean running;
/**
* The environment that defines the configuration of the rest api.
*/
private Environment environment;
/**
* The embedded jetty server instance that is managed by this lifecycle component.
*/
private Server server;
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
Assert.notNull(environment);
server = new Server();
server.setConnectors(new Connector[]{new InstrumentedSelectChannelConnector(environment.getRestPort())});
server.setThreadPool(new InstrumentedQueuedThreadPool());
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void start() {
LOGGER.info("*** RestLifecycleComponent startup commencing ***");
HandlerCollection requestHandlers = new HandlerCollection();
WebAppContext webapp = new WebAppContext();
webapp.setContextPath(environment.getContextPath());
webapp.setResourceBase(environment.getRestResourceBase());
requestHandlers.addHandler(new InstrumentedHandler(webapp));
RequestLogImpl requestLog = new RequestLogImpl();
requestLog.setResource(ACCESS_LOG_CONFIGURATION_RESOURCE);
RequestLogHandler logHandler = new RequestLogHandler();
logHandler.setRequestLog(requestLog);
requestHandlers.addHandler(logHandler);
try {
server.setHandler(requestHandlers);
server.start();
LOGGER.info(" Jetty server listening on {}", environment.getRestPort());
running = true;
LOGGER.info("*** RestLifecycleComponent startup completed ***");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void stop() {
LOGGER.info("*** RestLifecycleComponent stop commencing ***");
try {
if (server.isRunning()) {
server.stop();
}
running = false;
} catch (Exception e) {
throw new RuntimeException(e);
}
LOGGER.info("*** RestLifecycleComponent stop completed ***");
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return 10;
}
@Autowired
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
| true
|
b0d712f6631b87e7831be6e85887bd21ead3e36e
|
Java
|
danielmartinez96/Tp1IR
|
/TrabajoPractico1/src/trabajopractico1/TrabajoPractico1.java
|
UTF-8
| 649
| 1.890625
| 2
|
[] |
no_license
|
/*
* 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 trabajopractico1;
import datos.GeneradorDatos;
import presetador.PresentadorInicio;
import vista.Inicio;
/**
*
* @author Carlos
*/
public class TrabajoPractico1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
GeneradorDatos.instaciarDatos();
Inicio vista = new Inicio();
}
}
| true
|
4ba028e6f3723753f088eab6efe4c3d88302c396
|
Java
|
liangyingshao/goods
|
/oomall-test/src/test/java/cn/edu/xmu/oomall/SongRunhanTest.java
|
UTF-8
| 15,572
| 2.0625
| 2
|
[] |
no_license
|
package cn.edu.xmu.oomall;
import cn.edu.xmu.ooad.util.JacksonUtil;
import cn.edu.xmu.ooad.util.ResponseCode;
import cn.edu.xmu.oomall.LoginVo;
import cn.edu.xmu.test.TestApplication;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.reactive.server.WebTestClient;
import java.time.LocalDateTime;
/**
* 24320182203266
* 宋润涵
* 请注意!!!
* 由于时间段的更改本测试可能会发生错误,当时间段确定后会更新测试
* 如遇到冲突,请自行调整端口设置
* 本测试运行前务必清除Redis缓存,重置数据库
*/
@Slf4j
@SpringBootTest(classes = TestApplication.class) //标识本类是一个SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class SongRunhanTest {
private static final Logger logger = LoggerFactory.getLogger(SlyTest.class);
@Autowired
private ObjectMapper mObjectMapper;
@Value("${public-test.managementgate}")
private String managementGate;
@Value("${public-test.mallgate}")
private String mallGate;
private WebTestClient manageClient;
private WebTestClient mallClient;
@BeforeEach
public void setUp(){
this.manageClient = WebTestClient.bindToServer()
.baseUrl("http://"+managementGate)
.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")
.build();
this.mallClient = WebTestClient.bindToServer()
.baseUrl("http://"+mallGate)
.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")
.build();
}
/**
* 在时段"0"下新建秒杀活动,然后删除活动
*/
@Test
public void addFlashSaleActivity1() throws Exception{
String token = this.login("13088admin", "123456");
LocalDateTime dateTime = LocalDateTime.now().plusDays(3);
String requestJson = "{\"flashDate\":\"" + dateTime + "\"}";
byte[] responseBuffer = null;
WebTestClient.RequestHeadersSpec res = manageClient.post().uri("/shops/0/timesegments/8/flashsales").header("authorization",token).bodyValue(requestJson);
responseBuffer = res.exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").isMap()
.returnResult()
.getResponseBodyContent();
String response = new String(responseBuffer, "utf-8");
JsonNode jsonNode = mObjectMapper.readTree(response).findPath("data").get("id");
int insertId = jsonNode.asInt();
responseBuffer= manageClient.delete().uri("/shops/0/flashsales/"+insertId).header("authorization",token)
.exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
logger.error("insertid: "+insertId);
responseBuffer= manageClient.delete().uri("/shops/0/flashsales/"+insertId).header("authorization",token)
.exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectStatus().isNotFound()
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.RESOURCE_ID_NOTEXIST.getCode())
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
}
/**
* 新建今天的活动,应当阻止;
*/
@Test
public void addFlashSaleActivity2() throws Exception{
String token = this.login("13088admin", "123456");
LocalDateTime dateTime = LocalDateTime.now();
String requestJson = "{\"flashDate\":\"" + dateTime + "\"}";
byte[] responseBuffer = null;
WebTestClient.RequestHeadersSpec res = manageClient.post().uri("/shops/0/timesegments/8/flashsales").header("authorization",token).bodyValue(requestJson);
responseBuffer = res.exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(503)
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
}
/**
* 获取秒杀活动
* @throws Exception
*/
@Test
@Order(1)
public void getFlashSaleActivity1()throws Exception {
String token = this.login("13088admin", "123456");
byte[] responseBuffer = null;
WebTestClient.RequestHeadersSpec res = mallClient.get().uri("/flashsales/current?page=1&pageSize=10");
responseBuffer = res.exchange().expectHeader().contentType("application/json;charset=UTF-8").expectStatus().isOk()
.expectBody()
.jsonPath("$").isArray()
.jsonPath("$[?(@.id == 8)].goodsSku.id").isEqualTo(275)
.jsonPath("$[?(@.id == 7)].goodsSku.id").isEqualTo(290)
.returnResult()
.getResponseBodyContent();
String response = new String(responseBuffer, "utf-8");
}
/**
* 向秒杀活动中加入SKU、删除SKU
* @throws Exception
*/
@Test
public void addSKUToActivity()throws Exception {
String token = this.login("13088admin", "123456");
LocalDateTime dateTime = LocalDateTime.now().plusDays(3);
String requestJson = "{\"flashDate\":\"" + dateTime + "\"}";
byte[] responseBuffer = null;
WebTestClient.RequestHeadersSpec res = manageClient.post().uri("/shops/0/timesegments/8/flashsales").header("authorization",token).bodyValue(requestJson);
responseBuffer = res.exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").isMap()
.returnResult()
.getResponseBodyContent();
String response = new String(responseBuffer, "utf-8");
JsonNode jsonNode = mObjectMapper.readTree(response).findPath("data").get("id");
int insertActivityId = jsonNode.asInt();
requestJson = "{\"skuId\": 280,\"price\": 2365,\"quantity\": 36}";
responseBuffer = manageClient.post().uri("/shops/0/flashsales/" + insertActivityId + "/flashitems").header("authorization",token).bodyValue(requestJson).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").isMap()
.returnResult()
.getResponseBodyContent();
response = new String(responseBuffer, "utf-8");
jsonNode = mObjectMapper.readTree(response).findPath("data").get("id");
int insertItemId = jsonNode.asInt();
/* 重复加入 */
// requestJson = "{\"skuId\": 280,\"price\": 2365,\"quantity\": 36}";
// responseBuffer =webClient.post().uri("flashsales/" + insertId + "/flashitems").bodyValue(requestJson).exchange().expectHeader().contentType("application/json;charset=UTF-8")
// .expectBody()
// .jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
// .jsonPath("$.errmsg").isEqualTo("成功")
// .jsonPath("$.data").isMap()
// .returnResult()
// .getResponseBodyContent();
manageClient.delete().uri("/shops/0/flashsales/"+ insertActivityId +"/flashitems/"+ insertItemId).header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
//删除活动
responseBuffer= manageClient.delete().uri("/shops/0/flashsales/"+insertActivityId).header("authorization",token)
.exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
}
@Test
@Order(Integer.MAX_VALUE - 2)
public void delFlashItem() throws Exception {
String token = this.login("13088admin", "123456");
// region 删除今天的秒杀商品
manageClient.delete().uri("/shops/0/flashsales/3/flashitems/5").header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
manageClient.delete().uri("/shops/0/flashsales/3/flashitems/6").header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
manageClient.delete().uri("/shops/0/flashsales/4/flashitems/7").header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
manageClient.delete().uri("/shops/0/flashsales/4/flashitems/8").header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
// endregion
byte[] responseBuffer = null;
WebTestClient.RequestHeadersSpec res = mallClient.get().uri("/flashsales/current?page=1&pageSize=10");
responseBuffer = res.exchange().expectHeader().contentType("application/json;charset=UTF-8").expectStatus().isOk()
.expectBody()
.jsonPath("$").isArray()
.jsonPath("$.length()").isEqualTo(0)
.returnResult()
.getResponseBodyContent();
String response = new String(responseBuffer, "utf-8");
}
/**
* 上/下线秒杀活动
* @throws Exception
*/
@Test
@Order(Integer.MAX_VALUE - 1)
public void offLine() throws Exception {
String token = this.login("13088admin", "123456");
manageClient.put().uri("/shops/0/flashsales/1/offshelves").header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.returnResult()
.getResponseBodyContent();
manageClient.put().uri("/shops/0/flashsales/1/onshelves").header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.returnResult()
.getResponseBodyContent();
}
@Test
@Order(Integer.MAX_VALUE)
public void delFlashSale() throws Exception {
String token = this.login("13088admin", "123456");
for(int i=1;i<=4;++i){
manageClient.put().uri("/shops/0/flashsales/"+ i +"/offshelves").header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.returnResult()
.getResponseBodyContent();
}
for(int i=1;i<=4;++i){
manageClient.delete().uri("/shops/0/flashsales/" + i).header("authorization",token).exchange().expectHeader().contentType("application/json;charset=UTF-8")
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
}
/*
继续删,应当报错
*/
manageClient.delete().uri("/shops/0/flashsales/0").header("authorization",token).exchange()
.expectHeader().contentType("application/json;charset=UTF-8")
.expectStatus().isNotFound()
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.RESOURCE_ID_NOTEXIST.getCode())
.jsonPath("$.data").doesNotExist()
.returnResult()
.getResponseBodyContent();
}
/**
* 这个不是测试用例,不要算数!!!
* 这个不是测试用例,不要算数!!!
* 这个不是测试用例,不要算数!!!
* @param userName 登录的用户名
* @param password 登录的密码
* @return token
* @throws Exception
*/
private String login(String userName, String password) throws Exception{
LoginVo vo = new LoginVo();
vo.setUserName(userName);
vo.setPassword(password);
String requireJson = JacksonUtil.toJson(vo);
byte[] ret = manageClient.post().uri("/adminusers/login").bodyValue(requireJson).exchange()
.expectStatus().isCreated()
.expectBody()
.jsonPath("$.errno").isEqualTo(ResponseCode.OK.getCode())
.jsonPath("$.errmsg").isEqualTo("成功")
.returnResult()
.getResponseBodyContent();
return JacksonUtil.parseString(new String(ret, "UTF-8"), "data");
}
}
| true
|
0f5d1603407099d4d505d1aa2de8180f4a803f02
|
Java
|
sgzlyy/java-demo
|
/src/designPattern/command/Client.java
|
UTF-8
| 445
| 2.703125
| 3
|
[] |
no_license
|
package designPattern.command;
/**
* @author sby
* @Title: Client
* @Description: 命令模式
* @date 2019/1/29 15:11
*/
public class Client {
public static void main(String[] args) throws Exception {
Class c = Class.forName("designPattern.command.FanCommand");
AbstractCommand command = (AbstractCommand) c.newInstance();
PowerSwitch powerSwitch = new PowerSwitch(command);
powerSwitch.on();
}
}
| true
|
484dd5179d9687d4eb902747bf4d88a2699bd858
|
Java
|
dianyueneo/Agriculture
|
/app/src/main/java/com/cxwl/agriculture/IntroActivity.java
|
UTF-8
| 1,302
| 2.359375
| 2
|
[] |
no_license
|
package com.cxwl.agriculture;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import com.cxwl.agriculture.adapter.IntroImagePagerAdapter;
/**
* Created by hongge on 15/8/1.
*/
public class IntroActivity extends Activity implements View.OnClickListener{
private ViewPager viewPager;
private IntroImagePagerAdapter adapter;
private ImageView back;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_intro);
viewPager = (ViewPager)findViewById(R.id.viewpager);
adapter = new IntroImagePagerAdapter(this);
int images[] = {R.drawable.intro1, R.drawable.intro2, R.drawable.intro3, R.drawable.intro4, R.drawable.intro5, R.drawable.intro6, R.drawable.intro7};
adapter.setImages(images);
viewPager.setAdapter(adapter);
back = (ImageView)findViewById(R.id.back);
back.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back:
finish();
break;
default:
break;
}
}
}
| true
|
52b435fad1be82987dc6420a60e75cd4b6922541
|
Java
|
kreker92/ContextToCode
|
/plugin/src/main/java/tmt/attributes/TextAttributes.java
|
UTF-8
| 1,314
| 2.25
| 2
|
[] |
no_license
|
package tmt.attributes;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
public class TextAttributes {
public static final TextAttributesKey CRITICAL;
public static final TextAttributesKey MAJOR;
public static final TextAttributesKey MINOR;
public static final TextAttributesKey BLOCKER;
public static final TextAttributesKey INFO;
public static final TextAttributesKey SELECTED;
static {
/*
* Defaults should be consistent with SonarLintSeverity
*/
CRITICAL = TextAttributesKey.createTextAttributesKey("SONARLINT_CRITICAL", Severity.CRITICAL.defaultTextAttributes());
MAJOR = TextAttributesKey.createTextAttributesKey("SONARLINT_MAJOR", Severity.MAJOR.defaultTextAttributes());
MINOR = TextAttributesKey.createTextAttributesKey("SONARLINT_MINOR", Severity.MINOR.defaultTextAttributes());
INFO = TextAttributesKey.createTextAttributesKey("SONARLINT_INFO", Severity.INFO.defaultTextAttributes());
BLOCKER = TextAttributesKey.createTextAttributesKey("SONARLINT_BLOCKER", Severity.BLOCKER.defaultTextAttributes());
SELECTED = createTextAttributesKey("SONARLINT_SELECTED");
}
}
| true
|
4c695d9310658b05bbc36709e12ae33069aa5dac
|
Java
|
trongnguyen0503/FYP_project
|
/app/src/main/java/com/tntstudios/feedyourpig/adapters/MapAdapter.java
|
UTF-8
| 3,229
| 2.203125
| 2
|
[] |
no_license
|
package com.tntstudios.feedyourpig.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.tntstudios.feedyourpig.R;
import com.tntstudios.feedyourpig.gameplay.GameInterface;
public class MapAdapter extends RecyclerView.Adapter<MapAdapter.DataViewHolder> {
private Context context;
private GameInterface gameInterface;
private int[] list_star_map;
public MapAdapter(Context context,int[] list_star_map) {
this.gameInterface = (GameInterface)context;
this.context=context;
this.list_star_map=list_star_map;
}
@NonNull
@Override
public MapAdapter.DataViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.rv_list_map, parent, false);
return new MapAdapter.DataViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MapAdapter.DataViewHolder holder, final int position) {
holder.txt_map.setText(String.valueOf(position+1));
Glide.with(context)
.load(R.drawable.boxicon)
.into(holder.btn_map);
switch (list_star_map[position]){
case -1:{
Glide.with(context)
.load(R.drawable.lock)
.into(holder.star);
break;
}
case 0:{
Glide.with(context)
.load(R.drawable.star_point_0)
.into(holder.star);
break;
}
case 1:{
Glide.with(context)
.load(R.drawable.star_point_1)
.into(holder.star);
break;
}
case 2:{
Glide.with(context)
.load(R.drawable.star_point_2)
.into(holder.star);
break;
}
case 3:{
Glide.with(context)
.load(R.drawable.star_point_3)
.into(holder.star);
break;
}
}
holder.btn_map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
gameInterface.ChooseMap(position);
}
});
}
@Override
public int getItemCount() {
return 25;
}
public static class DataViewHolder extends RecyclerView.ViewHolder{
private ImageView btn_map,star;
private TextView txt_map;
public DataViewHolder(@NonNull View itemView) {
super(itemView);
btn_map = itemView.findViewById(R.id.rv_list_btn_map);
txt_map = itemView.findViewById(R.id.rv_list_txt_map);
star = itemView.findViewById(R.id.rv_list_img_star);
}
}
}
| true
|
2e3708429d560e1d0ea249a32d768ac2460b51f1
|
Java
|
hasithalakmal/RIP
|
/SQLScriptGen/src/main/java/com/rip/sqlscriptgen/DatabasePulgginInterface.java
|
UTF-8
| 854
| 1.585938
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.rip.sqlscriptgen;
import org.json.JSONObject;
/**
*
* @author Hasitha Lakmal
*/
public interface DatabasePulgginInterface {
String createDDLScript(JSONObject platformIndependentModel);
String createTable(JSONObject rip_sql_table);
String foreignKeys(JSONObject rip_sql_forign_key);
String createDMLScript(JSONObject platformIndependentModel);
String createInsertQuery(JSONObject rip_sql_table);
String createUpdateQuery(JSONObject rip_sql_table);
String createDeleteQuery(JSONObject rip_sql_table);
String createDQLScript(JSONObject platformIndependentModel);
String createSelectQuery(JSONObject rip_sql_table);
}
| true
|
3d07bf51224a3e5b15202068b6f5dc695162776d
|
Java
|
P79N6A/icse_20_user_study
|
/methods/Method_1017106.java
|
UTF-8
| 171
| 1.742188
| 2
|
[] |
no_license
|
private Map<String,String> payload(){
final ImmutableMap.Builder<String,String> payload=ImmutableMap.builder();
payload.put("state","ok");
return payload.build();
}
| true
|
065b2463b18930e869c54adcc327fb57fbe0666a
|
Java
|
vhctrungnq/mlmn
|
/MLMN-Statistics/src/vn/com/vhc/vmsc2/statistics/web/controller/MnCellHoController.java
|
UTF-8
| 10,564
| 2.0625
| 2
|
[] |
no_license
|
package vn.com.vhc.vmsc2.statistics.web.controller;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import vn.com.vhc.vmsc2.statistics.dao.BscDAO;
import vn.com.vhc.vmsc2.statistics.dao.CellDAO;
import vn.com.vhc.vmsc2.statistics.dao.HighlightConfigDAO;
import vn.com.vhc.vmsc2.statistics.dao.VRpMnCellHoBhDAO;
import vn.com.vhc.vmsc2.statistics.dao.VRpMnCellHoDAO;
import vn.com.vhc.vmsc2.statistics.domain.Bsc;
import vn.com.vhc.vmsc2.statistics.domain.Cell;
import vn.com.vhc.vmsc2.statistics.domain.HighlightConfig;
import vn.com.vhc.vmsc2.statistics.domain.VRpMnCellHo;
import vn.com.vhc.vmsc2.statistics.domain.VRpMnCellHoBh;
import vn.com.vhc.vmsc2.statistics.web.utils.Chart;
import vn.com.vhc.vmsc2.statistics.web.utils.Helper;
@Controller
public class MnCellHoController extends BaseController {
@Autowired
private VRpMnCellHoDAO vRpMnCellHoDao;
@Autowired
private VRpMnCellHoBhDAO vRpMnCellHoBhDao;
@Autowired
private HighlightConfigDAO highlightConfigDao;
@Autowired
private BscDAO bscDao;
@Autowired
private CellDAO cellDao;
@RequestMapping("/report/radio/cell-ho/mn/list")
public ModelAndView showReportList(@RequestParam(required = false) String bscid, @RequestParam(required = false) String cellid,
@RequestParam(required = false) Integer startMonth, @RequestParam(required = false) Integer startYear,
@RequestParam(required = false) Integer endMonth, @RequestParam(required = false) Integer endYear, ModelMap model, HttpServletRequest request) {
Calendar cal = Calendar.getInstance();
Calendar calender = Calendar.getInstance();
if (endYear ==null || endYear < 1900)
{
endYear = calender.get(Calendar.YEAR);
}
if (endMonth == null) {
cal.add(Calendar.MONTH, -1);
endMonth = cal.get(Calendar.MONTH) + 1;
endYear = cal.get(Calendar.YEAR);
}
if (startMonth == null) {
startMonth = endMonth;
startYear = endYear;
}
/*int startRecord = 0;
int order = 1;
String column = "YEAR, MONTH, REGION, BSCID, CELLID";
try {
startRecord = (Integer.parseInt(request.getParameter((new ParamEncoder("vRpMnCellHo").encodeParameterName(TableTagParameters.PARAMETER_PAGE)))) - 1) * 100;
order = Integer.parseInt(request.getParameter((new ParamEncoder("vRpMnCellHo").encodeParameterName(TableTagParameters.PARAMETER_ORDER))));
column = request.getParameter((new ParamEncoder("vRpMnCellHo").encodeParameterName(TableTagParameters.PARAMETER_SORT)));
} catch (NumberFormatException e) {
}
int endRecord = startRecord + 100;
*/
/*List<VRpMnCellHo> vRpMnCellHo = vRpMnCellHoDao.filter(bscid, cellid, month, year, startRecord, endRecord, column, order == 1 ? "ASC" : "DESC");
Integer totalSize = vRpMnCellHoDao.countRow(bscid, cellid, month, year);
model.addAttribute("totalSize", totalSize);*/
List<VRpMnCellHo> vRpMnCellHo = vRpMnCellHoDao.filterDetails(startMonth.toString(), startYear.toString(), endMonth.toString(),
endYear.toString(), bscid, cellid);
model.addAttribute("cellid", cellid);
model.addAttribute("bscid", bscid);
List<Bsc> bscList = bscDao.getAll();
model.addAttribute("bscList", bscList);
List<Cell> cellList = cellDao.getCellOfBsc(bscid);
model.addAttribute("cellList", cellList);
model.addAttribute("startMonth", startMonth);
model.addAttribute("endMonth", endMonth);
model.addAttribute("startYear", startYear);
model.addAttribute("endYear", endYear);
model.addAttribute("vRpMnCellHo", vRpMnCellHo);
String[] monthList = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
model.addAttribute("monthList", monthList);
List<HighlightConfig> highlightConfigList = highlightConfigDao.getAll();
model.addAttribute("highlight", Helper.highLight(highlightConfigList, "vRpMnCellHo"));
return new ModelAndView("mnCellHoList");
}
@RequestMapping("/report/radio/cell-ho/mn/details")
public String showReport(@RequestParam(required = true) String bscid, @RequestParam(required = true) String cellid,
@RequestParam(required = false) Integer startMonth, @RequestParam(required = false) Integer startYear,
@RequestParam(required = false) Integer endMonth, @RequestParam(required = false) Integer endYear, ModelMap model, HttpServletRequest request) {
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar calender = Calendar.getInstance();
if (endYear ==null || endYear < 1900)
{
endYear = calender.get(Calendar.YEAR);
}
if (endMonth == null) {
cal.add(Calendar.MONTH, -1);
endMonth = cal.get(Calendar.MONTH) + 1;
endYear = cal.get(Calendar.YEAR);
}
if (startMonth == null) {
if (endMonth > 3) {
startMonth = endMonth - 3;
startYear = endYear;
} else {
cal1.add(Calendar.MONTH, -3);
startMonth = cal1.get(Calendar.MONTH) + 1;
startYear = cal1.get(Calendar.YEAR);
}
}
model.addAttribute("startMonth", startMonth);
model.addAttribute("endMonth", endMonth);
model.addAttribute("startYear", startYear);
model.addAttribute("endYear", endYear);
List<VRpMnCellHo> vRpMnCellHoDetails = vRpMnCellHoDao.filterDetails(startMonth.toString(), startYear.toString(), endMonth.toString(),
endYear.toString(), bscid, cellid);
model.addAttribute("vRpMnCellHoDetails", vRpMnCellHoDetails);
model.addAttribute("cellid", cellid);
model.addAttribute("bscid", bscid);
List<Bsc> bscList = bscDao.getAll();
model.addAttribute("bscList", bscList);
List<Cell> cellList = cellDao.getCellOfBsc(bscid);
model.addAttribute("cellList", cellList);
/* Chart */
List<String> categories = new ArrayList<String>();
List<Float> inHoSucrList = new ArrayList<Float>();
List<Float> ogHoSucrList = new ArrayList<Float>();
for (VRpMnCellHo vRpMnCellHo : vRpMnCellHoDetails) {
categories.add(vRpMnCellHo.getMonth() + "/" + vRpMnCellHo.getYear());
inHoSucrList.add(vRpMnCellHo.getInHoSucr());
ogHoSucrList.add(vRpMnCellHo.getOgHoSucr());
}
Map<String, List<Float>> series = new LinkedHashMap<String, List<Float>>();
series.put("In_Ho_Sucr", inHoSucrList);
series.put("Og_Ho_Sucr", ogHoSucrList);
model.addAttribute("chart", Chart.basicLine("CELL HO " + cellid + " Monthly Report", categories, series));
// checkBox
String[] checkColumns = { "HO_ATT", "HO_SUCR", "INTRA_HO_ATT", "INTRA_HO_SUCR", "OG_HO_ATT", "OG_HO_SUCR", "IN_HO_ATT", "IN_HO_SUCR", "HO_REVERSION", "HO_LOST"};
model.addAttribute("checkColumns", Helper.checkColumns(checkColumns, "vRpMnCellHoDetail", 5));
String[] checkSeries = { "ogHoSucr", "inHoSucr" };
model.addAttribute("checkSeries", Chart.checkSeries(checkSeries));
List<HighlightConfig> highlightConfigList = highlightConfigDao.getAll();
model.addAttribute("highlight", Helper.highLight(highlightConfigList, "vRpMnCellHoDetail"));
String[] monthList = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
model.addAttribute("monthList", monthList);
return "mnCellHoDetails";
}
@RequestMapping("/report/radio/cell-ho/mn/bhDetails")
public String showReportBhDetails(@RequestParam(required = true) String bscid, @RequestParam(required = true) String cellid,
@RequestParam(required = false) Integer startMonth, @RequestParam(required = false) Integer startYear,
@RequestParam(required = false) Integer endMonth, @RequestParam(required = false) Integer endYear, ModelMap model, HttpServletRequest request) {
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar calender = Calendar.getInstance();
if (endYear ==null || endYear < 1900)
{
endYear = calender.get(Calendar.YEAR);
}
if (endMonth == null) {
cal.add(Calendar.MONTH, -1);
endMonth = cal.get(Calendar.MONTH) + 1;
endYear = cal.get(Calendar.YEAR);
}
if (startMonth == null) {
if (endMonth > 3) {
startMonth = endMonth - 3;
startYear = endYear;
} else {
cal1.add(Calendar.MONTH, -3);
startMonth = cal1.get(Calendar.MONTH) + 1;
startYear = cal1.get(Calendar.YEAR);
}
}
model.addAttribute("startMonth", startMonth);
model.addAttribute("endMonth", endMonth);
model.addAttribute("startYear", startYear);
model.addAttribute("endYear", startYear);
List<VRpMnCellHoBh> vRpMnCellHoBhDetails = vRpMnCellHoBhDao.filterDetails(startMonth.toString(), startYear.toString(), endMonth.toString(),
endYear.toString(), bscid, cellid);
model.addAttribute("vRpMnCellHoBhDetails", vRpMnCellHoBhDetails);
model.addAttribute("cellid", cellid);
model.addAttribute("bscid", bscid);
List<Bsc> bscList = bscDao.getAll();
model.addAttribute("bscList", bscList);
List<Cell> cellList = cellDao.getCellOfBsc(bscid);
model.addAttribute("cellList", cellList);
/* Chart */
List<String> categories = new ArrayList<String>();
List<Float> inHoSucrList = new ArrayList<Float>();
List<Float> ogHoSucrList = new ArrayList<Float>();
for (VRpMnCellHoBh vRpMnCellHoBh : vRpMnCellHoBhDetails) {
categories.add(vRpMnCellHoBh.getMonth() + "/" + vRpMnCellHoBh.getYear());
inHoSucrList.add(vRpMnCellHoBh.getBhInHoSucr());
ogHoSucrList.add(vRpMnCellHoBh.getBhOgHoSucr());
}
Map<String, List<Float>> series = new LinkedHashMap<String, List<Float>>();
series.put("Bh_In_Ho_Sucr", inHoSucrList);
series.put("Bh_Og_Ho_Sucr", ogHoSucrList);
model.addAttribute("chart", Chart.basicLine("CELL HO BH " + cellid + " Monthly Report", categories, series));
String[] monthList = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
model.addAttribute("monthList", monthList);
// checkBox
String[] checkColumns = { "bhOgHoAtt", "bhOgHoSucr", "bhInHoAtt", "bhInHoSucr" };
model.addAttribute("checkColumns", Helper.checkColumns(checkColumns, 5));
String[] checkSeries = { "bhOgHoSucr", "bhInHoSucr" };
model.addAttribute("checkSeries", Chart.checkSeries(checkSeries));
return "mnCellHoBhDetails";
}
}
| true
|
114dde8f9fcd02b08a53bf28a32f78b7ca1e939a
|
Java
|
yarn47/Dagger2-Android-WeatherSample
|
/app/src/main/java/com/example/daggerpractice00/api/response/ShownWeatherInfo.java
|
UTF-8
| 742
| 2.40625
| 2
|
[] |
no_license
|
package com.example.daggerpractice00.api.response;
public class ShownWeatherInfo {
private String cityName = "citys";
private Weather todayWeather = null;
private Weather tomorrowWeather = null;
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Weather getTodayWeather() {
return todayWeather;
}
public void setTodayWeather(Weather todayWeather) {
this.todayWeather = todayWeather;
}
public Weather getTomorrowWeather() {
return tomorrowWeather;
}
public void setTomorrowWeather(Weather tomorrowWeather) {
this.tomorrowWeather = tomorrowWeather;
}
}
| true
|
19cf7b80f8db3f239eef78dc3a33d565f5f30524
|
Java
|
Paramyth/javafx
|
/kodeklubben/src/game/FxmlApp.java
|
UTF-8
| 1,729
| 2.6875
| 3
|
[] |
no_license
|
package game;
import java.net.URL;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Shape;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public abstract class FxmlApp extends Application {
// fxml loading on startup
@Override
public void start(Stage primaryStage) throws Exception {
URL url = this.getClass().getResource(this.getClass().getSimpleName() + ".fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setController(this);
fxmlLoader.setLocation(url);
Parent root = (Parent) fxmlLoader.load();
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
// images
public Image createTextImage(Object o, Font font, Paint stroke, Paint fill) {
Text text = new Text(String.valueOf(o));
text.setFont(font);
return createShapeImage(text, stroke, fill, Color.TRANSPARENT);
}
public Image createShapeImage(Shape shape, Paint stroke, Paint fill, Paint background) {
shape.setStroke(stroke);
shape.setFill(fill);
return createNodeImage(shape, background);
}
public Image createNodeImage(Node node, Paint background) {
StackPane pane = new StackPane();
pane.getChildren().add(node);
SnapshotParameters params = new SnapshotParameters();
params.setFill(background);
WritableImage image = pane.snapshot(params, null);
return image;
}
}
| true
|
ade6442e16f4ae1c3119229caa4f20646758bacf
|
Java
|
XM-XiaoMa/AgentPermission
|
/permission/src/main/java/com/xm/permission/api/SettingPageDialog.java
|
UTF-8
| 281
| 1.546875
| 2
|
[] |
no_license
|
package com.xm.permission.api;
import android.content.Context;
import com.xm.permission.entity.PermissionParam;
import java.util.List;
public interface SettingPageDialog {
void showDialog(Context context, List<PermissionParam> permissions, SettingPageExecutor executor);
}
| true
|
96eb1e0ba512ac1176dc0a28aa279f201873f483
|
Java
|
ukiKwon/geofence-shop-coupon
|
/RemindMeThere-Materials/remindmethere-final/app/src/main/java/com/android/raywenderlich/remindmethere/GeoCouponActivity.java
|
UTF-8
| 2,487
| 2.375
| 2
|
[] |
no_license
|
package com.android.raywenderlich.remindmethere;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Toolbar;
import java.util.ArrayList;
import androidx.appcompat.app.ActionBar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class GeoCouponActivity extends BaseActivity {
private RecyclerView recyclerView;
private CouponAdapter mAdapter;//private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
//원래는 Server로부터 상호 작용 필요
private ArrayList < Coupon > mDataset = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coupon);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_coupon);
//gengerate coupon
genSampleCoupon();
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true);
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
// specify an adapter (see also next example)
mAdapter = new CouponAdapter(mDataset);
mAdapter.setOnItemClickListener(new CouponAdapter.OnItemClickListener() {
@Override
public void onItemClick(View v, int pos) {
Intent intent = new Intent(GeoCouponActivity.this, RunningUserActivity.class);
startActivity(intent);
}
});
recyclerView.setAdapter(mAdapter);
}
//generate Sample Coupon
private void genSampleCoupon() {
addItem(getDrawable(R.drawable.logo_nicy), "신발 매장", "17%", "10", "2F");
addItem(getDrawable(R.drawable.logo_puma), "신발 매장", "15%", "14", "3F");
addItem(getDrawable(R.drawable.logo_sinsaegae), "백화점 의류", "20%", "5", "4F");
addItem(getDrawable(R.drawable.logo_adidas), "신발 매장", "20%", "4", "1F");
}
public void addItem(Drawable icon, String storename, String discount, String lefttime, String floor) {
Coupon item = new Coupon(icon, storename, discount, lefttime ,floor);
mDataset.add(item);
}
}
| true
|
99faac6111d9138cc2e0c451ebb943a9da13179b
|
Java
|
alegna19/JavaExercises
|
/src/hackerrank/DeltaEncoding.java
|
UTF-8
| 1,550
| 3.953125
| 4
|
[] |
no_license
|
package hackerrank;
/*
1. Se tiene una lista de números y se debe sacar la diferencia de la resta entre el primer número de la lista con el segundo.
Ejemplo: 25626 - 25757 = -131 ese valor se debe cargar a una nueva lista para luego imprimir las diferencias.
2. si las diferencias(Delta) estan son mayores a 127 y menores o menores a -127 se debe agregar a la lista el número -128.
*/
public class DeltaEncoding {
public static void main(String[] args) {
int newLength = 0;
int array[] = {25626,25757,24367, 24267};
int length = array.length;
newLength = length;
int newArray[] = new int[length];
newArray[0] = array[0];
System.out.println(newArray[0]);
for (int i = 0; i <length -1; i++) {
int value = array[i + 1] - array[i];
if(value > 127 || value < -127){
newLength++;
}
System.out.println(value);
newArray[i] = value;
}
System.out.println("+++++++ new leng"+ newLength);
int otherArray[] = new int[newLength];
otherArray[0] = array[0];
int j = 1;
System.out.println(otherArray[0]);
for (int i = 0; i <length; i++) {
if(newArray[i] > 127 || newArray[i] < -127){
otherArray[j] = -128;
System.out.println(otherArray[j]);
j++;
}
if(j < otherArray.length){
otherArray[j] = newArray[i];
j++;
}
}
}
}
| true
|
c58bb1dd911584e492cd73a6cc24c115fca5e092
|
Java
|
jelem/capella
|
/task_8/andrew.samsonov/src/main/java/ua/pp/darknsoft/MultidimensionalArray.java
|
UTF-8
| 1,633
| 3.125
| 3
|
[] |
no_license
|
package ua.pp.darknsoft;
public class MultidimensionalArray {
public static int[][] pascalTriangle(int length) {
int[][] autoPascal = new int[length][];
for (int i = 0; i < autoPascal.length; i++) {
int[] innerArray = new int[i + 1];
autoPascal[i] = innerArray;
if (i > 0) {
for (int j = 0; j < autoPascal[i].length; j++) {
if (j > 0 && j < autoPascal[i].length - 1) {
innerArray[j] = autoPascal[i - 1][j] + autoPascal[i - 1][j - 1];
} else {
innerArray[j] = 1;
}
}
} else {
innerArray[i] = 1;
}
}
return autoPascal;
}
public static int[][] helixInit(int length) {
if (length <= 0) {
return new int[0][0];
}
int[][] helix = new int[length][length];
int x1 = 0;
int y1 = length - 1;
int x2 = length - 1;
int y2 = 0;
int tmp = 1;
int steps = 0;
if (length % 2 == 0) {
steps = length / 2;
} else {
steps = (length / 2) + 1;
}
for (int k = 0; k < steps; k++) {
for (int i = x1; i <= y1; i++) {
for (int j = y2; j <= y1; j++) {
if (i != x1 && j != y1) {
helix[i][j] = 0;
} else {
helix[i][j] = tmp;
tmp++;
}
}
}
y1--;
x1++;
for (int i = x2; i >= x1; i--) {
for (int j = y1; j >= y2; j--) {
if (i != x2 && j != y2) {
helix[i][j] = 0;
} else {
helix[i][j] = tmp;
tmp++;
}
}
}
x2--;
y2++;
}
return helix;
}
}
| true
|
8f3fb246f5c24980c742c4ede3089ba8151e839e
|
Java
|
jaboto/dhis2-android-capture-app
|
/tableview/src/main/java/com/evrencoskun/tableview/TableView.java
|
UTF-8
| 32,885
| 1.640625
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
/*
* Copyright (c) 2018. Evren Coşkun
*
* 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.evrencoskun.tableview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.AttrRes;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.evrencoskun.tableview.adapter.AbstractTableAdapter;
import com.evrencoskun.tableview.adapter.recyclerview.CellRecyclerView;
import com.evrencoskun.tableview.adapter.recyclerview.ColumnHeaderRecyclerViewAdapter;
import com.evrencoskun.tableview.adapter.recyclerview.holder.AbstractViewHolder;
import com.evrencoskun.tableview.filter.Filter;
import com.evrencoskun.tableview.handler.ColumnSortHandler;
import com.evrencoskun.tableview.handler.ColumnWidthHandler;
import com.evrencoskun.tableview.handler.FilterHandler;
import com.evrencoskun.tableview.handler.PreferencesHandler;
import com.evrencoskun.tableview.handler.ScrollHandler;
import com.evrencoskun.tableview.handler.SelectionHandler;
import com.evrencoskun.tableview.handler.VisibilityHandler;
import com.evrencoskun.tableview.layoutmanager.CellLayoutManager;
import com.evrencoskun.tableview.layoutmanager.ColumnHeaderLayoutManager;
import com.evrencoskun.tableview.listener.ITableViewListener;
import com.evrencoskun.tableview.listener.TableViewLayoutChangeListener;
import com.evrencoskun.tableview.listener.itemclick.ColumnHeaderRecyclerViewItemClickListener;
import com.evrencoskun.tableview.listener.itemclick.RowHeaderRecyclerViewItemClickListener;
import com.evrencoskun.tableview.listener.scroll.HorizontalRecyclerViewListener;
import com.evrencoskun.tableview.listener.scroll.VerticalRecyclerViewListener;
import com.evrencoskun.tableview.preference.SavedState;
import com.evrencoskun.tableview.sort.SortState;
import java.util.ArrayList;
import java.util.List;
/**
* Created by evrencoskun on 11/06/2017.
*/
public class TableView extends FrameLayout implements ITableView {
private static final String LOG_TAG = TableView.class.getSimpleName();
protected CellRecyclerView mCellRecyclerView;
protected CellRecyclerView mColumnHeaderRecyclerView;
protected List<CellRecyclerView> mColumnHeaderRecyclerViews = new ArrayList<>();
protected CellRecyclerView mRowHeaderRecyclerView;
protected AbstractTableAdapter mTableAdapter;
private ITableViewListener mTableViewListener;
private VerticalRecyclerViewListener mVerticalRecyclerListener;
private HorizontalRecyclerViewListener mHorizontalRecyclerViewListener;
private ColumnHeaderRecyclerViewItemClickListener mColumnHeaderRecyclerViewItemClickListener;
private RowHeaderRecyclerViewItemClickListener mRowHeaderRecyclerViewItemClickListener;
private List<ColumnHeaderLayoutManager> mColumnHeaderLayoutManagers = new ArrayList<>();
private LinearLayoutManager mRowHeaderLayoutManager;
private CellLayoutManager mCellLayoutManager;
private DividerItemDecoration mVerticalItemDecoration;
private DividerItemDecoration mHorizontalItemDecoration;
private SelectionHandler mSelectionHandler;
private ColumnSortHandler mColumnSortHandler;
private VisibilityHandler mVisibilityHandler;
private ScrollHandler mScrollHandler;
private FilterHandler mFilterHandler;
private PreferencesHandler mPreferencesHandler;
private ColumnWidthHandler mColumnWidthHandler;
private int mRowHeaderWidth;
private int mColumnHeaderHeight;
private int mHeaderHeight;
private int mHeaderWidth;
private int mSelectedColor;
private int mUnSelectedColor;
private int mShadowColor;
private int mSeparatorColor = -1;
private int mHeadersColor;
private boolean mHasFixedWidth;
private boolean mIgnoreSelectionColors;
private boolean mShowHorizontalSeparators = true;
private boolean mShowVerticalSeparators = true;
private boolean mIsSortable;
private int mHeaderCount = 1;
private List<CellRecyclerView> mBackupHeaders = new ArrayList<>();
private AbstractTableAdapter.OnScale scaleListener;
public TableView(@NonNull Context context) {
super(context);
initialDefaultValues(null);
initialize();
}
public TableView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initialDefaultValues(attrs);
initialize();
}
public TableView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int
defStyleAttr) {
super(context, attrs, defStyleAttr);
initialDefaultValues(null);
initialize();
}
private void initialDefaultValues(AttributeSet attrs) {
// Dimensions
mRowHeaderWidth = (int) getResources().getDimension(R.dimen.default_row_header_width);
mColumnHeaderHeight = (int) getResources().getDimension(R.dimen.default_column_header_height);
mHeaderHeight = (int) getResources().getDimension(R.dimen.small_column_header_height);
mHeaderWidth = (int) getResources().getDimension(R.dimen.small_row_header_width);
// Colors
mSelectedColor = ContextCompat.getColor(getContext(), R.color
.table_view_default_selected_background_color);
mUnSelectedColor = ContextCompat.getColor(getContext(), R.color
.table_view_default_unselected_background_color);
mShadowColor = ContextCompat.getColor(getContext(), R.color
.table_view_default_shadow_background_color);
mHeadersColor = ContextCompat.getColor(getContext(), R.color
.table_view_default_header_background_color);
if (attrs == null) {
// That means TableView is created programmatically.
return;
}
// Get values from xml attributes
TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable
.TableView, 0, 0);
try {
// Dimensions
mRowHeaderWidth = (int) a.getDimension(R.styleable.TableView_row_header_width,
mRowHeaderWidth);
mColumnHeaderHeight = (int) a.getDimension(R.styleable
.TableView_column_header_height, mColumnHeaderHeight);
// Colors
mSelectedColor = a.getColor(R.styleable.TableView_selected_color, mSelectedColor);
mUnSelectedColor = a.getColor(R.styleable.TableView_unselected_color, mUnSelectedColor);
mShadowColor = a.getColor(R.styleable.TableView_shadow_color, mShadowColor);
mSeparatorColor = a.getColor(R.styleable.TableView_separator_color, ContextCompat
.getColor(getContext(), R.color.table_view_default_separator_color));
// Booleans
mShowVerticalSeparators = a.getBoolean(R.styleable.TableView_show_vertical_separator,
mShowVerticalSeparators);
mShowHorizontalSeparators = a.getBoolean(R.styleable
.TableView_show_horizontal_separator, mShowHorizontalSeparators);
} finally {
a.recycle();
}
}
private void initialize() {
// Create Views
for (int i = 0; i < mHeaderCount; i++) {
mColumnHeaderRecyclerViews.add(createColumnHeaderRecyclerView(i));
}
mRowHeaderRecyclerView = createRowHeaderRecyclerView();
mCellRecyclerView = createCellRecyclerView();
// Add Views
for (int i = 0; i < mHeaderCount; i++) {
addView(mColumnHeaderRecyclerViews.get(i));
}
addView(mRowHeaderRecyclerView);
addView(mCellRecyclerView);
// Create Handlers
mSelectionHandler = new SelectionHandler(this);
mVisibilityHandler = new VisibilityHandler(this);
mScrollHandler = new ScrollHandler(this);
mPreferencesHandler = new PreferencesHandler(this);
mColumnWidthHandler = new ColumnWidthHandler(this);
mColumnHeaderRecyclerView = mColumnHeaderRecyclerViews.get(0);
mBackupHeaders = createHeaderBackUps();
initializeListeners();
}
protected void initializeListeners() {
// --- Listeners to help Scroll synchronously ---
// It handles Vertical scroll listener
mVerticalRecyclerListener = new VerticalRecyclerViewListener(this);
// Set this listener both of Cell RecyclerView and RowHeader RecyclerView
mRowHeaderRecyclerView.addOnItemTouchListener(mVerticalRecyclerListener);
mCellRecyclerView.addOnItemTouchListener(mVerticalRecyclerListener);
// It handles Horizontal scroll listener
mHorizontalRecyclerViewListener = new HorizontalRecyclerViewListener(this);
// Set scroll listener to be able to scroll all rows synchrony.
for (int i = 0; i < mHeaderCount; i++) {
mColumnHeaderRecyclerViews.get(i).addOnItemTouchListener(mHorizontalRecyclerViewListener);
mBackupHeaders.get(i).addOnItemTouchListener(mHorizontalRecyclerViewListener);
}
/*// --- Listeners to help item clicks ---
// Create item click listeners
mColumnHeaderRecyclerViewItemClickListener = new
ColumnHeaderRecyclerViewItemClickListener(mColumnHeaderRecyclerViews.get(mHeaderCount-1), this);
mRowHeaderRecyclerViewItemClickListener = new RowHeaderRecyclerViewItemClickListener
(mRowHeaderRecyclerView, this);
// Add item click listeners for both column header & row header recyclerView
mColumnHeaderRecyclerViews.get(mHeaderCount-1).addOnItemTouchListener
(mColumnHeaderRecyclerViewItemClickListener);
mRowHeaderRecyclerView.addOnItemTouchListener(mRowHeaderRecyclerViewItemClickListener);*/
// Add Layout change listener both of Column Header & Cell recyclerView to detect
// changing size
// For some case, it is pretty necessary.
TableViewLayoutChangeListener layoutChangeListener = new TableViewLayoutChangeListener
(this);
for (int i = 0; i < mHeaderCount; i++) {
mColumnHeaderRecyclerViews.get(i).addOnLayoutChangeListener(layoutChangeListener);
mBackupHeaders.get(i).addOnLayoutChangeListener(layoutChangeListener);
}
mCellRecyclerView.addOnLayoutChangeListener(layoutChangeListener);
}
protected CellRecyclerView createColumnHeaderRecyclerView(int header) {
CellRecyclerView recyclerView = new CellRecyclerView(getContext());
// Set layout manager
recyclerView.setLayoutManager(getColumnHeaderLayoutManager(header));
// Set layout params
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, mHeaderHeight);
layoutParams.setMarginStart(mRowHeaderWidth);
layoutParams.topMargin = mHeaderHeight * header;
recyclerView.setLayoutParams(layoutParams);
if (isShowHorizontalSeparators()) {
// Add vertical item decoration to display column line
recyclerView.addItemDecoration(getHorizontalItemDecoration());
recyclerView.addItemDecoration(getVerticalItemDecoration());
}
return recyclerView;
}
public List<CellRecyclerView> createHeaderBackUps() {
List<CellRecyclerView> headerBackups = new ArrayList<>();
for (int i = 0; i < mColumnHeaderLayoutManagers.size(); i++) {
CellRecyclerView recyclerView = new CellRecyclerView(getContext());
// Set layout manager
recyclerView.setLayoutManager(new ColumnHeaderLayoutManager(getContext(), this));
// Set layout params
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, mHeaderHeight);
layoutParams.setMarginStart(mRowHeaderWidth);
layoutParams.topMargin = mHeaderHeight * i;
recyclerView.setLayoutParams(layoutParams);
if (isShowHorizontalSeparators()) {
// Add vertical item decoration to display column line
recyclerView.addItemDecoration(getHorizontalItemDecoration());
recyclerView.addItemDecoration(getVerticalItemDecoration());
}
ColumnHeaderRecyclerViewAdapter adapter = (ColumnHeaderRecyclerViewAdapter) mColumnHeaderRecyclerViews.get(i).getAdapter();
recyclerView.setAdapter(adapter);
headerBackups.add(recyclerView);
}
return headerBackups;
}
protected CellRecyclerView createRowHeaderRecyclerView() {
if (mRowHeaderRecyclerView == null) {
mRowHeaderRecyclerView = new CellRecyclerView(getContext());
// Set layout manager
mRowHeaderRecyclerView.setLayoutManager(getRowHeaderLayoutManager());
} else {
// Set layout params
LayoutParams layoutParams = new LayoutParams(mRowHeaderWidth, LayoutParams.WRAP_CONTENT);
layoutParams.topMargin = mHeaderHeight * mHeaderCount;
mRowHeaderRecyclerView.setLayoutParams(layoutParams);
if (isShowVerticalSeparators()) {
// Add vertical item decoration to display row line
mRowHeaderRecyclerView.addItemDecoration(getVerticalItemDecoration());
mRowHeaderRecyclerView.addItemDecoration(getHorizontalItemDecoration());
}
}
return mRowHeaderRecyclerView;
}
protected CellRecyclerView createCellRecyclerView() {
if (mCellRecyclerView == null) {
mCellRecyclerView = new CellRecyclerView(getContext());
// Disable multitouch
mCellRecyclerView.setMotionEventSplittingEnabled(false);
// Set layout manager
mCellRecyclerView.setLayoutManager(getCellLayoutManager());
} else {
// Set layout params
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams
.WRAP_CONTENT);
layoutParams.setMarginStart(mRowHeaderWidth);
layoutParams.topMargin = mHeaderHeight * mHeaderCount;
mCellRecyclerView.setLayoutParams(layoutParams);
if (isShowVerticalSeparators()) {
// Add vertical item decoration to display row line on center recycler view
mCellRecyclerView.addItemDecoration(getVerticalItemDecoration());
}
}
return mCellRecyclerView;
}
public void setAdapter(AbstractTableAdapter tableAdapter) {
if (tableAdapter != null) {
this.mTableAdapter = tableAdapter;
this.mTableAdapter.setRowHeaderWidth(mRowHeaderWidth);
this.mTableAdapter.setColumnHeaderHeight(mColumnHeaderHeight);
this.mTableAdapter.setHeaderHeight(mHeaderHeight);
this.mTableAdapter.setTableView(this);
// set adapters
for (int i = 0; i < mHeaderCount; i++) {
if (mColumnHeaderRecyclerViews.get(i) != null) {
mColumnHeaderRecyclerViews.get(i).setAdapter(mTableAdapter
.getColumnHeaderRecyclerViewAdapter(i));
}
if (mBackupHeaders.get(i) != null) {
mBackupHeaders.get(i).setAdapter(mTableAdapter
.getColumnHeaderRecyclerViewAdapter(i));
}
}
if (mRowHeaderRecyclerView != null) {
mRowHeaderRecyclerView.setAdapter(mTableAdapter.getRowHeaderRecyclerViewAdapter());
}
if (mCellRecyclerView != null) {
mCellRecyclerView.setAdapter(mTableAdapter.getCellRecyclerViewAdapter());
// Create Sort Handler
mColumnSortHandler = new ColumnSortHandler(this);
// Create Filter Handler
mFilterHandler = new FilterHandler(this);
}
tableAdapter.setOnScaleListener(new AbstractTableAdapter.OnScale() {
@Override
public void scaleTo(int width, int height) {
//ROW HEADERS
FrameLayout.LayoutParams mRowHeaderParams = ((FrameLayout.LayoutParams) mRowHeaderRecyclerView.getLayoutParams());
mRowHeaderParams.topMargin = height * mHeaderCount;
//COLUMN HEADERS
for (int i = 0; i < mColumnHeaderRecyclerViews.size(); i++) {
FrameLayout.LayoutParams mColumnHeaderParams = ((FrameLayout.LayoutParams) mColumnHeaderRecyclerViews.get(i).getLayoutParams());
FrameLayout.LayoutParams mBuckupHeaderParams = ((FrameLayout.LayoutParams) mBackupHeaders.get(i).getLayoutParams());
mColumnHeaderParams.height = height;
mColumnHeaderParams.topMargin = height * i;
mBuckupHeaderParams.height = height;
mBuckupHeaderParams.topMargin = height * i;
mBackupHeaders.get(i).scrollToPosition(0);
}
//CELL HEADERS
FrameLayout.LayoutParams mCellHeaderParams = ((FrameLayout.LayoutParams) mCellRecyclerView.getLayoutParams());
mCellHeaderParams.topMargin = height * mHeaderCount;
scrollToColumnPosition(0);
//Corner
if (getAdapter().getCornerView() != null) {
FrameLayout.LayoutParams mCornerHeaderParams = ((FrameLayout.LayoutParams) getAdapter().getCornerView().getLayoutParams());
mCornerHeaderParams.height = height * mHeaderCount;
}
}
});
}
}
@Override
public boolean hasFixedWidth() {
return mHasFixedWidth;
}
public void setHasFixedWidth(boolean hasFixedWidth) {
this.mHasFixedWidth = hasFixedWidth;
// RecyclerView has also the same control to provide better performance.
mColumnHeaderRecyclerView.setHasFixedSize(hasFixedWidth);
}
@Override
public boolean isIgnoreSelectionColors() {
return mIgnoreSelectionColors;
}
public void setIgnoreSelectionColors(boolean ignoreSelectionColor) {
this.mIgnoreSelectionColors = ignoreSelectionColor;
}
@Override
public boolean isShowHorizontalSeparators() {
return mShowHorizontalSeparators;
}
@Override
public boolean isSortable() {
return mIsSortable;
}
public void setShowHorizontalSeparators(boolean showSeparators) {
this.mShowHorizontalSeparators = showSeparators;
}
@Override
public boolean isShowVerticalSeparators() {
return mShowVerticalSeparators;
}
public void setShowVerticalSeparators(boolean showSeparators) {
this.mShowVerticalSeparators = showSeparators;
}
@Override
public CellRecyclerView getCellRecyclerView() {
return mCellRecyclerView;
}
@Override
public CellRecyclerView getColumnHeaderRecyclerView(int header) {
return mColumnHeaderRecyclerViews.get(header);
}
@Override
public List<CellRecyclerView> getColumnHeaderRecyclerView() {
return mColumnHeaderRecyclerViews;
}
@Override
public CellRecyclerView getRowHeaderRecyclerView() {
return mRowHeaderRecyclerView;
}
@Override
public ColumnHeaderLayoutManager getColumnHeaderLayoutManager(int index) {
if (index >= mColumnHeaderLayoutManagers.size()) {
mColumnHeaderLayoutManagers.add(new ColumnHeaderLayoutManager(getContext(), this));
}
return mColumnHeaderLayoutManagers.get(index);
}
@Override
public CellLayoutManager getCellLayoutManager() {
if (mCellLayoutManager == null) {
mCellLayoutManager = new CellLayoutManager(getContext(), this);
}
return mCellLayoutManager;
}
@Override
public LinearLayoutManager getRowHeaderLayoutManager() {
if (mRowHeaderLayoutManager == null) {
mRowHeaderLayoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false);
}
return mRowHeaderLayoutManager;
}
@Override
public HorizontalRecyclerViewListener getHorizontalRecyclerViewListener() {
return mHorizontalRecyclerViewListener;
}
@Override
public VerticalRecyclerViewListener getVerticalRecyclerViewListener() {
return mVerticalRecyclerListener;
}
@Override
public ITableViewListener getTableViewListener() {
return mTableViewListener;
}
public void setTableViewListener(ITableViewListener tableViewListener) {
this.mTableViewListener = tableViewListener;
}
@Override
public void sortColumn(int columnPosition, SortState sortState) {
mIsSortable = true;
mColumnSortHandler.sort(columnPosition, sortState);
}
@Override
public void sortRowHeader(SortState sortState) {
mIsSortable = true;
mColumnSortHandler.sortByRowHeader(sortState);
}
@Override
public void remeasureColumnWidth(int column) {
// Remove calculated width value to be ready for recalculation.
mColumnHeaderLayoutManagers.get(0).removeCachedWidth(column);
// Recalculate of the width values of the columns
getCellLayoutManager().fitWidthSize(column, false);
}
@Override
public AbstractTableAdapter getAdapter() {
return mTableAdapter;
}
@Override
public void filter(Filter filter) {
mFilterHandler.filter(filter);
}
@Override
public FilterHandler getFilterHandler() {
return mFilterHandler;
}
@Override
public SortState getSortingStatus(int column) {
return mColumnSortHandler.getSortingStatus(column);
}
@Override
public SortState getRowHeaderSortingStatus() {
return mColumnSortHandler.getRowHeaderSortingStatus();
}
@Override
public void scrollToColumnPosition(int column) {
mScrollHandler.scrollToColumnPosition(column);
}
@Override
public void scrollToColumnPosition(int column, int offset) {
mScrollHandler.scrollToColumnPosition(column, offset);
}
@Override
public void scrollToRowPosition(int row) {
mScrollHandler.scrollToRowPosition(row);
}
@Override
public void scrollToRowPosition(int row, int offset) {
mScrollHandler.scrollToRowPosition(row, offset);
}
public ScrollHandler getScrollHandler() {
return mScrollHandler;
}
@Override
public int getHeaderCount() {
return mHeaderCount;
}
@Override
public List<CellRecyclerView> getBackupHeaders() {
return this.mBackupHeaders;
}
@Override
public void showRow(int row) {
mVisibilityHandler.showRow(row);
}
@Override
public void hideRow(int row) {
mVisibilityHandler.hideRow(row);
}
@Override
public void showAllHiddenRows() {
mVisibilityHandler.showAllHiddenRows();
}
@Override
public void clearHiddenRowList() {
mVisibilityHandler.clearHideRowList();
}
@Override
public void showColumn(int column) {
mVisibilityHandler.showColumn(column);
}
@Override
public void hideColumn(int column) {
mVisibilityHandler.hideColumn(column);
}
@Override
public boolean isColumnVisible(int column) {
return mVisibilityHandler.isColumnVisible(column);
}
@Override
public void showAllHiddenColumns() {
mVisibilityHandler.showAllHiddenColumns();
}
@Override
public void clearHiddenColumnList() {
mVisibilityHandler.clearHideColumnList();
}
@Override
public boolean isRowVisible(int row) {
return mVisibilityHandler.isRowVisible(row);
}
/**
* Returns the index of the selected row, -1 if no row is selected.
*/
public int getSelectedRow() {
return mSelectionHandler.getSelectedRowPosition();
}
public void setSelectedRow(int row) {
// Find the row header view holder which is located on row position.
AbstractViewHolder rowViewHolder = (AbstractViewHolder) getRowHeaderRecyclerView()
.findViewHolderForAdapterPosition(row);
mSelectionHandler.setSelectedRowPosition(rowViewHolder, row);
}
/**
* Returns the index of the selected column, -1 if no column is selected.
*/
public int getSelectedColumn() {
return mSelectionHandler.getSelectedColumnPosition();
}
public void setSelectedColumn(int column) {
// Find the column view holder which is located on column position .
AbstractViewHolder columnViewHolder = (AbstractViewHolder) getColumnHeaderRecyclerView(0)
.findViewHolderForAdapterPosition(column);
mSelectionHandler.setSelectedColumnPosition(columnViewHolder, column);
}
public void setSelectedCell(int column, int row) {
// Find the cell view holder which is located on x,y (column,row) position.
AbstractViewHolder cellViewHolder = getCellLayoutManager().getCellViewHolder(column, row);
mSelectionHandler.setSelectedCellPositions(cellViewHolder, column, row);
}
@Override
public SelectionHandler getSelectionHandler() {
return mSelectionHandler;
}
@Override
public ColumnSortHandler getColumnSortHandler() {
return mColumnSortHandler;
}
@Override
public DividerItemDecoration getHorizontalItemDecoration() {
if (mHorizontalItemDecoration == null) {
mHorizontalItemDecoration = createItemDecoration(DividerItemDecoration.HORIZONTAL);
}
return mHorizontalItemDecoration;
}
@Override
public DividerItemDecoration getVerticalItemDecoration() {
if (mVerticalItemDecoration == null) {
mVerticalItemDecoration = createItemDecoration(DividerItemDecoration.VERTICAL);
}
return mVerticalItemDecoration;
}
protected DividerItemDecoration createItemDecoration(int orientation) {
Drawable divider = ContextCompat.getDrawable(getContext(), R.drawable.cell_line_divider);
// That means; There is a custom separator color from user.
if (mSeparatorColor != -1) {
// Change its color
divider.setColorFilter(mSeparatorColor, PorterDuff.Mode.SRC_ATOP);
}
DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), orientation);
itemDecoration.setDrawable(divider);
return itemDecoration;
}
public void setHeaderCount(int headerCount) {
this.mHeaderCount = headerCount;
clear();
initialize();
mTableAdapter.setTableView(this);
setAdapter(mTableAdapter);
}
private void clear() {
mColumnHeaderRecyclerViews.clear();
mColumnHeaderLayoutManagers.clear();
mTableAdapter.clear();
removeAllViews();
}
/**
* This method helps to change default selected color programmatically.
*
* @param selectedColor It must be Color int.
*/
public void setSelectedColor(@ColorInt int selectedColor) {
this.mSelectedColor = selectedColor;
}
@Override
public @ColorInt
int getSelectedColor() {
return mSelectedColor;
}
public void setSeparatorColor(@ColorInt int mSeparatorColor) {
this.mSeparatorColor = mSeparatorColor;
}
@Override
public @ColorInt
int getSeparatorColor() {
return mSeparatorColor;
}
/**
* This method helps to change default unselected color programmatically.
*
* @param unSelectedColor It must be Color int.
*/
public void setUnSelectedColor(@ColorInt int unSelectedColor) {
this.mUnSelectedColor = unSelectedColor;
}
@Override
public @ColorInt
int getUnSelectedColor() {
return mUnSelectedColor;
}
public void setHeadersColor(@ColorInt int mHeadersColor) {
this.mHeadersColor = mHeadersColor;
}
@Override
public @ColorInt
int getHeadersColor() {
return mHeadersColor;
}
public void setShadowColor(@ColorInt int shadowColor) {
this.mShadowColor = shadowColor;
}
@Override
public @ColorInt
int getShadowColor() {
return mShadowColor;
}
/**
* get header width
*
* @return size in pixel
*/
@Override
public int getHeaderWidth() {
return mHeaderWidth;
}
/**
* set RowHeaderWidth
*
* @param rowHeaderWidth in pixel
*/
@Override
public void setRowHeaderWidth(int rowHeaderWidth) {
this.mRowHeaderWidth = rowHeaderWidth;
if (mRowHeaderRecyclerView != null) {
// Update RowHeader layout width
ViewGroup.LayoutParams layoutParams = mRowHeaderRecyclerView.getLayoutParams();
layoutParams.width = rowHeaderWidth;
mRowHeaderRecyclerView.setLayoutParams(layoutParams);
mRowHeaderRecyclerView.requestLayout();
}
if (mColumnHeaderRecyclerView != null) {
// Update ColumnHeaders left margin
for (CellRecyclerView mColumnHeaderRecyclerView : mColumnHeaderRecyclerViews) {
LayoutParams layoutParams = (LayoutParams) mColumnHeaderRecyclerView.getLayoutParams();
layoutParams.setMarginStart(rowHeaderWidth);
mColumnHeaderRecyclerView.setLayoutParams(layoutParams);
mColumnHeaderRecyclerView.requestLayout();
}
}
if (mCellRecyclerView != null) {
// Update Cells left margin
LayoutParams layoutParams = (LayoutParams) mCellRecyclerView.getLayoutParams();
layoutParams.setMarginStart(rowHeaderWidth);
mCellRecyclerView.setLayoutParams(layoutParams);
mCellRecyclerView.requestLayout();
}
if (mBackupHeaders != null) {
// Update BackupHeaders left margin
for (CellRecyclerView mBackupHeader : mBackupHeaders) {
LayoutParams layoutParams = (LayoutParams) mBackupHeader.getLayoutParams();
layoutParams.setMarginStart(rowHeaderWidth);
mBackupHeader.setLayoutParams(layoutParams);
mBackupHeader.requestLayout();
}
}
if (getAdapter() != null) {
// update CornerView size
getAdapter().setRowHeaderWidth(rowHeaderWidth);
}
}
@Override
public void setCellHeight(int hcellHeight) {
mColumnHeaderHeight = hcellHeight;
}
public void setColumnWidth(int columnPosition, int width) {
mColumnWidthHandler.setColumnWidth(columnPosition, width);
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState state = new SavedState(super.onSaveInstanceState());
// Save all preferences of The TableView before the configuration changed.
state.preferences = mPreferencesHandler.savePreferences();
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
// Reload the preferences
mPreferencesHandler.loadPreferences(savedState.preferences);
scrollToColumnPosition(mScrollHandler.getColumnPosition());
}
public View getCornerView() {
return getAdapter().getCornerView();
}
}
| true
|
c908f4c7df841e29faa5dfcd2022c8ca7d09f9ba
|
Java
|
lima-caio/role-service
|
/src/main/java/com/marvin/roleservice/rest/dto/RoleCreationDto.java
|
UTF-8
| 422
| 1.984375
| 2
|
[] |
no_license
|
package com.marvin.roleservice.rest.dto;
import com.marvin.roleservice.domain.Role;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* Data transfer object for {@link Role} creation.
*/
@Data
public class RoleCreationDto {
@ApiModelProperty(value = "name", position = 1)
private String name;
@ApiModelProperty(value = "description", position = 2)
private String description;
}
| true
|
e89552c4e033bf459b336a922fa14437ade21d29
|
Java
|
akmred/RNPT
|
/app/src/main/java/com/example/rnpt/fragments/FragmentOpenRNPT.java
|
UTF-8
| 2,290
| 2.0625
| 2
|
[] |
no_license
|
package com.example.rnpt.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.rnpt.R;
import com.example.rnpt.connection.authorization.ConvertDataAnswerCenterConnection;
import com.example.rnpt.connection.getpost.CenterConnectionRnpt;
import com.example.rnpt.connection.getpost.model.getid.ResponseInfo;
public class FragmentOpenRNPT extends Fragment {
String stringRNPT;
public FragmentOpenRNPT() {
}
public FragmentOpenRNPT(String stringRNPT) {
this.stringRNPT = stringRNPT;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_open_rnpt, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Инициализиуем переменные
initializationVariable(view);
initializationRequest();
// Заполняем реквизиты тестовыми данными
setTestingData();
// Заполняем форму
fillInDataOnForm(view);
}
// Выполняем асихронный запрос к сервису ФНС
private void initializationRequest() {
CenterConnectionRnpt convertDataAnswerCenterConnection= new CenterConnectionRnpt(stringRNPT, getActivity());
convertDataAnswerCenterConnection.infoCheck();
}
// При получении информации по РНППТ вызывается эта процедура
public void downLoadInfoRNPT(ResponseInfo responseInfo){
System.out.println("Здесь загружаем в фрагмент информацию по РНПТ");
}
private void initializationVariable(View view) {
}
private void setTestingData() {
}
private void fillInDataOnForm(View view) {
}
}
| true
|
ffd7bf25c2be2c24c8cd767bd58c029e3ebdb3a4
|
Java
|
scaiocesar/voy-microservices
|
/auth-common/src/main/java/com/voy/auth/model/UserActive.java
|
UTF-8
| 316
| 1.859375
| 2
|
[] |
no_license
|
package com.voy.auth.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by Bozo on 05/11/2015.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserActive {
public Boolean isActive;
public UserActive(){}
public UserActive(Boolean b){this.isActive = b;}
}
| true
|
d713ea828df5e9b742676e63a31feedb572db63a
|
Java
|
checkermu/LeetCode
|
/easy/LongestSubStringNo.java
|
UTF-8
| 3,983
| 3.828125
| 4
|
[] |
no_license
|
package com.uestc.gt.easy;
/**
* author: checkermu email:guotaoleng@163.com
* time: 2015年6月17日下午7:47:27
* Given a string, find the length of the longest substring without repeating characters.
* For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
* For "bbbbb" the longest substring is "b", with the length of 1.
*/
public class LongestSubStringNo {
public static void main(String[] args) {
// TODO Auto-generated method stub
LongestSubStringNo ls = new LongestSubStringNo();
String s = "hello world";
// String s = "dvdf";
System.out.println(ls.longestSubNew(s));
System.out.println(ls.func(s));
}
/**
* from internet
* @param s
* @return
*/
public int lengthOfLongestSubstring(String s) {
int res = 0, left = 0;
int prev[] = new int[300];
// init prev array
for (int i = 0; i < 300; ++i)
prev[i] = -1;
for (int i = 0; i < s.length(); ++i) {
if (prev[s.charAt(i)] >= left)
left = prev[s.charAt(i)] + 1;
prev[s.charAt(i)] = i;
if (res < i - left + 1)
res = i - left + 1;
}
return res;
}
/**
* hash table的用法,用重复的进行比较,
* 每次进行重复的比较,数组当前字符ascii下标位置存放的是当前字符在String的下标,
* 如果一直没有重复字符,那就最后的下标j减去0再1就是最长的字符,这个没问题。
* 如果有重复的,start就变为这个重复的下标索引再加1,后面的j一直减去这个start,和一开始最大的max长度比较。
* 在没碰到这个重复之前有个最长的,碰到了之后会一直变化,进行比较。
* @param s
* @return
*/
public int func(String s){
int[] count = new int[256];
for (int i=0; i<256; i++)
count[i]=-1;
int max =1;
int start = 0;
for(int j=0; j<s.length(); j++){
if(count[s.charAt(j)]>=start)
start = count[s.charAt(j)]+1;
count[s.charAt(j)] = j;
max = Math.max(max, j-start+1);
}
return max;
}
/**
* 修改后正确,但是时间超时
* 思想:采用动态规划思想,发现这里不能用动态规划思想,因为最优解的子解不是子解的最优解,如dvdf,最优解是 vdf,而并不是,发现是动态规划思想
* 这个是考虑连续的最长串,当前字符在与之前的没有重复则之前的length+1,有重复则重置为1.
* 需要注意的是如果有重复重置为1的话,后面的字符的比较子串会发生变化,这个版本有错,如 dvdf,输出应该是3,但是实际却是2
* 旧版本,思想比较简单,遇到dvdf这种情况输出2,而不是3
* @param s
* @return
* //超时了!!!
*/
public int longestSubNew(String s){
if(s.equals("")||s.equals(null))
return 0;
else{
char[] charArr = s.toCharArray();
int[] length = new int[charArr.length];
length[0]=1;
int max = 1;
int tmp=0;
for(int i=1; i<charArr.length; i++){
String sTmp = s.substring(tmp, i);
if(sTmp.indexOf(charArr[i])==-1)
length[i]=length[i-1]+1;
else{
//与之前的区别,在tmp的指定和有问题i的length[i]认定上重新计算
tmp=s.substring(0, i).lastIndexOf(charArr[i])+1;
length[i]=i-tmp+1;
}
if(length[i]>max)
max=length[i];
}
return max;
}
}
/**
* 错误版本,
* @param s
* @return
*/
public int longestSub(String s){
if(s.equals("")||s.equals(null))
return 0;
else{
char[] charArr = s.toCharArray();
int[] length = new int[charArr.length];
length[0]=1;
int max = 1;
int tmp=0;
for(int i=1; i<charArr.length; i++){
length[i]=1;
for(int j=i-1; j>=tmp; j--){
if(charArr[j]!=charArr[i])
length[i]++;
else{
tmp=j+1;
break;
}
}
if(length[i]>max)
max=length[i];
}
return max;
}
}
}
| true
|
25d0ed78fe5cd8b1367cd6537c7113afc866265f
|
Java
|
apache/servicemix-components
|
/engines/servicemix-bean/src/test/java/org/apache/servicemix/bean/LoggingPojoTest.java
|
UTF-8
| 11,842
| 1.960938
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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.servicemix.bean;
import junit.framework.TestCase;
import org.apache.servicemix.bean.pojos.LoggingPojo;
import org.apache.servicemix.client.ServiceMixClient;
import org.apache.servicemix.client.ServiceMixClientFacade;
import org.apache.servicemix.jbi.container.JBIContainer;
import org.apache.servicemix.jbi.jaxp.StringSource;
import org.slf4j.Logger;
import org.slf4j.Marker;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.jbi.messaging.*;
import javax.xml.namespace.QName;
import java.util.LinkedList;
import java.util.List;
public class LoggingPojoTest extends TestCase {
protected JBIContainer container;
protected BeanComponent component;
protected List<String> messages;
protected void setUp() throws Exception {
container = new JBIContainer();
container.setEmbedded(true);
container.init();
component = new BeanComponent();
messages = new LinkedList<String>();
BeanEndpoint loggingEndpoint = new BeanEndpoint();
LoggingPojo pojo = new LoggingPojo();
pojo.setMaxMsgDisplaySize(35);
pojo.setLog(new MyLogger("my-logger"));
loggingEndpoint.setBean(pojo);
loggingEndpoint.setService(new QName("logging"));
loggingEndpoint.setInterfaceName(new QName("logservice"));
loggingEndpoint.setEndpoint("endpoint");
component.addEndpoint(loggingEndpoint);
container.activateComponent(component, "servicemix-bean");
container.start();
}
protected void tearDown() throws Exception {
container.shutDown();
}
public void testInOnly() throws Exception {
ServiceMixClient client = new ServiceMixClientFacade(component.getComponentContext());
InOnly exchange = client.createInOnlyExchange();
fillExchange(exchange);
client.sendSync(exchange);
assertEquals(ExchangeStatus.DONE, exchange.getStatus());
assertLog();
}
public void testInOnlyWithWrongContent() throws Exception {
ServiceMixClient client = new ServiceMixClientFacade(component.getComponentContext());
InOnly exchange = client.createInOnlyExchange();
fillExchange(exchange);
exchange.getInMessage().setContent(new StringSource("This is not XML!"));
client.sendSync(exchange);
assertEquals(ExchangeStatus.DONE, exchange.getStatus());
assertLog();
assertTrue(messages.get(0).contains("Unable to display:"));
}
public void testInOut() throws Exception {
ServiceMixClient client = new ServiceMixClientFacade(component.getComponentContext());
InOut exchange = client.createInOutExchange();
fillExchange(exchange);
client.sendSync(exchange);
assertEquals(ExchangeStatus.ACTIVE, exchange.getStatus());
client.done(exchange);
assertLog();
}
private void fillExchange(MessageExchange exchange) throws MessagingException {
exchange.setService(new QName("logging"));
exchange.setInterfaceName(new QName("logservice"));
exchange.setOperation(new QName("log"));
exchange.setProperty("xml", new StringSource("<an>XML value</an>"));
exchange.getMessage("in").setContent(new StringSource("<hello>world</hello>"));
exchange.getMessage("in").setProperty("key", "value");
exchange.getMessage("in").setProperty("xml", new StringSource("<an>XML value</an>"));
exchange.getMessage("in").addAttachment("attachment", new DataHandler(new FileDataSource("src/test/resources/attachment.png")));
}
private void assertLog() {
assertEquals(1, messages.size());
String message = messages.get(0);
assertTrue(message.contains("service: logging"));
assertTrue(message.contains("endpoint: endpoint"));
assertTrue(message.contains("interface: logservice"));
assertTrue(message.contains("operation: log"));
assertTrue(message.contains("key = value"));
assertTrue(message.contains("xml = <an>XML value</an>"));
assertTrue(message.contains("attachments:"));
}
private class MyLogger implements Logger {
private String name;
public MyLogger(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void debug(String message) {
messages.add(message);
}
public void debug(Marker marker, String format, Object args1, Object args2) {
messages.add(marker.toString());
}
public void debug(Marker marker, String format, Object args) {
messages.add(marker.toString());
}
public void debug(Marker marker, String format, Object[] args) {
messages.add(marker.toString());
}
public void debug(Marker marker, String format) {
messages.add(marker.toString());
}
public void debug(Marker marker, String format, Throwable cause) {
messages.add(marker.toString());
}
public void debug(String message, Object args1, Object args2) {
messages.add(message);
}
public void debug(String message, Throwable cause) {
messages.add(message);
}
public void debug(String message, Object args) {
messages.add(message);
}
public void debug(String message, Object[] args) {
messages.add(message);
}
public void trace(Marker marker, String format, Object arg1, Object arg2) {
messages.add(marker.toString());
}
public void trace(Marker marker, String format) {
messages.add(marker.toString());
}
public void trace(String message, Object args) {
messages.add(message);
}
public void trace(String message, Throwable cause) {
messages.add(message);
}
public void trace(String message, Object[] args) {
messages.add(message);
}
public void trace(Marker marker, String format, Throwable cause) {
messages.add(marker.toString());
}
public void trace(Marker marker, String format, Object[] args) {
messages.add(marker.toString());
}
public void trace(Marker marker, String format, Object args) {
messages.add(marker.toString());
}
public void trace(String message, Object args1, Object args2) {
messages.add(message);
}
public void trace(String message) {
messages.add(message);
}
public void info(String message, Throwable cause) {
messages.add(message);
}
public void info(Marker marker, String format, Object[] argArray) {
messages.add(marker.toString());
}
public void info(Marker marker, String format, Throwable cause) {
messages.add(marker.toString());
}
public void info(Marker marker, String format, Object args) {
messages.add(marker.toString());
}
public void info(String message, Object[] args) {
messages.add(message);
}
public void info(String message, Object args) {
messages.add(message + args.toString());
}
public void info(String message, Object args1, Object args2) {
messages.add(message);
}
public void info(Marker marker, String format, Object args1, Object args2) {
messages.add(marker.toString());
}
public void info(Marker marker, String format) {
messages.add(marker.toString());
}
public void info(String message) {
messages.add(message);
}
public void warn(Marker marker, String format, Throwable cause) {
messages.add(marker.toString());
}
public void warn(Marker marker, String format, Object[] argArray) {
messages.add(marker.toString());
}
public void warn(String message, Object args1, Object args2) {
messages.add(message);
}
public void warn(String message, Object args) {
messages.add(message);
}
public void warn(Marker marker, String format, Object args) {
messages.add(marker.toString());
}
public void warn(String message, Throwable cause) {
messages.add(message);
}
public void warn(String message, Object[] args) {
messages.add(message);
}
public void warn(Marker marker, String format, Object args1, Object args2) {
messages.add(marker.toString());
}
public void warn(String message) {
messages.add(message);
}
public void warn(Marker marker, String format) {
messages.add(marker.toString());
}
public void error(String message, Throwable cause) {
messages.add(message);
}
public void error(String message, Object[] args) {
messages.add(message);
}
public void error(String message, Object args) {
messages.add(message);
}
public void error(String message) {
messages.add(message);
}
public void error(String message, Object args1, Object args2) {
messages.add(message);
}
public void error(Marker marker, String format, Throwable cause) {
messages.add(marker.toString());
}
public void error(Marker marker, String format, Object[] args) {
messages.add(marker.toString());
}
public void error(Marker marker, String format, Object args) {
messages.add(marker.toString());
}
public void error(Marker marker, String format) {
messages.add(marker.toString());
}
public void error(Marker marker, String format, Object args1, Object args2) {
messages.add(marker.toString());
}
public boolean isDebugEnabled(Marker marker) {
return true;
}
public boolean isErrorEnabled(Marker marker) {
return true;
}
public boolean isInfoEnabled(Marker marker) {
return true;
}
public boolean isTraceEnabled(Marker marker) {
return true;
}
public boolean isWarnEnabled(Marker marker) {
return true;
}
public boolean isInfoEnabled() {
return true;
}
public boolean isWarnEnabled() {
return true;
}
public boolean isErrorEnabled() {
return true;
}
public boolean isDebugEnabled() {
return true;
}
public boolean isTraceEnabled() {
return true;
}
}
}
| true
|
e91762820b3927117507956dde00344af4ae4399
|
Java
|
aligaber2020/projects
|
/src/main/java/com/app/datatransferobject/CountryDTO.java
|
UTF-8
| 1,068
| 2.03125
| 2
|
[] |
no_license
|
package com.app.datatransferobject;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CountryDTO {
private Long ID;
private String COUNTRYNAME;
private String ALIAS;
private String CODE;
private String PHONE_NUMBER;
private String FAX_NUMBER;
private String DESCRIPTION;
public Long getID() {
return ID;
}
public void setID(Long iD) {
ID = iD;
}
public String getALIAS() {
return ALIAS;
}
public void setALIAS(String aLIAS) {
ALIAS = aLIAS;
}
public String getCODE() {
return CODE;
}
public void setCODE(String cODE) {
CODE = cODE;
}
public String getPHONE_NUMBER() {
return PHONE_NUMBER;
}
public void setPHONE_NUMBER(String pHONE_NUMBER) {
PHONE_NUMBER = pHONE_NUMBER;
}
public String getFAX_NUMBER() {
return FAX_NUMBER;
}
public void setFAX_NUMBER(String fAX_NUMBER) {
FAX_NUMBER = fAX_NUMBER;
}
public String getDESCRIPTION() {
return DESCRIPTION;
}
public void setDESCRIPTION(String dESCRIPTION) {
DESCRIPTION = dESCRIPTION;
}
}
| true
|
bd6d723417094501f37562c475c9550c237c2ad4
|
Java
|
STPS-PORTALDIGITAL/Portal-Empleo-Nuevo
|
/PortalDigital/src/main/java/stps/gob/mx/dto/InicioDTO.java
|
UTF-8
| 1,482
| 1.992188
| 2
|
[] |
no_license
|
package stps.gob.mx.dto;
import java.util.List;
public class InicioDTO {
private List<String> listaEmpleos;//ok
private List<String> listaMunicipiosEntidad;
private List<String> listaFerias;
private List<String> listaConvocatorias;
private int numeroOfertasEmpleo;//ok
private int numeroCandidatos;
public List<String> getListaEmpleos() {
return listaEmpleos;
}
public void setListaEmpleos(List<String> listaEmpleos) {
this.listaEmpleos = listaEmpleos;
}
public List<String> getListaMunicipiosEntidad() {
return listaMunicipiosEntidad;
}
public void setListaMunicipiosEntidad(List<String> listaMunicipiosEntidad) {
this.listaMunicipiosEntidad = listaMunicipiosEntidad;
}
public List<String> getListaFerias() {
return listaFerias;
}
public void setListaFerias(List<String> listaFerias) {
this.listaFerias = listaFerias;
}
public List<String> getListaConvocatorias() {
return listaConvocatorias;
}
public void setListaConvocatorias(List<String> listaConvocatorias) {
this.listaConvocatorias = listaConvocatorias;
}
public int getNumeroOfertasEmpleo() {
return numeroOfertasEmpleo;
}
public void setNumeroOfertasEmpleo(int numeroOfertasEmpleo) {
this.numeroOfertasEmpleo = numeroOfertasEmpleo;
}
public int getNumeroCandidatos() {
return numeroCandidatos;
}
public void setNumeroCandidatos(int numeroCandidatos) {
this.numeroCandidatos = numeroCandidatos;
}
}
| true
|
f81ca6c8b412a09722d3a627f695f273a25bc8df
|
Java
|
conceptslearningmachine-FEIN-85-1759293/fssi-file-processor
|
/src/main/java/gov/gsa/fssi/files/sourcefiles/utils/SourceFileValidator.java
|
UTF-8
| 3,279
| 2.609375
| 3
|
[] |
no_license
|
package main.java.gov.gsa.fssi.files.sourcefiles.utils;
import main.java.gov.gsa.fssi.files.File;
import main.java.gov.gsa.fssi.files.schemas.schemafields.SchemaField;
import main.java.gov.gsa.fssi.files.schemas.schemafields.fieldconstraints.FieldConstraint;
import main.java.gov.gsa.fssi.files.sourcefiles.SourceFile;
import main.java.gov.gsa.fssi.files.sourcefiles.records.SourceFileRecord;
import main.java.gov.gsa.fssi.files.sourcefiles.records.datas.Data;
import main.java.gov.gsa.fssi.files.sourcefiles.utils.contexts.ConstraintValidationContext;
import main.java.gov.gsa.fssi.files.sourcefiles.utils.contexts.TypeValidationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The purpose of this class is to handle the automated processing of all source
* files.
*
* @author davidlarrimore
*
*/
public class SourceFileValidator {
static Logger logger = LoggerFactory.getLogger(SourceFileValidator.class);
public void validate(SourceFile sourceFile) {
logger.info(
"Starting sourceFile validation for file '{}'. it is in '{}' status",
sourceFile.getFileName(), sourceFile.getStatusName());
if (sourceFile.getSchema() == null) {
logger.error("Cannot validate file '{}', it has no Schema",
sourceFile.getFileName());
} else if (!sourceFile.getStatus()) {
logger.error("file '{}' is in '{}' state and cannot be processed",
sourceFile.getFileName(),
File.getErrorLevelName(sourceFile.getMaxErrorLevel()));
} else {
for (SourceFileRecord sourceFileRecord : sourceFile.getRecords()) {
for (SchemaField field : sourceFile.getSchema().getFields()) {
Data data = sourceFileRecord.getDataByHeaderIndex(field.getHeaderIndex());
if (data != null) {
TypeValidationContext typeContext = new TypeValidationContext();
typeContext.validate(field, data);
if (data.getMaxErrorLevel() < 2
&& data.getStatus() == true) {
for (FieldConstraint constraint : field
.getConstraints()) {
ConstraintValidationContext context = new ConstraintValidationContext();
context.validate(field, constraint, data);
if (logger.isDebugEnabled()
&& data.getMaxErrorLevel() > 0) {
logger.debug(
"Row {} - Field '{}' validation {}: '{}' = {}, Value = '{}'",
sourceFileRecord.getRowIndex(),
sourceFile.getSourceHeaderName(field.getHeaderIndex()),
constraint.getLevelName(),
constraint.getType(),
constraint.getValue(),
data.getData());
}
}
}
sourceFileRecord.setMaxErrorLevel(data
.getMaxErrorLevel());
sourceFileRecord.setStatus(data.getMaxErrorLevel());
}
}
if (logger.isDebugEnabled())
logger.debug(
"sourceFileRecord for Row '{}' is in '{}' State",
sourceFileRecord.getRowIndex(), File
.getErrorLevelName(sourceFileRecord
.getMaxErrorLevel()));
sourceFile.logError(sourceFileRecord.getMaxErrorLevel());
}
}
if (logger.isDebugEnabled())
logger.debug("File '{}' is in '{}' State",
sourceFile.getFileName(),
File.getErrorLevelName(sourceFile.getMaxErrorLevel()));
if (!sourceFile.getStatus())
logger.error("File is now in Fatal State");
}
}
| true
|
6c5be430f50409f40907b263fd3d06ae93c6a3e1
|
Java
|
emmahawk/Lab3
|
/lab3_EclipseProject_emma/src/ca/uwaterloo/crysp/otr/crypt/rim/RIMDHPrivateKey.java
|
UTF-8
| 2,017
| 1.804688
| 2
|
[] |
no_license
|
/*
* Java OTR library
* Copyright (C) 2008-2009 Ian Goldberg, Muhaimeen Ashraf, Andrew Chung,
* Can Tang
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of version 2.1 of the GNU Lesser General
* Public License as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package ca.uwaterloo.crysp.otr.crypt.rim;
import net.rim.device.api.crypto.DHPrivateKey;
import net.rim.device.api.crypto.InvalidKeyException;
import ca.uwaterloo.crysp.otr.OTRException;
import net.rim.device.api.crypto.CryptoTokenException;
/**
* Private key for the Diffie Hellman key exchange.
*
*/
public class RIMDHPrivateKey extends RIMDHKey implements
ca.uwaterloo.crysp.otr.crypt.DHPrivateKey {
private DHPrivateKey priv;
public RIMDHPrivateKey(byte[] val) throws OTRException {
super(RIMDHKeyPairGenerator.DH_G, RIMDHKeyPairGenerator.DH_P);
try {
priv = new DHPrivateKey(super.getDHCS(), val);
} catch (Exception e) {
throw new OTRException(e.toString());
}
}
public RIMDHPrivateKey(DHPrivateKey val) {
super(RIMDHKeyPairGenerator.DH_G, RIMDHKeyPairGenerator.DH_P);
priv = val;
}
public byte[] getX() {
try {
return RIMMPI.toBytes(priv.getPrivateKeyData());
} catch (Exception e) {
}
return null;
}
public DHPrivateKey getDHPrivateKey() {
return priv;
}
public String toString() {
return priv.toString();
}
}
| true
|
1573fb9d799c3d0cb235f9c54c6d234fcbc3d2be
|
Java
|
gitskarios/Gitskarios
|
/app/src/main/java/com/alorma/github/ui/fragment/issues/IssuesListFragment.java
|
UTF-8
| 11,686
| 1.554688
| 2
|
[
"MIT"
] |
permissive
|
package com.alorma.github.ui.fragment.issues;
import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.alorma.github.R;
import com.alorma.github.injector.component.ApiComponent;
import com.alorma.github.injector.component.ApplicationComponent;
import com.alorma.github.injector.component.DaggerApiComponent;
import com.alorma.github.injector.module.ApiModule;
import com.alorma.github.injector.module.issues.IssuesModule;
import com.alorma.github.presenter.issue.IssuesPresenter;
import com.alorma.github.sdk.bean.info.IssueInfo;
import com.alorma.github.sdk.bean.info.RepoInfo;
import com.alorma.github.ui.activity.IssueDetailActivity;
import com.alorma.github.ui.activity.NewIssueActivity;
import com.alorma.github.ui.activity.PullRequestDetailActivity;
import com.alorma.github.ui.activity.SearchIssuesActivity;
import com.alorma.github.ui.adapter.base.RecyclerArrayAdapter;
import com.alorma.github.ui.fragment.base.LoadingListFragment;
import com.alorma.github.ui.fragment.detail.repo.BackManager;
import com.alorma.github.ui.fragment.detail.repo.PermissionsManager;
import com.alorma.github.ui.fragment.issues.user.IssuesAdapter;
import com.alorma.github.ui.listeners.TitleProvider;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.typeface.IIcon;
import com.mikepenz.octicons_typeface_library.Octicons;
import core.search.IssuesSearchRequest;
import core.issues.Issue;
import core.repositories.Permissions;
import java.util.List;
import javax.inject.Inject;
public class IssuesListFragment extends LoadingListFragment<IssuesAdapter>
implements TitleProvider, PermissionsManager, BackManager, com.alorma.github.presenter.View<List<Issue>>,
RecyclerArrayAdapter.ItemCallback<Issue> {
@Inject IssuesPresenter presenter;
private static final String REPO_INFO = "REPO_INFO";
private static final String FROM_SEARCH = "FROM_SEARCH";
private static final int ISSUE_REQUEST = 1234;
private RepoInfo repoInfo;
private boolean fromSearch = false;
private int currentFilter = 0;
private View revealView;
public static IssuesListFragment newInstance(RepoInfo repoInfo, boolean fromSearch) {
Bundle bundle = new Bundle();
bundle.putParcelable(REPO_INFO, repoInfo);
bundle.putBoolean(FROM_SEARCH, fromSearch);
IssuesListFragment fragment = new IssuesListFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(!fromSearch);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.issues_list_fragment, null, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
revealView = view.findViewById(R.id.revealView);
Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
String[] items = getResources().getStringArray(R.array.issues_filter);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (currentFilter != position) {
currentFilter = position;
clear();
IssuesSearchRequest request = getIssueSearchRequest(position);
presenter.execute(request);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
@Override
protected void injectComponents(ApplicationComponent applicationComponent) {
super.injectComponents(applicationComponent);
ApiComponent apiComponent = DaggerApiComponent.builder().applicationComponent(applicationComponent).apiModule(new ApiModule()).build();
apiComponent.plus(new IssuesModule()).inject(this);
presenter.attachView(this);
}
@Override
public void onStop() {
presenter.detachView();
super.onStop();
}
@Override
protected int getLightTheme() {
return R.style.AppTheme_Repository;
}
@Override
protected int getDarkTheme() {
return R.style.AppTheme_Dark_Repository;
}
@Override
public void onStart() {
super.onStart();
if (revealView != null) {
revealView.setVisibility(View.INVISIBLE);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.issue_list_filter, menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_search)
.setIcon(
new IconicsDrawable(this.getContext(), GoogleMaterial.Icon.gmd_search).color(Color.WHITE).sizeDp(24).respectFontBounds(true));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Intent intent = SearchIssuesActivity.launchIntent(getActivity(), repoInfo);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void loadArguments() {
if (getArguments() != null) {
repoInfo = getArguments().getParcelable(REPO_INFO);
fromSearch = getArguments().getBoolean(FROM_SEARCH, false);
}
}
@NonNull
private IssuesSearchRequest getIssueSearchRequest(int status) {
IssuesSearchRequest builder = new IssuesSearchRequest();
builder.setIsOpen(status == 0);
builder.setRepo(repoInfo.name, repoInfo.owner);
builder.setIsPullRequest(false);
return builder;
}
protected void executeRequest() {
if (currentFilter == 0 || currentFilter == 1) {
IssuesSearchRequest builder = getIssueSearchRequest(currentFilter);
presenter.execute(builder);
}
}
@Override
protected void executePaginatedRequest(int page) {
if (currentFilter == 0 || currentFilter == 1) {
IssuesSearchRequest builder = getIssueSearchRequest(currentFilter);
presenter.executePaginated(builder);
}
}
protected void onResponse(List<Issue> issues) {
if (issues.size() > 0) {
hideEmpty();
if (refreshing || getAdapter() == null) {
IssuesAdapter issuesAdapter = new IssuesAdapter(LayoutInflater.from(getActivity()));
issuesAdapter.addAll(issues);
issuesAdapter.setCallback(this);
setAdapter(issuesAdapter);
} else {
getAdapter().addAll(issues);
}
} else if (getAdapter() == null || getAdapter().getItemCount() == 0) {
setEmpty();
} else {
getAdapter().clear();
setEmpty();
}
}
@Override
protected Octicons.Icon getNoDataIcon() {
return Octicons.Icon.oct_issue_opened;
}
@Override
protected int getNoDataText() {
return R.string.no_issues_found;
}
@Override
protected boolean useFAB() {
return !fromSearch && (repoInfo.permissions == null || repoInfo.permissions.pull);
}
@Override
protected void fabClick() {
super.fabClick();
if (repoInfo.permissions != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && fab != null) {
animateRevealFab();
} else {
openNewIssueActivity();
}
}
}
private void openNewIssueActivity() {
Intent intent = NewIssueActivity.createLauncherIntent(getActivity(), repoInfo);
startActivityForResult(intent, ISSUE_REQUEST);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void animateRevealFab() {
float x = fab.getX() + (fab.getWidth() / 2);
float y = fab.getY() + (fab.getHeight() / 2);
int finalRadius = Math.max(revealView.getWidth(), revealView.getHeight());
Animator anim = ViewAnimationUtils.createCircularReveal(revealView, (int) x, (int) y, fab.getWidth() / 2, finalRadius);
revealView.setVisibility(View.VISIBLE);
anim.setDuration(600);
anim.setInterpolator(new AccelerateInterpolator());
anim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
openNewIssueActivity();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
anim.start();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_FIRST_USER) {
invalidate();
} else if (requestCode == ISSUE_REQUEST && resultCode == Activity.RESULT_OK) {
invalidate();
}
}
public void invalidate() {
onRefresh();
}
public void setPermissions(Permissions permissions) {
if (this.repoInfo != null) {
this.repoInfo.permissions = permissions;
checkFAB();
}
}
@Override
protected Octicons.Icon getFABGithubIcon() {
return Octicons.Icon.oct_bug;
}
@Override
public int getTitle() {
return R.string.issues_fragment_title;
}
@Override
public IIcon getTitleIcon() {
return Octicons.Icon.oct_issue_opened;
}
public void clear() {
if (getAdapter() != null) {
getAdapter().clear();
}
}
@Override
public void setPermissions(boolean admin, boolean push, boolean pull) {
if (this.repoInfo != null) {
Permissions permissions = new Permissions();
permissions.admin = admin;
permissions.push = push;
permissions.pull = pull;
setPermissions(permissions);
}
}
@Override
public boolean onBackPressed() {
return true;
}
public void executeSearch() {
onRefresh();
}
@Override
protected boolean autoStart() {
return !fromSearch;
}
@Override
public void setRefreshing() {
super.setRefreshing();
startRefresh();
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void onDataReceived(List<Issue> data, boolean isFromPaginated) {
onResponse(data);
}
@Override
public void showError(Throwable throwable) {
}
@Override
public void onItemSelected(Issue item) {
if (item != null) {
IssueInfo info = new IssueInfo();
info.repoInfo = repoInfo;
info.num = item.getNumber();
if (item.getPullRequest() == null) {
Intent intent = IssueDetailActivity.createLauncherIntent(getActivity(), info);
startActivityForResult(intent, ISSUE_REQUEST);
} else {
Intent intent = PullRequestDetailActivity.createLauncherIntent(getActivity(), info);
startActivityForResult(intent, ISSUE_REQUEST);
}
}
}
public interface SearchClientRequest {
String request();
}
}
| true
|
4bd0d9c359512575e074a88742f7f50e56ba6d9d
|
Java
|
chorlick/mining-automator
|
/src/main/java/edu/regis/miningautomator/repository/MiningInsallationRepository.java
|
UTF-8
| 826
| 1.976563
| 2
|
[] |
no_license
|
/*
* 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 edu.regis.miningautomator.repository;
import edu.regis.miningautomator.models.MiningInstallation;
import edu.regis.miningautomator.models.User;
import java.util.UUID;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
/**
*
* @author chorl_000
*/
@Repository
public interface MiningInsallationRepository extends CrudRepository<MiningInstallation, UUID> {
MiningInstallation findById(UUID id);
MiningInstallation save(MiningInstallation installation);
Iterable<MiningInstallation> findAllByUserId(UUID id);
void delete(MiningInstallation installation);
}
| true
|
dd6d216ab2b9bdbf9a21aa108b3ee882b3b67183
|
Java
|
Sudheerbolla/Dev
|
/app/src/main/java/com/devotted/fragments/SortBottomSheetFragment.java
|
UTF-8
| 3,622
| 2.171875
| 2
|
[] |
no_license
|
package com.devotted.fragments;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.View;
import android.widget.RadioGroup;
import com.devotted.BaseApplication;
import com.devotted.R;
import com.devotted.activities.SearchActivity;
public class SortBottomSheetFragment extends BottomSheetDialogFragment {
private SearchActivity searchActivity;
private BaseApplication baseApplication;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
BottomSheetDialog dialog;
private View rootView;
private int checkedId;
private RadioGroup rgSortBy;
private OnSortOptionSelected mListener;
public SortBottomSheetFragment() {
// Required empty public constructor
}
public static SortBottomSheetFragment newInstance(String param1, String param2) {
SortBottomSheetFragment fragment = new SortBottomSheetFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static SortBottomSheetFragment newInstance(int param1) {
SortBottomSheetFragment fragment = new SortBottomSheetFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
checkedId = getArguments().getInt(ARG_PARAM1);
}
searchActivity = (SearchActivity) getActivity();
baseApplication = (BaseApplication) searchActivity.getApplication();
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
try {
if (rootView == null) {
rootView = View.inflate(getContext(), R.layout.fragment_bottom_sheet_sort, null);
}
dialog.setContentView(rootView);
initComponents();
} catch (Exception e) {
e.printStackTrace();
}
return dialog;
}
private void initComponents() {
rgSortBy = rootView.findViewById(R.id.rg_sort_by);
if (checkedId != -1) {
rgSortBy.check(checkedId);
}
rgSortBy.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
onButtonPressed(checkedId);
}
});
}
public void onButtonPressed(int position) {
if (mListener != null) {
mListener.sortOptionSelected(position);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnSortOptionSelected) {
mListener = (OnSortOptionSelected) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFilterOptionSelected");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnSortOptionSelected {
void sortOptionSelected(int checkedId);
}
}
| true
|
52bc9132dbca9489723c26b9d57249147366f894
|
Java
|
RoelvdBurght/Journal
|
/app/src/main/java/e/roel/journal/EntryAdapter.java
|
UTF-8
| 1,866
| 2.46875
| 2
|
[] |
no_license
|
package e.roel.journal;
import android.content.Context;
import android.database.Cursor;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import e.roel.journal.R;
public class EntryAdapter extends ResourceCursorAdapter {
String tag = "EntryAdapter";
public EntryAdapter(Context context, Cursor cursor) {
super(context, R.layout.entry_row, cursor);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get content to display from database
int titleIndex = cursor.getColumnIndex("title");
int contentIndex = cursor.getColumnIndex("content");
int moodIndex = cursor.getColumnIndex("mood");
int timestampIndex = cursor.getColumnIndex("time_stamp");
String title = cursor.getString(titleIndex);
String timestamp = cursor.getString(timestampIndex);
int mood = cursor.getInt(moodIndex);
// Set content in correct views
TextView titleView = view.findViewById(R.id.title);
titleView.setText(title);
TextView dateTimeView = view.findViewById(R.id.dateTime);
dateTimeView.setText(timestamp);
// Switch on possible mood integers to find correct image to display
ImageView moodView = view.findViewById(R.id.moodImage);
switch (mood) {
case 1:
moodView.setImageResource(R.raw.smile);
break;
case 2:
moodView.setImageResource(R.raw.laugh);
break;
case 3:
moodView.setImageResource(R.raw.sad);
break;
case 4:
moodView.setImageResource(R.raw.angry);
break;
}
}
}
| true
|
0e9d49e07cc8c9ae30b605ff960d4427deac1766
|
Java
|
Faiz-Hasan/COE420-Carpool-Project
|
/Carpool/app/src/main/java/com/example/rjurri/carpool/SelectSeats.java
|
UTF-8
| 539
| 1.882813
| 2
|
[] |
no_license
|
package com.example.rjurri.carpool;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class SelectSeats extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_seats);
}
public void submitClick(View view){
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
| true
|
04fbc44dc9c69a6f10ffbb3c04a4a902d67f1f1f
|
Java
|
1547753613/springboot
|
/src/main/java/com/aaa/springboothomestay/entity/UserBrowse.java
|
UTF-8
| 282
| 1.585938
| 2
|
[] |
no_license
|
package com.aaa.springboothomestay.entity;
import lombok.Data;
import java.util.Date;
@Data
public class UserBrowse {
private int id;// int 主键
private int uid;// int 用户外键
private int hid;// int 房屋表外键
private Date date;// date 浏览日期
}
| true
|
4d3b816a818cbb7d08a87ab65ebf07ad03d3da2f
|
Java
|
james1896/Phippy_Android
|
/app/src/main/java/com/tiffany/phippy/tour/TourFragment.java
|
UTF-8
| 3,631
| 1.9375
| 2
|
[] |
no_license
|
package com.tiffany.phippy.tour;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.tiffany.phippy.base.BaseFragment;
import com.tiffany.phippy.R;
import com.tiffany.phippy.base.BaseModel;
import com.tiffany.phippy.base.JsonParse;
import com.tiffany.phippy.venv.RequestCallBack;
import com.tiffany.phippy.venv.RequestManager;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
/**
* A simple {@link Fragment} subclass.
*/
public class TourFragment extends BaseFragment implements View.OnClickListener {
ArrayList<TourModel> dataArray;
TourListAdapter adapter;
public TourFragment() {
// Required empty public constructor
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_tour, container, false);
// }
@Override
public int getContentView() {
return R.layout.fragment_tour;
}
@Override
protected void viewWillAppear() {
super.viewWillAppear();
RequestManager.getInstant().getarticle("", new RequestCallBack() {
@Override
public void onSuccess(String s, Call call, Response response) {
super.onSuccess(s, call, response);
BaseModel<List<TourModel>> model = JsonParse.parser.fromJson(s, new TypeToken<BaseModel<List<TourModel>>>(){}.getType());
Log.e("FoodModel",""+model);
adapter.setDataList((ArrayList) model.getData());
adapter.notifyDataSetChanged();
}
});
}
@Override
public void init() {
this.adapter = new TourListAdapter(getContext(),null);
ListView listview = (ListView) contentView.findViewById(R.id.tour_listview);
LinearLayout mLoadingLayout = (LinearLayout) View.inflate(getContext(), R.layout.img_and_text_header, null);
listview.addHeaderView(mLoadingLayout);
listview.setAdapter(this.adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Intent intent = new Intent(getActivity(),TourRecActivity.class);
// intent.putExtra("com.tiffany.tour", i);
// startActivity(intent);
}
});
TextView headerText = (TextView) mLoadingLayout.findViewById(R.id.header_text);
headerText.setText("推荐攻略");
ViewGroup upleft = (ViewGroup) mLoadingLayout.findViewById(R.id.upleft);
ViewGroup upright = (ViewGroup) mLoadingLayout.findViewById(R.id.upright);
ViewGroup downleft = (ViewGroup) mLoadingLayout.findViewById(R.id.downleft);
ViewGroup downright = (ViewGroup) mLoadingLayout.findViewById(R.id.downright);
upleft.setOnClickListener(this);
upright.setOnClickListener(this);
downleft.setOnClickListener(this);
downright.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),TourRecActivity.class);
startActivity(intent);
}
}
| true
|
031114b45a42c94e73674567766f8be73eaa6703
|
Java
|
kamleshsindhal08/react-native-xmpp
|
/android/src/main/java/rnxmpp/mam/MamElements.java
|
UTF-8
| 3,241
| 2.421875
| 2
|
[
"BSD-2-Clause"
] |
permissive
|
package rnxmpp.mam;
import org.jivesoftware.smack.packet.DefaultExtensionElement;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jivesoftware.smackx.forward.packet.Forwarded;
/**
* MAM elements.
*
* @see <a href="http://xmpp.org/extensions/xep-0313.html">XEP-0313: Message
* Archive Management</a>
* @author Fernando Ramirez and Florian Schmaus
*
*/
public class MamElements {
public static final String NAMESPACE = "urn:xmpp:mam:0";
/**
* MAM result extension class.
*
* @see <a href="http://xmpp.org/extensions/xep-0313.html">XEP-0313: Message
* Archive Management</a>
*
*/
public static class MamResultExtension extends DefaultExtensionElement {
/**
* result element.
*/
public static final String ELEMENT = "result";
/**
* id of the result.
*/
private final String id;
/**
* the forwarded element.
*/
private final Forwarded forwarded;
/**
* the query id.
*/
private String queryId;
/**
* MAM result extension constructor.
*
* @param queryId
* @param id
* @param forwarded
*/
public MamResultExtension(String queryId, String id, Forwarded forwarded) {
super(ELEMENT,NAMESPACE);
if (StringUtils.isEmpty(id)) {
throw new IllegalArgumentException("id must not be null or empty");
}
if (forwarded == null) {
throw new IllegalArgumentException("forwarded must no be null");
}
this.id = id;
this.forwarded = forwarded;
this.queryId = queryId;
}
/**
* Get the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Get the forwarded element.
*
* @return the forwarded element
*/
public Forwarded getForwarded() {
return forwarded;
}
/**
* Get query id.
*
* @return the query id
*/
public final String getQueryId() {
return queryId;
}
@Override
public String getElementName() {
return ELEMENT;
}
@Override
public final String getNamespace() {
return NAMESPACE;
}
@Override
public CharSequence toXML() {
XmlStringBuilder xml = new XmlStringBuilder();
xml.halfOpenElement(this);
xml.xmlnsAttribute(NAMESPACE);
xml.optAttribute("queryid", getQueryId());
xml.optAttribute("id", getId());
xml.rightAngleBracket();
xml.element(getForwarded());
xml.closeElement(this);
return xml;
}
public static MamResultExtension from(Message message) {
return (MamResultExtension) message.getExtension(ELEMENT, NAMESPACE);
}
}
}
| true
|
a09279ee807e991512f400fe48964b390195501d
|
Java
|
vtqveant/ccg-corpus
|
/importer/src/main/java/ru/eventflow/ccg/data/corpus/SQLDataBridge.java
|
UTF-8
| 8,760
| 2.046875
| 2
|
[] |
no_license
|
package ru.eventflow.ccg.data.corpus;
import ru.eventflow.ccg.datasource.model.corpus.*;
import java.sql.*;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SQLDataBridge implements DataBridge {
private final Map<String, BitSet> grammemeFlags = new HashMap<>(); // grammeme name -> single grammeme bitset
private String version;
private String revision;
private Connection conn;
private PreparedStatement stVariant;
private PreparedStatement stToken;
private PreparedStatement stSentence;
private PreparedStatement stParagraph;
private PreparedStatement stText;
private PreparedStatement stTag;
private PreparedStatement stFormDetails;
private PreparedStatement stForm;
private PreparedStatement stLexeme;
private PreparedStatement stFormGrammeme;
private int counter = 0;
public SQLDataBridge(String connectionUrl) {
try {
if (conn == null) {
conn = DriverManager.getConnection(connectionUrl);
conn.setAutoCommit(false);
stVariant = conn.prepareStatement("INSERT INTO corpus.variant (token_id, form_id) VALUES (?, ?)");
stToken = conn.prepareStatement("INSERT INTO corpus.token (id, orthography, revision, sentence_id, pos) VALUES (?, ?, ?, ?, ?)");
stSentence = conn.prepareStatement("INSERT INTO corpus.sentence (id, source, paragraph_id, pos) VALUES (?, ?, ?, ?)");
stParagraph = conn.prepareStatement("INSERT INTO corpus.paragraph (id, text_id, pos) VALUES (?, ?, ?)");
stText = conn.prepareStatement("INSERT INTO corpus.text (id, name, parent_id) VALUES (?, ?, ?)");
stTag = conn.prepareStatement("INSERT INTO corpus.tag (source, text_id) VALUES (?, ?)");
stForm = conn.prepareStatement("INSERT INTO dictionary.form (lemma, orthography, lexeme_id, flags) VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
stLexeme = conn.prepareStatement("INSERT INTO dictionary.lexeme (id, rev, lemma_id) VALUES (?, ?, ?)");
stFormGrammeme = conn.prepareStatement("INSERT INTO dictionary.form_to_grammeme (form_id, grammeme_id) VALUES (?, ?)");
// form resolver
PreparedStatement st = conn.prepareStatement("SELECT name, flags FROM dictionary.grammeme");
ResultSet rs = st.executeQuery();
while (rs.next()) {
BitSet bs = BitSet.valueOf(rs.getBytes("flags"));
grammemeFlags.put(rs.getString("name"), bs);
}
stFormDetails = conn.prepareStatement("SELECT id, lexeme_id, flags FROM dictionary.form f WHERE lexeme_id = ?");
}
} catch (SQLException e) {
e.printStackTrace();
System.exit(-1);
}
}
@Override
public void addText(Text text) {
try {
for (Paragraph paragraph : text.getParagraphs()) {
for (Sentence sentence : paragraph.getSentences()) {
for (Token token : sentence.getTokens()) {
for (Variant variant : token.getVariants()) {
stVariant.setInt(1, variant.getToken().getId());
stVariant.setInt(2, variant.getForm().getId());
stVariant.execute();
}
stToken.setInt(1, token.getId());
stToken.setString(2, token.getOrthography());
stToken.setInt(3, token.getRevision());
stToken.setInt(4, token.getSentence().getId());
stToken.setInt(5, token.getPosition());
stToken.execute();
}
stSentence.setInt(1, sentence.getId());
stSentence.setString(2, sentence.getSource());
stSentence.setInt(3, sentence.getParagraph().getId());
stSentence.setInt(4, sentence.getPosition());
stSentence.execute();
}
stParagraph.setInt(1, paragraph.getId());
stParagraph.setInt(2, paragraph.getText().getId());
stParagraph.setInt(3, paragraph.getPosition());
stParagraph.execute();
}
stText.setInt(1, text.getId());
stText.setString(2, text.getName());
if (text.getParent() != null) {
stText.setInt(3, text.getParent().getId());
} else {
stText.setNull(3, Types.INTEGER);
}
stText.execute();
for (Tag tag : text.getTags()) {
stTag.setString(1, tag.getValue());
stTag.setInt(2, tag.getText().getId());
stTag.execute();
}
conn.commit();
if (++counter % 100 == 0) {
System.out.println(counter);
}
} catch (SQLException e) {
e.printStackTrace();
System.exit(-1);
}
}
@Override
public void setRevision(String revision) {
this.revision = revision;
}
@Override
public void setVersion(String version) {
this.version = version;
}
/**
* links tokens in the dump to dictionary entries based on grammatical information
*/
@Override
public int resolve(int lexemeId, List<String> grammemes) {
try {
stFormDetails.setInt(1, lexemeId);
ResultSet rs = stFormDetails.executeQuery();
while (rs.next()) {
BitSet flags = BitSet.valueOf(rs.getBytes("flags"));
BitSet formFlags = buildFlags(grammemes);
if (flags.equals(formFlags)) {
return rs.getInt("id");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
private BitSet buildFlags(List<String> grammemes) {
BitSet formFlags = new BitSet();
for (String grammeme : grammemes) {
BitSet flag = grammemeFlags.get(grammeme);
if (flag == null) { // fix OOV gramemes
int size = grammemeFlags.size();
flag = new BitSet();
flag.set(size);
grammemeFlags.put(grammeme, flag);
}
formFlags.or(flag);
}
return formFlags;
}
@Override
public int addForm(String orthography, List<String> grammemes) {
try {
// check if there is such form already
PreparedStatement stFindForm = conn.prepareStatement("SELECT f.id FROM dictionary.form f WHERE f.orthography = ? AND NOT f.lemma LIMIT 1");
stFindForm.setString(1, orthography);
ResultSet findFormResultSet = stFindForm.executeQuery();
if (findFormResultSet.next()) {
return findFormResultSet.getInt("id");
}
// id in 'dictionary.lexeme' is manual
PreparedStatement stNextLexemeId = conn.prepareStatement("SELECT max(id) FROM dictionary.lexeme");
ResultSet rs = stNextLexemeId.executeQuery();
rs.next();
int lexemeId = rs.getInt(1) + 1;
// add lemma
stForm.setBoolean(1, true);
stForm.setString(2, orthography);
stForm.setInt(3, lexemeId);
stForm.setBytes(4, buildFlags(grammemes).toByteArray());
stForm.executeUpdate();
ResultSet generatedKeys = stForm.getGeneratedKeys();
generatedKeys.next();
int lemmaId = generatedKeys.getInt(1);
// add regular form
stForm.setBoolean(1, false);
stForm.setString(2, orthography);
stForm.setInt(3, lexemeId);
stForm.setBytes(4, new byte[]{});
stForm.executeUpdate();
ResultSet generatedKeys2 = stForm.getGeneratedKeys();
generatedKeys2.next();
int formId = generatedKeys2.getInt(1);
// add lexeme
stLexeme.setInt(1, lexemeId);
stLexeme.setInt(2, -1);
stLexeme.setInt(3, lemmaId);
stLexeme.executeUpdate();
// add grammemes
for (String grammeme : grammemes) {
stFormGrammeme.setInt(1, lemmaId);
stFormGrammeme.setString(2, grammeme);
stFormGrammeme.executeUpdate();
}
return formId;
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
| true
|
d4ea5b66b831641c4d56adc2d9ef8df1e3ce0d0a
|
Java
|
huzza/shifu
|
/src/main/java/ml/shifu/shifu/core/datestat/DateStatComputeReducer.java
|
UTF-8
| 21,709
| 2.09375
| 2
|
[
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
/*
* Copyright [2012-2019] PayPal Software Foundation
*
* 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 ml.shifu.shifu.core.datestat;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.collections.MapUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.clearspring.analytics.stream.cardinality.CardinalityMergeException;
import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus;
import ml.shifu.shifu.container.obj.ColumnConfig;
import ml.shifu.shifu.container.obj.ModelConfig;
import ml.shifu.shifu.container.obj.RawSourceData.SourceType;
import ml.shifu.shifu.core.ColumnStatsCalculator;
import ml.shifu.shifu.util.CommonUtils;
import ml.shifu.shifu.util.Constants;
/**
* Collect all statistics together in reducer.
*
* The DateStatComputeReducer will first calculate accumulate values, then for each accumulated value, do aggregated
* The result will wrote to HDFS with format: variable name|date|column type|max|min|mean|mean|median value|count|missing count|standard deviation|missing ratio|WOE|KS|IV|weighted WOE|weighted KS|weighted IV|skewness|kurtosis|P25th|P75th
*
* <p>
* Reducer first calculate sum value, then do the aggregate
*
* <p>
* Only one reducer to make sure all info can be collected together. One reducer is not bottleneck as some times we only
* have thousands of variables.
*/
public class DateStatComputeReducer extends Reducer<Text, DateStatInfoWritable, NullWritable, Text> {
private final static Logger LOG = LoggerFactory.getLogger(DateStatComputeReducer.class);
private static final double EPS = 1e-6;
/**
* Column Config list read from HDFS
*/
private List<ColumnConfig> columnConfigList;
/**
* Prevent too many new objects for output key.
*/
private Text outputValue;
/**
* To concat output string
*/
private StringBuilder sb = new StringBuilder(2000);
/**
* To format double value.
*/
private DecimalFormat df = new DecimalFormat("##.######");
private boolean statsExcludeMissingValue;
private int maxCateSize;
/**
* Model Config read from HDFS
*/
private ModelConfig modelConfig;
/**
* Load all configurations for modelConfig and columnConfigList from source type.
*/
private void loadConfigFiles(final Context context) {
try {
SourceType sourceType = SourceType.valueOf(
context.getConfiguration().get(Constants.SHIFU_MODELSET_SOURCE_TYPE, SourceType.HDFS.toString()));
this.modelConfig = CommonUtils.loadModelConfig(context.getConfiguration().get(Constants.SHIFU_MODEL_CONFIG),
sourceType);
this.columnConfigList = CommonUtils
.loadColumnConfigList(context.getConfiguration().get(Constants.SHIFU_COLUMN_CONFIG), sourceType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Do initialization like ModelConfig and ColumnConfig loading.
*/
@Override
protected void setup(Context context) throws IOException, InterruptedException {
this.maxCateSize = context.getConfiguration().getInt(Constants.SHIFU_MAX_CATEGORY_SIZE,
Constants.MAX_CATEGORICAL_BINC_COUNT);
loadConfigFiles(context);
this.statsExcludeMissingValue = context.getConfiguration().getBoolean(Constants.SHIFU_STATS_EXLCUDE_MISSING,
true);
this.outputValue = new Text();
}
@Override
protected void reduce(Text key, Iterable<DateStatInfoWritable> values, Context context)
throws IOException, InterruptedException {
long start = System.currentTimeMillis();
Map<String, DateStatInfoWritable.VariableStatInfo> result = new TreeMap<String, DateStatInfoWritable.VariableStatInfo>(new Comparator<String>() {
public int compare(String obj1, String obj2) {
return obj1.compareTo(obj2);
}
});
//Merge into result
for(DateStatInfoWritable info: values) {
if(MapUtils.isEmpty(info.getVariableDailyStatInfo())) {
// mapper has no stats, skip it
continue;
}
for(Map.Entry<String, DateStatInfoWritable.VariableStatInfo> entry : info.getVariableDailyStatInfo().entrySet()){
DateStatInfoWritable.VariableStatInfo variableStatInfo = result.get(entry.getKey());
if(variableStatInfo == null){
variableStatInfo = new DateStatInfoWritable.VariableStatInfo();
result.put(entry.getKey(), variableStatInfo);
}
DateStatInfoWritable.VariableStatInfo statInfo = entry.getValue();
if(statInfo.getCfiw().getHyperBytes() != null) {
if (variableStatInfo.getHyperLogLogPlus() == null) {
variableStatInfo.setHyperLogLogPlus(HyperLogLogPlus.Builder.build(statInfo.getCfiw().getHyperBytes()));
} else {
try {
variableStatInfo.setHyperLogLogPlus((HyperLogLogPlus) variableStatInfo.getHyperLogLogPlus()
.merge(HyperLogLogPlus.Builder.build(statInfo.getCfiw().getHyperBytes())));
} catch (CardinalityMergeException e) {
throw new RuntimeException(e);
}
}
}
variableStatInfo.setColumnConfigIndex(statInfo.getColumnConfigIndex());
ColumnConfig columnConfig = this.columnConfigList.get(statInfo.getColumnConfigIndex());
variableStatInfo.setTotalCount(variableStatInfo.getTotalCount() + statInfo.getTotalCount());
variableStatInfo.setMissingCount(variableStatInfo.getMissingCount() + statInfo.getMissingCount());
variableStatInfo.setSum(variableStatInfo.getSum() + statInfo.getSum());
variableStatInfo.setSquaredSum(variableStatInfo.getSquaredSum() + statInfo.getSquaredSum());
variableStatInfo.setTripleSum(variableStatInfo.getTripleSum() + statInfo.getTripleSum());
variableStatInfo.setQuarticSum(variableStatInfo.getQuarticSum() + statInfo.getQuarticSum());
if(Double.compare(variableStatInfo.getMax(), statInfo.getMax()) < 0) {
variableStatInfo.setMax(statInfo.getMax());
}
if(Double.compare(variableStatInfo.getMin(), statInfo.getMin()) > 0) {
variableStatInfo.setMin(statInfo.getMin());
}
int binSize = 0;
if(columnConfig.isNumerical() && variableStatInfo.getBinCountPos() == null) {
binSize = columnConfig.getBinBoundary().size();
variableStatInfo.setBinCountPos(new long[binSize + 1]);
variableStatInfo.setBinCountNeg(new long[binSize + 1]);
variableStatInfo.setBinWeightPos(new double[binSize + 1]);
variableStatInfo.setBinWeightNeg(new double[binSize + 1]);
variableStatInfo.setBinCountTotal(new long[binSize + 1]);
} else if(columnConfig.isCategorical() && variableStatInfo.getBinCountPos() == null) {
binSize = columnConfig.getBinCategory().size();
variableStatInfo.setBinCountPos(new long[binSize + 1]);
variableStatInfo.setBinCountNeg(new long[binSize + 1]);
variableStatInfo.setBinWeightPos(new double[binSize + 1]);
variableStatInfo.setBinWeightNeg(new double[binSize + 1]);
variableStatInfo.setBinCountTotal(new long[binSize + 1]);
}
for(int i = 0; i < statInfo.getBinCountPos().length; i++) {
variableStatInfo.getBinCountPos()[i] += statInfo.getBinCountPos() == null ? 0 : statInfo.getBinCountPos()[i];
variableStatInfo.getBinCountNeg()[i] += statInfo.getBinCountNeg() == null ? 0 : statInfo.getBinCountNeg()[i];
variableStatInfo.getBinWeightPos()[i] += statInfo.getBinWeightPos() == null ? 0 : statInfo.getBinWeightPos()[i];
variableStatInfo.getBinWeightNeg()[i] += statInfo.getBinWeightNeg() == null ? 0 : statInfo.getBinWeightNeg()[i];
variableStatInfo.getBinCountTotal()[i] += statInfo.getBinCountPos() == null ? 0 : statInfo.getBinCountPos()[i];
variableStatInfo.getBinCountTotal()[i] += statInfo.getBinCountNeg() == null ? 0 : statInfo.getBinCountNeg()[i];
}
}
}
//calculate result
for (Map.Entry<String, DateStatInfoWritable.VariableStatInfo> entry: result.entrySet()){
DateStatInfoWritable.VariableStatInfo variableStatInfo = entry.getValue();
ColumnConfig columnConfig = this.columnConfigList.get(variableStatInfo.getColumnConfigIndex());
//for numerical, need to do special process
if(columnConfig.isNumerical()) {
long p25Count = variableStatInfo.getTotalCount() / 4;
long medianCount = p25Count * 2;
long p75Count = p25Count * 3;
int currentCount = 0;
//init P25, P75 and median to min value, that is Double.MAX_VALUE
variableStatInfo.setP25th(variableStatInfo.getMin());
variableStatInfo.setMedian(variableStatInfo.getMin());
variableStatInfo.setP75th(variableStatInfo.getMin());
for(int i = 0; i < columnConfig.getBinBoundary().size(); i++) {
double left = getCutoffBoundary(columnConfig.getBinBoundary().get(i), variableStatInfo.getMax(), variableStatInfo.getMin());
double right = ((i == columnConfig.getBinBoundary().size() - 1) ?
variableStatInfo.getMax() : getCutoffBoundary(columnConfig.getBinBoundary().get(i + 1), variableStatInfo.getMax(), variableStatInfo.getMin()));
if (p25Count >= currentCount && p25Count < currentCount + variableStatInfo.getBinCountTotal()[i]) {
variableStatInfo.setP25th(((p25Count - currentCount) / (double) variableStatInfo.getBinCountTotal()[i])
* ( right - left) + left);
}
if (medianCount >= currentCount && medianCount < currentCount + variableStatInfo.getBinCountTotal()[i]) {
variableStatInfo.setMedian(((medianCount - currentCount) / (double) variableStatInfo.getBinCountTotal()[i])
* ( right - left) + left);
}
if (p75Count >= currentCount && p75Count < currentCount + variableStatInfo.getBinCountTotal()[i]) {
variableStatInfo.setP75th(((p75Count - currentCount) / (double) variableStatInfo.getBinCountTotal()[i])
* ( right - left) + left);
// when get 75 percentile stop it
break;
}
currentCount += variableStatInfo.getBinCountTotal()[i];
}
}
double[] binPosRate;
if(modelConfig.isRegression()) {
binPosRate = computePosRate(variableStatInfo.getBinCountPos(), variableStatInfo.getBinCountNeg());
} else {
// for multiple classfication, use rate of categories to compute a value
binPosRate = computeRateForMultiClassfication(variableStatInfo.getBinCountPos());
}
//for categorical, need to do special process
if(columnConfig.isCategorical()) {
if(columnConfig.getBinCategory().size() > this.maxCateSize) {
LOG.warn("Column {} {} with invalid bin category size.", new String(key.getBytes()), columnConfig.getColumnName(),
columnConfig.getBinCategory().size());
return;
}
// recompute such value for categorical variables
variableStatInfo.setMin(Double.MAX_VALUE);
variableStatInfo.setMax(Double.MIN_VALUE);
variableStatInfo.setSum(0d);
variableStatInfo.setSquaredSum(0d);
for(int i = 0; i < binPosRate.length; i++) {
if(!Double.isNaN(binPosRate[i])) {
if(Double.compare(variableStatInfo.getMax(), binPosRate[i]) < 0) {
variableStatInfo.setMax(binPosRate[i]);
}
if(Double.compare(variableStatInfo.getMin(), binPosRate[i]) > 0) {
variableStatInfo.setMin(binPosRate[i]);
}
long binCount = variableStatInfo.getBinCountPos()[i] + variableStatInfo.getBinCountNeg()[i];
variableStatInfo.setSum(variableStatInfo.getSum() + binPosRate[i] * binCount);
double squaredVal = binPosRate[i] * binPosRate[i];
variableStatInfo.setSquaredSum(variableStatInfo.getSquaredSum() + squaredVal * binCount);
variableStatInfo.setTripleSum(variableStatInfo.getTripleSum() + squaredVal * binPosRate[i] * binCount);
variableStatInfo.setQuarticSum(variableStatInfo.getQuarticSum() + squaredVal * squaredVal * binCount);
}
}
}
long realCount = this.statsExcludeMissingValue ? (variableStatInfo.getTotalCount() - variableStatInfo.getMissingCount()) : variableStatInfo.getTotalCount();
variableStatInfo.setMean(variableStatInfo.getSum() / realCount);
variableStatInfo.setStdDev(Math.sqrt(Math.abs((variableStatInfo.getSquaredSum() - (variableStatInfo.getSum() * variableStatInfo.getSum()) / realCount + EPS) / (realCount - 1))));
double aStdDev = Math.sqrt(Math.abs((variableStatInfo.getSquaredSum() - (variableStatInfo.getSum() * variableStatInfo.getSum()) / realCount + EPS) / realCount));
variableStatInfo.setSkewness(ColumnStatsCalculator.computeSkewness(realCount, variableStatInfo.getMean(), aStdDev, variableStatInfo.getSum(), variableStatInfo.getSquaredSum(), variableStatInfo.getTripleSum()));
variableStatInfo.setKurtosis(ColumnStatsCalculator.computeKurtosis(realCount, variableStatInfo.getMean(), aStdDev, variableStatInfo.getSum(), variableStatInfo.getSquaredSum(), variableStatInfo.getTripleSum(),
variableStatInfo.getQuarticSum()));
if(modelConfig.isRegression()) {
variableStatInfo.setColumnCountMetrics(ColumnStatsCalculator.calculateColumnMetrics(variableStatInfo.getBinCountNeg(), variableStatInfo.getBinCountPos()));
variableStatInfo.setColumnWeightMetrics(ColumnStatsCalculator.calculateColumnMetrics(variableStatInfo.getBinWeightNeg(), variableStatInfo.getBinWeightPos()));
}
if(variableStatInfo.getMin() == Double.MAX_VALUE){
variableStatInfo.setMin(0);
}
//variable name|date|column type|max|min|mean|median value|count|missing count|standard deviation|missing ratio|WOE|KS|IV|weighted WOE|weighted KS|weighted IV|skewness|kurtosis|cardinality|P25th|P75th
sb.append(key)
// variable name
.append(Constants.DEFAULT_DELIMITER).append(entry.getKey())
// date
.append(Constants.DEFAULT_DELIMITER).append(columnConfig.getColumnType().toString())
// column type
.append(Constants.DEFAULT_DELIMITER).append(df.format(variableStatInfo.getMax()))
// max
.append(Constants.DEFAULT_DELIMITER).append(df.format(variableStatInfo.getMin()))
// min
.append(Constants.DEFAULT_DELIMITER).append(normDoubleValue(variableStatInfo.getMean()))
// mean
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getMedian())
// median value ?
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getTotalCount())
// count
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getMissingCount())
// missing count
.append(Constants.DEFAULT_DELIMITER).append(normDoubleValue(variableStatInfo.getStdDev()))
// standard deviation
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getMissingCount() * 1.0d / variableStatInfo.getTotalCount())
// missing ratio
.append(Constants.DEFAULT_DELIMITER)
.append(variableStatInfo.getColumnCountMetrics() == null ? "" : variableStatInfo.getColumnCountMetrics().getWoe())
// WOE
.append(Constants.DEFAULT_DELIMITER)
.append(variableStatInfo.getColumnCountMetrics() == null ? "" : df.format(variableStatInfo.getColumnCountMetrics().getKs()))
// KS
.append(Constants.DEFAULT_DELIMITER)
.append(variableStatInfo.getColumnCountMetrics() == null ? "" : df.format(variableStatInfo.getColumnCountMetrics().getIv()))
// IV
.append(Constants.DEFAULT_DELIMITER)
.append(variableStatInfo.getColumnWeightMetrics() == null ? "" : variableStatInfo.getColumnWeightMetrics().getWoe())
// weighted WOE
.append(Constants.DEFAULT_DELIMITER)
.append(variableStatInfo.getColumnWeightMetrics() == null ? "" : variableStatInfo.getColumnWeightMetrics().getKs())
// weighted KS
.append(Constants.DEFAULT_DELIMITER)
.append(variableStatInfo.getColumnWeightMetrics() == null ? "" : variableStatInfo.getColumnWeightMetrics().getIv())
// weighted IV
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getSkewness()) // skewness
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getKurtosis()) // kurtosis
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getHyperLogLogPlus() == null ? "" : variableStatInfo.getHyperLogLogPlus().cardinality()) // cardinality
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getP25th()) // the 25 percentile value
.append(Constants.DEFAULT_DELIMITER).append(variableStatInfo.getP75th());
LOG.info("Output str:"+ sb.toString());
outputValue.set(sb.toString());
context.write(NullWritable.get(), outputValue);
sb.delete(0, sb.length());
}
LOG.debug("Time:{}", (System.currentTimeMillis() - start));
}
/**
* Normalize double value, process exception case include NaN and infinite and format it with ##.######
* @param value double value need to be format
* @return a String formated value
*/
private String normDoubleValue(double value){
if(Double.isNaN(value) || Double.isInfinite(value)){
return "NaN";
}
return df.format(value);
}
private double[] computePosRate(long[] binCountPos, long[] binCountNeg) {
assert binCountPos != null && binCountNeg != null && binCountPos.length == binCountNeg.length;
double[] posRate = new double[binCountPos.length];
for(int i = 0; i < posRate.length; i++) {
if(Double.compare(binCountPos[i] + binCountNeg[i], 0d) != 0) {
// only compute effective pos rate, if /0, don't do it
posRate[i] = binCountPos[i] * 1.0d / (binCountPos[i] + binCountNeg[i]);
}
}
return posRate;
}
private double[] computeRateForMultiClassfication(long[] binCount) {
double[] rate = new double[binCount.length];
double sum = 0d;
for(int i = 0; i < binCount.length; i++) {
sum += binCount[i];
}
for(int i = 0; i < binCount.length; i++) {
if(Double.compare(sum, 0d) != 0) {
rate[i] = binCount[i] * 1.0d / sum;
}
}
return rate;
}
private double getCutoffBoundary(double val, double max, double min) {
if ( val == Double.POSITIVE_INFINITY ) {
return max;
} else if ( val == Double.NEGATIVE_INFINITY ) {
return min;
} else {
return val;
}
}
}
| true
|
fc3aa0a196664fa85a93f01b5787397a2ab38246
|
Java
|
MrZ1995/learning-project
|
/first-year/src/main/java/com/learning/maven/string_class/StringDemo12.java
|
UTF-8
| 271
| 2.421875
| 2
|
[] |
no_license
|
package com.learning.maven.string_class;
public class StringDemo12 {
public static void main(String args[]){
String logo = "yootk";
String strA = "www.yootk.com";
String strB = "www.logo.com";
System.out.println(strA==strB);
}
}
| true
|
5e9236f3f6c0c2961c9cfc08289636bfca7574ca
|
Java
|
rahulyhg/Volta
|
/app/src/main/java/com/jmjsolution/solarup/interfaces/DeletePack.java
|
UTF-8
| 108
| 1.617188
| 2
|
[] |
no_license
|
package com.jmjsolution.solarup.interfaces;
public interface DeletePack {
void onDeletePack(int i);
}
| true
|
2b008ee8270ab424f52a1c0b3448986642fa86b0
|
Java
|
jessica1127/algorithmJava
|
/amazon/LetterCombinationOfAPhone17.java
|
UTF-8
| 1,551
| 3.546875
| 4
|
[] |
no_license
|
import java.util.*;
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(2, "abc");
map.put(3, "def");
map.put(4, "ghi");
map.put(5, "jkl");
map.put(6, "mno");
map.put(7, "pqrs");
map.put(8, "tuv");
map.put(9, "wxyz");
if(digits == null || digits.length() == 0 ){
return res;
}
StringBuffer sb = new StringBuffer();
dfsHelper(digits, 0, res, sb, map );
return res;
}
private void dfsHelper(String digits, int index, List<String> res, StringBuffer sb, HashMap<Integer, String> map){
//base case
if(digits.length() == index){
res.add(sb.toString());
return;
}
int ch = digits.charAt(index) - '0';
String values = map.get(ch);
for(char val : values.toCharArray()){
sb.append(val);
dfsHelper(digits, index+1, res, sb, map);
//
System.out.println("sb= " + sb.toString());
sb.deleteCharAt(sb.length()-1);
}
}
}
public class LetterCombinationOfAPhone17 {
public static void main(String[] args){
Solution s = new Solution();
String digits = "23";
List<String> res = new ArrayList<String>();
res = s.letterCombinations(digits);
System.out.println("res= " + res.toString());
}
}
| true
|
c38fecd734797d4e987d8fec97487c34dc009c27
|
Java
|
ilialeonov/Epam_training
|
/FinalProject/src/java/by/epam/interpol/entity/User.java
|
UTF-8
| 3,296
| 2.703125
| 3
|
[] |
no_license
|
/*
* 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 by.epam.interpol.entity;
import java.util.Objects;
/**
*
* @author Ilia Leonov
* User entity
*/
public class User {
private int id;
private String name;
private String login;
private String mail;
private double money;
private boolean status;
/**
*
*/
public User() {
}
/**
*
* @return user's id
*/
public int getId() {
return id;
}
/**
*
* @param id user's id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* @return user's name
*/
public String getName() {
return name;
}
/**
*
* @param name user's name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* @return user's login
*/
public String getLogin() {
return login;
}
/**
*
* @param login user's login
*/
public void setLogin(String login) {
this.login = login;
}
/**
*
* @return user's mail
*/
public String getMail() {
return mail;
}
/**
*
* @param mail user's mail
*/
public void setMail(String mail) {
this.mail = mail;
}
/**
*
* @return if user's admin
*/
public boolean isAdmin() {
return status;
}
/**
*
* @param status user's admin
*/
public void setAdmin(boolean status) {
this.status = status;
}
/**
*
* @return user's money
*/
public double getMoney() {
return money;
}
/**
*
* @param money user's money
*/
public void setMoney(double money) {
this.money = money;
}
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + this.id;
hash = 67 * hash + Objects.hashCode(this.name);
hash = 67 * hash + Objects.hashCode(this.login);
hash = 67 * hash + Objects.hashCode(this.mail);
hash = 67 * hash + (int) this.money;
hash = 67 * hash + (this.status ? 1 : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final User other = (User) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.login, other.login)) {
return false;
}
if (!Objects.equals(this.mail, other.mail)) {
return false;
}
if (this.money != other.money) {
return false;
}
if (this.status != other.status) {
return false;
}
return true;
}
@Override
public String toString() {
return "User" + "id=" + id + ", name=" + name + ", login=" + login
+ ", mail=" + mail + ", money=" + money + ", status=" + status;
}
}
| true
|
daebd7400e2cac529ff1afe3b90a4fe9027d5f17
|
Java
|
CloritoPicado/POO
|
/src/proyecto1/UI/EditarVehiculo.java
|
UTF-8
| 36,257
| 2.171875
| 2
|
[] |
no_license
|
/*
* 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 proyecto1.UI;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.List;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import proyecto1.Controlador;
import proyecto1.EEstado;
import proyecto1.EEstilo;
import proyecto1.ESede;
import proyecto1.ETransmision;
import proyecto1.ListaVehiculos;
import proyecto1.RegEx;
import proyecto1.Vehiculo;
/**
*
* @author Patrixito
*/
public class EditarVehiculo extends javax.swing.JFrame {
String foto = "";
Controlador controlador;
/**
* Creates new form AgregarVehiculo
* @param controlador
*/
public EditarVehiculo(Controlador controlador) {
this.controlador = controlador;
initComponents();
inicializarElementos();
//System.out.println("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}");
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
tAnho = new javax.swing.JTextField();
tMarca = new javax.swing.JTextField();
tKilometro = new javax.swing.JTextField();
tMPG = new javax.swing.JTextField();
tCostoXDia = new javax.swing.JTextField();
jSeparator2 = new javax.swing.JSeparator();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
cEstilo = new javax.swing.JComboBox<>();
cColor = new javax.swing.JComboBox<>();
cPasajeros = new javax.swing.JComboBox<>();
cPuertas = new javax.swing.JComboBox<>();
jLabel15 = new javax.swing.JLabel();
tMaletero = new javax.swing.JTextField();
cTransmision = new javax.swing.JComboBox<>();
cSede = new javax.swing.JComboBox<>();
jSeparator3 = new javax.swing.JSeparator();
jLabel12 = new javax.swing.JLabel();
lImagen = new javax.swing.JLabel();
bCancelar = new javax.swing.JButton();
bAceptar = new javax.swing.JButton();
bBrowse = new javax.swing.JButton();
jLabel16 = new javax.swing.JLabel();
tPlaca = new javax.swing.JTextField();
cVINs = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
setSize(new java.awt.Dimension(1050, 600));
jLabel1.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N
jLabel1.setText("Editar Vehículo");
jLabel2.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel2.setText("VIN");
jLabel3.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel3.setText("Año");
jLabel4.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel4.setText("Marca");
jLabel5.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel5.setText("Kilometraje");
jLabel6.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel6.setText("MPG");
jLabel7.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel7.setText("Costo por día");
tAnho.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
tMarca.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
tKilometro.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
tKilometro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tKilometroActionPerformed(evt);
}
});
tMPG.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
tCostoXDia.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jLabel8.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel8.setText("Estilo");
jLabel9.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel9.setText("Color");
jLabel10.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel10.setText("Pasajeros");
jLabel11.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel11.setText("Puertas");
jLabel13.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel13.setText("Transmisión");
jLabel14.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel14.setText("Sede");
cEstilo.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cEstilo.setPreferredSize(new java.awt.Dimension(100, 21));
cEstilo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cEstiloActionPerformed(evt);
}
});
cColor.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cColor.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Azul", "Rojo", "Amarillo", "Blanco", "Negro", "Verde", "Gris", "Café", " " }));
cColor.setPreferredSize(new java.awt.Dimension(100, 21));
cPasajeros.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cPasajeros.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "2", "3", "4", "5", "6", "7", "8" }));
cPasajeros.setPreferredSize(new java.awt.Dimension(100, 21));
cPasajeros.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cPasajerosActionPerformed(evt);
}
});
cPuertas.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cPuertas.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "2", "3", "4", "5", "6" }));
cPuertas.setPreferredSize(new java.awt.Dimension(100, 21));
jLabel15.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel15.setText("Capacidad maletero");
tMaletero.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cTransmision.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cTransmision.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Manual", "Automática" }));
cTransmision.setPreferredSize(new java.awt.Dimension(100, 21));
cSede.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cSede.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cSede.setPreferredSize(new java.awt.Dimension(100, 21));
jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
jLabel12.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel12.setText("Agregar imagen");
lImagen.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
lImagen.setToolTipText("");
lImagen.setMaximumSize(new java.awt.Dimension(100, 100));
lImagen.setMinimumSize(new java.awt.Dimension(100, 100));
lImagen.setPreferredSize(new java.awt.Dimension(450, 280));
bCancelar.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
bCancelar.setText("Cancelar");
bCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bCancelarActionPerformed(evt);
}
});
bAceptar.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
bAceptar.setText("Aceptar");
bAceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bAceptarActionPerformed(evt);
}
});
bBrowse.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
bBrowse.setText("Browse...");
bBrowse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bBrowseActionPerformed(evt);
}
});
jLabel16.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
jLabel16.setText("Placa");
tPlaca.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N
cVINs.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "..." }));
cVINs.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
}
public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
}
public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
cVINsPopupMenuWillBecomeVisible(evt);
}
});
cVINs.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cVINsMouseClicked(evt);
}
});
cVINs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cVINsActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel15)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel5)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(tCostoXDia, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tMPG, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tKilometro, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tMarca, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tAnho, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tMaletero, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cVINs, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(tPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cSede, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cTransmision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cPuertas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cPasajeros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel8)
.addGap(92, 92, 92)
.addComponent(cEstilo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(34, 34, 34)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12)
.addComponent(lImagen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(bBrowse))))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bAceptar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bCancelar)))
.addGap(63, 63, 63))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel12)
.addGap(18, 18, 18)
.addComponent(lImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bBrowse))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(cVINs, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tAnho, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(tMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(tKilometro, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(tMPG, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(tCostoXDia, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(cEstilo, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(cColor, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(cPasajeros, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(cPuertas, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(cTransmision, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(cSede, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(tMaletero, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(tPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jSeparator2)
.addComponent(jSeparator3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 189, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bCancelar)
.addComponent(bAceptar))
.addGap(25, 25, 25))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void tKilometroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tKilometroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tKilometroActionPerformed
private void cPasajerosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cPasajerosActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cPasajerosActionPerformed
private void bBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBrowseActionPerformed
//lImagen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyecto1/Imagenes/Vehiculos/fortunerToyota.png")));
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new File(System.getProperty("user.dir")));
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println(convertirPath(selectedFile.getAbsolutePath()));
foto = selectedFile.getName();
BufferedImage imagen = null;
try {
imagen = ImageIO.read(selectedFile);
} catch (IOException ex) {
Logger.getLogger(EditarVehiculo.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
lImagen.setIcon(new ImageIcon(imagen));
}
catch (Exception e)
{
System.out.println(e);
}
}
}//GEN-LAST:event_bBrowseActionPerformed
private void cEstiloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cEstiloActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cEstiloActionPerformed
private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
new PantallaPrincipal(controlador).setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_bCancelarActionPerformed
private void bAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAceptarActionPerformed
Vehiculo vehiculo = new Vehiculo();
RegEx regEx = new RegEx();
if(regEx.chequearAnho(tAnho.getText()))
{
vehiculo.setAnho(Integer.parseInt(tAnho.getText()));
if(regEx.chequearNombre(tMarca.getText()))
{
vehiculo.setMarca(tMarca.getText());
if(regEx.chequearKilometraje(tKilometro.getText()))
{
vehiculo.setKilometraje(Float.parseFloat(tKilometro.getText()));
if(regEx.chequearKilometraje(tMPG.getText()))
{
vehiculo.setMpg(Integer.parseInt(tMPG.getText()));
if(regEx.chequearPrecio(tCostoXDia.getText()))
{
vehiculo.setCostoPorDia(Float.parseFloat(tCostoXDia.getText()));
if(regEx.chequearKilometraje(tMaletero.getText()))
{
vehiculo.setCapacidadMaletas(Integer.parseInt(tMaletero.getText()));
if (regEx.chequearPlaca(tPlaca.getText())) {
vehiculo.setPlaca(tPlaca.getText());
vehiculo.setImagen(foto);
vehiculo.setNumVim((String) cVINs.getSelectedItem());
vehiculo.setEstilo((EEstilo) cEstilo.getSelectedItem());
vehiculo.setColor((String) cColor.getSelectedItem());
vehiculo.setCapacidad(Integer.parseInt((String) cPasajeros.getSelectedItem()));
vehiculo.setNumPuertas(Integer.parseInt((String) cPuertas.getSelectedItem()));
vehiculo.setTransmision((ETransmision) cTransmision.getSelectedItem());
vehiculo.setSedePertenencia((ESede) cSede.getSelectedItem());
vehiculo.setImagen(foto);
ListaVehiculos listaVehiculos = controlador.getListaVehiculos();
listaVehiculos.reemplazar((String) cVINs.getSelectedItem(), vehiculo);
controlador.serializador(listaVehiculos, "vehiculos.json");
foto = "";
new PantallaPrincipal(controlador).setVisible(true);
this.setVisible(false);
}
else
System.out.println("Error placa");
}
else
System.out.println("Error maletero");
}
else
System.out.println("Error costo por día");
}
else
System.out.println("Error MPG");
}
else
System.out.println("Error kilometraje");
}
else
System.out.println("Error marca");
}
else
System.out.println("Error año");
}//GEN-LAST:event_bAceptarActionPerformed
private void cVINsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cVINsActionPerformed
Vehiculo v = controlador.getListaVehiculos().getVehiculo((String) cVINs.getSelectedItem());
bloquearElementos(false);
tAnho.setText(v.getAnho()+"");
tMarca.setText(v.getMarca());
tKilometro.setText((int)v.getKilometraje()+"");
tMPG.setText(v.getMpg()+"");
tCostoXDia.setText(v.getCostoPorDia()+"");
tMaletero.setText(v.getCapacidadMaletas()+"");
tPlaca.setText(v.getPlaca());
cEstilo.setSelectedItem(v.getEstilo());
cColor.setSelectedItem(v.getColor());
cPasajeros.setSelectedItem(v.getCapacidad()+"");
cPuertas.setSelectedItem(v.getNumPuertas()+"");
cTransmision.setSelectedItem(v.getTransmision());
cSede.setSelectedItem(v.getSedePertenencia());
foto = v.getImagen();
lImagen.setIcon(new ImageIcon("Imagenes/Vehiculos/"+v.getImagen()));
}//GEN-LAST:event_cVINsActionPerformed
private void cVINsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cVINsMouseClicked
}//GEN-LAST:event_cVINsMouseClicked
private void cVINsPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_cVINsPopupMenuWillBecomeVisible
cVINs.setModel(new DefaultComboBoxModel(controlador.getListaVehiculos().devolverVINs()));
}//GEN-LAST:event_cVINsPopupMenuWillBecomeVisible
private String convertirPath(String s)
{
String resultado = "";
for(int a = 0; a < s.length(); a++)
{
if(s.charAt(a) == '\\')
{
resultado = resultado + "/";
}
else
resultado = resultado + s.charAt(a);
}
return resultado;
}
public void inicializarElementos()
{
cEstilo.setModel(new DefaultComboBoxModel(EEstilo.values()));
cTransmision.setModel(new DefaultComboBoxModel(ETransmision.values()));
cSede.setModel(new DefaultComboBoxModel(ESede.values()));
bloquearElementos(true);
}
public void bloquearElementos(boolean a)
{
tAnho.setEnabled(!a);
tMarca.setEnabled(!a);
tKilometro.setEnabled(!a);
tMPG.setEnabled(!a);
tCostoXDia.setEnabled(!a);
tMaletero.setEnabled(!a);
tPlaca.setEnabled(!a);
cEstilo.setEnabled(!a);
cColor.setEnabled(!a);
cPasajeros.setEnabled(!a);
cPuertas.setEnabled(!a);
cTransmision.setEnabled(!a);
cSede.setEnabled(!a);
bBrowse.setEnabled(!a);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bAceptar;
private javax.swing.JButton bBrowse;
private javax.swing.JButton bCancelar;
private javax.swing.JComboBox<String> cColor;
private javax.swing.JComboBox<String> cEstilo;
private javax.swing.JComboBox<String> cPasajeros;
private javax.swing.JComboBox<String> cPuertas;
private javax.swing.JComboBox<String> cSede;
private javax.swing.JComboBox<String> cTransmision;
private javax.swing.JComboBox<String> cVINs;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JLabel lImagen;
private javax.swing.JTextField tAnho;
private javax.swing.JTextField tCostoXDia;
private javax.swing.JTextField tKilometro;
private javax.swing.JTextField tMPG;
private javax.swing.JTextField tMaletero;
private javax.swing.JTextField tMarca;
private javax.swing.JTextField tPlaca;
// End of variables declaration//GEN-END:variables
}
| true
|
71795472b20bd05c804242ca41e36c7445bc7752
|
Java
|
myandy/shishi
|
/shishi/src/main/java/com/myth/shishi/fragment/ChangeBackgroundFragment.java
|
UTF-8
| 2,467
| 2.09375
| 2
|
[] |
no_license
|
package com.myth.shishi.fragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.myth.shishi.MyApplication;
import com.myth.shishi.R;
import com.myth.shishi.adapter.ImageAdapter;
import com.myth.shishi.entity.Writing;
import com.myth.shishi.util.ResizeUtil;
import com.myth.shishi.wiget.HorizontalListView;
import com.myth.shishi.wiget.ShareView;
public class ChangeBackgroundFragment extends Fragment {
private Context mContext;
private Writing writing;
private int bg_index = 0;
private ShareView shareView;
public ChangeBackgroundFragment() {
}
public static ChangeBackgroundFragment getInstance(Writing writing) {
ChangeBackgroundFragment fileViewFragment = new ChangeBackgroundFragment();
fileViewFragment.writing = writing;
return fileViewFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mContext = inflater.getContext();
View view = inflater.inflate(R.layout.fragment_background,container, false);
initViews(view);
return view;
}
@Override
public void onResume() {
super.onResume();
refresh();
}
@Override
public void onStop() {
super.onStop();
save();
}
public void save() {
writing.setBgimg(bg_index + "");
}
private void refresh() {
shareView.setWriting(writing);
}
private void initViews(View view) {
HorizontalListView imgs = (HorizontalListView) view.findViewById(R.id.imgs);
ImageAdapter adapter = new ImageAdapter(mContext);
imgs.setAdapter(adapter);
imgs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bg_index = position;
shareView.getBackgroundView().setDrawableId(MyApplication.bgimgList[position]);
}
});
shareView = (ShareView) view.findViewById(R.id.share_view);
shareView.setType(ShareView.TYPE_BACKGROUND);
ResizeUtil.getInstance().layoutSquareView(shareView);
}
}
| true
|
47892536c5edec8e4fc94a378d4294c41266bb53
|
Java
|
iyakiwan/MovieDB-Jetpack
|
/app/src/main/java/com/example/java/submission_jetpack/ui/movie/MovieViewModel.java
|
UTF-8
| 904
| 2.09375
| 2
|
[] |
no_license
|
package com.example.java.submission_jetpack.ui.movie;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.java.submission_jetpack.data.source.SubmissionRepository;
import com.example.java.submission_jetpack.data.source.remote.response.movie.MovieResponse;
import java.util.List;
public class MovieViewModel extends ViewModel {
MutableLiveData<List<MovieResponse>> movieResponse = new MutableLiveData<>();
private SubmissionRepository submissionRepository;
public MovieViewModel(SubmissionRepository submissionRepository) {
this.submissionRepository = submissionRepository;
}
public LiveData<List<MovieResponse>> getListMovie() {
if (movieResponse.getValue() == null) {
submissionRepository.getAllMovie(movieResponse);
}
return movieResponse;
}
}
| true
|
85a8f87889dcd14daf6677ea62abde9eb7987249
|
Java
|
yilberth16/ParcialFinal
|
/app/src/main/java/com/example/covid/RastreoMapa.java
|
UTF-8
| 667
| 1.726563
| 2
|
[] |
no_license
|
package com.example.covid;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class RastreoMapa extends AppCompatActivity {
private WebView miWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rastreo_mapa);
miWebView = findViewById(R.id.webView);
miWebView.loadUrl("file:///android_asset/index2.html");
miWebView.getSettings().setJavaScriptEnabled(true);
miWebView.setWebViewClient(new WebViewClient());
}
}
| true
|
685bfd9ac5313eb5b8f2f3626a49aeea3d212145
|
Java
|
iliedorobat/LIDO-Parser
|
/src/ro/webdata/parser/xml/lido/core/leaf/objectID/ObjectIDDAO.java
|
UTF-8
| 239
| 1.882813
| 2
|
[
"MIT"
] |
permissive
|
package ro.webdata.parser.xml.lido.core.leaf.objectID;
import org.w3c.dom.Node;
public interface ObjectIDDAO {
/**
*
* @param node <b>lido:objectID</b> node type.
* @return <b>ObjectID</b>
*/
ObjectID getObjectID(Node node);
}
| true
|
5baa9ce840dc5d1827b0fcbdc2d146d6345505ee
|
Java
|
wangshengkui/smartPenForBoard
|
/src/com/example/smartpengesture/DealSmartPenGesture.java
|
UTF-8
| 37,445
| 1.796875
| 2
|
[] |
no_license
|
package com.example.smartpengesture;
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.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.example.smartpenforboard.MainActivity;
import com.example.smartpenforboard.Position;
import com.example.smartpenforboard.R;
import com.example.smartpenforboard.RecordingService;
import com.example.smartpenforboard.RecordingService.MyBinder;
import com.example.smartpenforboard.UpLoad;
import com.google.common.collect.ArrayListMultimap;
import com.tqltech.tqlpencomm.Dot;
import android.R.integer;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.gesture.GestureStroke;
import android.gesture.Prediction;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
public class DealSmartPenGesture {
com.example.smartpenforboard.MainActivity activity;
public com.example.smartpenforboard.RecordingService.MyBinder recordService;
public Intent intent;
public int PageID=-1;
public ArrayList<Integer> tag=null;
public String gestureFinalName="手势名称";
public String gestureResponce="响应方式";
private ArrayList<Integer> itemsContainer=new ArrayList<Integer>();//布置作业的时候的题目容器
private ParseXml parseXml=null;
private volatile long lastItemTime=0; //老师最后一次选择题目的当前系统时间(正常是为了布置作业)
public void setPageID( int PageID) {
this.PageID=PageID;
if (parseXml==null) {
parseXml=new ParseXml();
}
int parseXmlStatus=parseXml.setParseXml(PageID);
switch (parseXmlStatus) {
case 0:
parseXml=null;
break;
case -1:
parseXml=null;
break;
case 1:
return;
default:
break;
}
}
public final ServiceConnection recordConnection=new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
recordService=null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
recordService=(MyBinder) service;
}
};
public void setDealSmartPenGesture(MainActivity activity){
this.activity=activity;
intent = new Intent(activity, RecordingService.class);
}
private ArrayListMultimap<String, GesturePlaceAndResource> gesturePlaceContainer= ArrayListMultimap.create(); // Book=100笔迹数据
private float delt=15;//判断手势是否在同一个地方的手势边框的冗余量;
public String recogniseSmartPenGesture(SmartPenGesture gesture){
// GestureLibrary gestureLibrary=GestureLibraries.fromFile("/sdcard/zgmgesture");
if (activity.gestureLibrary.load()) {
// Log.e("zgm", "1210:手势文件装载成功");
Set<String> aSet=activity.gestureLibrary.getGestureEntries();
/* for (String string : aSet) {
Log.e("zgm", "0113:"+string);
}*/
/* Gesture firstGesture=new Gesture();
firstGesture.addStroke(gesture.getStrokes().get(0));*/
ArrayList<Prediction> predictions=activity.gestureLibrary.recognize(gesture);
ArrayList<GestureScore> gestureScores=new ArrayList<DealSmartPenGesture.GestureScore>();
for (Prediction prediction :predictions) {
if (prediction.score>2.5) {
gestureScores.add(new GestureScore(prediction.name, prediction.score));
}
}
String gestureName = getHightestScoreGesture(gestureScores);
return gestureName;
}else {
return null;
}
}
/**
*
* @author: nkxm
* @name:
* @description :手势识别主逻辑
* @parameter:
* @parameter:
* @return:
* @date:2019-1-24 下午4:08:41
* @param currentSmartPenGesture
*/
public void dealWithGesture(SmartPenGesture currentSmartPenGesture) {
String gestureName = null;
if (currentSmartPenGesture.getStrokesCount()==1) {
gestureName=recogniseSmartPenGesture(currentSmartPenGesture);
if (gestureName==null) {
// activity.updateUsingInfo("未识别的手势",activity.ORDERSTATE);
gestureFinalName="未知手势";
return;
}
// if (gestureName.equals("录音")&&tag.get(1)!=2) {//不等于题号区
if (gestureName.equals("录音")) {
activity.showTextView(activity.textView,"截屏");
final SmartPenGesture tempSmartPenGesture=currentSmartPenGesture;
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
RectF disTailContorlGestureBoundingBox= getControlGestureBody(activity.temContair);
int delt=10;
if(disTailContorlGestureBoundingBox.bottom-disTailContorlGestureBoundingBox.top>20||disTailContorlGestureBoundingBox.right-disTailContorlGestureBoundingBox.left>20) {
// Log.e("zgm","bottom-top:"+(disTailContorlGestureBoundingBox.bottom-disTailContorlGestureBoundingBox.top));
// Log.e("zgm","right-left:"+(disTailContorlGestureBoundingBox.right-disTailContorlGestureBoundingBox.left ));
activity.showSharePicture(activity.saveScreen(activity.drawView,disTailContorlGestureBoundingBox));
// boolean statsu= UpLoad.uploadFile("http://118.24.109.3/Public/smartpen/upload.php","/sdcard/-1/"
// + activity.sharePictureName);
/* if (statsu) {
activity.showSound(R.raw.upload_sucess);
// Toast.makeText(getBaseContext(), "上传成功", Toast.LENGTH_SHORT).show();
}
else {
activity.showSound(R.raw.upload_fail);
// Toast.makeText(getBaseContext(), "上传失败", Toast.LENGTH_SHORT).show();
}*/
return;
}
// activity.showTextView(activity.textView,"控制指令");
// Log.e("zgm", "gestureName:"+gestureName);
// String audioName="001-"+activity.studentNumber+"-"+activity.gCurBookID+"-"+activity.gCurPageID+"-"+tag.get(0)+".mp3";
/* String audioName="123.mp3";
Log.e("zgm", "audioName:"+audioName);
File file=new File("/sdcard/xyz/"+audioName);
if (file.exists()) {
Log.e("zgm", "音频文件存在");
playAudio("/sdcard/xyz/"+audioName);
return;
}*/
recordAudioGestureProcess(disTailContorlGestureBoundingBox);//录音文件不存在,则启动录音
}}).start();
return ;
}
if (gestureName.equals("对")) {
//正常这里不应该进行处理直接返回
// activity.updateUsingInfo("您画的是判题类手势:对",activity.ORDERSTATE);
activity.showTextView(activity.textView,"您画的是判题类手势:对");
gestureFinalName="对";
gestureResponce="语音响应";
return;
}
//手势只有一笔,且不是录音和选题,交给wsk处理
activity.showTextView(activity.textView,"未识别的一笔手势");
return;
}
else {//手势笔画数大于1,对每一笔都进行识别,看是否有对号,录音符号
SmartPenGesture tempGesture=new SmartPenGesture();
int tempIndex=-1;
int situation=-1;
for (int i = 0; i < currentSmartPenGesture.getStrokesCount(); i++) {//拆分手势,进行单笔识别
tempGesture.SmartPenGestureClearAllStroke();
tempGesture.SmartPenGestureClearmBoundingBox();
tempGesture.addStroke( currentSmartPenGesture.getStrokes().get(i));//将每一笔手势都重新放入临时手势中进行识别
gestureName=recogniseSmartPenGesture(tempGesture);
if (gestureName==null) {
continue;
}
if (gestureName.equals("录音")) {
situation=1;
tempIndex=i;
break;
}
if (gestureName.equals("对")) {
situation=2;
// tempIndex=i;
break;
}
}
switch (situation) {
case 1://其中一笔是录音手势
// 重新封装剩下的笔画,用其他方法识别
tempGesture.SmartPenGestureClearAllStroke();
for (int i = 0; i <currentSmartPenGesture.getStrokesCount(); i++) {
if (i==tempIndex) {
continue;
}
tempGesture.addStroke(currentSmartPenGesture.getStrokes().get(i));
}
//将剩下的手势进行重新处理
Bitmap bitmap=tempGesture.toBitmap(32, 32, 2, Color.WHITE);
String simble= matrix(bitmap);//概率小于0.6则返回null
if (simble==null) {
activity.showTextView(activity.textView,"您画的是投票类手势:但我不知道选了什么");
gestureFinalName="未知手势";
return;
}
activity.showTextView(activity.textView,"选择:"+simble);
break;
case 2://其中一笔是对
switch (currentSmartPenGesture.getStrokesCount()) {
case 2:
gestureName=recogniseSmartPenGesture(currentSmartPenGesture);
if (gestureName!=null&&gestureName.equals("错")) {
// activity.updateUsingInfo("您画的是判题类手势:错",activity.ORDERSTATE);
// activity.textView.setText("您画的是判题类手势:错");
activity.showTextView(activity.textView,"您画的是判题类手势:错");
gestureResponce="语音响应";
gestureFinalName="错";
return;
}
// activity.updateUsingInfo("您画的是判题类手势:半对",activity.ORDERSTATE);
// activity.textView.setText("您画的是判题类手势:半对");
activity.showTextView(activity.textView,"您画的是判题类手势:半对");
gestureFinalName="半对";
return;
case 3:
// activity.textView.setText("您画的是判题类手势:半对2");
activity.showTextView(activity.textView,"您画的是判题类手势:半对2");
// activity.updateUsingInfo("您画的是判题类手势:半对2",activity.ORDERSTATE);
gestureResponce="语音响应";
gestureFinalName="半对2";
return;
case 4:
// activity.textView.setText("您画的是判题类手势:半对3");
activity.showTextView(activity.textView,"您画的是判题类手势:半对3");
// activity.updateUsingInfo("您画的是判题类手势:半对3",activity.ORDERSTATE);
gestureResponce="语音响应";
gestureFinalName="半对3";
return;
default:
gestureFinalName="未知手势";
break;
}
// activity.textView.setText("您画的手势我没有识别");
activity.showTextView(activity.textView,"您画的手势我没有识别");
// activity.updateUsingInfo("您画的手势我没有识别",activity.ORDERSTATE);
gestureFinalName="未知手势";
break;
case -1:
gestureName=recogniseSmartPenGesture(currentSmartPenGesture);
if (gestureName!=null&&gestureName.equals("错")) {
// activity.textView.setText("您画的是判题类手势:错");
activity.showTextView(activity.textView,"您画的是判题类手势:错");
// activity.updateUsingInfo("您画的是判题类手势:错",activity.ORDERSTATE);
gestureResponce="语音响应";
gestureFinalName="错";
return;
}
/* Bitmap mbitmap=currentSmartPenGesture.toBitmap(32, 32, 2, Color.WHITE);
String msimble= matrix(mbitmap);
if (msimble==null) {
if (currentSmartPenGesture.getStrokesCount()==2) {
gestureName=recogniseSmartPenGesture(currentSmartPenGesture);
}*/
// activity.updateUsingInfo("您画的手势我没有识别",activity.ORDERSTATE);
// }
// activity.updateUsingInfo("您画的手势是:"+msimble,activity.ORDERSTATE);
// activity.updateUsingInfo("您画的手势我没有识别",activity.ORDERSTATE);
activity.showTextView(activity.textView,"您画的是判题类手势:错");
// activity.textView.setText("您画的是判题类手势:错");
gestureFinalName="未知手势";
break;
default:
gestureFinalName="未知手势";
break;
}
}
}
public String getHightestScoreGesture(ArrayList<GestureScore> arrayList){
if (arrayList.size()==0) {
return null;
}
double hightestScore=-5;
String gestureName=null;
for (int i=0;i<arrayList.size();i++) {
if (arrayList.get(i).getGestureScore()>hightestScore) {
hightestScore=arrayList.get(i).getGestureScore();
gestureName=arrayList.get(i).getGestureNmae();
}
}
return gestureName;
}
private boolean isAlmostEqual(RectF rectF1,RectF rectF2){
float centerPointX1=(rectF1.right+rectF1.left)/2;
float centerPointY1=(rectF1.bottom+rectF1.top)/2;
float centerPointX2=(rectF2.right+rectF2.left)/2;
float centerPointY2=(rectF2.bottom+rectF2.top)/2;
/* float leftDistance=Math.abs(rectF1.left-rectF2.left);
// float topDistance=Math.abs(rectF1.top-rectF2.top);
// float rightDistance=Math.abs(rectF1.right-rectF2.right);
float bottomDistance=Math.abs(rectF1.bottom-rectF2.bottom);
*/
if (Math.abs(centerPointX1-centerPointX2)<delt&&Math.abs(centerPointY1-centerPointY2)<delt) {
return true;
}
return false;
}
public class GestureScore{
String gestureName="";
double gestureScore=0;
public GestureScore(String gestureName, double score) {
// TODO Auto-generated constructor stub
this.gestureName=gestureName;
this.gestureScore=score;
}
public String getGestureNmae() {
return gestureName;
}
public double getGestureScore(){
return gestureScore;
}
}
private class GesturePlaceAndResource{
String gestureNameString="";
String resourcePathString="";
long resourceElpased=0;
final RectF rectF;
GesturePlaceAndResource(String gestureNameString,String resourcePathString,long resourceElpased,RectF rectF){
this.gestureNameString=gestureNameString;
this.resourcePathString=resourcePathString;
this.resourceElpased=resourceElpased;//播放时长
this.rectF=rectF;
}
public String getGestureNameString(){
return gestureNameString;
}
public String getResourcePath(){
return resourcePathString;
}
public RectF getGesturePlace(){
return this.rectF;
}
public long getresourceElpased(){
return resourceElpased;
}
}
private void onRecord(boolean start) {
if (start) {
// Toast.makeText(activity, "开始录音...", Toast.LENGTH_SHORT).show();
File folder = new File(Environment.getExternalStorageDirectory() + "/penconNativeRecord");
if (!folder.exists()) {
//folder /SoundRecorder doesn't exist, create the folder
folder.mkdir();
}
//start Chronometer
// mChronometerTime.setBase(SystemClock.elapsedRealtime());
// mChronometerTime.start();
//start RecordingService
activity.startService(intent);
if (activity.bindService(intent,recordConnection,Service.BIND_AUTO_CREATE)) {
Log.e("zgm", "1217:绑定成功!");
}else {
Log.e("zgm", "1217:绑定失败! "+activity.getClass().getName());
}
//
//keep screen on while recording
// getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
// Toast.makeText(activity, "录音结束...", Toast.LENGTH_SHORT).show();
activity.unbindService(recordConnection);
activity.stopService(intent);
}
}
public void playAudio(GesturePlaceAndResource gesturePlaceAndResource){
// activity.updateUsingInfo("播放相关资源"+gesturePlaceAndResource.getResourcePath(),activity.ORDERSTATE);
Log.e("zgm","1218:播放相关资源"+gesturePlaceAndResource.getResourcePath());
final MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource( Environment.getExternalStorageDirectory().getAbsolutePath()+"/SoundRecorder/" + "recordAudio"+ ".mp3");
mMediaPlayer.prepare();
} catch (IOException e) {
Log.e("zgm", "prepare() failed");
}
mMediaPlayer.start();
new Thread(new Runnable() {
@Override
public void run() {
long tempStartTime=System.currentTimeMillis();
while (System.currentTimeMillis()-tempStartTime<3*1000) {
//空循环
}
// activity.updateUsingInfo("留言播放结束",activity.ORDERSTATE);
// activity.textView.setText("留言播放结束");
activity.showTextView(activity.textView,"留言播放结束");
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.release();
activity.isDealPenPoint=true;
}
}).start();
return;
/* com.example.pencon.RecordingItem recordingItem = new com.example.pencon.RecordingItem();
//播放相关资源
recordingItem.setLength((int) gesturePlaceAndResource.getresourceElpased());
recordingItem.setFilePath(gesturePlaceAndResource.getResourcePath());
com.example.pencon.PlaybackDialogFragment fragmentPlay = com.example.pencon.PlaybackDialogFragment.newInstance(recordingItem);
fragmentPlay.show(activity.getSupportFragmentManager(), com.example.pencon.PlaybackDialogFragment.class.getSimpleName());
*/
}
public void playAudio(final String path){
final MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepare();
} catch (IOException e) {
Log.e("zgm", "prepare() failed");
}
mMediaPlayer.start();
new Thread(new Runnable() {
@Override
public void run() {
while(mMediaPlayer.isPlaying()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.release();
}
}
}).start();
}
public void recordAndio(final RectF boundingBox,boolean isjustforname){
String gestureNameString="录音";
GesturePlaceAndResource gesturePlaceAndResource;
// Log.e("zgm","/sdcard/xyz/001-"+activity.studentNumber+"-"+activity.gCurBookID+"-"+activity.gCurPageID+"-"+tag.get(1)+".mp3");
if (isjustforname) {
if(boundingBox!=null){
RectF tempRectF=new RectF(boundingBox);
gesturePlaceAndResource=new GesturePlaceAndResource(gestureNameString,"/sdcard/xyz/001-"+activity.studentNumber+"-"+activity.gCurBookID+"-"+activity.gCurPageID+"-"+tag.get(1)+".mp3",2000,tempRectF);
Log.e("zgm","/sdcard/xyz/001-"+activity.studentNumber+"-"+activity.gCurBookID+"-"+activity.gCurPageID+"-"+tag.get(1)+".mp3");
gesturePlaceContainer.put(gestureNameString, gesturePlaceAndResource);//将手势和相关的信息加入gesturePlaceContainer中;
return;
}
}
// activity.updateUsingInfo("请录音",activity.ORDERSTATE);
// activity.textView.setText("请录音");
activity.showTextView(activity.textView,"请录音");
onRecord(true);
// activity.updateUsingInfo("录音当中,录音3s,请留言",activity.ORDERSTATE);
// activity.textView.setText("录音当中,录音3s,请留言");
activity.showTextView(activity.textView,"录音当中,录音3s,请留言");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
long temStartTime=System.currentTimeMillis();
while (System.currentTimeMillis()-temStartTime<3*1000) {
}
onRecord(false);//结束录音
// activity.showSound(R.raw.endrecord);
// activity.showVibrator();// 震动
String filePath=recordService.getService().getMFilePath();
activity.soundPathString=filePath;
if (filePath==null) {
// activity.updateUsingInfo("没有录音",activity.ORDERSTATE);
// activity.textView.setText("没有录音");
activity.showTextView(activity.textView,"没有录音");
return;
}
long elpased =recordService.getService().getMFileElpased();
String gestureNameString="录音";
if(boundingBox!=null){
RectF tempRectF=new RectF(boundingBox);
GesturePlaceAndResource gesturePlaceAndResource=new GesturePlaceAndResource(gestureNameString,filePath,elpased,tempRectF);
gesturePlaceContainer.put(gestureNameString, gesturePlaceAndResource);//将手势和相关的信息加入gesturePlaceContainer中;
}
// activity.textView.setText("录音完成,音频文件路径:"+filePath);
activity.showTextView(activity.textView,"录音完成,音频文件路径:"+filePath);
// activity.updateUsingInfo("录音完成,音频文件路径:"+filePath,activity.ORDERSTATE);
activity.isDealPenPoint=true;
}
}).start();
}
/**
*
* @author: nkxm
* @name:
* @description :
* @parameter:
* @parameter:
* @return:
* @date:2019-1-23 下午10:33:44
* @param gestureName
* @param gestureStroke
* @return:返回的是点的序号(从零开始),因此返回值不会大于gestureStroke.points.length/2-1;
*/
public int getTailIndex(String gestureName,ArrayList<Position> temContair){
if (!gestureName.equals("录音")) {
return -1;
}
if ( temContair.size()<8) {
return -1;
}
boolean first=true;
boolean second=false,third=false,forth=false;
int index=-1;
float x1,y1,x2,y2;
for (int i = 0; i < temContair.size()-1; i++) {
x1=temContair.get(i).x;
y1=temContair.get(i).y;
x2=temContair.get(i+1).x;
y2=temContair.get(i+1).y;
if(first){
if ((x2-x1)>1&&(y2-y1)>1) {//从左上到右下变化趋势
first=false;
second=true;
}
}
if(second) {
if ((x2-x1)>=1&&(y2-y1)<=-1) {//从左下到右上
second=false;
third=true;
}
}
if(third) {
if ((x2-x1)<=-1&&(y2-y1)>=-1) {//从右上到左下
third=false;
forth=true;
}
}
if (forth) {
if ((x2-x1)>1&&(y2-y1)<1) {//从左下到右上
index=i;
return index;
}
}
}
return -1;
}
public RectF getBoundingBox(int endIndex,ArrayList<Position> temContaier){
if (endIndex<0||temContaier.size()==0) {
return null;
}
RectF boundingBox=new RectF();
Dot tempDot;
for (int i = 0;i < temContaier.size(); i++) {
if (i<=endIndex) {
if (i==0) {
boundingBox.left=temContaier.get(i).x;
boundingBox.right=temContaier.get(i).x;
boundingBox.top=temContaier.get(i).y;
boundingBox.bottom=temContaier.get(i).y;
continue;
}
boundingBox.union(temContaier.get(i).x,temContaier.get(i).y);
continue;
}
break;
}
return boundingBox;
}
/**
*
* @author: nkxm
* @name:
* @description :还未进行调试(可能有bug,暂时还没有使用),对点序列中的相邻两个点直接进行插值,使其x坐标连续(每一个整数都能对应一个x坐标).
* @parameter:
* @parameter:
* @return:
* @date:2019-1-20 上午11:26:58
* @param gestureStroke
* @return
*/
public void recordAudioGestureProcess(RectF disTailContorlGestureBoundingBox){
if(activity==null){ return; }
String gestureName="录音";
/*
* 以下代码主要是获得录音手势去掉尾巴的的边界矩形
*/
// RectF mainBoundingBox=null;
/*
* 注意录音手势应该只有一笔,这里就认为其只有一笔,所以下面的代码只适用于只有一笔的录音手势
*/
/* int endIndex= getTailIndex( gestureName,currentSmartPenGesture.getStrokes().get(0));
if (endIndex==-1) {
endIndex=currentSmartPenGesture.getStrokes().get(0).points.length/2-1;
}
mainBoundingBox=getBoundingBox(endIndex, currentSmartPenGesture.getStrokes().get(0));
*/ /*
* 以上代码主要是获得录音手势去掉尾巴的的边界矩形
*/
/* if(gesturePlaceContainer.get(gestureName).size()==0){
//还没有录过音,开始第一个录音
return;
}else */
{//代码块,匹配手势用
activity.isDealPenPoint=false;
Log.e("zgm", "1218:"+gestureName);
List<GesturePlaceAndResource> a = gesturePlaceContainer.get(gestureName);
if (a.size()>0) {
Log.e("zgm","0108:"+a.size()+":"+a.get(0).rectF);
}
for (GesturePlaceAndResource gesturePlaceAndResource : gesturePlaceContainer.get(gestureName)) {
if (isAlmostEqual(disTailContorlGestureBoundingBox,gesturePlaceAndResource.getGesturePlace())) {
playAudio(gesturePlaceAndResource);
return;
}
}
}
{//代码块,没有匹配到手势,那么就开始录音相关的操作
Log.e("zgm","1216:没有匹配到录音手势");
recordAndio( disTailContorlGestureBoundingBox,!activity.doSomeworkIsOK);
}//代码块完
}
public float[] linearInterpolation(GestureStroke gestureStroke){
ArrayList<Float> interpolatedPoints=new ArrayList<Float>();
if (gestureStroke.points.length<4) {
return gestureStroke.points;
}
int x1,y1,x2,y2;
for (int i = 0; i < gestureStroke.points.length/2-1; i=i+1) {
x1=Math.round(gestureStroke.points[i*2]);
y1=Math.round(gestureStroke.points[i*2+1]);
x2=Math.round(gestureStroke.points[(i+1)*2]);
y2=Math.round(gestureStroke.points[(i+1)*2+1]);
if (i==0) {
interpolatedPoints.add((float) x1);
interpolatedPoints.add((float) y1);
}
if (x1==x2&&y1==y2) {//情况1
interpolatedPoints.add((float) x2);
interpolatedPoints.add((float) y2);
continue;
}
if (x1==x2&&y1!=y2) {//情况2
int tempy=y1;
if (tempy<y2) {
while(tempy<y2){
interpolatedPoints.add((float) x1);
interpolatedPoints.add((float) tempy+1);
tempy=tempy+1;
}
continue;
}
if (tempy>y2) {
while(tempy<y2){
interpolatedPoints.add((float) x1);
interpolatedPoints.add((float) tempy-1);
tempy=tempy-1;
}
continue;
}
}
if (x1!=x2&&y1==y2) {//情况3
int tempx=x1;
if (tempx<x2) {
while(tempx<x2){
interpolatedPoints.add((float) tempx+1);
interpolatedPoints.add((float) y1);
tempx=tempx+1;
}
continue;
}
if (tempx>x2) {
while(tempx>x2){
interpolatedPoints.add((float) tempx-1);
interpolatedPoints.add((float) y1);
tempx=tempx-1;
}
continue;
}
}
if (x1!=x2&&y1!=y2) {//情况4
float bx1x2 =y1*(x2-x1)-x1*(y2-y1);
int tempx=x1;
float tempy;
if (tempx<x2) {
while (tempx<x2) {
tempy=((tempx+1)*(y2-y1)+bx1x2)/(x2-x1);
interpolatedPoints.add((float) tempx+1);
interpolatedPoints.add((float) y1);
tempx=tempx+1;
}
continue;
}
if (tempx>x2) {
while (tempx>x2) {
tempy=((tempx-1)*(y2-y1)+bx1x2)/(x2-x1);
interpolatedPoints.add((float) tempx-1);
interpolatedPoints.add((float) y1);
tempx=tempx-1;
}
continue;
}
}
}
return null;
}
/**
*
* @author: nkxm
* @name:
* @description :求得手势的中心点坐标(所有笔画的中心)
* @date:2019-1-23 下午9:05:28
* @param currentSmartPenGesture
* @return:返回手势的中心点坐标
*/
public float[] getGestureCenture(SmartPenGesture currentSmartPenGesture){
float[] averges=new float[2];
averges[0]=0;//averges[0]存放的是中心点x的坐标
averges[1]=0;//averges[1]存放的是中心点y的坐标
int counter=0;
for (GestureStroke gStroke:currentSmartPenGesture.getStrokes()) {
for (int i =0;i< gStroke.points.length/2; i++) {
counter++;
averges[0]=averges[0]+gStroke.points[2*i];
averges[1]=averges[1]+gStroke.points[2*i+1];
}
}
averges[0]=averges[0]/counter;
averges[1]=averges[1]/counter;
return averges;
}
public double[][] layerout(double[][] a,double[][] b,double[][]c){
double[][] d=new double[a.length][b[0].length];
if(a[0].length==b.length) {
for(int i=0;i<a.length;i++) {
for(int j=0;j<b[0].length;j++) {
for(int k=0;k<a[0].length;k++) {
d[i][j]+=a[i][k]*b[k][j];
}
}
}
}
if(d.length==c.length&&d[0].length==c[0].length) {
for(int i=0;i<d.length;i++) {
for(int j=0;j<d[0].length;j++) {
d[i][j]=d[i][j]+c[i][j];
}
}
}
for(int i=0;i<c.length;i++) {
d[i][0]=1.0/(1+1/Math.exp(d[i][0]));
}
return d;
}
public double[][] in_array(String string,int wigth,int height) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(string));
double[][] arr = new double [height][wigth];
String line = "";
int row=0;
while((line =in.readLine())!=null) {
Log.i("di", "tmp"+row);
String[] tmp = line.split(" ");
// Log.i("di", "tmp"+tmp[25]);
for(int i=0;i<tmp.length;i++) {
// Log.i("di", "tmpi"+i);
arr[row][i]= Double.valueOf(tmp[i]);
}
row++;
}
in.close();
return arr;
}
private String matrix(Bitmap bitmap) {
String picName = System.currentTimeMillis()+".jpg";
File file = new File( "/sdcard/classify/"+picName);
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
System.out.println("___________保存__sd___下_______________________");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.flush();
out.close();
} catch (IOException e) {
Log.e("zgm", ":"+e);
e.printStackTrace();
}
double[][] arr=new double[1024][1];
int r=0;
for(int i=0;i<32;i++) {
for(int j=0;j<32;j++) {
Log.i("di", "pixel"+bitmap.getPixel(j, i));
if(bitmap.getPixel(j,i)==0) {
arr[r][0]=1;
}
else {
arr[r][0]=0;
}
// Log.i("di", "a"+r);
if(arr[r][0]==0) {
// Log.i("di", "a"+r);
}
r++;
}
}
if (!bitmap.isRecycled()) {
bitmap.recycle();
}
try {
double[][]w=in_array("/sdcard/classify/w.txt",28,5);
double[][]b=in_array("/sdcard/classify/b.txt",1,5);
double[][]w_h=in_array("/sdcard/classify/w_h.txt",1024,28);
double[][]b_h=in_array("/sdcard/classify/b_h.txt",1,28);
double[][] hid=layerout(w_h,arr,b_h);
double[][] pre=layerout(w,hid,b);
String[] a = {"A","B","C","D","E"};
double max=0;
for (int i=0;i<pre.length;i++) {
Log.i("di", "type"+pre[i][0]);
if(pre[i][0]>max) {
max=pre[i][0];
}
}
if (max<0.9) {
return null;
}
for (int i=0;i<pre.length;i++) {
if(pre[i][0]==max) {
//showInftTextView.setText("字母:" + a[i]);
return a[i];
}
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("zgm", "读取参数矩阵失败:"+e);
return null;
}
return null;
}
/**
* 判断某个手势是否是单击
* @param currentSmartPenGesture
* @return true:是单击;false:不是单击
*/
public boolean isclick(SmartPenGesture currentSmartPenGesture) {
if (currentSmartPenGesture.getStrokesCount()!=1) {
return false;
}
RectF rectF=currentSmartPenGesture.getGestureBoundBoxRect();
if (Math.abs(rectF.right-rectF.left)<1&&Math.abs(rectF.bottom-rectF.top)<1) {
return true;
}
return false;
}
//wsk 2019.1.26
//读题目和三维语义
/*public void ReadTiMu(int pageID)
{
ArrayList<Integer> tag = new ArrayList<Integer>();
tag = ReadQuestion.ReceiveQuestionDots(point_number1, point_number2, bihua, pageID);
if(tag == null)
{
return;
}
else
{
//读题
if(tag.get(1) == 0)
{
switch(tag.get(0))
{
case 1:showSound(R.raw.onetigan);
break;
case 2:showSound(R.raw.twotigan);
break;
case 3:showSound(R.raw.threetigan);
break;
case 4:showSound(R.raw.fourtigan);
break;
case 5:showSound(R.raw.fivetigan);
break;
case 6:showSound(R.raw.sixtigan);
break;
case 7:showSound(R.raw.seventigan);
break;
case 8:showSound(R.raw.eigthttigan);
break;
case 9:showSound(R.raw.ninetigan);
break;
default:break;
}
}
else if(tag.get(1) == 1)
{
//读要求
showSound(R.raw.sanweiyuyi);
}
else return;
}
}
*/
public List<points> singleSmartPenGestureToPointsList(SmartPenGesture currentSmartPenGesture){
List<points> points;
return null;
}
/**
*
* @param currentSmartPenGesture 一笔手势,多笔不做处理
* @return: tag[2],tag=null:不在任何区域 ;tag[0]:题号;tag[1]:题号对应题目的某个区域
*/
public ArrayList<Integer> getChirographyPositionInfo(SmartPenGesture currentSmartPenGesture,int mPageID ) {
/* if (currentSmartPenGesture.getStrokesCount()!=1) {//不是一笔,直接返回null
return null;
}*/
float[] averages=getGestureCenture(currentSmartPenGesture);//averages[0]:x平均值;averages[1]:x平均值
//得到区域-题干区
averages[0]=(float) (averages[0]/138.14*1519)+20;
averages[1]=(float) (averages[1]/194.296*2151)+100;
ArrayList<Integer> tag=testxml.test( averages[0], averages[1],activity.gCurBookID);
return tag;
}
/**
*
* @Title: getControlGestureBody
* @Description: TODO :获取控制指令符号的主体(去掉最后的尾巴)
* @return
*@return:RectF(返回类型)
* @throws:异常描述
*
* @version: v1.0.0
* @author: lfgm
* @date: 2019年4月25日 下午4:04:15
*/
public RectF getControlGestureBody(ArrayList<Position> temContainer) {
/*
* 注意录音手势应该只有一笔,这里就认为其只有一笔,所以下面的代码只适用于只有一笔的录音手势
*/
int endIndex= getTailIndex("录音",temContainer);
if (endIndex==-1) {
endIndex=temContainer.size();
}
RectF mainBoundingBox = getBoundingBox(endIndex,temContainer);
/*
* 以上代码主要是获得录音手势去掉尾巴的的边界矩形
*/
//activity.drawRectF(mainBoundingBox);
activity.updateInfo(getsignallength(endIndex,temContainer), activity.TAILLENGTH);//控制符号尾巴长度
activity.updateInfo(getsignallength(0,temContainer), activity.GESTURELENGTH);//控制符号整体长度
activity.updateInfo(mainBoundingBox.right-mainBoundingBox.left, activity.BOUNDINGBOXWIDTH);//控制符号主体边框宽
activity.updateInfo(mainBoundingBox.bottom-mainBoundingBox.top, activity.BOUNDINGBOXHEIGHT);//控制符号主体边框高
activity.updateInfo(changeTimes(endIndex,temContainer), activity.TAILECHANGETIMES);//控制符号尾巴变化次数
activity.updateInfo(temContainer.size()-endIndex,activity.TAILPOINTCOUNTER);//控制符号尾巴变化次数
ArrayList<Position> tepmCountainer1=new ArrayList<Position>();
//int[] temIndexs=getLongestLineArea(endIndex,temContainer);
//for (int i = temIndexs[0]; i <temIndexs[1]+1; i++) {
for (int i =endIndex; i <temContainer.size(); i++) {
tepmCountainer1.add(temContainer.get(i));
}
float[] a_b=getKandB(tepmCountainer1);
activity.updateInfo(a_b[0],activity.TAILSLOPE);//控制符号尾巴变化次数
float temp =temContainer.get(temContainer.size()-1).x;
//activity.drawLine(temContainer.get(temIndexs[0]).x,temContainer.get(temIndexs[0]).y, temp, a_b[0]*temp+a_b[1]);
activity.drawLine(temContainer.get(endIndex).x,temContainer.get(endIndex).y,temp,a_b[0]*temp+a_b[1]);
return mainBoundingBox;
}
public float getsignallength(int startIndex,ArrayList<Position> temContainer) {
float sum=0;
float x=0,y=0,tmpx=0,tmpy=0;
for (int i = startIndex; i < temContainer.size(); i++) {
if(i==startIndex) {
x=temContainer.get(i).x;
y=temContainer.get(i).y;
tmpx=x;
tmpy=y;
sum+=Math.sqrt((x-tmpx)*(x-tmpx)+(y-tmpy)*(y-tmpy));
}else {
x=temContainer.get(i).x;
y=temContainer.get(i).y;
sum+=Math.sqrt((x-tmpx)*(x-tmpx)+(y-tmpy)*(y-tmpy));
tmpx=x;
tmpy=y;
}
}
return sum;
}
public int changeTimes(int startIndex,ArrayList<Position> temContainer) {
int changeTimes=0;
float x0=0,y0=0,x1=0,y1=0;
int lastStateX=-1;
int currentStateX=-1;
int lastStateY=-1;
int currentStateY=-1;
for (int i =startIndex; i < temContainer.size()-1; i++) {
x0=temContainer.get(i).x;
y0=temContainer.get(i).y;
x1=temContainer.get(i+1).x;
y1=temContainer.get(i+1).y;
if (x1-x0>1) {//x增加
currentStateX=0;
}
if (x1-x0<-1) {//x减少
currentStateX=1;
}
if (x1-x0>-1&&x1-x0<1) {//x持平
currentStateX=2;
}
if (y1-y0>1) {//x增加
currentStateY=0;
}
if (y1-y0<-1) {//x减少
currentStateY=1;
}
if (y1-y0>-1&&y1-y0<1) {//x持平
currentStateY=2;
}
if(currentStateX!=lastStateX||currentStateY!=lastStateY) {
changeTimes++;
if (currentStateX!=lastStateX) {
lastStateX=currentStateX;
}
if (currentStateY!=lastStateY) {
lastStateY=currentStateY;
}
}
}
return changeTimes;
}
public float[] getKandB(ArrayList<Position> posList){
//List<Position>posList = new ArrayList();
float[] result = new float[2];
float k;
float b;
float x_y = 0;
float x = 0;
float y = 0;
float x2 = 0;
float x_mean;
float y_mean;
for(Position pos:posList){
x_y+=pos.x*pos.y;
x+=pos.x;
y+=pos.y;
x2+=pos.x*pos.x;
}
x_mean=x/posList.size();
y_mean=y/posList.size();
// b=y_mean-x_mean;
if(x2-x*x/posList.size()!=0){
k=(x_y-x*y/posList.size())/(x2-x*x/posList.size());
b=y_mean-x_mean*k;
result[0]=k;//斜率
result[1]=b;//截距
}
else{
result[0]=Float.MAX_VALUE;//斜率
result[1]=0;//截距
}
return result;
}
public int[] getLongestLineArea(int startIndex,ArrayList<Position> positions) {
int[] mIndex=new int[2];
int tempStartIndex=startIndex;
double length=0;
double sum=0;
double d=0;
float x0=0,y0=0,x1=0,y1=0;
int lastStateX=-1;
int currentStateX=-1;
int lastStateY=-1;
int currentStateY=-1;
for (int i =startIndex; i < positions.size()-1; i++) {
x0= positions.get(i).x;
y0= positions.get(i).y;
x1= positions.get(i+1).x;
y1= positions.get(i+1).y;
d=Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0));
// sum=sum+d;
if (x1-x0>1) {//x增加
currentStateX=0;
}
if (x1-x0<-1) {//x减少
currentStateX=1;
}
if (x1-x0>-1&&x1-x0<1) {//x持平
currentStateX=2;
}
if (y1-y0>1) {//x增加
currentStateY=0;
}
if (y1-y0<-1) {//x减少
currentStateY=1;
}
if (y1-y0>-1&&y1-y0<1) {//x持平
currentStateY=2;
}
if(currentStateX!=lastStateX||currentStateY!=lastStateY) {
if (sum>length) {
length=sum;
sum=0;
sum=+d;
mIndex[0]=tempStartIndex;
mIndex[1]=i;
tempStartIndex=i;
}
if (currentStateX!=lastStateX) {
lastStateX=currentStateX;
}
if (currentStateY!=lastStateY) {
lastStateY=currentStateY;
}
}else {
sum=+d;
}
}
if (sum>length) {
length=sum;
mIndex[0]=tempStartIndex;
mIndex[1]= positions.size()-1;
}
return mIndex;
}
}
| true
|
edeb9d5bb4b5a3ee0abc2e21e6e77272b3805f5f
|
Java
|
jbro885/couchbase-lite-java
|
/lib/src/main/java/com/couchbase/lite/internal/NativeLibrary.java
|
UTF-8
| 6,047
| 2.296875
| 2
|
[
"Apache-2.0"
] |
permissive
|
//
// NativeLibrary.java
//
// Copyright (c) 2019 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package com.couchbase.lite.internal;
import android.support.annotation.NonNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* For extracting and loading native libraries for couchbase-lite-java.
*/
final class NativeLibrary {
private NativeLibrary() { }
private static final String[] LIBRARIES = {"LiteCore", "LiteCoreJNI"};
private static final String LIBS_RES_BASE_DIR = "/libs";
@SuppressWarnings("PMD.UnusedPrivateField")
private static final String TARGET_BASE_DIR = "com.couchbase.lite.java/native";
private static final AtomicBoolean LOADED = new AtomicBoolean(false);
/**
* Extracts and loads native libraries.
*/
static void load() {
CouchbaseLiteInternal.requireInit("Cannot load native libraries");
if (LOADED.getAndSet(true)) { return; }
try {
final String[] libPaths = Arrays.stream(LIBRARIES).map(lib -> getResourcePath(lib)).toArray(String[]::new);
final String targetDir = getTargetDirectory(libPaths);
for (String path : libPaths) { System.load(extract(path, targetDir).getCanonicalPath()); }
}
catch (Exception th) {
final String platform = System.getProperty("os.name") + "/" + System.getProperty("os.arch");
throw new IllegalStateException("Cannot load native library for " + platform, th);
}
}
/**
* Returns a target directory for extracting the native libraries into. The structure of the
* directory will be <System Temp Directory>/com.couchbase.lite.java/native/<MD5-Hash>.
* The MD5-Hash is the combined MD5 hash of the hashes of all native libraries.
*/
@NonNull
@SuppressFBWarnings("DE_MIGHT_IGNORE")
private static String getTargetDirectory(@NonNull String... libPaths)
throws NoSuchAlgorithmException, IOException {
final MessageDigest md = MessageDigest.getInstance("MD5");
for (String path : libPaths) {
try (InputStream in = NativeLibrary.class.getResourceAsStream(path + ".MD5")) {
if (in == null) { throw new IOException("Cannot find MD5 for library at " + path); }
final byte[] buffer = new byte[128];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
}
}
final String md5 = String.format("%032x", new BigInteger(1, md.digest()));
return new File(CouchbaseLiteInternal.getTmpDirectoryPath(), md5).getCanonicalPath();
}
/**
* Extracts the given path to the native library in the resource directory into the target directory.
* If the native library already exists in the target library, the existing native library will be used.
*/
@NonNull
@SuppressFBWarnings("DE_MIGHT_IGNORE")
private static File extract(@NonNull String libResPath, @NonNull String targetDir)
throws IOException, InterruptedException {
final File targetFile = new File(targetDir, new File(libResPath).getName());
if (targetFile.exists()) { return targetFile; }
final File dir = new File(targetDir);
if (!dir.mkdirs() && !dir.exists()) {
throw new IOException("Cannot create target directory: " + dir.getCanonicalPath());
}
// Extract the library to the target directory:
try (
InputStream in = NativeLibrary.class.getResourceAsStream(libResPath);
OutputStream out = Files.newOutputStream(targetFile.toPath());
) {
if (in == null) { throw new IOException("Native library not found at " + libResPath); }
final byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); }
}
// On non-windows systems set up permissions for the extracted native library.
if (!System.getProperty("os.name").toLowerCase(Locale.getDefault()).contains("windows")) {
Runtime.getRuntime().exec(new String[] {"chmod", "755", targetFile.getCanonicalPath()}).waitFor();
}
return targetFile;
}
/**
* Returns the path in the resource directory where the native libraries are located.
*/
@NonNull
private static String getResourcePath(@NonNull String libraryName) {
// Root native library folder.
String path = LIBS_RES_BASE_DIR;
// OS:
final String osName = System.getProperty("os.name");
if (osName.contains("Linux")) { path += "/linux"; }
else if (osName.contains("Mac")) { path += "/macos"; }
else if (osName.contains("Windows")) { path += "/windows"; }
else { path += "/" + osName; }
// Arch:
final String archName = "x86_64";
path += '/' + archName;
// Platform specific name part of path.
path += '/' + System.mapLibraryName(libraryName);
return path;
}
}
| true
|
726bb48e959874c7984d0d981e68200dd97a3be7
|
Java
|
shibing624/similarity
|
/src/main/java/org/xm/classification/Feature.java
|
UTF-8
| 1,812
| 2.96875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.xm.classification;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* 文档的特征
*/
public class Feature {
/**
* 每个关键词在不同类别中出现的文档数量
*/
private Map<String, Integer> docCountMap = new HashMap<>();
/**
* 特征名称
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void incDocCount(String category) {
if (docCountMap.containsKey(category)) {
docCountMap.put(category, docCountMap.get(category) + 1);
} else {
docCountMap.put(category, 1);
}
}
public int getDocCount(String category) {
if (docCountMap.containsKey(category)) {
return docCountMap.get(category);
} else {
return 0;
}
}
public void write(DataOutput out) throws IOException {
out.writeUTF(name == null ? "" : name);
out.writeInt(docCountMap.size());
for (String category : docCountMap.keySet()) {
out.writeUTF(category);
out.writeInt(docCountMap.get(category));
}
}
public void readFields(DataInput in) throws IOException {
this.name = in.readUTF();
docCountMap = new HashMap<>();
int size = in.readInt();
for (int i = 0; i < size; i++) {
String category = in.readUTF();
int docCount = in.readInt();
docCountMap.put(category, docCount);
}
}
public static Feature read(DataInput in) throws IOException {
Feature f = new Feature();
f.readFields(in);
return f;
}
}
| true
|
6cd76dab9c18d19134e6c7b118bf7501fb9b8be6
|
Java
|
lvelezsantos/Generacion-Numeros-Aleatorios
|
/src/simulaciones/Auto.java
|
UTF-8
| 525
| 2.46875
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Autores:
* Luis Alfonso Velez Santos
* Carlos Yesid Hernandez Herrera
* Jose Esteban Betin Diaz
*/
package simulaciones;
public class Auto {
int diasrenta;
public void setDiasrenta(int diasrenta) {
this.diasrenta = diasrenta;
}
public int getDiasrenta() {
return diasrenta;
}
public Auto(){
this.diasrenta= 0;
}
public Auto(int diasrenta){
this.diasrenta= diasrenta;
}
}
| true
|
112002d4e2428137bb0d3cd8459d6997220ec83b
|
Java
|
rajithaS/Wikia
|
/app/src/main/java/com/rajithas/apps/wikia/ui/WikiListAdapter.java
|
UTF-8
| 3,308
| 2.328125
| 2
|
[] |
no_license
|
package com.rajithas.apps.wikia.ui;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.rajithas.apps.wikia.R;
import com.rajithas.apps.wikia.model.WikiListItem;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by rajitha.siriwardena on 15-Feb-15.
*/
public class WikiListAdapter extends WikiaAdapter<WikiListItem> {
private final Context context;
private final List<WikiListItem> data;
private int totalServerDataCount = 0;
public WikiListAdapter(Context context, List<WikiListItem> data, int layoutResource) {
super(context, data, layoutResource);
this.context = context;
this.data = data;
}
public void appendItems(List<WikiListItem> data) {
this.data.addAll(data);
}
public void removeItems() {
data.clear();
}
public void setTotalServerDataCount(int totalServerDataCount) {
this.totalServerDataCount = totalServerDataCount;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (getItemViewType(position) == VIEW_TYPE_LOADING) {
return view;
}
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.imgThumbnail = (ImageView) view.findViewById(R.id.imgThumbnail);
holder.txtTitle = (TextView) view.findViewById(R.id.txtTitle);
holder.txtUrl = (TextView) view.findViewById(R.id.txtUrl);
view.setTag(holder);
}
WikiListItem item = getItem(position);
holder.txtTitle.setText(item.getTitle());
holder.txtUrl.setText(item.getUrl());
String thumbnailUrl = item.getThumbnailUrl();
if (!TextUtils.isEmpty(thumbnailUrl)) {
Picasso.with(context).load(thumbnailUrl)
.resize(48, 48)
.centerCrop().into(holder.imgThumbnail);
} else {
Picasso.with(context).load(R.drawable.no_image)
.resize(48, 48)
.centerCrop().into(holder.imgThumbnail);
}
return view;
}
@Override
public View getLoadingView(int position, View convertView, ViewGroup parent) {
if (position >= totalServerDataCount && totalServerDataCount > 0) {
TextView txtNoMoreData = new TextView(context);
txtNoMoreData.setTextColor(Color.BLACK);
txtNoMoreData.setText(context.getString(R.string.no_more_data));
txtNoMoreData.setGravity(Gravity.CENTER);
txtNoMoreData.setPadding(0, 10, 0, 10);
return txtNoMoreData;
}
View view = convertView;
if (view == null || position == 0) {
view = LayoutInflater.from(context).inflate(R.layout.item_list_loading, parent, false);
}
return view;
}
class ViewHolder {
ImageView imgThumbnail;
TextView txtTitle;
TextView txtUrl;
}
}
| true
|
afbed6e3beac7804df0eff423dc1e94b9b6518fc
|
Java
|
GabeOchieng/ggnn.tensorflow
|
/data/libgdx/Bresenham2_newObject.java
|
UTF-8
| 76
| 1.609375
| 2
|
[] |
no_license
|
@Override
protected GridPoint2 newObject() {
return new GridPoint2();
}
| true
|
07ba94bb596d759a74d99edf5e88db11f4f8dcb4
|
Java
|
SEO2317/StarbucksWeb
|
/src/feedback/controller/FeedbackUpdateAction.java
|
UTF-8
| 828
| 2.0625
| 2
|
[] |
no_license
|
package feedback.controller;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import common.controller.AbstractController;
import feedback.model.FeedbackDAO;
import feedback.model.InterFeedbackDAO;
public class FeedbackUpdateAction extends AbstractController {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
String feedback_board_seq = request.getParameter("feedback_board_seq");
InterFeedbackDAO dao = new FeedbackDAO();
HashMap<String, String> map = dao.updateOneFeedback(feedback_board_seq); // 한개만 불러오는 메소드 생성
request.setAttribute("map", map);
// super.setRedirect(false);
super.setViewPage("/WEB-INF/feedback/feedbackEdit.jsp");
}
}
| true
|
256841f91232fde4cb54e7f4e046566461b9ff57
|
Java
|
contactBoostTag/softwareengineer
|
/src/main/java/State_Pattern/TestClientState.java
|
UTF-8
| 547
| 2.46875
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package State_Pattern;
/**
*
* @author Romell
*/
public class TestClientState {
public static void main(String[] args) {
StateContext sc = new StateContext();
sc.writeName("Monday");
sc.writeName("Tuesday");
sc.writeName("Wednesday");
sc.writeName("Thursday");
sc.writeName("Saturday");
sc.writeName("Sunday");
}
}
| true
|
93cd7fd21453bcb3b3aa703cd818b99462a94934
|
Java
|
HansenBerlin/deztoint
|
/deztoint/src/DecimalToBinaryTool.java
|
UTF-8
| 10,486
| 3.546875
| 4
|
[] |
no_license
|
import javax.swing.*;
/**
* Author: Hannes
* Created: 04.11.2020
*
* CC BY
**/
public class DecimalToBinaryTool
{
// Deklarieren der Variable die ich später ausgeben möchte
private static String binaryValue = "";
public static void main(String[] args)
{
// Abfrage des Inputs und speichern in valueToCalculate.
// Der Input wird von der Methode "validateUserInput" geprüft (s.u.)
long valueToCalculate = validateUserInput();
// Hier wird die Methode aufgerufen, die den Wert von valueToCalculate umrechnet
calculateDecimalToBinary(valueToCalculate);
// Hier angekommen wurde durch die Methode calculateDecimalToBinary in der Variablen
// bitSequence das Ergebnis bereits gespeichert. Jetzt muss noch alles ausgegeben werden,
// konsequenterweise mittels einer GUI, da die Abfrage ja auch dadurch erfolgt ist.
// Die dritte Methode printBitCount wird direkt in der Ausgabe abgerufen und ihr Wert ausgegeben
JOptionPane.showMessageDialog(new JFrame(), valueToCalculate + " in Binärschreibweise: " + binaryValue + "\n" +
"Dieser Wert enthält " + printBitCount() + " zusammenhängende Bits.", "Decimal To Binary Tool", JOptionPane.PLAIN_MESSAGE);
}
static String calculateDecimalToBinary(long valueToConvert)
{
long decimalValue = 1;
// BEISPIEL // wir nehmen an der übergebene Wert valueToConvert war 12 (also binär 1100)
// Nur im einen Fall, dass der umzurechnende Wert 0 Beträgt soll auch das Ergebnis 0 sein
// und die Methode beendet werden. Denn 0 in Dezimalschreibweise ist auch 0 in Binärschreibweise
if(valueToConvert == 0)
{
binaryValue += "0";
return "";
}
// BEISPIEL // Überspringt diese Methode, weil 12 != 0 ist
// Solange decimalValue kleiner als valueToConvert ist wird durch die Linksverschiebung der Stelle
// im Binärsystem der Wert verdoppelt, bis decimalValue schließlich größer als valueToConvert ist.
while(decimalValue<valueToConvert)
{
decimalValue <<= 1;
}
// BEISPIEL //
// Schleifendurchlauf decimalValue der VOR Schleifendurchlauf geprüft wird decimalValue NACH Durchlauf enspricht Binärwert
// 1 1 2 10
// 2 2 4 100
// 3 4 8 1000
// 4 8 16 10000
// ABBBRUCH 16 - -
// Mit dieser Funktion soll nun aus dem ermittelten Decimal Value ein String in
// Form eines Binärwertes erzeugt werden. Zunächst wird geprüft, ob decimalValue
// gleich 0 ist, solange dies nicht der Fall ist, läft die Schleife.
// In der ersten Abfrage (valueToConvert & decimalValue) passiert folgendes:
// Der Binärwert beider Variablen wird verglichen. Dies passiert für jede einzelne
// Stelle. Nach der Logik des "AND" wird nur ein true (1) zurückgegeben wenn
// beide Werte auch true (1) sind. Wenn der ermittelte Binärwert nicht 0 ist, wird
// dem string binaryValue eine 1 hinzugefügt.
//
// BEISPIEL //
// valueToConvert an diesem Punkt: 12
// decimalValue an diesem Punkt: 16
// Umrechnung binär valueToConvert: 01100
// Umrechnung binär decimalValue: 10000
// Vergleich: 00000 --> Da es keinen Vergleich 1 & 1 = 1 gibt, ist der Wert 0
// Der Else Block wird ausgelöst und binaryValue ist nun 0
// Nun wird noch eine Stelle nach rechts verschoben, so dass decimalValue jetzt 8 ist
//
// zur Verdeutlichung noch der zweite Durchlauf (weil ja decimalValue nach wie vor NICHT 0 ist):
// valueToConvert an diesem Punkt: 12
// decimalValue an diesem Punkt: 8
// Umrechnung binär valueToConvert: 1100
// Umrechnung binär decimalValue: 1000
// Vergleich: 1000 --> 1 und 1 an der ersten Stelle ist 1, die Bedingung ist also erfüllt (!= 0)
// Der If Block wird ausgelöst und binaryValue ist nun 0 + die nun hinzugefügte 1, also 01
// Rechtsverschiebung, decimalValue ist jetzt 4
//
// USW., bis decimalValue 0 ist, die Schleife damit beendet wird und binary value mit dem
// Wert 01100 zurückgegeben und gleichzeitig in der ganz oben angelegten Variablen gespeichert wird
while(decimalValue != 0)
{
if((valueToConvert & decimalValue) != 0) binaryValue += "1";
else binaryValue += "0";
decimalValue >>= 1;
}
return binaryValue;
}
// Da die Originalfunktion ähnlich wie die obige funktioniert hat, hier eine andere und
// besser nachvollziehbare Herangehensweise. Die Methode nimmt keine Argumente an und
// gibt einen int zurück, der der Anzahl von zusammenhängenden Einsen im BinärString entspricht
static int printBitCount()
{
// Dekl der Variablen. Die Initialisierung muss man nicht machen, da aber hier später
// der Wert als Bedingung abgefragt wird und wir Fehler vermeiden wollen, wwerden sie auf 0 gesetzt
int maximumCount = 0;
int currentCount = 0;
// die Schleife durchläuft alle Elemente (also Zeichen/Chars) in einem Element,
// hier dem String mit den Binärwerten. Also bei unserem Beispiel 12 fünfmal, da
// in dem String der Wert 01100 gespeichert ist
// Die Funktionsweise ist einfach: Wenn du eine 1 findest, erhöhe currentCount um 1
// Prüfe dann ob currentCount höher ist als der bisherige Rekordwert maximumCount.
// Wenn ja, überschreibe maxCount mit currentCount
// Wenn du eine 0 findest prüfe genau das gleiche, setze aber anschließend
// currentCount auf 0 zurück. der Wert von maxCount kann also nie sinken
for (char singlBitInformation : binaryValue.toCharArray())
{
if(singlBitInformation == '1')
{
currentCount++;
if(currentCount > maximumCount) maximumCount = currentCount;
}
else
{
if(currentCount > maximumCount) maximumCount = currentCount;
currentCount = 0;
}
}
return maximumCount;
}
// Kleine Helfermethode zur Abfrage des Inputs. Die Schleife läuft einfach so lange
// und nervt mit der Abfrage bis eine gültige Zahlenfolge eingegeben wird ("\\d+")
// Sobald die Abfrage gültig ist endet die Schleife und der Wert wird zurückgegeben
static long validateUserInput()
{
String userInput = "";
while(!userInput.matches("\\d+"))
{
userInput = JOptionPane.showInputDialog("Bitte gültige Ganzzahl eingeben!");
}
// Kleine Spielerei, relevant für alles unter den beiden dicken grünen Strichen
if(userInput.matches("101010"))
{
startBinaryConverter();
System.exit(0);
}
return Long.parseLong(userInput);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Wie oben, nur dass jetzt ausschließlich 1 und 0 als gültige Eingaben akzeptiert werden
static long validateUserInputOnlyBinaryFormat()
{
String userInput = "";
while(!userInput.matches("[0-1]+"))
{
userInput = JOptionPane.showInputDialog("Bitte Binärzahl im Format 100100110 eingeben!");
}
return Long.parseLong(userInput);
}
// Umwandlung von Binär zu Dezimal mit anderem Ansatz als oben. Sieht erstmal schlimmer aus als es ist:
// Die Eingabe wird erstmal umgedreht (reverse), aus 1100 (also dezimal 12) wird dann zB 0011. Diese Folge
// wird dann als Array gespeichert (haben wir bald), kurz gesagt ist das eine Kette von Variablen die einen
// unterschiedlichen Wert haben können, aber den gleichen Datentyp haben müssen. Die Werte werden dann nacheinander
// an den Positionen im Array gespeichert, die Index heißen. Gezählt wird immer ab 0 aufsteigend. Wir haben also
// jetzt:
// Index Wert
// 0 0
// 1 0
// 2 1
// 3 1
//
// Im Loop, der solange läuft bis i so groß wie die Arraylänge ist wird nun einfach jedesmal wenn an der
// Indexposition die wir gerade untersuchen eine 1 gefunden wird 2 hoch der Indexnummer zu decimalReturnValue
// hinzugefügt. Anschließend wir der Wert zurückgegeben.
static long convertFromBinaryToDecimal(String binaryNumberInput)
{
long decimalReturnValue = 0;
String reverseInput = new StringBuilder(new String(binaryNumberInput)).reverse().toString();
char[] singleBits = reverseInput.toCharArray();
for(int i = 0; i < singleBits.length ; i++)
{
if(singleBits[i] == '1') decimalReturnValue += Math.pow(2, i);
}
return decimalReturnValue;
}
// Dies ist einfach nur die Methode um den Input und die Ausgabe aufzurufen, sobald jemand bei der Abfrage nach der Dezimalzahl 101010 eingibt
static void startBinaryConverter()
{
long binaryToCalculate = validateUserInputOnlyBinaryFormat();
JOptionPane.showMessageDialog(new JFrame(), binaryToCalculate + " als Ganzzahl: " + convertFromBinaryToDecimal(Long.toString(binaryToCalculate)), "Binary to Decimal Tool", JOptionPane.PLAIN_MESSAGE);
}
}
| true
|
7c443e5f2e072b178b8f86fe98ba79075e70179e
|
Java
|
somi92/eKlub
|
/src/main/java/rs/fon/eklub/json/mixins/AttendanceForMemberSerializationMixin.java
|
UTF-8
| 440
| 1.59375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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 rs.fon.eklub.json.mixins;
import com.fasterxml.jackson.annotation.JsonIgnore;
import rs.fon.eklub.core.entities.Member;
/**
*
* @author EC
*/
public interface AttendanceForMemberSerializationMixin {
@JsonIgnore Member getMember();
}
| true
|
63a36f9d97e463eadd2480500328db8afcdca1ee
|
Java
|
khetreJagdish/JAVA
|
/Collection/src/collection/QueueDemo.java
|
UTF-8
| 1,297
| 3.859375
| 4
|
[] |
no_license
|
package collection;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
//Queue<Integer> queue = new LinkedList<Integer>();
Queue<Integer> queue = new PriorityQueue<Integer>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(5);
queue.add(4);
queue.add(4);
//queue.add(null);// not allowed
System.out.println("Elements of Queue : " + queue);
int peek = queue.peek();
System.out.println(peek);
int poll = queue.poll();
System.out.println(poll);
int element = queue.element();
System.out.println(element);
int remove = queue.remove();
System.out.println(remove);
System.out.println("Elements of Queue : " + queue);
System.out.println("Conversion of ArrayList into PriorityQueue");
ArrayList arrayList = new ArrayList<>();
arrayList.add(10);
arrayList.add(20);
arrayList.add(30);
arrayList.add(40);
arrayList.add(50);
arrayList.add(50);
// arrayList.add("Hello"); // java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
PriorityQueue priorityQueue = new PriorityQueue<>(arrayList);
System.out.println("Priority Queue" + priorityQueue);
}
}
| true
|
25f9b208cc34248f834f1c0c76b94d5b3d6b6c80
|
Java
|
m-barnas/langusta3-web
|
/rest/src/main/java/cz/fi/muni/PB138/rest/controller/PatternController.java
|
UTF-8
| 1,732
| 2.203125
| 2
|
[] |
no_license
|
package cz.fi.muni.PB138.rest.controller;
import cz.fi.muni.PB138.dto.PatternBaseDTO;
import cz.fi.muni.PB138.dto.PatternDTO;
import cz.fi.muni.PB138.facade.PatternFacade;
import cz.fi.muni.PB138.rest.Uri;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import javax.xml.bind.JAXBException;
import javax.xml.xpath.XPathExpressionException;
import java.util.Collections;
import java.util.List;
/**
* Created by Erik Macej 433744 , on 1.6.17.
*
* @author Erik Macej 433744
*/
@RestController
@RequestMapping(path = Uri.ROOT_URI_PATTERN, produces = MediaType.APPLICATION_JSON_VALUE)
public class PatternController {
@Inject
private PatternFacade patternFacade;
@RequestMapping(path = "/pattern/{id}", method = RequestMethod.GET)
public PatternDTO findByName(@PathVariable("id") String name) throws JAXBException, XPathExpressionException {
return patternFacade.findByName(name);
}
@RequestMapping(path = "/findall", method = RequestMethod.GET)
public List<String> findAllPatterns() throws XPathExpressionException {
return Collections.unmodifiableList(patternFacade.findAllPatterns());
}
@RequestMapping(path = "/patternbase/{id}", method = RequestMethod.GET)
public PatternBaseDTO findByNameBase(@PathVariable("id") String name) throws JAXBException, XPathExpressionException {
return patternFacade.findByNameBase(name);
}
@RequestMapping(path = "/findallbases", method = RequestMethod.GET)
public List<PatternBaseDTO> findAllPatternsBases() throws XPathExpressionException, JAXBException {
return Collections.unmodifiableList(patternFacade.findAllPaternBases());
}
}
| true
|
23e7ba527325047423d4bfb2090bff76eb2c325d
|
Java
|
Carryours/algorithm004-03
|
/Week 01/id_628/LeetCode_141_628.java
|
GB18030
| 3,634
| 3.484375
| 3
|
[] |
no_license
|
import java.util.HashSet;
import java.util.Set;
import com.leetCode.exercise.struct.ListNode;
//һжǷл
//
// Ϊ˱ʾеĻʹ pos ʾβӵеλã 0 ʼ pos -1ڸûл
//
//
//
// ʾ 1
//
// 룺head = [3,2,0,-4], pos = 1
//true
//ͣһβӵڶڵ㡣
//
//
//
//
// ʾ 2
//
// 룺head = [1,2], pos = 0
//true
//ͣһβӵһڵ㡣
//
//
//
//
// ʾ 3
//
// 룺head = [1], pos = -1
//false
//ͣûл
//
//
//
//
//
//
// ף
//
// O(1)ڴ
// Related Topics ˫ָ
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class LeetCode_141_628 {
public boolean hasCycle(ListNode head) {
hasCycle1(head);
}
/**
* ˼·ָ롣
* ÿָָͬлԽ
*
* ʹÿָʶȻοָ㻷ڽڵ
* ָʱ
* ָ߹ p=a+x+n*(x+y)
* ָ߹2p=a+x+m*(x+y)
* ʽϲɵã
* a=(m-2n)(x+y)-x
* a=(m-2n-1)(x+y)+y
* x+yǻijȣΪֵ
* ҲָaĻ൱m-2n-1ȦԼyʱָ뽫صA
* ʶΪָߵIJa
* οָ-ָ룬ʹ㿪ʼָB㿪ʼͬʱÿһڵ㣬
* ָaA㣬ָaҲA
* ָ뽫ͬʱߵA㣬A,ʱָָڵ㼴Ϊڵ㡣
*
*
* ʱ临ӶȡO(n+k)
* ռ临ӶȡO(1)
* @param head ԭʼͷ
* @return <boolean> true-ڻ false-ڻ
*/
public static boolean hasCycle1(ListNode head) {
if (null == head || head.next == null)
return false;
ListNode fastNode = head.next.next;// ָ
ListNode slowNode = head.next;// ָ
while (fastNode != slowNode) {
if (fastNode == null || null == fastNode.next)
return false;
fastNode = fastNode.next.next;
slowNode = slowNode.next;
}
return true;
}
/**
* ˼·¼
* һÿ뻺setУжǷ˽ڵȷǷл
* ʱ临ӶȡO(n)
* ռ临ӶȡO(n)
* @param head ԭʼͷ
* @return <boolean> true-ڻ false-ڻ
*/
public static boolean hasCycle2(ListNode head) {
Set<ListNode> cacheSet = new HashSet<ListNode>();
while (!cacheSet.contains(head)) {
if (head == null)
return false;
cacheSet.add(head);
head = head.next;
}
return true;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| true
|
9a00bf081a73c1b098478ce14bb3eda769c137ec
|
Java
|
NarekDallakyan/AndroidNewsMVVM
|
/app/src/main/java/am/ith/myapplication/webservice/Service.java
|
UTF-8
| 236
| 1.835938
| 2
|
[] |
no_license
|
package am.ith.myapplication.webservice;
import am.ith.myapplication.model.AppResponse;
import retrofit2.Call;
import retrofit2.http.GET;
public interface Service {
@GET("/temp//json.php")
Call<AppResponse> getAllProduct();
}
| true
|
a034da6557ba445fe4f42b130a8d1225ea2b91d5
|
Java
|
xfhy/HelloSpringBoot
|
/src/main/java/com/xfhy/girl/repository/GirlRepository.java
|
UTF-8
| 438
| 2.015625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.xfhy.girl.repository;
import com.xfhy.girl.domain.Girl;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* author xfhy
* create at 2018/3/23 12:33
* description:
*/
//继承JpaRepository bean类名,id类型
public interface GirlRepository extends JpaRepository<Girl, Integer> {
List<Girl> findByAge(Integer age); //findBy 属性名 这里的名字不能随便写
}
| true
|