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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0b7266e5139ec056269a3c1411303fdc26139728
|
Java
|
Linyuzai/AndroidCommon
|
/easonicon/src/main/java/eason/linyuzai/easonicon/painter/basic/rect/RectPainter.java
|
UTF-8
| 3,579
| 2.5
| 2
|
[] |
no_license
|
package eason.linyuzai.easonicon.painter.basic.rect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import eason.linyuzai.easonicon.annotation.RoundRectField;
import eason.linyuzai.easonicon.open.support.RoundRectSupport;
import eason.linyuzai.easonicon.painter.basic.path.PathPainter;
@RoundRectField
public class RectPainter extends PathPainter implements RoundRectSupport {
private float[] radii = new float[8];
public RectPainter() {
}
public RectPainter(float leftTop, float leftBottom, float rightTop, float rightBottom) {
setLeftTop(leftTop);
setLeftBottom(leftBottom);
setRightTop(rightTop);
setRightBottom(rightBottom);
}
@Override
public void configurePath(Path path, RectF draw, RectF original, Paint paint) {
path.addRoundRect(getRectF(draw, paint), radii, Path.Direction.CW);
}
public void setRoundAll(float r) {
setRoundAll(r, r);
}
public void setRoundAll(float x, float y) {
setTop(x, y);
setBottom(x, y);
}
public void setTop(float r) {
setTop(r, r);
}
public void setTop(float x, float y) {
setLeftTop(x, y);
setRightTop(x, y);
}
public void setLeft(float r) {
setLeft(r, r);
}
public void setLeft(float x, float y) {
setLeftTop(x, y);
setLeftBottom(x, y);
}
public void setRight(float r) {
setRight(r, r);
}
public void setRight(float x, float y) {
setRightTop(x, y);
setRightBottom(x, y);
}
public void setBottom(float r) {
setBottom(r, r);
}
public void setBottom(float x, float y) {
setLeftBottom(x, y);
setRightBottom(x, y);
}
@Override
public void setLeftTop(float r) {
setLeftTop(r, r);
}
public void setLeftTop(float x, float y) {
radii[0] = x;
radii[1] = y;
}
@Override
public void setRightTop(float r) {
setRightTop(r, r);
}
public void setRightTop(float x, float y) {
radii[2] = x;
radii[3] = y;
}
@Override
public void setLeftBottom(float r) {
setLeftBottom(r, r);
}
public void setLeftBottom(float x, float y) {
radii[6] = x;
radii[7] = y;
}
@Override
public void setRightBottom(float r) {
setRightBottom(r, r);
}
public void setRightBottom(float x, float y) {
radii[4] = x;
radii[5] = y;
}
public void setLeftTopRightBottom(float r) {
setLeftTopRightBottom(r, r);
}
public void setLeftTopRightBottom(float x, float y) {
setLeftTop(x, y);
setRightBottom(x, y);
}
public void setRightTopLeftBottom(float r) {
setRightTopLeftBottom(r, r);
}
public void setRightTopLeftBottom(float x, float y) {
setRightTop(x, y);
setLeftBottom(x, y);
}
public float[] getRadii() {
return radii;
}
@Override
public float getLeftTop() {
if (radii[0] == radii[1])
return radii[0];
return -1;
}
@Override
public float getRightTop() {
if (radii[2] == radii[3])
return radii[2];
return -1;
}
@Override
public float getLeftBottom() {
if (radii[6] == radii[7])
return radii[6];
return -1;
}
@Override
public float getRightBottom() {
if (radii[4] == radii[5])
return radii[4];
return -1;
}
}
| true
|
95ec63e5f8c34335efb29c552dc91999c3c65fd0
|
Java
|
musthafapulikkal/HospitalManagement
|
/app/src/main/java/com/example/hospitalmanagement/Activity/Activity/HospitalSingleViewActivity.java
|
UTF-8
| 4,961
| 1.9375
| 2
|
[] |
no_license
|
package com.example.hospitalmanagement.Activity.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.hospitalmanagement.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class HospitalSingleViewActivity extends AppCompatActivity {
ImageView imageView;
TextView txt_name;
String lat;
String longt;
String place;
Button btn_doctor,btn_facility,btn_service,btn_location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_single_view);
imageView=(ImageView)findViewById(R.id.img_single_id);
txt_name=(TextView)findViewById(R.id.id_single_txt_name);
btn_doctor=(Button)findViewById(R.id.id_single_view_docttors);
btn_facility=(Button)findViewById(R.id.id_single_view_facility);
btn_service=(Button)findViewById(R.id.id_single_view_service);
btn_location=(Button)findViewById(R.id.id_single_view_location);
Intent intent=getIntent();
final String hosid=intent.getStringExtra("hosid");
RequestQueue requestQueue= Volley.newRequestQueue(HospitalSingleViewActivity.this);
String Url="http://hospitalmanagement.fabstudioz.com/viewsinglehospital.php";
StringRequest stringRequest=new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v("single response",response);
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<=jsonArray.length();i++)
{
JSONObject jsonObject=(JSONObject)jsonArray.get(i);
String hosname=jsonObject.optString("hos_name");
String image=jsonObject.optString("image");
lat=jsonObject.optString("latitude");
longt=jsonObject.optString("logtitude");
place=jsonObject.optString("hos_place");
txt_name.setText(hosname);
String Url="http://hospitalmanagement.fabstudioz.com/"+image;
Glide.with(getApplicationContext()).load(Url).into(imageView);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("hos_id",hosid);
return params;
}
};
requestQueue.add(stringRequest);
btn_doctor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),ViewDoctorsActivity.class);
i.putExtra("hosid",hosid);
startActivity(i);
}
});
btn_facility.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),ViewFacilitiesActivity.class);
i.putExtra("hosid",hosid);
startActivity(i);
}
});
btn_service.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),ViewServiceActivity.class);
i.putExtra("hosid",hosid);
startActivity(i);
}
});
btn_location.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v("abc",lat);
Intent i=new Intent(getApplicationContext(),ViewLocationActivity.class);
i.putExtra("lat",lat);
i.putExtra("longt",longt);
i.putExtra("place",place);
startActivity(i);
}
});
}
}
| true
|
dc3518be7dc9cf3a707ab099850d2c54faf7c990
|
Java
|
yangaphero/MyMvpDemo
|
/app/src/main/java/com/example/aphero/mymvpdemo/presenter/LoginPresenterImp.java
|
UTF-8
| 1,041
| 2.390625
| 2
|
[] |
no_license
|
package com.example.aphero.mymvpdemo.presenter;
import com.example.aphero.mymvpdemo.model.ILoginModel;
import com.example.aphero.mymvpdemo.model.LoginModelImp;
import com.example.aphero.mymvpdemo.view.ILogview;
/**
* Created by aphero on 17-5-24.
*/
public class LoginPresenterImp implements ILoginPresenter{
private ILogview mILoginview;
private ILoginModel mILoginmodel;
public LoginPresenterImp(ILogview mILoginview){
this.mILoginview=mILoginview;
this.mILoginmodel= new LoginModelImp(this);
}
public void startlogin(String username,String password){
mILoginmodel.login(username,password);
}
@Override
public void showprogress(boolean flag) {
mILoginview.loginprogress(flag);
}
@Override
public void handlerprogress(int count) {
mILoginview.handlerprogress(count);
}
@Override
public void loginsucess() {
mILoginview.loginsucess();
}
@Override
public void loginfail() {
mILoginview.loginfail();
}
}
| true
|
e8e6db5e0750c2ee78d4b8af17190d5296d9e1ad
|
Java
|
laidu/java-learn
|
/algorithm/src/main/java/org/laidu/learn/algorithm/leetcode/FirstMissingPositive.java
|
UTF-8
| 1,890
| 3.859375
| 4
|
[
"Apache-2.0"
] |
permissive
|
package org.laidu.learn.algorithm.leetcode;
/**
* 41. 缺失的第一个正数
* 给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数。
* <p>
* 示例 1:
* 输入: [1,2,0]
* 输出: 3
* <p>
* 示例 2:
* 输入: [3,4,-1,1]
* 输出: 2
* <p>
* 示例 3:
* 输入: [7,8,9,11,12]
* 输出: 1
*/
public class FirstMissingPositive {
/**
*
* @param nums
* @return
*/
public int firstMissingPositive(int[] nums) {
int n = nums.length;
if (n == 0) {
return 1;
}
if (n == 1) {
return nums[0] == 1 ? 2 : 1;
}
for (int i = 0; i < n; i++) {
while (nums[i] > 0 && nums[i] < n && nums[i] != nums[nums[i]]) {
swap(nums, i, nums[i]);
}
}
for (int i = 1; i < n; i++) {
if (nums[i] != i) {
return i;
}
}
return nums[0] == n ? n + 1 : n;
}
/**
* 查找不包含的最小整数
*
* @param nums
* @return
*/
public int firstMissingPositive2(int[] nums) {
if (nums.length == 0) {
return 1;
}
if (nums.length == 1) {
return nums[0] == 1 ? 2 : 1;
}
// 1、查找最小整数
int min = 1;
// 2、查找比第一个元素大,却不在当前数组中的元素
while (contain(nums, min) || min < 1) {
++min;
}
return min;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private boolean contain(int[] nums, int min) {
for (int i = 0; i < nums.length; i++) {
if (min == nums[i]) {
return true;
}
}
return false;
}
}
| true
|
fb99efc27407addb8007a8ffce6cad05e34f68ba
|
Java
|
yanbronshtein/CS316Repo
|
/TJNov27_2019/Simple2.java
|
UTF-8
| 237
| 2.796875
| 3
|
[] |
no_license
|
import java.util.Scanner;
class Simple2 {
static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
int x = input.nextInt();
x = x % 3;
System.out.println(x + 2);
}
}
| true
|
035942a8d97a0ab6792e3eab22e1509c05f91b7b
|
Java
|
aalhabib001/Ticket-Chai-Backend
|
/src/main/java/tech/ticketchai/TicketChaiBackend/jwt/model/UserModel.java
|
UTF-8
| 1,122
| 2.078125
| 2
|
[] |
no_license
|
package tech.ticketchai.TicketChaiBackend.jwt.model;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;
import tech.ticketchai.TicketChaiBackend.model.ProfileModel;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
@Data
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "users_model")
public class UserModel {
@Id
private String id;
boolean isVerified;
@Column(unique = true)
@NotBlank
@Size(min = 3, max = 100)
private String username;
private String email;
@NotBlank
@Size(min = 6, max = 100)
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
@OneToOne(fetch = FetchType.LAZY)
private ProfileModel profileModel;
@ColumnDefault("false")
private Boolean isDeleted;
}
| true
|
3cea1d752bd7367a9f9bdb7a59a4127050950ce7
|
Java
|
bao17634/SpringbootDemo_Example
|
/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/ElasticsearchAdvanceApplication.java
|
UTF-8
| 586
| 1.75
| 2
|
[] |
no_license
|
package com.dashuai.learnin.elasticsearchadvance;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Elasticsearch advance application
* <p/>
* Created in 2018.12.21
* <p/>
*
* @author Liaozihong
*/
@SpringBootApplication
public class ElasticsearchAdvanceApplication {
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
SpringApplication.run(ElasticsearchAdvanceApplication.class, args);
}
}
| true
|
13d1343e6c8ddd2382637e6711ec0469c51733a3
|
Java
|
Felipecan/Hyperledger-Fabric---Java-SDK
|
/src/main/java/api/conductor/com/converts/AccountConverts.java
|
UTF-8
| 722
| 2.40625
| 2
|
[] |
no_license
|
package api.conductor.com.converts;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import api.conductor.chaincodes.Account;
import api.conductor.com.dto.AccountDTO;
public class AccountConverts {
private static Logger LOGGER = LoggerFactory.getLogger(AccountConverts.class);
public static Account toEntity(AccountDTO accountModel) {
ModelMapper modelMapper = new ModelMapper();
LOGGER.info("Convert AccountModel to Account");
Account account = modelMapper.map(accountModel, Account.class);
account.setArgs(new String[] {account.getNumber(), account.getBalance(), account.getOwner()});
LOGGER.info("Return {}", account.toString());
return account;
}
}
| true
|
b1a35675aa1132e18f8fc9b9d54de096b2aaa35a
|
Java
|
jiji87432/coeus
|
/coeus-core/src/main/java/com/pay/coeus/core/dubbo/inner/NewOrLossCustomerFacadeImpl.java
|
UTF-8
| 1,522
| 2.1875
| 2
|
[] |
no_license
|
package com.pay.coeus.core.dubbo.inner;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pay.coeus.api.inner.dubbo.NewOrLossCustomerFacade;
import com.pay.coeus.core.service.NewCustomerActivateService;
import com.pay.coeus.core.service.OldCustomerLossService;
import com.pay.coeus.model.entity.NewCustomerActivate;
import com.pay.coeus.model.entity.OldCustomerLoss;
import com.pay.commons.utils.Page;
@Service("newOrLossCustomerFacade")
public class NewOrLossCustomerFacadeImpl implements NewOrLossCustomerFacade{
Logger logger = LoggerFactory.getLogger(NewOrLossCustomerFacadeImpl.class);
@Autowired
private NewCustomerActivateService newCustomerActivateService;
@Autowired
private OldCustomerLossService oldCustomerLossService;
@Override
public Page<List<NewCustomerActivate>> findAllNewCustomerList(Page<List<NewCustomerActivate>> page,
Map<String, String> param) {
logger.info("findAllNewCustomerList参数:{}",param.toString());
List<NewCustomerActivate> list = newCustomerActivateService.findAllList(page, param);
page.setObject(list);
return page;
}
@Override
public Page<List<OldCustomerLoss>> findAllOldCustomerList(Page<List<OldCustomerLoss>> page,
Map<String, String> param) {
List<OldCustomerLoss> list = oldCustomerLossService.findAllOldCustomer(page, param);
page.setObject(list);
return page;
}
}
| true
|
12b670bd79118d72f2f937f4b55a98d639bfe8cb
|
Java
|
gautamelectronicschaitanya/Finance-Management-System
|
/register/src/main/java/com/lti/repository/UserDetailsRepository.java
|
UTF-8
| 1,510
| 2.40625
| 2
|
[] |
no_license
|
package com.lti.repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
import com.lti.entity.BankDetails;
import com.lti.entity.Registeration;
@Repository
public class UserDetailsRepository { //dao class for interacting with database
@PersistenceContext
private EntityManager entityManager;
@Transactional
public Object insertUser(Object object){ //insert user data - mapping registeration class into the table
Object obj= entityManager.merge(object);
return obj;
}
@Transactional
public Object insertBankDetails(Object object){ //insert bank details of the user
Object obj= entityManager.merge(object);
return obj;
}
@Transactional
public Object fetchById(Class claz, int pkey){ // //fetch username and password
Object obj= entityManager.find(claz, pkey);
System.out.println("in dao");
return obj;
}
@Transactional
public boolean loginCheck(String username, String password){
String sql = "select count(c) from Registeration c where username = username and password= password";
Query q = (Query) entityManager.createQuery(sql);
Number i=(Number)q.getSingleResult();
if(i.intValue()>0)
{
return true;
}
else
{
return false;
}
}
}
| true
|
2722ba08f5d7dbe99dd2d94d3a7034a1da88511e
|
Java
|
Admin1024Admin/jrfp
|
/rzdj6/src/main/java/com/ky/ct/rzdj/service/QtgrjzfpdkDdpkhHistoryService.java
|
UTF-8
| 898
| 2
| 2
|
[] |
no_license
|
package com.ky.ct.rzdj.service;
import com.ky.ct.rzdj.dao.QtgrjzfpdkDdpkhHistoryDao;
import com.ky.ct.rzdj.model.BaseQtgrjzfpdkDdpkh;
import com.ky.ct.rzdj.model.BaseQtgrjzfpdkDdpkhHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class QtgrjzfpdkDdpkhHistoryService {
@Autowired
private QtgrjzfpdkDdpkhHistoryDao qtgrjzfpdkDdpkhHistoryDao;
/**
* 根据合同编号查询
*/
public List<BaseQtgrjzfpdkDdpkhHistory> findByAgreementNo(String agreementNo){
Map<String,Object> map = new HashMap<>();
map.put("agreementNo",agreementNo);
List<BaseQtgrjzfpdkDdpkhHistory> qtgrjzfpdkDdpkhHistories = qtgrjzfpdkDdpkhHistoryDao.findByCondition(map);
return qtgrjzfpdkDdpkhHistories;
}
}
| true
|
8954a9e2a81fff501cc22dd0ee8265ddef430563
|
Java
|
greatypine/GASM
|
/src/com/cnpc/pms/bizbase/rbac/funcpermision/manager/RoleAppFuncManager.java
|
UTF-8
| 814
| 1.867188
| 2
|
[] |
no_license
|
package com.cnpc.pms.bizbase.rbac.funcpermision.manager;
import com.cnpc.pms.base.exception.InvalidFilterException;
import com.cnpc.pms.base.manager.IManager;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* 角色功能接口 Copyright(c) 2014 Yadea Technology Group ,
* http://www.yadea.com.cn
*
* @author IBM
* @since 2011-4-25
*/
public interface RoleAppFuncManager extends IManager {
/**
* 为角色分配权限
*
* @param selectNodes
* @param unSelectNodes
* @throws IOException
* @throws InvalidFilterException
*/
public void deleteBeforeAdd(List<Map<String, Object>> selectNodes,
List<Map<String, Object>> unSelectNodes, String roleId)
throws IOException, InvalidFilterException;
}
| true
|
4fbd06431c8ba827438097a0bfec8011d8fd965d
|
Java
|
orangestar/libsys
|
/java_src/pro/libsys/test/HelloWorld.java
|
UTF-8
| 114
| 1.828125
| 2
|
[] |
no_license
|
package pro.libsys.test;
public class HelloWorld {
public String sayHello() {
return "Hello, world!";
}
}
| true
|
85a22c7ffb8f03ea51150f5209ca84203f1a8e95
|
Java
|
stevencomiskey/Java-Assignment
|
/Search Engine/src/com/test/searchengine/FileManager.java
|
UTF-8
| 1,294
| 3.359375
| 3
|
[] |
no_license
|
package com.test.searchengine;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileManager
{
static int count = 0;
public static String Search(String query) throws IOException
{
String s;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = query;
File f1 = new File("C:/TextFiles/NewTextDocument.txt");
String[] line=null;
FileReader file = new FileReader(f1);
BufferedReader f = new BufferedReader(file);
// While loop which will run for as long as BufferedReader object can find content
count =0;
while((s=f.readLine())!=null)
{
line=s.split(" "); //Split the word using space
for (String word : line)
{
if (word.equals(input)) //Search for the given word
{
count++; //If Present count is incremented
}
}
}
if(count!=0) //Check for count not equal to zero
{
String return1 = "The word "+input+" was found "+count+ " times";
file.close();
return return1;
}
else
{
String return1 = input + " was not found";
file.close();
return return1;
}
}
}
| true
|
48e9315d75d8b714f76fe6586dd0e2ac89cfc490
|
Java
|
DarkHorse-CN/DHNews
|
/app/src/main/java/com/example/darkhorse/dhnews/mvp/presenter/NewsPresenter.java
|
UTF-8
| 3,564
| 2.171875
| 2
|
[] |
no_license
|
package com.example.darkhorse.dhnews.mvp.presenter;
import android.content.Context;
import com.darkhorse.httpmanager.HttpManager;
import com.darkhorse.preferencesmanager.PreferencesUtils;
import com.example.darkhorse.dhnews.bean.NewsBean;
import com.example.darkhorse.dhnews.bean.NewsJson;
import com.example.darkhorse.dhnews.bean.NewsResult;
import com.example.darkhorse.dhnews.retrofit.NewsService;
import com.example.darkhorse.dhnews.mvp.model.NewsModel;
import com.example.darkhorse.dhnews.mvp.view.INewsView;
import com.example.darkhorse.dhnews.utils.DBManager;
import com.example.darkhorse.dhnews.utils.constant.API;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* Created by DarkHorse on 2017/11/16.
*/
public class NewsPresenter implements INewsPresenter {
private Context mContext;
private INewsView mView;
private NewsModel mNewsModel;
public NewsPresenter(Context context, INewsView view) {
mContext = context;
attachView(view);
mNewsModel = new NewsModel();
}
@Override
public void attachView(INewsView view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
@Override
public void update() {
NewsService newsService = HttpManager.getInstance().getService(NewsService.class);
Observable<NewsJson> observable = newsService.getNewsJson(mView.getType(), API.NEWS_APPKEY);
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<NewsJson>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(NewsJson value) {
NewsResult result = value.getResult();
if (result != null) {
List<NewsBean> newList = result.getData();
List<NewsBean> oldList;
if ("top".equals(mView.getType())) {
oldList = DBManager.getInstance(mContext).queryNewsListAll();
} else {
oldList = DBManager.getInstance(mContext).queryNewsListByType((String) PreferencesUtils.get(mContext, mView.getType(), ""));
oldList.addAll(DBManager.getInstance(mContext).queryNewsListByType((String) PreferencesUtils.get(mContext, "top", "")));
}
mNewsModel.update(mContext, newList, oldList);
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
refresh();
}
});
}
@Override
public void refresh() {
List<NewsBean> list = mNewsModel.refresh(mContext, (String) PreferencesUtils.get(mContext, mView.getType(), ""));
mView.refresh(list);
}
@Override
public void loadMore(int fromIndex) {
List<NewsBean> list = mNewsModel.loadMore(mContext, (String) PreferencesUtils.get(mContext, mView.getType(), ""), fromIndex);
mView.loadMore(list);
}
}
| true
|
0b14ba310cc1ad4a587376e3b6082bb61677ec72
|
Java
|
samlhalliburton/Design-Patterns--Farm-Simulator
|
/src/test/java/FarmerDecoratorTest.java
|
UTF-8
| 1,031
| 3.03125
| 3
|
[] |
no_license
|
package test.java;
import main.java.Decorator.Farmer;
import main.java.Decorator.FarmerGrowing;
import main.java.Decorator.FarmerImpl;
import main.java.Decorator.FarmerMoney;
import main.java.Decorator.FarmerRearing;
import org.junit.Assert;
import org.junit.Test;
public class FarmerDecoratorTest {
@Test
public void testDecoratorRearing() {
Farmer farmer = new FarmerRearing(new FarmerImpl());
Assert.assertEquals(farmer.decorate(),
"A farmer was created and has an affinity for rearing.");
}
@Test
public void testDecoratorGrowing() {
Farmer farmer = new FarmerGrowing(new FarmerImpl());
Assert.assertEquals(farmer.decorate(),
"A farmer was created and has an affinity for growing.");
}
@Test
public void testDecoratorMoneyMaking() {
Farmer farmer = new FarmerMoney(new FarmerImpl());
Assert.assertEquals(farmer.decorate(),
"A farmer was created and has an affinity for money-making.");
}
}
| true
|
f453adf6f19ebfc0b349fa161573228bec03fb22
|
Java
|
GrosSacASac/Java2014HTW_CL
|
/uebung12/StringQueue.java
|
UTF-8
| 1,985
| 3.78125
| 4
|
[] |
no_license
|
/**
* StringQueue
*
* @version 1
*/
public class StringQueue implements Queue {
private int size;
private String[] queue;//Internally we use array
private final static int QUEUE_DEFAULT_SIZE = 250;
private static final String ERROR_STRING_REQUIRED = "ERROR_STRING_REQUIRED";
/**
* Constructor
*
* @param int size
*/
public StringQueue(int size)
{
queue = new String[size];
size = 0;
}
/**
* Constructor 2
*/
public StringQueue()
{
this(QUEUE_DEFAULT_SIZE);
}
/**
* returns true if empty
*/
public boolean empty()
{
return (size == 0);
}
/**
* returns true if full
*/
public boolean full()
{
return (queue.length <= size);
}
/**
* gibt die Anzahl der Elemente in der Queue aus.
* @return size.
*/
public int size()
{
return size;
}
/**
* append object to the queue
*/
public void addLast(Object o) throws StringQueueException
{
check(!full(), ERROR_QUEUE_MAX_SIZE);
check(o instanceof String, ERROR_STRING_REQUIRED);
queue[size] = (String)o;
size ++;
}
/**
* pop first element
*/
@Override
public String removeFirst()throws StringQueueException
{
check(!empty(),ERROR_QUEUE_IS_EMPTY);
String string = queue[0];
Library.shiftLeftArray(queue, 0, size);
size--;
return string;
}
/**
*
*/
@Override
public String get(int index)
{
Library.check(index < size,ERROR_INDEX_TOO_HIGH);
return queue[index];
}
/**
* Ueberpruefung der Bedinggung, Ausloesung eine StringQueueException.
*/
public void check(boolean test, String msg)throws StringQueueException
{
if(!test)
{
throw new StringQueueException(msg);
}
}
}
| true
|
0d64b01c9aedfd9e7a4119bdc25a006bd21d8fe4
|
Java
|
bozonhiggsa/Practice_tasks
|
/src/main/java/ua/examples/practice/practice5/Spam.java
|
UTF-8
| 2,118
| 3.3125
| 3
|
[] |
no_license
|
package ua.examples.practice.practice5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Spam {
private String[] messages;
private int[] time;
private static Thread[] threads;
private static int numberThread;
public static void main(String[] args) throws InterruptedException {
Spam spam = new Spam(
new String[]{"@@@", "bbbbbbb"}, new int[]{333, 222}
);
numberThread = spam.messages.length;
threads = new Thread[numberThread];
for(int i = 0; i < numberThread; i++){
threads[i] = new Worker(spam.messages[i], spam.time[i]);
}
start(threads, numberThread);
Thread.sleep(2000);
String nextString = null;
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
while(!(nextString = reader.readLine()).equals("")){}
stop();
}
catch (IOException e){
e.printStackTrace();
}
}
public static void start(Thread[] threads, int numberThread){
for(int i = 0; i < numberThread; i++){
threads[i].start();
}
}
public static void stop(){
for(int i = 0; i < numberThread; i++){
threads[i].interrupt();
}
}
public Spam(String[] messages, int[] time) {
this.messages = messages;
this.time = time;
}
private static class Worker extends Thread {
private String message;
private int timeout;
public Worker(String message, int timeout) {
this.message = message;
this.timeout = timeout;
}
@Override
public void run() {
try{
while(true){
if(isInterrupted()){
return;
}
System.out.println(message);
Thread.sleep(timeout);
}
}
catch(InterruptedException e){
return;
}
}
}
}
| true
|
6bf89c5d12744c293a1de76346bd8e11d4e27ffb
|
Java
|
ted-hsieh/android_practice_YouTubeUI
|
/app/src/main/java/com/example/tedhsieh/praticeyoutube/Views/Fragment_FirstPage_SlidingTabs.java
|
UTF-8
| 18,188
| 2.078125
| 2
|
[] |
no_license
|
package com.example.tedhsieh.praticeyoutube.Views;
import com.example.tedhsieh.praticeyoutube.TabSlider.SlidingTabLayout;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.tedhsieh.praticeyoutube.R;
public class Fragment_FirstPage_SlidingTabs extends Fragment{
static final String Song_Message = "com.example.tedhsieh.praticeyoutube.Song_Message";
static final String LOG_TAG = "SlidingTabsFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
PlayVideoWithTitleListener PlayVideoWithTitleCallback;
// Container Activity must implement this interface
public interface PlayVideoWithTitleListener {
public void PlayVideoWithTitle(String Title);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.content_first_page, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
PlayVideoWithTitleCallback = (PlayVideoWithTitleListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mViewPager = (ViewPager) view.findViewById(R.id.pagecontent);
mViewPager.setAdapter(new SlidingTabsAdapter());
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.firstpage_slidingtab);
mSlidingTabLayout.setCustomTabView(R.layout.slidingtab_icon, 0);
mSlidingTabLayout.setDividerColors(new int[]{ContextCompat.getColor(getContext(), R.color.colorPrimary)});
mSlidingTabLayout.setSelectedIndicatorColors(new int[]{ContextCompat.getColor(getContext(), android.R.color.white)});
mSlidingTabLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
mSlidingTabLayout.setViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
String[] SlidingTabsTitle = getResources().getStringArray(R.array.slidingtab_title);
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
getActivity().setTitle(SlidingTabsTitle[position]);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
class SlidingTabsAdapter extends PagerAdapter {
private int[] imageResId = {
R.drawable.ic_tab_home,
R.drawable.ic_tab_hotvideo,
R.drawable.ic_tab_playlist,
R.drawable.ic_tab_account
};
@Override
public int getCount() {
return 4;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
@Override
public CharSequence getPageTitle(int position) {
Drawable image = ContextCompat.getDrawable(getContext(),imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view;
// Inflate a new layout from our resources
switch (position){
case 0:
view = initFragmentHomePage(container);
break;
case 1:
view = initFragmentHotVideo(container);
break;
case 2:
view = initFragmentSubscribedChannel(container);
break;
case 3:
view = initFragmentAccountPage(container);
break;
default:
view = initDebugPage(container, position);
break;
}
// Add the newly created View to the ViewPager
container.addView(view);
// Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");
// Return the View
return view;
}
private View initFragmentHomePage(ViewGroup container){
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_home_page,
container, false);
View floatingbutton = view.findViewById(R.id.homepage_floatingbutton);
floatingbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "Floating Button Clicked ", Toast.LENGTH_SHORT).show();
}
});
final ListView playlist = (ListView) view.findViewById(R.id.homepage_playlist);
final PlayList_Adapter playlist_adapter = new PlayList_Adapter(getContext());
setplaylisview(view, playlist, playlist_adapter);
return view;
}
private View initFragmentHotVideo(ViewGroup container){
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_hotvideo, container, false);
final ListView playlist = (ListView) view.findViewById(R.id.hotvideo_playlist);
final HotVideo_Adapter playlist_adapter = new HotVideo_Adapter(getContext());
sethotvideolistview(view, playlist, playlist_adapter);
return view;
}
private View initFragmentSubscribedChannel(ViewGroup container){
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_subcribedchannel, container, false);
final ListView chnanellist = (ListView) view.findViewById(R.id.subscibedchannel_channellist);
final SubscribedChannel_Adapter channellist_adapter = new SubscribedChannel_Adapter(getContext());
setsubcribedchannellistview(view, chnanellist, channellist_adapter);
return view;
}
private View initFragmentAccountPage(ViewGroup container){
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_accountpage, container, false);
final ListView informationlist = (ListView) view.findViewById(R.id.accountpage_information);
final AccountPage_Adapter informationlist_adapter = new AccountPage_Adapter(getContext());
setaccountpage(view, informationlist, informationlist_adapter);
return view;
}
private View initDebugPage(ViewGroup container, int position){
View view = getActivity().getLayoutInflater().inflate(R.layout.debug_settitle_page,
container, false);
TextView viewtext = (TextView) view.findViewById(R.id.item_title);
viewtext.setText("test" + position);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
// Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
}
public void setplaylisview(final View view, ListView playlist, final PlayList_Adapter playlist_adapter){
playlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PlayList_Item item = (PlayList_Item) playlist_adapter.getItem(position);
switch (item.getItemType()){
case PlayList_Item.ItemType_ListTitle:
// Show a toast if the user clicks on a list
Toast.makeText(getContext(), "List Clicked: " + item.getOwner(), Toast.LENGTH_SHORT).show();
break;
case PlayList_Item.ItemType_Song:
// Intent intent = new Intent(getActivity(), Activity_VideoView.class);
// intent.putExtra(Song_Message, item.getTitle());
// startActivity(intent);
PlayVideoWithTitleCallback.PlayVideoWithTitle(item.getTitle());
// Toast.makeText(getContext(), "Song Of " + item.getOwner() + " Clicked : " +item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case PlayList_Item.ItemType_MoreButton:
playlist_adapter.addSongItemAtIndex(position, "song_2", "Song_2", item.getOwner(), "Nice Song_2", "30:35");
playlist_adapter.addSongItemAtIndex(position, "song_1", "Song_1", item.getOwner(), "Nice Song_1", "12:35");
Toast.makeText(getContext(), "MoreButton Of " + item.getOwner() + "Clicked.", Toast.LENGTH_SHORT).show();
break;
}
}
});
playlist.setOnScrollListener(new AbsListView.OnScrollListener() {
int LastFirstVisibleItem = 0;
final View flaotingbutton = view.findViewById(R.id.homepage_floatingbutton);
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
LastFirstVisibleItem = view.getFirstVisiblePosition();
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean onTop = firstVisibleItem == 0 && view.getChildAt(0) != null && view.getChildAt(0).getTop() == 0;
if( (firstVisibleItem + 6 < LastFirstVisibleItem) || onTop ){
flaotingbutton.setVisibility(View.VISIBLE);
}
if (firstVisibleItem > LastFirstVisibleItem) {
flaotingbutton.setVisibility(View.INVISIBLE);
}
}
});
playlist.setDivider(null);
playlist_adapter.addListItem("Owner_1");
playlist_adapter.addSongItem("song_1", "Song_1", "Owner_1", "Nice Song_1", "5:02");
playlist_adapter.addSongItem("song_2", "Song_2", "Owner_1", "Nice Song_2", "10:31");
playlist_adapter.addSongItem("song_1", "Song_1", "Owner_1", "Nice Song_1", "30:35");
playlist_adapter.addMoreButtonItem("Owner_1");
playlist_adapter.addListItem("Owner_2");
playlist_adapter.addSongItem("song_2", "Song_2", "Owner_2", "Great Song_2", "5:02");
playlist_adapter.addSongItem("song_1", "Song_1", "Owner_2", "Great Song_1", "10:31");
playlist_adapter.addSongItem("song_2", "Song_2", "Owner_2", "Great Song_2", "30:35");
playlist_adapter.addMoreButtonItem("Owner_2");
playlist_adapter.addListItem("Owner_3");
playlist_adapter.addSongItem("song_2", "Song_2", "Owner_3", "Great Song_2", "5:02");
playlist_adapter.addSongItem("song_1", "Song_1", "Owner_3", "Great Song_1", "10:31");
playlist_adapter.addSongItem("song_2", "Song_2", "Owner_3", "Great Song_2", "30:35");
playlist_adapter.addSongItem("song_1", "Song_1", "Owner_3", "Great Song_1", "5:02");
playlist_adapter.addSongItem("song_2", "Song_2", "Owner_3", "Great Song_2", "10:31");
playlist_adapter.addSongItem("song_1", "Song_1", "Owner_3", "Great Song_1", "30:35");
playlist_adapter.addMoreButtonItem("Owner_3");
playlist.setAdapter(playlist_adapter);
}
public void sethotvideolistview(final View view, final ListView playlist, final HotVideo_Adapter playlist_adapter){
playlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HotVideo_Item item = (HotVideo_Item) playlist_adapter.getItem(position);
switch (item.getItemType()) {
case HotVideo_Item.ItemType_Channel:
break;
case HotVideo_Item.ItemType_Video:
// Show a toast if the user clicks on a list
PlayVideoWithTitleCallback.PlayVideoWithTitle(item.getTitle());
// Toast.makeText(getContext(), "Video Clicked: " + item.getTitle(), Toast.LENGTH_SHORT).show();
break;
}
}
});
playlist.setDivider(null);
playlist_adapter.addChannelView();
playlist_adapter.addVideoItemView("first song", "song_1", "12:43", "popsong 觀看次數: 66k");
playlist_adapter.addVideoItemView("this song again", "song_2", "32:13", "greatsong 觀看次數: 100k");
playlist_adapter.addVideoItemView("another song", "song_1", "59:59", "longvideo 觀看次數: 88k");
playlist.setAdapter(playlist_adapter);
}
public void setsubcribedchannellistview(final View view, final ListView channellist, final SubscribedChannel_Adapter channellist_adapter){
channellist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SubscribedChannel_Item item = (SubscribedChannel_Item) channellist_adapter.getItem(position);
switch (item.getItemType()) {
case SubscribedChannel_Item.ItemType_ChannelListItem:
// Show a toast if the user clicks on a list
Toast.makeText(getContext(), "Video Clicked: " + item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case SubscribedChannel_Item.ItemType_MoreButton:
channellist_adapter.addChannelItemAtIndex(position, "ic_action_search", "#Game", "訂閱人數: 1,092,984");
channellist_adapter.addChannelItemAtIndex(position, "ic_tab_account", "#Music", "訂閱人數: 9,091,156");
break;
}
}
});
channellist.setDivider(null);
channellist_adapter.addTopBlock();
channellist_adapter.addListTitleItem("YouTube 精選");
channellist_adapter.addChannelItem("ic_action_search", "#Game", "訂閱人數: 1,092,984");
channellist_adapter.addChannelItem("ic_tab_account", "#Music", "訂閱人數: 9,091,156");
channellist_adapter.addMoreButton();
channellist_adapter.addListTitleItem("Music");
channellist_adapter.addChannelItem("ic_tab_hotvideo", "#Sport", "訂閱人數: 1,092,984");
channellist_adapter.addChannelItem("ic_tab_playlist", "#News", "訂閱人數: 9,091,156");
channellist_adapter.addMoreButton();
channellist.setAdapter(channellist_adapter);
}
public void setaccountpage(final View view, final ListView informationllist, final AccountPage_Adapter informationllist_adapter){
view.findViewById(R.id.accountpage_rippleeffect).setClickable(true);
// view.setOnTouchListener(new View.OnTouchListener() {
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// v.findViewById(R.id.accountpage_accountitem).getBackground().setHotspot(event.getX(), event.getY());
// return false;
// }
// });
//TODO set account page
informationllist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AccountPage_InformationItem item = (AccountPage_InformationItem) informationllist_adapter.getItem(position);
Toast.makeText(getContext(), item.getTitle() + " Clicked.", Toast.LENGTH_SHORT).show();
}
});
informationllist.setDivider(null);
informationllist_adapter.addListItem("ic_tab_home", "觀看紀錄");
informationllist_adapter.addListItem("ic_tab_account", "我的影片");
informationllist_adapter.addListItem("ic_tab_hotvideo", "稍後觀看");
informationllist_adapter.addListItem("ic_tab_playlist", "YouTube Red");
informationllist.setAdapter(informationllist_adapter);
}
}
}
| true
|
83712c6c6733b9ce6bbe8cf6af440ac35d181be8
|
Java
|
ASO1501014/FamilyApps
|
/app/src/main/java/jp/ac/asojuku/st/familyapps/FamilyAdapter.java
|
UTF-8
| 1,651
| 2.1875
| 2
|
[] |
no_license
|
package jp.ac.asojuku.st.familyapps;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
import jp.ac.asojuku.st.familyapps.FamilyData;
import jp.ac.asojuku.st.familyapps.FamilyViewHolder;
public class FamilyAdapter extends RecyclerView.Adapter<FamilyViewHolder> {
private ArrayList<FamilyData> rouletteDataSet;
private Activity activity;
public FamilyAdapter(ArrayList<FamilyData> roulette, Activity activity) {
this.activity = activity;
this.rouletteDataSet = roulette;
}
public FamilyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
return new FamilyViewHolder(view);
}
public void onBindViewHolder(final FamilyViewHolder holder, final int listPosition) {
holder.base.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("mailto:");
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra(Intent.EXTRA_SUBJECT, "やること");
intent.putExtra(Intent.EXTRA_TEXT, rouletteDataSet.get(listPosition).getComment());
activity.startActivity(intent);
}
});
}
public int getItemCount() {
return rouletteDataSet.size();
}
}
| true
|
2c0675338d6a5fa61839ef3444032143b0cd1543
|
Java
|
Walnoot/RTSGame
|
/src/walnoot/rtsgame/map/entities/SnakeEntity.java
|
UTF-8
| 1,781
| 2.859375
| 3
|
[] |
no_license
|
package walnoot.rtsgame.map.entities;
import java.awt.Color;
import java.awt.Graphics;
import walnoot.rtsgame.InputHandler;
import walnoot.rtsgame.Util;
import walnoot.rtsgame.map.Map;
import walnoot.rtsgame.popups.Option;
import walnoot.rtsgame.popups.OptionsPopup;
import walnoot.rtsgame.screen.GameScreen;
import walnoot.rtsgame.screen.Screen;
public class SnakeEntity extends MovingEntity {
private boolean scared = false;
private int ticksScared = 11;
public static final int WALK_RANGE = 3, WALK_CHANGE_NORMAL = 3, MAX_TICKS_SCARED = 1000, WALK_CHANGE_SCARED = 20;
public SnakeEntity(Map map, int xPos, int yPos) {
super(map, xPos, yPos, null);
}
protected double getTravelTime() {
return 100;
}
public int getSelectedOption() {
return -1;
}
public void update(){
if(ticksScared >= MAX_TICKS_SCARED)scared = false;
if(scared) {
ticksScared++;
}
super.update();
if(scared)if(!isMoving() && Util.RANDOM.nextInt(1000) < WALK_CHANGE_SCARED) moveRandomLocation(WALK_RANGE);
else if(!isMoving() && Util.RANDOM.nextInt(1000) < WALK_CHANGE_NORMAL) moveRandomLocation(WALK_RANGE);
}
public void onRightClick(GameScreen screen, InputHandler input){
OptionsPopup popup = new OptionsPopup(input, this);
Option option1 = new Option("boe!"){
public void onClick() {
scare();
}
};
popup.addOption(option1);
screen.setPopup(popup);
}
public void scare(){
scared = true;
ticksScared = 0;
System.out.println("boe!!!");
}
public void setSelectedOption(int indexSelected) {}
public void render(Graphics g) {
g.setColor(Color.YELLOW);
Screen.font.drawLine(g, getName(), getScreenX(), getScreenY());
}
public int getMaxHealth() {
return 5;
}
public String getName() {
return "Snake";
}
}
| true
|
69b8acbff8549ca8d8a678a8b3a51f6ef2434abf
|
Java
|
luisfrsa/seven-money
|
/seven-money/src/main/java/com/luis/sevenmoney/service/UserService.java
|
UTF-8
| 850
| 2.078125
| 2
|
[] |
no_license
|
package com.luis.sevenmoney.service;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.luis.sevenmoney.domain.User;
import com.luis.sevenmoney.repository.child.UserRepository;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Service
public class UserService {
private static final String ENTITY_NAME = "user";
@Autowired
UserRepository userRepository;
public void setUsers(List<User> users) {
userRepository.set(users);
}
public List<User> getAll() {
return userRepository.getAll();
}
}
| true
|
a05ae572b562e0d738472c3115fdb798c17c828d
|
Java
|
tqmk127/HomeWork1
|
/LR1/src/first/Intro.java
|
UTF-8
| 763
| 3.421875
| 3
|
[] |
no_license
|
package first;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Intro
{
public static void main(String[] args) throws IOException {
System.out.println("Ласкаво просимо!");
System.out.println("Яке Ваше ім'я?");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String userName = input.readLine();
System.out.println("Приві,"+userName+"!");
int now = 2019;
System.out.println("Скільки Вам років?");
int age = Integer.parseInt(input.readLine());
System.out.println("Ви народилися в " + (now - age) + " році.");
}
}
| true
|
8d14c65def54b0d96659d9ebf0f655b4b9f4b471
|
Java
|
tweerlei/dbgrazer
|
/main/plugins/jdbc/src/main/java/de/tweerlei/dbgrazer/plugins/jdbc/support/LimitedResultSetExtractor.java
|
UTF-8
| 2,247
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018 tweerlei Wruck + Buchmeier GbR - http://www.tweerlei.de/
*
* 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 de.tweerlei.dbgrazer.plugins.jdbc.support;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
/**
* A ResultSetExtractor that employs a RowCallbackHandler for handling rows but limits the number of rows processed.
* This is necessary because some JDBC drivers don't honor Statement.setMaxRows().
*
* @author Robert Wruck
*/
public class LimitedResultSetExtractor implements ResultSetExtractor
{
private final RowCallbackHandler handler;
private final int limit;
private int rows;
private boolean moreAvailable;
/**
* Constructor
* @param handler RowCallbackHandler for processing single rows
* @param limit Max number of rows to process
*/
public LimitedResultSetExtractor(RowCallbackHandler handler, int limit)
{
this.handler = handler;
this.limit = limit;
this.rows = 0;
this.moreAvailable = false;
}
/**
* Get the number of processed rows (<= limit)
* @return number of processed rows
*/
public int getRowCount()
{
return (rows);
}
/**
* Get whether more than the actually extracted rows were available
* @return true if more available
*/
public boolean isMoreAvailable()
{
return (moreAvailable);
}
@Override
public Object extractData(ResultSet rs) throws SQLException, DataAccessException
{
while (rs.next())
{
if (rows >= limit)
break;
handler.processRow(rs);
rows++;
}
moreAvailable = (rows >= limit);
return (null);
}
}
| true
|
987456b61ed1c4c856dd1cb2e21a7f030e2597bf
|
Java
|
matamicen/EscuelaJavaAbstracta
|
/EmpleadoAbstracta/src/com/captton/programa/inicio.java
|
UTF-8
| 1,072
| 2.828125
| 3
|
[] |
no_license
|
package com.captton.programa;
import java.util.ArrayList;
import com.captton.empleado.Empleado;
import com.captton.empleado.Gerente;
import com.captton.empleado.Subordinado;
public class inicio {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gerente g1 = new Gerente("Jose",18888999);
System.out.println("Posicion Gerente" + " Nombre:" + g1.getNombre());
System.out.println(g1.Almorzar());
System.out.println(g1.Trabajar());
System.out.println(g1.TrabajarHorasExtras());
Subordinado s1 = new Subordinado("Pablo",24587416);
s1.AgregarServicio("Pago de Internet Home");
s1.AgregarServicio("Pago de Gimansio");
System.out.println("Posicion Subordinado" + " Nombre:" + s1.getNombre());
System.out.println(s1.Almorzar());
System.out.println(s1.Trabajar());
System.out.println(s1.TrabajarHorasExtras());
System.out.println("Los servicios pagos son:");
for(String ser: s1.getServiciosPagos())
{
System.out.println(ser + " ");
}
}
}
| true
|
fbc32a06f90d59f424f3866402abcc2d137350cd
|
Java
|
guoyufu-study/Hello-algs-Leetcode
|
/src/main/java/com/jasper/algs/leetcode/greedy/qu0392/solu2/Solution.java
|
UTF-8
| 976
| 3.46875
| 3
|
[] |
no_license
|
package com.jasper.algs.leetcode.greedy.qu0392.solu2;
/**
* 0392. 判断子序列
*
* <p>
* 二维辅助数组
*/
class Solution {
public boolean isSubsequence(String s, String t) {
// 预处理
t = " " + t; // 开头加一个空字符作为匹配入口
int n = t.length();
// 记录每个位置的下一个ch的位置
int[][] dp = new int[n][26];
for (char ch = 0; ch < 26; ch++) {
int p = -1;
for (int i = n - 1; i >= 0; i--) { // 从后往前记录dp
dp[i][ch] = p;
if (t.charAt(i) == ch + 'a')
p = i;
}
}
// 匹配
int i=0;
for (char c : s.toCharArray()) {// 跳跃遍历
if((i = dp[i][c-'a'])==-1)
return false;
}
return true;
}
public static void main(String[] args) {
// false
// String s = "aaaaaa";
// String t = "bbaaaa";
// true
// String s = "abc";
// String t = "ahbgdc";
// true
String s = "abcd";
String t = "abcd";
System.out.println(new Solution().isSubsequence(s, t));
}
}
| true
|
50fde70b177ddf5866a98b70fe9739ab9aa9cbaa
|
Java
|
lazyguy21/zookeeperDemo
|
/src/main/java/org/yyf/zookeeperDemo/baseAPITest/query/ExistTest.java
|
UTF-8
| 2,602
| 2.75
| 3
|
[] |
no_license
|
//package org.yyf.zookeeperDemo.baseAPITest.query;
//
//import org.apache.zookeeper.CreateMode;
//import org.apache.zookeeper.KeeperException;
//import org.apache.zookeeper.WatchedEvent;
//import org.apache.zookeeper.Watcher;
//import org.apache.zookeeper.ZooDefs;
//import org.apache.zookeeper.ZooKeeper;
//import org.apache.zookeeper.data.Stat;
//import org.yyf.zookeeperDemo.baseAPITest.common.CommonZKWatcher;
//
//import java.io.IOException;
//import java.util.List;
//import java.util.concurrent.CountDownLatch;
//
///**
// * Created by tobi on 16-8-19.
// *比较违反直觉的是exist这个api会监听createNode,deleteNode,而且还有NodeDataChanged
// */
//public class ExistTest implements Watcher {
// private static CountDownLatch countDownLatch = new CountDownLatch(1);
// private static Stat stat=new Stat();
// private static ZooKeeper zooKeeper;
// private static String path="/existNode";;
// public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
// zooKeeper = new ZooKeeper("localhost:2181", 6000, new CommonZKWatcher(countDownLatch));
// countDownLatch.await();
//
//
// zooKeeper.create(path, "whatever".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,stat);
// System.out.println("after create zk ,stat : "+stat);
//
// zooKeeper.exists(path, new ExistTest());
//
// Thread.sleep(1000*1000);
////
// }
//
//
//
// @Override
// public void process(WatchedEvent event) {
// Event.EventType type = event.getType();
// System.out.println(event);
// switch (type) {
// case None:
// break;
// case NodeCreated:
// keepExistWatch();
// break;
// case NodeDeleted:
// keepExistWatch();
// break;
// case NodeDataChanged:
// keepExistWatch();
// break;
// case NodeChildrenChanged:
//
// break;
// case DataWatchRemoved:
// break;
// case ChildWatchRemoved:
// break;
// }
// }
//
// private void keepExistWatch() {
// try {
// Stat stat = zooKeeper.exists(path, new ExistTest());
// System.out.println(ExistTest.stat);
// System.out.println("the watching stat "+stat);
// } catch (KeeperException e) {
// e.printStackTrace();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
//
//}
| true
|
62932ba009c07af2695e59672d6d39c4869cc805
|
Java
|
yangjian1225/HotMap
|
/mainmodule/src/main/java/com/example/mainmodule/mvp/view/activity/MapActivity.java
|
UTF-8
| 2,021
| 1.890625
| 2
|
[] |
no_license
|
package com.example.mainmodule.mvp.view.activity;
import android.animation.ValueAnimator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.RelativeLayout;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.MapView;
import com.example.basemodel.domain.BaseCode;
import com.example.basemodel.mvp.view.BaseActivity;
import com.example.mainmodule.R;
@Route(path = BaseCode.AROUTER_MAIN_MODULE_MAPACTIVITY)
public class MapActivity extends BaseActivity {
MapView mMapView;
AMap aMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mMapView = findViewById(R.id.map_mapview);
mMapView.onCreate(savedInstanceState);
if (aMap == null) {
aMap = mMapView.getMap();
}
//去掉地图右下角缩放按钮
aMap.getUiSettings().setZoomControlsEnabled(false);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),销毁地图
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView.onResume (),重新绘制加载地图
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView.onPause (),暂停地图的绘制
mMapView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态
mMapView.onSaveInstanceState(outState);
}
}
| true
|
b1018603b00aae2b8cda81f828a2ad6a838195cf
|
Java
|
tratanhieu/spr_db
|
/src/main/java/dashboard/controllers/post/PostController.java
|
UTF-8
| 3,018
| 2.171875
| 2
|
[] |
no_license
|
package dashboard.controllers.post;
import dashboard.commons.ValidationUtils;
import dashboard.dto.post.PostForm;
import dashboard.entities.post.Post;
import dashboard.enums.EntityStatus;
import dashboard.exceptions.customs.ResourceNotFoundException;
import dashboard.generics.MultipleExecute;
import dashboard.services.PostService;
import dashboard.services.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("post")
public class PostController {
@Autowired
PostService postService;
@Autowired
TagService tagService;
@GetMapping
public ResponseEntity index() {
return ResponseEntity.ok(postService.getAll());
}
@GetMapping("{postId}")
public ResponseEntity<Post> getOne(
@PathVariable(name = "postId") Long postId
) throws ResourceNotFoundException {
return ResponseEntity.ok(postService.getOne(postId));
}
@GetMapping("create")
public ResponseEntity getCreate() {
return ResponseEntity.ok(postService.getCreate());
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity create(
@RequestBody PostForm postForm
) {
ValidationUtils.validate(postForm);
List response = postService.create(postForm);
return ResponseEntity.ok(response);
}
@PostMapping(value = "{postId}/update", consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpStatus update(
@PathVariable(name = "postId") Long postId,
@RequestBody Post postParams
) throws ResourceNotFoundException {
Post post = postService.getOne(postId);
if (post.equals(postParams)) {
return HttpStatus.NOT_MODIFIED;
}
post.setName(postParams.getName());
post.setSlugName(postParams.getSlugName());
post.setImage(postParams.getImage());
post.setContent(postParams.getContent());
post.setStatus(postParams.getStatus());
post.setUpdateDate(new Date());
// post.setTags(postParams.getTags());
// postService.update(post);
return HttpStatus.OK;
}
@GetMapping("{postId}/delete")
public HttpStatus delete(
@PathVariable(name = "postId") Long postId
) throws ResourceNotFoundException {
tagService.deletePostTag(postId);
postService.delete(postId);
return HttpStatus.OK;
}
@PostMapping(value = "execute", consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpStatus execute(@RequestBody MultipleExecute<Long, EntityStatus> multipleExecute) throws ResourceNotFoundException {
postService.updateStatusWithMultipleId(multipleExecute.getListId(), multipleExecute.getStatus());
return HttpStatus.OK;
}
}
| true
|
7e1dbb02c6da240ec8a3b8ef075af87e809c90ff
|
Java
|
GeneralAngels/Shleam
|
/src/main/java/com/ga2230/shleam/base/communication/Client.java
|
UTF-8
| 4,764
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) 2020 Nadav Tasher of General Angels
* https://github.com/GeneralAngels/Shleam
*/
package com.ga2230.shleam.base.communication;
import com.ga2230.shleam.base.structure.Module;
import com.ga2230.shleam.base.structure.Result;
import com.ga2230.shleam.base.utils.Logger;
import java.io.*;
import java.net.Socket;
import java.util.Base64;
/**
* This is used to handle incoming clients and serve them content.
*/
class Client {
// Log tag
private static final String TAG = "Client";
// Client constants
private static final String ARGUMENT_SEPARATOR = " ";
private static final String OUTPUT_SEPARATOR = ":";
private static final String BASE64_SEPARATOR = "base64:";
// Alive state
private boolean listening = true;
// Socket I/O
private BufferedReader reader;
private BufferedWriter writer;
/**
* Default constructor.
* @param socket Network socket
* @param parent Module
*/
public Client(Socket socket, Module parent) {
// Setup I/O
try {
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
this.reader = null;
this.writer = null;
} finally {
// Make sure we are connected to a good client
if (this.reader != null && this.writer != null) {
// Start a new thread
new Thread(() -> {
try {
// Begin listening for function calls
while (this.listening) {
// Make sure the reader is ready
if (this.reader.ready()) {
// Read the received line
String received = this.reader.readLine();
// Parse the information
String parsed = received;
// Check if the information is base64 encoded or not and decode it accordingly
boolean isBase64 = received.startsWith(BASE64_SEPARATOR);
// Decode base64
if (isBase64) {
parsed = new String(Base64.getDecoder().decode(received.substring(BASE64_SEPARATOR.length())));
}
Result result = null;
// Try parsing even further
try {
// Call parsing
String[] moduleID = parsed.split(ARGUMENT_SEPARATOR, 2);
String[] functionCall = moduleID[1].split(ARGUMENT_SEPARATOR, 2);
// Module lookup
Module module = parent.descendant(moduleID[0]);
// Make sure the module exists
if (module != null) {
// Execute the call
result = module.execute(functionCall[0], functionCall.length > 1 ? functionCall[1] : null);
} else {
result = Result.notFinished("Module not found");
}
} catch (Exception thrownException) {
// Create a failure result
result = Result.notFinished(thrownException.toString());
}
if (result != null) {
writer.write(String.valueOf(result.isFinished()));
writer.write(OUTPUT_SEPARATOR);
writer.write(isBase64 ? new String(Base64.getEncoder().encode(result.getResult().getBytes())) : result.getResult());
}
writer.newLine();
writer.flush();
}
Thread.sleep(10);
}
} catch (Exception e) {
Logger.log(TAG, e.toString());
}
try {
socket.close();
} catch (Exception e) {
Logger.log(TAG, e.toString());
}
}).start();
}
}
}
}
| true
|
88037e76de67714df402f36e9b37670e03b65e32
|
Java
|
vkrishnaraj/x43ntpersistencemodel
|
/nt-persistence-model/src/main/java/aero/nettracer/persistence/util/TemplateType.java
|
UTF-8
| 1,688
| 2.8125
| 3
|
[] |
no_license
|
package aero.nettracer.persistence.util;
import java.util.ArrayList;
import java.util.List;
public enum TemplateType {
INCIDENT("Incident", "Incidents"),
CLAIM("Claim", "Claims"),
FOUND_ITEM("FoundItem", "Found Items"),
STATIC("Static", "All"),
INVALID("Invalid", "None"),
CLAIM_SETTLEMENT("Expense", "Claim Settlements"),
ISSUANCE_ITEM("IssuanceItem", "IssuanceItems");
private String defaultName;
private String displayName;
private TemplateType(String defaultName, String displayName) {
this.defaultName = defaultName;
this.displayName = displayName;
}
public String getDefaultName() {
return this.defaultName;
}
public String getDisplayName() {
return this.displayName;
}
public int getOrdinal() {
return this.ordinal();
}
public static TemplateType fromOrdinal(int ordinal) {
for (TemplateType type: TemplateType.values()) {
if (type.ordinal() == ordinal) {
return type;
}
}
return INVALID;
}
/**
* Returns an array of TemplateTypes that can be dependencies of variables
* defined in Template data.
* @return an array of dependency TemplateTypes
*/
public static List<TemplateType> getDependencyTemplateTypes() {
ArrayList<TemplateType> types = new ArrayList<TemplateType>();
types.add(INCIDENT);
types.add(CLAIM);
types.add(FOUND_ITEM);
types.add(CLAIM_SETTLEMENT);
types.add(ISSUANCE_ITEM);
return types;
}
public static Integer[] getOrdinals(List<TemplateType> types) {
if (types == null || types.isEmpty()) return null;
Integer[] ordinals = new Integer[types.size()];
for (int i = 0; i < ordinals.length; ++i) {
ordinals[i] = types.get(i).ordinal();
}
return ordinals;
}
}
| true
|
c96be1a0677d7c4d85e7cded1e5d446db33776be
|
Java
|
Adil1999/BistroChat
|
/app/src/main/java/com/adil/i170127/MessageAdpater.java
|
UTF-8
| 3,220
| 2.140625
| 2
|
[] |
no_license
|
package com.adil.i170127;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.squareup.picasso.Picasso;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageAdpater extends RecyclerView.Adapter<MessageAdpater.MyViewHolder> {
public static final int msg_left = 0;
public static final int msg_right = 1;
Context context;
List<Chat> chats;
String imageUrl;
FirebaseUser fuser;
public MessageAdpater(Context c, List<Chat> chats, String imgUrl){
super();
this.context = c;
this.chats = chats;
this.imageUrl = imgUrl;
}
@NonNull
@Override
public MessageAdpater.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == msg_right){
View itemView = LayoutInflater.from(context).inflate(R.layout.chat_item_right, parent, false);
return new MessageAdpater.MyViewHolder(itemView);
} else {
View itemView = LayoutInflater.from(context).inflate(R.layout.chat_item_left, parent, false);
return new MessageAdpater.MyViewHolder(itemView);
}
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
final Chat chat = chats.get(position);
if(chat.isImg() == true){
//holder.show_message.setVisibility(View.GONE);
holder.iv.setVisibility(View.VISIBLE);
Uri myUri = Uri.parse(chat.getMessage());
Log.d("IMage URi: ", chat.getMessage());
Log.d("IMage URi: ", chat.getMessage());
holder.iv.setImageURI(myUri);
Picasso.get().load(chat.getMessage()).into(holder.iv);
} else {
holder.show_message.setVisibility(View.VISIBLE);
//holder.iv.setVisibility(View.GONE);
holder.show_message.setText(chat.getMessage());
}
Picasso.get().load(imageUrl).into(holder.profile_pic);
}
@Override
public int getItemCount() {
return chats.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView show_message;
public CircleImageView profile_pic;
public ImageView iv;
public MyViewHolder(View itemView){
super(itemView);
show_message = itemView.findViewById(R.id.show_message);
profile_pic = itemView.findViewById(R.id.profile_image);
iv = itemView.findViewById(R.id.img_msg);
}
}
@Override
public int getItemViewType(int position) {
fuser = FirebaseAuth.getInstance().getCurrentUser();
if(chats.get(position).getSender().equals(fuser.getUid())){
return msg_right;
} else {
return msg_left;
}
}
}
| true
|
278a48b7f1ab65f15138f67b9e9fd4687f2a63f9
|
Java
|
smitkumarpatel4/CS2013_JAVA_PROGRAMMING_WITH_DATASTRUCTURE
|
/CS_2013_JAVA_PROGRAMMING_WITH_DATASTRUCTURE/src/CHAPTER_18_RECURSION/Reverse_String.java
|
UTF-8
| 507
| 3.53125
| 4
|
[] |
no_license
|
package CHAPTER_18_RECURSION;
import java.util.Scanner;
public class Reverse_String {
public static void main(String[] args) {
System.out.print("Enter String: ");
String s = new Scanner(System.in).nextLine();
reverseDisplay(s);
}
public static void reverseDisplay(String s) {
if (s.length() == 0)
return;
else
System.out.print(s.charAt(s.length()-1));
reverseDisplay(s.substring(0, s.length()-1));
}
}
| true
|
7badb1953d4d4e8d12f3d0120863a3a19d7f5233
|
Java
|
sathish1983400/RestfulExample
|
/src/main/java/com/mkyong/rest/JSONService.java
|
UTF-8
| 4,527
| 2.421875
| 2
|
[] |
no_license
|
package com.mkyong.rest;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.mkyong.Track;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
@Path("/json/metallica")
public class JSONService {
private static final String AAPI_105 = "AAPI_105";
private static final String AAPI_104 = "AAPI_104";
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public List getTrackInJSON() throws UnknownHostException {
List<Track> trackList = new ArrayList();
MongoDBUtility mongoDBUtility = new MongoDBUtility();
DBCollection collection = mongoDBUtility.findCollection();
DBCursor cursorDoc = collection.find();
Track track =null ;
// iterate list from db to show in the screen
while (cursorDoc.hasNext()) {
track = new Track();
DBObject dbObject = cursorDoc.next();
List list = new ArrayList(((LinkedHashMap<String, Object>) dbObject).values());
track.setTitle((String) list.get(1));
track.setSinger((String) list.get(2));
trackList.add(track);
}
return trackList;
}
@GET
@Path("/{title}")
@Produces(MediaType.APPLICATION_JSON)
public List getTrackDetailInJSON(@PathParam("title") String id) throws UnknownHostException {
List<Track> trackList = new ArrayList();
MongoDBUtility mongoDBUtility = new MongoDBUtility();
DBCollection collection = mongoDBUtility.findCollection();
DBCursor cursorDoc = collection.find();
Track track =null ;
while (cursorDoc.hasNext()) {
track = new Track();
DBObject dbObject = cursorDoc.next();
List list = new ArrayList(((LinkedHashMap<String, Object>) dbObject).values());
// iterate list from db , match the title to show corresponding details in the screen
// iterate list from db to show in the screen
track = new Track();
if(list.get(1).toString().equalsIgnoreCase(id)) {
track.setTitle((String) list.get(1));
track.setSinger((String) list.get(2));
trackList.add(track);
}
}
return trackList;
}
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) throws UnknownHostException, CustomReasonPhraseException {
String result = "Track saved : " + track;
MongoDBUtility mongoDBUtility = new MongoDBUtility();
DBCollection collection = mongoDBUtility.findCollection();
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
DBObject dbObject = cursorDoc.next();
List list = new ArrayList(((LinkedHashMap<String, Object>) dbObject).values());
//same combination existing check
if (list!= null && list.get(1).toString().equalsIgnoreCase(track.getTitle()) && (list.get(2).toString().equalsIgnoreCase(track.getSinger()))) {
throw new CustomReasonPhraseException(AAPI_105, "This data already exists");
}
// Only one entry allowed per title
if (list!= null && list.get(1).toString().equalsIgnoreCase(track.getTitle())) {
//return Response.status(428).entity(result).build();
throw new CustomReasonPhraseException(AAPI_104, "Data exists already for the chosen option");
}
}
mongoDBUtility.insertRow(track);
return Response.status(201).entity(result).build();
}
@PUT
@Path("/{singer}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Track updateTrackInJSON(@PathParam("singer") String id, Track track) throws UnknownHostException {
MongoDBUtility mongoDBUtility = new MongoDBUtility();
mongoDBUtility.updateRow(id, track);
return track;
}
@DELETE
@Path("/{singer}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void deleteTrackInJSON(@PathParam("singer") String id) throws UnknownHostException {
MongoDBUtility mongoDBUtility = new MongoDBUtility();
mongoDBUtility.deleteRow(id);
}
}
| true
|
c240bd5c6e9d1c3bd069dee410ed1c4598348f2f
|
Java
|
bellmit/marketing-cloud
|
/marketing-tool-vo/src/main/java/cn/rongcapital/mkt/vo/out/YestodayOut.java
|
UTF-8
| 779
| 1.820313
| 2
|
[] |
no_license
|
package cn.rongcapital.mkt.vo.out;
import org.codehaus.jackson.annotate.JsonProperty;
/**
* Created by byf on 10/28/16.
*/
public class YestodayOut {
private String starDate;
private String Yestoday;
private String EndDate;
@JsonProperty("StarDate")
public String getStarDate() {
return starDate;
}
public void setStarDate(String starDate) {
this.starDate = starDate;
}
@JsonProperty("Yestoday")
public String getYestoday() {
return Yestoday;
}
public void setYestoday(String yestoday) {
Yestoday = yestoday;
}
@JsonProperty("EndDate")
public String getEndDate() {
return EndDate;
}
public void setEndDate(String endDate) {
EndDate = endDate;
}
}
| true
|
213a0a94dccdd0df51c5b79842bb5d1a87db9037
|
Java
|
luwanding/Common
|
/sso/systemMemcache/src/java/com/platform/cache/memcache/common/CacheXMLParser.java
|
UTF-8
| 4,511
| 2.40625
| 2
|
[] |
no_license
|
package com.platform.cache.memcache.common;
import java.io.File;
import java.util.List;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
/**
* <pre>
* MEMCACHE的解析类
* </pre>
*
* @author pengchenq
* @version $ MemcacheUtil.java, v 0.1 2011-8-24 下午02:58:10 pengchenq Exp $
* @since JDK1.6
*/
public class CacheXMLParser {
private final static Logger logger = Logger.getLogger(CacheXMLParser.class);
private SocketPoolBean commonSocketPoolBean = null;
public CacheXMLParser(String fileName) {
readXML(fileName);
}
/**
* 解析配置文件
*
* @param fileName
*/
private void readXML(String fileName) {
SAXReader saxReader = new SAXReader();
Document document = null;
File file = new File(fileName);
try {
document = saxReader.read(file);
commonSocketPoolBean = readCommonSocketPool(document);// 解析commonsocketpool标签
} catch (Exception e) {
logger.error("file can not find", e);
}
}
/**
* 解析commonsocketpool标签
*
* @param document
*/
@SuppressWarnings("unchecked")
private SocketPoolBean readCommonSocketPool(Document document) {
List<Element> socketpools = document
.selectNodes("/cache/commonsocketpool");
return readSocketPool(socketpools);
}
private SocketPoolBean readSocketPool(List<Element> socketpools) {
if (socketpools == null || socketpools.size() == 0) {
logger.warn("Configuration file is not valid!");
return null;
}
for (Element element : socketpools) {
SocketPoolBean socketPoolBean = new SocketPoolBean();
socketPoolBean.setName(element.attributeValue("name").trim());
socketPoolBean.setFailover(Boolean.parseBoolean(element
.attributeValue("failover").trim()));
socketPoolBean.setInitConn(Integer.parseInt(element.attributeValue(
"initConn").trim()));
socketPoolBean.setMinConn(Integer.parseInt(element.attributeValue(
"minConn").trim()));
socketPoolBean.setMaxConn(Integer.parseInt(element.attributeValue(
"maxConn").trim()));
socketPoolBean.setMaintSleep(Integer.parseInt(element
.attributeValue("maintSleep").trim()));
socketPoolBean.setNagle(Boolean.parseBoolean(element
.attributeValue("nagle").trim()));
socketPoolBean.setSocketTo(Integer.parseInt(element.attributeValue(
"socketTo").trim()));
socketPoolBean.setAliveCheck(Boolean.parseBoolean(element
.attributeValue("aliveCheck").trim()));
List<Element> servers = element.selectNodes("servers/value");
for (Element server : servers) {
socketPoolBean.add(server.getTextTrim());
}
return socketPoolBean;
}
logger.warn("Configuration file is not valid!");
return null;
}
/**
*实例化解析的commonsocketpool标签成SocketIOPool和MemcachedClient
*/
public MemCachedClient getCommonMemcachedClient() {
return getMemcachedClient(commonSocketPoolBean);
}
private MemCachedClient getMemcachedClient(SocketPoolBean socketPoolBean) {
if (socketPoolBean == null) {
logger.warn("please check your xml file!");
return null;
}
SockIOPool pool = SockIOPool.getInstance(socketPoolBean.getName());
pool.setServers(socketPoolBean.getServers().toArray(
new String[socketPoolBean.getServers().size()]));
pool.setInitConn(socketPoolBean.getInitConn());// 设置cache服务器的初始化可用连接
pool.setMinConn(socketPoolBean.getMinConn()); // 设置每个服务器最少可用连接数
pool.setMaxConn(socketPoolBean.getMaxConn()); // 设置每个服务器最大可用连接数
pool.setMaxIdle(socketPoolBean.getMaxIdle()); // 设置可用连接池的等待时间
pool.setMaintSleep(socketPoolBean.getMaintSleep());// 设置连接池维护线程的睡眠时间,设置为0,维护线程不启动
pool.setNagle(socketPoolBean.isNagle()); // 设置是否使用Nagle算法,因为我们的通讯数据量�?常比较大
pool.setSocketTO(socketPoolBean.getSocketTo()); // 设置读取等待超时
pool.setAliveCheck(socketPoolBean.isAliveCheck());// 设置连接心跳监测
pool.setHashingAlg(SockIOPool.CONSISTENT_HASH);
pool.initialize();
MemCachedClient mc = new MemCachedClient(socketPoolBean.getName());
mc.setCompressEnable(true); // 压缩开关
mc.setCompressThreshold(64 * 1024); // 压缩设置,超过指定大小(单位为K)的数据都会被压缩
return mc;
}
}
| true
|
16b4cb6f01813a0542229da785dfd9639466fecd
|
Java
|
ideveloper2017/LM_PosFx
|
/src/main/java/com/libanminds/repositories/ExpenseTypesRepository.java
|
UTF-8
| 2,769
| 2.765625
| 3
|
[] |
no_license
|
package com.libanminds.repositories;
import com.libanminds.models.Type;
import com.libanminds.singletons.DBConnection;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ExpenseTypesRepository {
public static ObservableList<Type> getExpenseTypes() {
String query = "SELECT * FROM expense_types";
return getTypesFromQuery(query);
}
public static ObservableList<Type> getExpenseTypesLike(String value) {
String query = "SELECT * FROM expense_types where name like '%" + value + "%'";
return getTypesFromQuery(query);
}
public static boolean addExpenseType(Type type) {
String query = "INSERT INTO expense_types(name) VALUES (?)";
try {
PreparedStatement statement = DBConnection.getInstance().getPreparedStatement(query);
statement.setString(1, type.getName());
statement.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public static boolean updateExpenseType(Type type) {
String query = "UPDATE expense_types SET name = ? WHERE id = ?";
try {
PreparedStatement statement = DBConnection.getInstance().getPreparedStatement(query);
statement.setString(1, type.getName());
statement.setInt(2, type.getID());
statement.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public static boolean deleteExpenseType(Type type) {
try {
String query = "DELETE FROM expense_types where id = " + type.getID();
Statement statement = DBConnection.getInstance().getStatement();
statement.executeUpdate(query);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
}
private static ObservableList<Type> getTypesFromQuery(String query) {
ObservableList<Type> data = FXCollections.observableArrayList();
try {
Statement statement = DBConnection.getInstance().getStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
data.add(new Type(
rs.getInt("id"),
rs.getString("name")
));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
return null;
}
return data;
}
}
| true
|
6dbfaafd5d82e92d8db31fc7a287f82e3793db67
|
Java
|
MiraclesSoftwareLaboratories/InitialgitProject
|
/First Java project/src/miracleslaboratories/RepetativeAlarm.java
|
UTF-8
| 3,434
| 3.265625
| 3
|
[] |
no_license
|
package miracleslaboratories;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
//Repetative Alarm
public class RepetativeAlarm {
public static void main(String[] args) {
repeatAlarm();
}
public static void repeatAlarm(){
Calendar cal=Calendar.getInstance();
LocalTime now= LocalTime.now();
Date date = new Date();
LocalTime limit=LocalTime.parse("06:00");
LocalTime limit1=LocalTime.parse("06:30");
LocalTime limit2=LocalTime.parse("07:00");
LocalTime limit3=LocalTime.parse("07:30");
LocalTime limit4=LocalTime.parse("09:30");
LocalTime limit5=LocalTime.parse("14:00");
LocalTime limit6=LocalTime.parse("14:30");
LocalTime limit7=LocalTime.parse("19:00");
LocalTime limit8=LocalTime.parse("20:30");
LocalTime limit9=LocalTime.parse("22:00");
LocalTime limit10=LocalTime.parse("22:30");
int day=cal.get(Calendar.DAY_OF_WEEK);
System.out.println(date);
while((day>1)||(day<7)){
if(now.isBefore(limit))
System.out.println("Sleeping");
while(now.equals(limit)) {
System.out.println(" Wake Up");
System.out.println(" Good Morning");
}
while(now.equals(limit1)||now.equals(limit2)) {
System.out.println("*********Jogging***********");
}
while(now.isAfter(limit2)){
while(now.isBefore(limit3)) {
System.out.println("Have Morining Tea");
}
while(now.isAfter(limit3)&&now.isBefore(limit4))
System.out.println("Ready for the Office");
}
if(now.equals(limit4)||now.isAfter(limit4))
System.out.println("Leave for the Office");
while(now.isAfter(limit4)||now.equals(limit5)||now.isAfter(limit5));{
System.out.println("Working at office");
}
while(now.isAfter(limit5)||(now.equals(limit6))) {
System.out.println("Lunch Time");
}
while(now.equals(limit7))
System.out.println("Tea time");
if(now.isBefore(limit8)&&(now.isAfter(limit7)))
System.out.println("Having Dinner");
else
System.out.println("Dinner preparing");
if(now.equals(limit9)||now.isAfter(limit9)){
if(now.isAfter(limit9)||now.isBefore(limit10))
System.out.println("Time to sleep now");
else
System.out.println("You have to Sleep now");
}
if(now.isAfter(limit10))
System.out.println("Sleep it's too late");
}
while((day==0)||(day==7)) {
if(now.isBefore(limit1))
System.out.println("Sleeping");
while(now.equals(limit1)) {
System.out.println("**********Wake Up**********");
System.out.println("Good Morning");
}
while(now.equals(limit2)||now.equals(limit3)) {
System.out.println("*********Jogging***********");
}
while(now.equals(limit3)||now.equals(limit4)) {
System.out.println("Watching T.V with Tea");
}
while(now.equals(limit4)||now.isAfter(limit4)&&now.equals(limit5)||now.isBefore(limit5)) {
System.out.println("House hold Work");
}
while(now.equals(limit5)||now.isAfter(limit5)&&now.equals(limit6)||now.isBefore(limit6)) {
System.out.println("Lunch time");
}
while(now.isAfter(limit6)||now.isBefore(limit7)) {
System.out.println("Sleeping");
}
while(now.equals(limit7)||now.isAfter(limit7)) {
System.out.println("Having Tea");
}
while(now.isAfter(limit7)&&now.isBefore(limit9)) {
System.out.println("Dinner with T.V");
}
if(now.isAfter(limit10))
System.out.println("Sleeping Time"+"\nGoodNight");
}
}
}
| true
|
2fb9c7b3f225d61224f8bb9eba26601bfe2969b7
|
Java
|
owncloud/android-scenario-testing
|
/src/main/java/utils/date/DateUtils.java
|
UTF-8
| 3,731
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
package utils.date;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import utils.log.Log;
public class DateUtils {
public static String dateInDaysAndroidFormat(String days) {
Log.log(Level.FINE, "Starts: Turns days in date");
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.add(Calendar.DAY_OF_YEAR, Integer.valueOf(days));
Log.log(Level.FINE, "Date to format: " + gregorianCalendar.getTime());
String dateAfterDays = formatInt(gregorianCalendar.get(Calendar.DAY_OF_MONTH))
+ " " + getNameMonth(gregorianCalendar.get(Calendar.MONTH))
+ " " + gregorianCalendar.get(Calendar.YEAR);
Log.log(Level.FINE, "Date formatted: " + dateAfterDays);
return dateAfterDays;
}
public static String dateInDaysShareRequestFormat(String days) {
Log.log(Level.FINE, "Starts: Turns days in date fot Share request");
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.add(Calendar.DAY_OF_YEAR, Integer.valueOf(days));
Log.log(Level.FINE, "Date to format: " + gregorianCalendar.getTime());
String dateAfterDays = gregorianCalendar.get(Calendar.YEAR) + "-"
+ "-" + gregorianCalendar.get(Calendar.MONTH) + 1
+ "-" + formatInt(gregorianCalendar.get(Calendar.DAY_OF_MONTH));
Log.log(Level.FINE, "Date formatted: " + dateAfterDays);
return dateAfterDays;
}
public static String dateInDaysWithServerFormat(String days) {
Log.log(Level.FINE, "Starts: Turns days in date with server response format");
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.add(Calendar.DAY_OF_YEAR, Integer.valueOf(days));
Log.log(Level.FINE, "Date to format: " + gregorianCalendar.getTime());
String dateAfterDays = gregorianCalendar.get(Calendar.YEAR)
+ "-" + formatInt(gregorianCalendar.get(Calendar.MONTH) + 1)
+ "-" + formatInt(gregorianCalendar.get(Calendar.DAY_OF_MONTH))
+ " 00:00:00";
Log.log(Level.FINE, "Date formatted: " + dateAfterDays);
return dateAfterDays;
}
public static String shortDate(String days) {
Log.log(Level.FINE, "Starts: Build shortDate string");
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.add(Calendar.DAY_OF_YEAR, Integer.valueOf(days));
Log.log(Level.FINE, "Date: " + gregorianCalendar.getTime());
String shortDate = getNameMonth(gregorianCalendar.get(Calendar.MONTH)).substring(0, 3)
+ " " + gregorianCalendar.get(Calendar.DAY_OF_MONTH)
+ ", " + gregorianCalendar.get(Calendar.YEAR);
Log.log(Level.FINE, "Short Date: " + shortDate);
return shortDate;
}
private static String getNameMonth(int numMonth) {
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
String[] months = dateFormatSymbols.getMonths();
if (numMonth >= 0 && numMonth <= 11) {
return months[numMonth];
} else
return "";
}
private static String formatInt(int dateNumber) {
String day;
if (dateNumber < 10) {
day = "0" + dateNumber;
} else {
day = String.valueOf(dateNumber);
}
return day;
}
public static int minExpirationDate(int a, int b) {
if (a == 0 && b > 0) {
return b;
}
if (a > 0 && b == 0) {
return a;
}
return a <= b ? a : b;
}
}
| true
|
1ed6dc2f0c41b24f0e72224ac0bf7790213247d8
|
Java
|
l853762433/summer
|
/LearnList/src/List/Employee.java
|
UTF-8
| 706
| 3.34375
| 3
|
[] |
no_license
|
package List;
public class Employee {
String name;
String num;
double salary;
public Employee(String name,String num,double salary) {
this.name=name;
this.num=num;
this.salary=salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee [name=" + name + ", num=" + num + ", salary=" + salary + "]";
}
}
| true
|
35821f107b94e435b025e7d347b19e8a374289b6
|
Java
|
jiaweiho/LifeNoteFlip
|
/app/src/main/java/com/jwho/lifenoteflip/service/EvernoteGetResources.java
|
UTF-8
| 2,472
| 2.046875
| 2
|
[] |
no_license
|
package com.jwho.lifenoteflip.service;
import android.os.AsyncTask;
import android.util.Log;
import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.Resource;
import com.evernote.edam.userstore.PublicUserInfo;
import com.evernote.edam.userstore.UserStore;
import com.evernote.thrift.TException;
import com.evernote.thrift.protocol.TBinaryProtocol;
import com.evernote.thrift.transport.THttpClient;
import com.evernote.thrift.transport.TTransportException;
import com.jwho.lifenoteflip.app.BuildConfig;
import com.jwho.lifenoteflip.dataaccess.NoteFromEvernote;
import java.util.ArrayList;
import java.util.List;
public class EvernoteGetResources extends AsyncTask<List<Note>, Void, List<Resource>> {
private static final String TAG = EvernoteGetResources.class.getSimpleName();
@Override
protected List<Resource> doInBackground(List<Note>... notes) {
List<Resource> resources = new ArrayList<>();
THttpClient userStoreTrans;
try {
userStoreTrans = new THttpClient(BuildConfig.USER_STORE_URL);
TBinaryProtocol userStoreProt = new TBinaryProtocol(userStoreTrans);
UserStore.Client userStore = new UserStore.Client(userStoreProt, userStoreProt);
PublicUserInfo userInfo = userStore.getPublicUserInfo("theitninja");
for (Note note : notes[0]) {
//NoteFromEvernote everNote = new NoteFromEvernote(note.getGuid(), note.getTitle(), note.getContent(), note.getResources());
String resGuid = note.getResources().get(0).getGuid();
String resUrl = userInfo.getWebApiUrlPrefix() + "res/" + resGuid;
Log.i(TAG, "ResUrl: " + resUrl);
}
// TODO: Get multiple resources
} catch (TTransportException e) {
e.printStackTrace();
} catch (EDAMUserException e) {
e.printStackTrace();
} catch (EDAMSystemException e) {
e.printStackTrace();
} catch (TException e) {
e.printStackTrace();
} catch (EDAMNotFoundException e) {
e.printStackTrace();
}
return resources;
}
@Override
protected void onPostExecute(List<Resource> resources) {
if (resources != null && !resources.isEmpty()) {
}
}
}
| true
|
392c19b860d4fa5572f26e6efafcfa64dd6f649c
|
Java
|
Anassifi/ReservationYoucode
|
/ReservationPlaceYoucode/src/main/java/org/example/DAO/RoleDAO.java
|
UTF-8
| 334
| 2.15625
| 2
|
[] |
no_license
|
package org.example.DAO;
import org.example.Entity.RoleEntity;
import java.util.List;
public interface RoleDAO {
public void addRole(RoleEntity role);
public RoleEntity getRoleById(int id);
public List<RoleEntity> getAllRoles();
public void deleteRole(int id);
public RoleEntity updateRole(RoleEntity role);
}
| true
|
4e92489eafa17cae6cc36a314ac6cc5a4e12d209
|
Java
|
fromlabs/micronaut_kafka_issue1
|
/src/test/java/org/fromlabs/issue1/Issue1Test.java
|
UTF-8
| 1,955
| 2.09375
| 2
|
[] |
no_license
|
package org.fromlabs.issue1;
import io.micronaut.configuration.kafka.config.AbstractKafkaConfiguration;
import io.micronaut.context.ApplicationContext;
import io.micronaut.test.annotation.MicronautTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Map;
@MicronautTest
class Issue1Test {
@Test
void testBookClient() {
Map<String, Object> config =
Collections.singletonMap(AbstractKafkaConfiguration.EMBEDDED, true);
try (ApplicationContext ctx = ApplicationContext.run(config)) {
BookClient bookClient = ctx.getBean(BookClient.class);
Book book = new Book();
book.setTitle("The Stand");
bookClient.send("Stephen King", book);
KafkaProducerFactoryMonitor kafkaProducerFactoryMonitor =
ctx.getBean(KafkaProducerFactoryMonitor.class);
Assertions.assertEquals(
"book-client",
kafkaProducerFactoryMonitor.getConfiguration().getConfig().getProperty("client.id"));
Assertions.assertEquals(
"all", kafkaProducerFactoryMonitor.getConfiguration().getConfig().getProperty("acks"));
}
}
@Test
void testBookSender() {
Map<String, Object> config =
Collections.singletonMap(AbstractKafkaConfiguration.EMBEDDED, true);
try (ApplicationContext ctx = ApplicationContext.run(config)) {
BookSender bookSender = ctx.getBean(BookSender.class);
Book book = new Book();
book.setTitle("The Stand");
bookSender.send("Stephen King", book);
KafkaProducerFactoryMonitor kafkaProducerFactoryMonitor =
ctx.getBean(KafkaProducerFactoryMonitor.class);
Assertions.assertEquals(
"book-sender",
kafkaProducerFactoryMonitor.getConfiguration().getConfig().getProperty("client.id"));
Assertions.assertEquals(
"all", kafkaProducerFactoryMonitor.getConfiguration().getConfig().getProperty("acks"));
}
}
}
| true
|
6b0a9575515866c3a481a70010dfd1c60a317030
|
Java
|
MonkeyDatabase/DesignPattern
|
/src/io/github/monkeydatabase/command/remotecontroller/RemoteContorller.java
|
UTF-8
| 1,514
| 3.015625
| 3
|
[] |
no_license
|
package io.github.monkeydatabase.command.remotecontroller;
import io.github.monkeydatabase.command.remotecontroller.command.Command;
import io.github.monkeydatabase.command.remotecontroller.command.NoCommand;
public class RemoteContorller {
Command[] onCommands;
Command[] offCommands;
//缓存上一个命令,预留给执行撤销功能
//此处如果是List,可以undo redo
Command undoCommand;
public RemoteContorller(){
//分成五组,每组有一个开按钮和一个关按钮
onCommands=new Command[5];
offCommands=new Command[5];
for (int i=0;i<5;i++){
onCommands[i]=new NoCommand();
offCommands[i]=new NoCommand();
}
}
//给特定的按钮绑定命令
public void setCommand(int no,Command onCommand,Command offCommand){
onCommands[no]=onCommand;
offCommands[no]=offCommand;
}
//按下开按钮
public void onButtonPushed(int no){
//找到开按钮的组,并执行对应方法
onCommands[no].execute();
//将这个命令记录下来,用于撤销
undoCommand=onCommands[no];
}
//按下关按钮
public void offButtonPushed(int no){
//找到开按钮的组,并执行对应方法
offCommands[no].execute();
//将这个命令记录下来,用于撤销
undoCommand=offCommands[no];
}
//按下撤销按钮
public void undoButtonPushed(){
undoCommand.undo();
}
}
| true
|
ae7bbd1f9b0f399942240f0928490f391dd767a5
|
Java
|
mbaluda/LuMiNous
|
/uml2ajTests/src/testModel/MyNonComparable.java
|
UTF-8
| 232
| 1.804688
| 2
|
[] |
no_license
|
package testModel;
/**
* Description of the class MyNonComparable.
*
*
*/
public class MyNonComparable {
/**
* Description of the method hashCode.
*
* @return return
*/
public int hashCode() {
return 0;
}
}
| true
|
c51d9e4ffeb3fa71b97f50159aba6e4ff9a70563
|
Java
|
zhengjie19901102/myieb
|
/ieb/src/main/java/com/ieb/dao/AuthorityDao.java
|
UTF-8
| 229
| 1.5
| 2
|
[] |
no_license
|
package com.ieb.dao;
import org.springframework.data.repository.CrudRepository;
import com.ieb.bean.Authority;
public interface AuthorityDao extends BaseRepositoryDao<Authority, Integer>, CrudRepository<Authority, Integer>{
}
| true
|
d021c59bb79e37098592a090419fd5ee01ac283f
|
Java
|
Alexandrqaz/-udit
|
/Interface.java
|
WINDOWS-1251
| 1,781
| 3.015625
| 3
|
[] |
no_license
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Interface {
public static void main (String [] args) {
JTextField Text = new JTextField ();
level_of_damage T1= new level_of_damage();
level_of_probability_of_attack T2=new level_of_probability_of_attack();
JPanel p1=new JPanel();
p1.setLayout(new GridLayout(10,1));
JLabel L1 = new JLabel ();
L1.setText(" ");
JComboBox CB1 = new JComboBox(T1.t1);
JLabel L2 = new JLabel ();
L2.setText(" ");
JComboBox CB2 = new JComboBox(T2.t2);
JLabel L3 = new JLabel ();
JButton b2 =new JButton(" ");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
risk_level_of_information_security q= new risk_level_of_information_security();
if (((String) CB1.getSelectedItem()=="") || ((String) CB2.getSelectedItem()==""))
{
Text.setText(" ");
}
Text.setText(q.level((String) CB1.getSelectedItem(),(String) CB2.getSelectedItem()));
}
});
L3.setText(" ");
Text.setEditable(false);
p1.add(L1);
p1.add(CB1);
p1.add(L2);
p1.add(CB2);
p1.add(b2);
p1.add(L3);
p1.add(Text);
JFrame myWindow = new JFrame("");
myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myWindow.setSize(400, 300);
myWindow.setVisible(true);
myWindow.setContentPane(p1);
}
}
| true
|
9a1c721feccb47dffb903d1e2c9e86948ef60291
|
Java
|
cgchavarro/Iteracion_3
|
/src/rest/RESTMenu.java
|
UTF-8
| 2,688
| 2.53125
| 3
|
[] |
no_license
|
package rest;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import master.RotondAndesTM;
import vo.Menu;
@Path("menu")
public class RESTMenu
{
@Context
private ServletContext context;
private String doErrorMessage(Exception e){
return "{ \"ERROR\": \""+ e.getMessage() + "\"}" ;
}
private String getPath() {
return context.getRealPath("WEB-INF/ConnectionData");
}
@GET
@Path( "{id: \\d+}" )
@Produces( { MediaType.APPLICATION_JSON } )
public Response darMenuId( @PathParam( "id" ) Long id )
{
RotondAndesTM tm = new RotondAndesTM( getPath( ) );
try
{
Menu menu = tm.darMenuPorId(id);
return Response.status( 200 ).entity( menu ).build( );
}
catch( Exception e )
{
return Response.status( 500 ).entity( doErrorMessage( e ) ).build( );
}
}
@GET
@Path( "{idRestaurante: \\d+}" )
@Produces( { MediaType.APPLICATION_JSON } )
public Response darMenuRestaurante( @PathParam( "idRestaurante" ) Long idRestaurante )
{
RotondAndesTM tm = new RotondAndesTM( getPath( ) );
try
{
ArrayList<Menu> menus = tm.darMenusPorRestaurante(idRestaurante);
return Response.status( 200 ).entity( menus ).build( );
}
catch( Exception e )
{
return Response.status( 500 ).entity( doErrorMessage( e ) ).build( );
}
}
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response darMenus() {
RotondAndesTM tm = new RotondAndesTM(getPath());
List<Menu> menus;
try {
menus = tm.darMenus();
} catch (Exception e) {
return Response.status(500).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(menus).build();
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response actualizarMenu(Menu menu) {
RotondAndesTM tm = new RotondAndesTM(getPath());
try {
tm.actualizarMenu(menu);
} catch (Exception e) {
return Response.status(500).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(menu).build();
}
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response eliminarMenu(Menu menu) {
RotondAndesTM tm = new RotondAndesTM(getPath());
try {
tm.eliminarMenu(menu);
} catch (Exception e) {
return Response.status(500).entity(doErrorMessage(e)).build();
}
return Response.status(200).entity(menu).build();
}
}
| true
|
9f0ce3bb5b95753639b4566fa6197ce5f71be9b7
|
Java
|
gitchong/NetDiscovery
|
/admin/src/main/java/com/cv4j/netdiscovery/admin/LaunchSchedule.java
|
UTF-8
| 741
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.cv4j.netdiscovery.admin;
import com.cv4j.netdiscovery.admin.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 服务器起来的时候,启动任务调度器,把数据库里配置的任务全部启动起来
*/
@Component
@Order(value=1)
@Slf4j
public class LaunchSchedule implements CommandLineRunner {
@Autowired
JobService jobService;
@Override
public void run(String... args) throws Exception {
log.info("LaunchSchedule run");
jobService.initSchedule();
}
}
| true
|
5d2a65050f2dd96378ea5fb090c60419a368f668
|
Java
|
eric-zheng/distributed-system
|
/src/app_kvServer/ClientConnection.java
|
UTF-8
| 17,445
| 2.296875
| 2
|
[] |
no_license
|
package app_kvServer;
import client.ClientSocketListener;
import common.Entry;
import common.Metadata;
import common.messages.*;
import Helper.Helper;
import common.messages.KVMessage.StatusType;
import common.messages.KVMImplement;
import common.messages.TextMessage;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.apache.log4j.*;
import storage.DBResponse;
import storage.Storage;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
/**
* Connection end point for each client connected to server. Used to receive,
* process and send data with client.
*/
public class ClientConnection implements Runnable {
private static Logger logger = Logger.getRootLogger();
// the KVServer name corresponding to this thread
// format: <IP>:<port number>
private String serverName;
private boolean isOpen;
private static final int BUFFER_SIZE = 1024;
private static final int DROP_SIZE = 128 * BUFFER_SIZE;
private Socket clientSocket;
private InputStream input;
private OutputStream output;
private Storage s;
private MutableBoolean isLocked;
private MutableBoolean isRunning;
private Metadata md;
// pass in the zk
private ZooKeeper zk;
/**
* Constructs a new CientConnection object for a given TCP socket.
*
* @param clientSocket the Socket object for the client connection.
*/
public ClientConnection(Socket clientSocket, Storage s, MutableBoolean isLocked, MutableBoolean isRunning,
Metadata md, String zname, ZooKeeper zk) {
this.clientSocket = clientSocket;
this.isOpen = true;
this.s = s;
this.isLocked = isLocked;
this.isRunning = isRunning;
this.md = md;
this.serverName = zname;
this.zk = zk;
}
private boolean isRunning() {
return this.isRunning.booleanValue();
}
private boolean isLocked() {
return this.isLocked.booleanValue();
}
void debug_put_data_on_znode() {
String start_range = "00000000000000000000000000000000";
String end_range = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
// create the sending message
ArrayList<DBResponse> result = null;
try {
result = s.getInRange(start_range, end_range);
} catch (IOException e1) {
e1.printStackTrace();
}
String allData = "";
for (DBResponse data : result) {
// send each data in result array
allData = allData + data.key + ":" + data.value + " - ";
}
try {
if (zk.exists("/" + serverName + "/debug", false) != null) {
// remove the debug node if it exists previously
zk.delete("/" + serverName + "/debug", -1);
}
zk.create(("/" + serverName + "/debug"), null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.setData(("/" + serverName + "/debug"), allData.getBytes(), -1);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
/**
* Initializes and starts the client connection. Loops until the connection is
* closed or aborted by the client.
*/
public void run() {
try {
output = clientSocket.getOutputStream();
input = clientSocket.getInputStream();
while (isOpen) {
try {
TextMessage latestMsg = receiveMessage();
if (latestMsg.getMsg().equals("")) {
// disconnect
isOpen = false;
break;
}
// Convert TextMessage to KVMessage
KVMImplement kvmsg = new KVMImplement(latestMsg);
// Check if the request is to move data
// Highest priority
if (kvmsg.getStatus().equals(StatusType.SERVER_STOPPED)
|| kvmsg.getStatus().equals(StatusType.SERVER_WRITE_LOCK)) {
// Request from another KVServer to move data
KVMImplement rtnmsg = null;
DBResponse result;
if (kvmsg.getStatus().equals(StatusType.SERVER_WRITE_LOCK) || kvmsg.getValue() == null) {
// DELETE request
result = s.put(kvmsg.getKey(), null);
if (result.success) {
rtnmsg = new KVMImplement("DELETE_SUCCESS", kvmsg.getKey(), null);
} else {
rtnmsg = new KVMImplement("DELETE_ERROR", kvmsg.getKey(), null);
}
} else {
// PUT request
result = s.put(kvmsg.getKey(), kvmsg.getValue());
if (result.success && result.isNewTuple) { // insert tuple successfully
rtnmsg = new KVMImplement("PUT_SUCCESS", kvmsg.getKey(), kvmsg.getValue());
} else if (result.success && !result.isNewTuple) { // update value successfully
rtnmsg = new KVMImplement("PUT_UPDATE", kvmsg.getKey(), kvmsg.getValue());
} else if (!result.success) { // put error
rtnmsg = new KVMImplement("PUT_ERROR", kvmsg.getKey(), kvmsg.getValue());
}
}
byte[] tempBytes = rtnmsg.getmsgbyte();
try {
output.write(tempBytes, 0, tempBytes.length);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
// Return message to the sender
// sendMessage(rtnmsg.getTextMessage());
continue;
} else {
if (!isRunning()) {
// server is stopped and not moving data
KVMImplement rtnmsg = new KVMImplement("SERVER_STOPPED", null, null);
latestMsg = null;
TextMessage returnMsg = rtnmsg.getTextMessage();
sendMessage(returnMsg);
continue;
} else if (isLocked() && (kvmsg.getStatus().equals(StatusType.PUT)
|| kvmsg.getStatus().equals(StatusType.DELETE_SUCCESS))) {
// write lock is active - send back message to client
KVMImplement rtnmsg = new KVMImplement("SERVER_WRITE_LOCK", null, null);
TextMessage returnMsg = rtnmsg.getTextMessage();
latestMsg = null;
sendMessage(returnMsg);
continue;
}
}
// Add log info
if (kvmsg.getStatus().equals(StatusType.GET)) {
logger.info("RECEIVE \t<" + clientSocket.getInetAddress().getHostAddress() + ":"
+ clientSocket.getPort() + ">: '" + kvmsg.getStringStatus() + " " + kvmsg.getKey()
+ "'");
} else if (kvmsg.getStatus().equals(StatusType.DELETE_SUCCESS)) {
logger.info("RECEIVE \t<" + clientSocket.getInetAddress().getHostAddress() + ":"
+ clientSocket.getPort() + ">: '" + "DELETE" + " " + kvmsg.getKey() + "'");
} else {
logger.info("RECEIVE \t<" + clientSocket.getInetAddress().getHostAddress() + ":"
+ clientSocket.getPort() + ">: '" + kvmsg.getStringStatus() + " " + kvmsg.getKey() + " "
+ kvmsg.getValue() + "'");
}
// Call storage function provided by DB
// Note to acquire lock before using them
KVMImplement rtnmsg = null;
synchronized (s) {
// Need to check whether the object is in this server
if (this.md.requestReplicaInRange(this.serverName, kvmsg.getKey())) {
// within the replica range
if (kvmsg.getStatus().equals(StatusType.GET)) {
DBResponse result = s.get(kvmsg.getKey());
if (result.success) {
rtnmsg = new KVMImplement("GET_SUCCESS", kvmsg.getKey(), result.value);
} else {
rtnmsg = new KVMImplement("GET_ERROR", kvmsg.getKey(), null);
}
} else if (kvmsg.getStatus().equals(StatusType.PUT)
&& this.md.requestCoordInRange(this.serverName, kvmsg.getKey())) {
// Update itself data
DBResponse result = s.put(kvmsg.getKey(), kvmsg.getValue());
// Tell the replicas to put data
boolean send_reps_success = sendDataToReplicas(false, kvmsg);
if (send_reps_success) {
if (result.success && result.isNewTuple) { // insert tuple successfully
rtnmsg = new KVMImplement("PUT_SUCCESS", kvmsg.getKey(), kvmsg.getValue());
} else if (result.success && !result.isNewTuple) { // update value successfully
rtnmsg = new KVMImplement("PUT_UPDATE", kvmsg.getKey(), kvmsg.getValue());
} else if (!result.success) { // put error
rtnmsg = new KVMImplement("PUT_ERROR", kvmsg.getKey(), kvmsg.getValue());
}
} else {
rtnmsg = new KVMImplement("PUT_ERROR", kvmsg.getKey(), kvmsg.getValue());
}
} else if (kvmsg.getStatus().equals(StatusType.DELETE_SUCCESS)
&& this.md.requestCoordInRange(this.serverName, kvmsg.getKey())) {
// Need to delete the tuple based on the key
DBResponse result = s.put(kvmsg.getKey(), null);
boolean send_reps_success = sendDataToReplicas(true, kvmsg);
if (send_reps_success) {
if (result.success) {
rtnmsg = new KVMImplement("DELETE_SUCCESS", kvmsg.getKey(), null);
} else {
rtnmsg = new KVMImplement("DELETE_ERROR", kvmsg.getKey(), null);
}
}
} else {
// not in coord range but need to put or delete
// not responsible
KVMImplement rtmsg = new KVMImplement("SERVER_NOT_RESPONSIBLE", md.sendMeta(), null);
TextMessage returnMsg = rtmsg.getTextMessage();
sendMessage(returnMsg);
continue;
}
} else {
// This server doesn't responsible for the client request (read or write)
KVMImplement rtmsg = new KVMImplement("SERVER_NOT_RESPONSIBLE", md.sendMeta(), null);
TextMessage returnMsg = rtmsg.getTextMessage();
sendMessage(returnMsg);
continue;
}
}
// debug function
// debug_put_data_on_znode();
// Return message to the client
// convert KVMessage to TextMessage
TextMessage returnMsg = rtnmsg.getTextMessage();
sendMessage(returnMsg);
} catch (IOException ioe) {
logger.error("Error! Connection lost!");
isOpen = false;
}
}
} catch (IOException ioe) {
logger.error("Error! Connection could not be established!", ioe);
} finally {
try {
if (clientSocket != null) {
input.close();
output.close();
clientSocket.close();
}
} catch (IOException ioe) {
logger.error("Error! Unable to tear down connection!", ioe);
}
logger.info("Client disconnected.");
}
}
/**
* Send/Delete the data to the following TWO replicas
*/
boolean sendDataToReplicas(boolean isDelete, KVMImplement kvmsg) {
// get the name of next two replicas
Entry rep1 = this.md.getNextServer(this.serverName);
Entry rep2 = this.md.getNextServer((rep1.getAddressPortString()));
String rep1_addr = rep1.getAddressString();
String rep2_addr = rep2.getAddressString();
int rep1_port = rep1.getPortInt();
int rep2_port = rep2.getPortInt();
boolean returnedValue = false;
// build sockets and transfer data
Socket rep1_socket = null, rep2_socket = null;
OutputStream rep1_output = null, rep2_output = null;
InputStream rep1_input = null, rep2_input = null;
Set<ClientSocketListener> rep1_listeners, rep2_listeners;
try {
rep1_socket = new Socket(rep1_addr, rep1_port);
rep2_socket = new Socket(rep2_addr, rep2_port);
rep1_listeners = new HashSet<ClientSocketListener>();
rep2_listeners = new HashSet<ClientSocketListener>();
rep1_output = rep1_socket.getOutputStream();
rep2_output = rep2_socket.getOutputStream();
rep1_input = rep1_socket.getInputStream();
rep2_input = rep2_socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
// create the sending message
KVMImplement data_to_send;
if (!isDelete) {
// put or update data
data_to_send = new KVMImplement("SERVER_STOPPED", kvmsg.getKey(), kvmsg.getValue());
} else {
// delete data
data_to_send = new KVMImplement("SERVER_WRITE_LOCK", kvmsg.getKey(), null);
}
byte[] msgBytes = data_to_send.getmsgbyte();
try {
rep1_output.write(msgBytes, 0, msgBytes.length);
rep1_output.flush();
} catch (IOException e) {
e.printStackTrace();
}
TextMessage ackMsg1 = null;
try {
ackMsg1 = receiveMessage_withinput(rep1_input);
} catch (IOException e) {
e.printStackTrace();
}
KVMImplement ack1 = new KVMImplement(ackMsg1);
if (!(ack1.getStatus().equals(StatusType.PUT_ERROR))) {
// correct response from the receiver
// move next data
try {
rep2_output.write(msgBytes, 0, msgBytes.length);
rep2_output.flush();
} catch (IOException e) {
e.printStackTrace();
}
TextMessage ackMsg2 = null;
try {
ackMsg2 = receiveMessage_withinput(rep2_input);
} catch (IOException e) {
e.printStackTrace();
}
KVMImplement ack2 = new KVMImplement(ackMsg2);
if (!(ack2.getStatus().equals(StatusType.PUT_ERROR))) {
// correct response from the receiver
returnedValue = true;
}
}
// close the client sockets
try {
rep1_socket.close();
rep2_socket.close();
} catch (IOException e) {
e.printStackTrace();
}
rep1_socket = null;
rep2_socket = null;
return returnedValue;
}
/**
* Method sends a TextMessage using this socket.
*
* @param msg the message that is to be sent.
* @throws IOException some I/O error regarding the output stream
*/
public void sendMessage(TextMessage msg) throws IOException {
byte[] msgBytes = msg.getMsgBytes();
output.write(msgBytes, 0, msgBytes.length);
output.flush();
}
private TextMessage receiveMessage() throws IOException {
int index = 0;
byte[] msgBytes = null, tmp = null;
byte[] bufferBytes = new byte[BUFFER_SIZE];
/* read first char from stream */
byte read = (byte) input.read();
boolean reading = true;
while (/* read != 13 && */ read != 10 && read != -1 && reading) {/* CR, LF, error */
/* if buffer filled, copy to msg array */
if (index == BUFFER_SIZE) {
if (msgBytes == null) {
tmp = new byte[BUFFER_SIZE];
System.arraycopy(bufferBytes, 0, tmp, 0, BUFFER_SIZE);
} else {
tmp = new byte[msgBytes.length + BUFFER_SIZE];
System.arraycopy(msgBytes, 0, tmp, 0, msgBytes.length);
System.arraycopy(bufferBytes, 0, tmp, msgBytes.length, BUFFER_SIZE);
}
msgBytes = tmp;
bufferBytes = new byte[BUFFER_SIZE];
index = 0;
}
/* only read valid characters, i.e. letters and constants */
bufferBytes[index] = read;
index++;
/* stop reading is DROP_SIZE is reached */
if (msgBytes != null && msgBytes.length + index >= DROP_SIZE) {
reading = false;
}
/* read next char from stream */
read = (byte) input.read();
}
if (msgBytes == null) {
tmp = new byte[index];
System.arraycopy(bufferBytes, 0, tmp, 0, index);
} else {
tmp = new byte[msgBytes.length + index];
System.arraycopy(msgBytes, 0, tmp, 0, msgBytes.length);
System.arraycopy(bufferBytes, 0, tmp, msgBytes.length, index);
}
msgBytes = tmp;
/* build final String */
TextMessage msg = new TextMessage(msgBytes);
return msg;
}
private TextMessage receiveMessage_withinput(InputStream input) throws IOException {
int index = 0;
byte[] msgBytes = null, tmp = null;
byte[] bufferBytes = new byte[BUFFER_SIZE];
/* read first char from stream */
byte read = (byte) input.read();
boolean reading = true;
while (/* read != 13 && */ read != 10 && read != -1 && reading) {/* CR, LF, error */
/* if buffer filled, copy to msg array */
if (index == BUFFER_SIZE) {
if (msgBytes == null) {
tmp = new byte[BUFFER_SIZE];
System.arraycopy(bufferBytes, 0, tmp, 0, BUFFER_SIZE);
} else {
tmp = new byte[msgBytes.length + BUFFER_SIZE];
System.arraycopy(msgBytes, 0, tmp, 0, msgBytes.length);
System.arraycopy(bufferBytes, 0, tmp, msgBytes.length, BUFFER_SIZE);
}
msgBytes = tmp;
bufferBytes = new byte[BUFFER_SIZE];
index = 0;
}
/* only read valid characters, i.e. letters and constants */
bufferBytes[index] = read;
index++;
/* stop reading is DROP_SIZE is reached */
if (msgBytes != null && msgBytes.length + index >= DROP_SIZE) {
reading = false;
}
/* read next char from stream */
read = (byte) input.read();
}
if (msgBytes == null) {
tmp = new byte[index];
System.arraycopy(bufferBytes, 0, tmp, 0, index);
} else {
tmp = new byte[msgBytes.length + index];
System.arraycopy(msgBytes, 0, tmp, 0, msgBytes.length);
System.arraycopy(bufferBytes, 0, tmp, msgBytes.length, index);
}
msgBytes = tmp;
/* build final String */
TextMessage msg = new TextMessage(msgBytes);
return msg;
}
}
/*
* // Add server log info if
* (rtnmsg.getStatus().equals(StatusType.DELETE_ERROR)) { logger.info("SEND \t<"
* + clientSocket.getInetAddress().getHostAddress() + ":" +
* clientSocket.getPort() + ">: '" + "DELETE_ERROR" + " " + rtnmsg.getKey() +
* "'"); } else if (rtnmsg.getStatus().equals(StatusType.DELETE_SUCCESS)) {
* logger.info("SEND \t<" + clientSocket.getInetAddress().getHostAddress() + ":"
* + clientSocket.getPort() + ">: '" + "DELETE_SUCCESS" + " " + rtnmsg.getKey()
* + "'"); } else if (rtnmsg.getStatus().equals(StatusType.GET_ERROR)) {
* logger.info("SEND \t<" + clientSocket.getInetAddress().getHostAddress() + ":"
* + clientSocket.getPort() + ">: '" + "GET_ERROR" + " " + rtnmsg.getKey() +
* "'"); } else { logger.info("SEND \t<" +
* clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort()
* + ">: '" + rtnmsg.getStringStatus() + " " + rtnmsg.getKey() + " " +
* rtnmsg.getValue() + "'"); }
*/
| true
|
7856064fe8c8f0c809172bf4af7d27929f6ddcac
|
Java
|
nrg-dev/stumosys
|
/src/main/java/com/stumosys/managedBean/ParentsViewMB.java
|
UTF-8
| 65,708
| 1.679688
| 2
|
[] |
no_license
|
package com.stumosys.managedBean;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.imageio.ImageIO;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.context.ApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.stumosys.controler.SmsController;
import com.stumosys.domain.ParentsDataBean;
import com.stumosys.domain.StudentDataBean;
/*import com.stumosys.domain.TeacherDataBean;
import com.stumosys.shared.ParentDetail;
*/import com.stumosys.util.CommonValidate;
import com.stumosys.util.MailSendJDBC;
@ManagedBean(name = "parentsViewMB")
@RequestScoped
public class ParentsViewMB {
ParentsDataBean parentsDataBean = new ParentsDataBean();
StudentDataBean studentDataBean = new StudentDataBean();
public List<ParentsDataBean> parentsBean;
Date now = new Date();
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
private List<String> classSectionList = null;
private List<String> classSectionList1 = null;
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle text = context.getApplication().evaluateExpressionGet(context, "#{text}", ResourceBundle.class);
ResourceBundle paths = context.getApplication().evaluateExpressionGet(context, "#{paths}", ResourceBundle.class);
private static Logger logger = Logger.getLogger(ParentsViewMB.class);
private List<ParentsDataBean> ImageListPath = null;
private boolean flag=false;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public List<ParentsDataBean> getParentsBean() {
return parentsBean;
}
public void setParentsBean(List<ParentsDataBean> parentsBean) {
this.parentsBean = parentsBean;
}
public List<ParentsDataBean> getImageListPath() {
return ImageListPath;
}
public void setImageListPath(List<ParentsDataBean> imageListPath) {
ImageListPath = imageListPath;
}
public List<String> getClassSectionList1() {
return classSectionList1;
}
public void setClassSectionList1(List<String> classSectionList1) {
this.classSectionList1 = classSectionList1;
}
private boolean tableflag = false;
private List<ParentsDataBean> patentTableList = null;
private List<ParentsDataBean> patentFilterList;
private List<ParentsDataBean> parentList = null;
private List<String> studentIDList = null;
private UploadedFile file;
private boolean boxflag = false;
private boolean delBoxflag = false;
private boolean flag1 = false;
private boolean flag2 = false;
private String studClass;
private List<String> teaClass = null;
public List<String> getTeaClass() {
return teaClass;
}
public void setTeaClass(List<String> teaClass) {
this.teaClass = teaClass;
}
public String getStudClass() {
return studClass;
}
public void setStudClass(String studClass) {
this.studClass = studClass;
}
public boolean isFlag2() {
return flag2;
}
public void setFlag2(boolean flag2) {
this.flag2 = flag2;
}
public boolean isFlag1() {
return flag1;
}
public void setFlag1(boolean flag1) {
this.flag1 = flag1;
}
/**
* @return the parentsDataBean
*/
public ParentsDataBean getParentsDataBean() {
return parentsDataBean;
}
/**
* @param parentsDataBean
* the parentsDataBean to set
*/
public void setParentsDataBean(ParentsDataBean parentsDataBean) {
this.parentsDataBean = parentsDataBean;
}
/**
* @return the patentTableList
*/
public List<ParentsDataBean> getPatentTableList() {
return patentTableList;
}
/**
* @param patentTableList
* the patentTableList to set
*/
public void setPatentTableList(List<ParentsDataBean> patentTableList) {
this.patentTableList = patentTableList;
}
/**
* @return the patentFilterList
*/
public List<ParentsDataBean> getPatentFilterList() {
return patentFilterList;
}
/**
* @param patentFilterList
* the patentFilterList to set
*/
public void setPatentFilterList(List<ParentsDataBean> patentFilterList) {
this.patentFilterList = patentFilterList;
}
/**
* @return the studentIDList
*/
public List<String> getStudentIDList() {
return studentIDList;
}
/**
* @param studentIDList
* the studentIDList to set
*/
public void setStudentIDList(List<String> studentIDList) {
this.studentIDList = studentIDList;
}
/**
* @return the file
*/
public UploadedFile getFile() {
return file;
}
/**
* @param file
* the file to set
*/
public void setFile(UploadedFile file) {
this.file = file;
}
/**
* @return the tableflag
*/
public boolean isTableflag() {
return tableflag;
}
/**
* @param tableflag
* the tableflag to set
*/
public void setTableflag(boolean tableflag) {
this.tableflag = tableflag;
}
public String parentsView() {
logger.debug("Inside.........");
parentsDataBean.setParStuClass("");
parentsDataBean.setParStuSection("");
classSectionList = null;
setTableflag(false);
SmsController controller = null;
String status = "";
String rollnumber = "";flag=false;
try {
classSectionList = new ArrayList<String>();
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
status = controller.getRoll(personID);
if (personID != null) {
if (status.equalsIgnoreCase("Admin")) {
setFlag2(false);
setFlag1(true);
classSectionList = controller.getClassSection(personID);
} else if (status.equalsIgnoreCase("Student")) {
setFlag1(false);
setFlag2(true);
rollnumber = controller.getRollNumber(personID);
logger.debug("------student roll number-----" + rollnumber);
studClass = controller.getStudClsSection(rollnumber);
parentsDataBean.setParStuClass(studClass);
patentTableList = controller.getParentInfo(personID, parentsDataBean);
setTableflag(true);
} else if (status.equalsIgnoreCase("Teacher")) {
setFlag1(true);
setFlag2(false);
classSectionList = new ArrayList<String>();
//rollnumber = controller.getRollNumber(personID);
rollnumber=personID;
classSectionList1 = controller.getTeaClass(rollnumber, studentDataBean);
logger.debug("----------outside controller------");
for (int i = 0; i < studentDataBean.getTeaClassList().size(); i++) {
classSectionList.add(studentDataBean.getTeaClassList().get(i).getTeaclssection());
}
logger.debug("-----teaClass---" + teaClass);
}
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
return "parentsInfo";
}
public String search() {
try {
logger.debug("---------- submit Method -----");
if (validate(true)) {
return "parentsInformations";
}
} catch (Exception e) {
logger.debug("---------- submit Method Calling-----");
logger.warn("Exception -->"+e.getMessage());
}
return "";
}
private boolean validate(boolean flag) {
boolean valid = true;
String fieldName;
FacesContext fc = FacesContext.getCurrentInstance();
if (parentsDataBean.getParStuClass().equalsIgnoreCase("")) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parViewClass").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.class")));
}
valid = false;
}
if (parentsDataBean.getParStuSection().equalsIgnoreCase("")) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parViewSec").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.section")));
}
valid = false;
}
return valid;
}
public String reset() {
parentsDataBean.setParStuClass("");
parentsDataBean.setParStuSection("");
return "";
}
/**
* @return the classSectionList
*/
public List<String> getClassSectionList() {
return classSectionList;
}
/**
* @param classSectionList
* the classSectionList to set
*/
public void setClassSectionList(List<String> classSectionList) {
this.classSectionList = classSectionList;
}
/* Ragulan OCT 25 classChange*/
public void classChange(ValueChangeEvent event) {
SmsController controller = null;
String status = "";flag=false;
try {
patentTableList=new ArrayList<ParentsDataBean>();
if (event.getNewValue().toString() != null) {
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
status = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("Role").toString();
String schoolID=FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("schoolID").toString();
if (personID != null) {
if (status.equalsIgnoreCase("Admin")) {
parentsDataBean.setParStuClass(event.getNewValue().toString());
patentTableList = controller.getParentInfo(personID, parentsDataBean);
logger.debug("size "+patentTableList.size());
setTableflag(true);
setFlag2(false);
flag=true;
} else if (status.equalsIgnoreCase("Teacher")) {
parentsDataBean.setParStuClass(event.getNewValue().toString());
patentTableList = controller.getParentInfo(personID, parentsDataBean);
setTableflag(true);
setFlag2(false);
if(schoolID.equalsIgnoreCase(paths.getString("SMRV.SCHOOLID"))){
flag=true;
}else{
flag=false;
}
}
} else {
setTableflag(false);
}
} else {
setTableflag(false);
}
} catch (NullPointerException e1) {
setTableflag(false);
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
}
public String addStudent()
{
String fieldName;
FacesContext fc = FacesContext.getCurrentInstance();
if(studentCheck(true))
{
int count=0;
parentsDataBean=new ParentsDataBean();
parentsDataBean.setParFirstName(fname);parentsDataBean.setParLastName(lname);
parentsDataBean.setParEmail(mail);parentsDataBean.setParPhoneNo(phno);
parentsDataBean.setParentRelation(relation);parentsDataBean.setParParentID(parentID);
parentsDataBean.setParFile(filename);parentsDataBean.setParfilePath(filepath);
parentsDataBean.setParPathDate(date);
if(parentsBean.size()>1){
for (int i = 0; i < parentsBean.size()-1; i++) {
if (studentID.equalsIgnoreCase(parentsBean.get(i).getParStudID())) count++;
}
}
logger.debug("count "+count);
if(count>0){
fieldName = CommonValidate.findComponentInRoot("parStudentID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.astudentID")));
parentsBean.remove(parentsBean.size()-1);
parentsDataBean.setParStuClass(classname);parentsDataBean.setParStudID(studentID);
}
else{
parentsDataBean.setParFirstName(fname);parentsDataBean.setParLastName(lname);
parentsDataBean.setParEmail(mail);parentsDataBean.setParPhoneNo(phno);
parentsDataBean.setParentRelation(relation);parentsDataBean.setParParentID(parentID);
parentsDataBean.setParFile(filename);parentsDataBean.setParPathDate(date);
parentsDataBean.setParfilePath(filepath);
}
}
else {
parentsBean.remove(parentsBean.size()-1);
}
return "";
}
public String studentID;
public String classname;
public String fname;
public String lname;
public String relation;
public String parentID;
public String mail;
public String phno;
public UploadedFile filename;
public String filepath;
public Date date;
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getRelation() {
return relation;
}
public void setRelation(String relation) {
this.relation = relation;
}
public String getParentID() {
return parentID;
}
public void setParentID(String parentID) {
this.parentID = parentID;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPhno() {
return phno;
}
public void setPhno(String phno) {
this.phno = phno;
}
public UploadedFile getFilename() {
return filename;
}
public void setFilename(UploadedFile filename) {
this.filename = filename;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public boolean studentCheck(boolean flag){
String fieldName;
boolean valid=true;
FacesContext fc = FacesContext.getCurrentInstance();
if (parentsDataBean.getParStuClass().equalsIgnoreCase("Choose")) {
if(flag){
fieldName = CommonValidate.findComponentInRoot("parClassID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.select")));
}
valid=false;
}
if (StringUtils.isBlank(parentsDataBean.getParStudID())) {
if(flag){
fieldName = CommonValidate.findComponentInRoot("parStudentID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.studentID")));
}
valid=false;
}
studentID=parentsDataBean.getParStudID();
classname=parentsDataBean.getParStuClass();
fname=parentsDataBean.getParFirstName();lname=parentsDataBean.getParLastName();
mail=parentsDataBean.getParEmail();phno=parentsDataBean.getParPhoneNo();
relation=parentsDataBean.getParentRelation();parentID=parentsDataBean.getParParentID();
filename=parentsDataBean.getParFile();filepath=parentsDataBean.getParfilePath();
date=parentsDataBean.getParPathDate();
return valid;
}
public void delete() {
SmsController controller = null;
try {
logger.debug("-----Inside call Parents delete method ------" + parentsDataBean.getParParentID());
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
if (personID != null) {
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
String status = controller.deleteParent(personID, parentsDataBean);
if (status.equalsIgnoreCase("Success")) {
setDelBoxflag(true);
} else {
setDelBoxflag(false);
setTableflag(false);
setBoxflag(false);
}
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
}
/**
* @return the parentList
*/
public List<ParentsDataBean> getParentList() {
return parentList;
}
/**
* @param parentList
* the parentList to set
*/
public void setParentList(List<ParentsDataBean> parentList) {
this.parentList = parentList;
}
public void imageview(OutputStream out, Object data) throws IOException {
String s = paths.getString("sms.parents.photo");
BufferedImage img = ImageIO.read(
new File(s + ft.format(parentsDataBean.getParPathDate()) + "/" + parentsDataBean.getParfilePath()));
ImageIO.write(img, "png", out);
}
public void classChange1(ValueChangeEvent event) {
SmsController controller = null;
try {
studentIDList = new ArrayList<String>();
logger.debug("classChange Calling");
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
String name = event.getNewValue().toString();
logger.debug(name);
if (personID != null && name != null) {
studentIDList = controller.getStudentRollNumber(personID, name);
logger.debug(studentIDList);
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
}
public String dummyAction(FileUploadEvent event) throws IOException {
this.setFile(event.getFile());
parentsDataBean.setParFile(event.getFile());
FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
logger.debug(parentsDataBean.getParFile().getContentType());
return "";
}
/**
* @return the boxflag
*/
public boolean isBoxflag() {
return boxflag;
}
/**
* @param boxflag
* the boxflag to set
*/
public void setBoxflag(boolean boxflag) {
this.boxflag = boxflag;
}
/**
* @return the delBoxflag
*/
public boolean isDelBoxflag() {
return delBoxflag;
}
/**
* @param delBoxflag
* the delBoxflag to set
*/
public void setDelBoxflag(boolean delBoxflag) {
this.delBoxflag = delBoxflag;
}
public String returnToHome() {
SmsController controller = null;
logger.debug("Calling");
try {
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
if (personID != null) {
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
patentTableList = controller.getParentInfo(personID, parentsDataBean);
setBoxflag(false);
setDelBoxflag(false);
setTableflag(true);
return "parentviewPageLoad";
} else {
setTableflag(false);
setBoxflag(false);
setDelBoxflag(false);
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
return "";
}
public String update() {
setBoxflag(false);
parentList = null;
try {
parentList = new ArrayList<ParentsDataBean>();
logger.debug("Inside Update method calling....");
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
if (validate1(true)) {
if (personID != null) {
RequestContext reqcontextt = RequestContext.getCurrentInstance();
reqcontextt.execute("check();");
}
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
return null;
}
public String updateParent() {
SmsController controller = null;
setBoxflag(false);
parentList = null;
try {
String schoolName = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("schoolName");
String schoolID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("schoolID");
int schoolid=Integer.parseInt(schoolID);
parentList = new ArrayList<ParentsDataBean>();
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
if (personID != null) {
if (parentsDataBean.getParFile() != null) {
String s = parentsDataBean.getParFile().getContentType();
logger.debug("file Type " + s);
String type = s.substring(s.lastIndexOf("/") + 1);
logger.debug(type);
copyFile(parentsDataBean.getParParentID(), parentsDataBean.getParFile().getInputstream(), type);
logger.debug(parentsDataBean.getParParentID() + "." + type);
String path = ft.format(now) + "/" + parentsDataBean.getParParentID() + "." + type;
parentsDataBean.setParfilePath(path);
logger.debug(parentsDataBean.getParfilePath());
} else {
parentsDataBean.setParFile(null);
}
if(parentsBean.size()==0){
ParentsDataBean parents=new ParentsDataBean();
parents.setParStuClass(parentsDataBean.getParStuClass());
parents.setParStudID(parentsDataBean.getParStudID());
parentsBean.add(parents);
parentsDataBean.setParentdetails(parentsBean);
}else{
parentsDataBean.setParentdetails(parentsBean);
}
/*if(parentsDataBean.getParPhoneNo().startsWith("0")){
String phoneno=parentsDataBean.getParPhoneNo().substring(1);
parentsDataBean.setParPhoneNo(text.getString("sms.phno")+phoneno);
}else if(parentsDataBean.getParPhoneNo().startsWith(text.getString("sms.phno"))){
parentsDataBean.setParPhoneNo(parentsDataBean.getParPhoneNo());
}else{
parentsDataBean.setParPhoneNo(text.getString("sms.phno")+parentsDataBean.getParPhoneNo());
}*/
String status = controller.updateParent(personID, parentsDataBean);
if (status.equalsIgnoreCase("Success")) {
parentList = controller.getParentDetilsList(personID, parentsDataBean);
logger.debug("MB List Size" + parentList.size());
if (parentList.size() > 0) {
/*String pdfStatus = generatePdf(parentList, parentsDataBean);*/
MailSendJDBC.parentUpdate(parentsDataBean,schoolName,schoolid);
/*if (pdfStatus.equalsIgnoreCase("Success")){*/
/*String emailStatus = sendEmail(parentList, personID, parentsDataBean);
logger.debug("pdfStatus--" + pdfStatus + "emailStatus" + emailStatus);
if (pdfStatus.equalsIgnoreCase("Success") && emailStatus.equalsIgnoreCase("Success")) {*/
parentList = null;
ImageListPath = null;
RequestContext reqcontextt = RequestContext.getCurrentInstance();
reqcontextt.execute("PF('blockUIW').hide();");
reqcontextt.execute("PF('parentUpdateDialog').show();");
setBoxflag(true);
/*}*/
}
}
}
} catch (Exception e) {
logger.warn("Inside Exception",e);
}
return "";
}
/*private String sendEmail(List<ParentsDataBean> parentList2, String personID, ParentsDataBean parentsDataBean2) {
String status = "Fail";
try {
// String to="robertarjun46@gmail.com";
String to = parentsDataBean2.getParEmail();
Properties prop = new Properties();
prop.put("mail.smtp.host", text.getString("sms.mail.host"));
prop.put("mail.smtp.socketFactory.port", text.getString("sms.mail.port"));
prop.put("mail.smtp.socketFactory.class", text.getString("sms.mail.class"));
prop.put("mail.smtp.starttls.enable", text.getString("sms.mail.smtp.startles"));
prop.put("mail.smtp.auth", text.getString("sms.mail.auth"));
prop.put("mail.smtp.port", text.getString("sms.mail.smtp.port"));
prop.put("mail.smtp.ssl.trust", text.getString("sms.mail.smtp.trust"));
String body1 = "<htm><head></heade><body>"
+ " <header style='background-color:orange;color:white;height:50px;'>" + "<br></br>" + "<center>"
+ "<h1> Welcome to Student Monitoring System</h1><br></br></center>" + "</center>" + "</header>"
+ "<h3>Dear " + parentsDataBean2.getParParentID() + ",</h3>"
+ "<p>Welcome to join our Student Monitoring System. you can find the following features ."
+ "you can check your child report card, attendence,online payment,notice board and time table."
+ "also you can get our user name and password, from that you can check our website itself</p>"
+ "<br></br>" + "Your Profile is Updated" + "<footer>" + "<center>"
+ "<h4>© 2016 PT. Neotural Era Graha</h4>" + "</center>" + "</footer>" + "</body></html>";
Session session = Session.getInstance(prop, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("nrgsolutions.india@gmail.com", "Nrg@1234");
}
});
// compose message
try {
* session = Session.getInstance(prop, this);// this is the
* local variable not the instance one
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("nrgsolutions.india@gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("SMS Confirmation-" + parentsDataBean2.getParParentID());
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setContent(body1, "text/html");
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = paths.getString("sms.parents.pdf") + ft.format(now) + "/" + parentsDataBean2.getParParentID()
+ ".pdf";// change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(parentsDataBean2.getParParentID() + ".pdf");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
Transport.send(message);
logger.debug("message sent successfully");
status = "Success";
} catch (MessagingException e) {
throw new RuntimeException(e);
}
} catch (Exception e) {
logger.warn("Inside Exception",e);
logger.warn("Exception -->"+e.getMessage());
}
return status;
}*/
private String generatePdf(List<ParentsDataBean> parentList2, ParentsDataBean parentsDataBean2) {
String status = "fail";
SmsController controller = null;
try {
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
String schoolID=(String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("schoolID");
int schoolid=Integer.parseInt(schoolID);
if (personID != null) {
ImageListPath = new ArrayList<ParentsDataBean>();
logger.debug("parid-------" + parentsDataBean2.getParParentID());
ImageListPath = controller.getImagePath2(personID, parentsDataBean2.getParParentID());
logger.debug("image path size----------" + ImageListPath.size());
if (ImageListPath.size() > 0) {
// Create Directory
File files = new File(paths.getString("sms.parents.pdf") + ft.format(now));
if (!files.exists()) {
files.mkdirs();
} else {
logger.debug("Alreday Found");
}
// Write PDF File
OutputStream file = new FileOutputStream(
new File(files + paths.getString("path_context").toString() + parentsDataBean2.getParParentID() + ".pdf"));
parentsDataBean.setParfilePath(files +paths.getString("path_context").toString() + parentsDataBean2.getParParentID() + ".pdf");
Document document = new Document(PageSize.A4, 50, 50, 10, 50);
PdfWriter.getInstance(document, file);
document.open();
String logo ="";
if(schoolid==1 || schoolid==2 || schoolid==3 || schoolid==4 || schoolid==5 || schoolid==6){
logo = paths.getString(schoolID+"_LOGO");
document.add(Image.getInstance(getClass().getClassLoader().getResource(logo)));
}else{
logo = parentsDataBean.getSchoolLogo();
document.add(Image.getInstance(logo));
}
document.add(new Paragraph(
"------------------------------------------------------------------------------------------------------------------------"));
float[] columnWidths = { 20f, 1f };
//Font font3 = new Font(Font.TIMES_ROMAN, 27);
PdfPTable table = new PdfPTable(2); // .
table.setWidthPercentage(100f);
table.setWidths(columnWidths);
PdfPCell cell1 = new PdfPCell(new Paragraph());
cell1.setBorder(PdfPCell.NO_BORDER);
PdfPCell cell2 = new PdfPCell(new Paragraph());
cell2.setBorder(PdfPCell.NO_BORDER);
table.setSpacingBefore(10f);
table.setSpacingAfter(25f);
PdfPTable nestedTable = new PdfPTable(4);
nestedTable.setWidthPercentage(100f);
PdfPCell nesCell1 = new PdfPCell(new Paragraph("First Name:"));
PdfPCell nesCell2 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParFirstName()));
PdfPCell nesCell3 = new PdfPCell(new Paragraph("Last Name:"));
PdfPCell nesCell4 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParLastName()));
nesCell1.setBorder(PdfPCell.NO_BORDER);
nesCell2.setBorder(PdfPCell.NO_BORDER);
nesCell3.setBorder(PdfPCell.NO_BORDER);
nesCell4.setBorder(PdfPCell.NO_BORDER);
nestedTable.addCell(nesCell1);
nestedTable.addCell(nesCell2);
nestedTable.addCell(nesCell3);
nestedTable.addCell(nesCell4);
nestedTable.setSpacingBefore(3f);
nestedTable.setSpacingAfter(3f);
cell1.addElement(nestedTable);
if(ImageListPath.size()==1)
{
PdfPTable nestedTable1 = new PdfPTable(4);
nestedTable1.setWidthPercentage(100f);
PdfPCell nesCell5 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell6 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStudID()));
PdfPCell nesCell7 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell8 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStuClass()));
nesCell5.setBorder(PdfPCell.NO_BORDER);
nesCell6.setBorder(PdfPCell.NO_BORDER);
nesCell7.setBorder(PdfPCell.NO_BORDER);
nesCell8.setBorder(PdfPCell.NO_BORDER);
nestedTable1.addCell(nesCell5);
nestedTable1.addCell(nesCell6);
nestedTable1.addCell(nesCell7);
nestedTable1.addCell(nesCell8);
nestedTable1.setSpacingBefore(3f);
nestedTable1.setSpacingAfter(3f);
cell1.addElement(nestedTable1);
}
else if(ImageListPath.size()==2)
{
PdfPTable nestedTable1 = new PdfPTable(4);
nestedTable1.setWidthPercentage(100f);
PdfPCell nesCell5 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell6 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStudID()));
PdfPCell nesCell7 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell8 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStuClass()));
nesCell5.setBorder(PdfPCell.NO_BORDER);
nesCell6.setBorder(PdfPCell.NO_BORDER);
nesCell7.setBorder(PdfPCell.NO_BORDER);
nesCell8.setBorder(PdfPCell.NO_BORDER);
nestedTable1.addCell(nesCell5);
nestedTable1.addCell(nesCell6);
nestedTable1.addCell(nesCell7);
nestedTable1.addCell(nesCell8);
nestedTable1.setSpacingBefore(3f);
nestedTable1.setSpacingAfter(3f);
cell1.addElement(nestedTable1);
PdfPTable nestedTable11 = new PdfPTable(4);
nestedTable11.setWidthPercentage(100f);
PdfPCell nesCell51 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell61 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStudID()));
PdfPCell nesCell71 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell81 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStuClass()));
nesCell51.setBorder(PdfPCell.NO_BORDER);
nesCell61.setBorder(PdfPCell.NO_BORDER);
nesCell71.setBorder(PdfPCell.NO_BORDER);
nesCell81.setBorder(PdfPCell.NO_BORDER);
nestedTable11.addCell(nesCell51);
nestedTable11.addCell(nesCell61);
nestedTable11.addCell(nesCell71);
nestedTable11.addCell(nesCell81);
nestedTable11.setSpacingBefore(3f);
nestedTable11.setSpacingAfter(3f);
cell1.addElement(nestedTable11);
}
else if(ImageListPath.size()==3)
{
PdfPTable nestedTable1 = new PdfPTable(4);
nestedTable1.setWidthPercentage(100f);
PdfPCell nesCell5 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell6 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStudID()));
PdfPCell nesCell7 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell8 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStuClass()));
nesCell5.setBorder(PdfPCell.NO_BORDER);
nesCell6.setBorder(PdfPCell.NO_BORDER);
nesCell7.setBorder(PdfPCell.NO_BORDER);
nesCell8.setBorder(PdfPCell.NO_BORDER);
nestedTable1.addCell(nesCell5);
nestedTable1.addCell(nesCell6);
nestedTable1.addCell(nesCell7);
nestedTable1.addCell(nesCell8);
nestedTable1.setSpacingBefore(3f);
nestedTable1.setSpacingAfter(3f);
cell1.addElement(nestedTable1);
PdfPTable nestedTable11 = new PdfPTable(4);
nestedTable11.setWidthPercentage(100f);
PdfPCell nesCell51 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell61 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStudID()));
PdfPCell nesCell71 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell81 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStuClass()));
nesCell51.setBorder(PdfPCell.NO_BORDER);
nesCell61.setBorder(PdfPCell.NO_BORDER);
nesCell71.setBorder(PdfPCell.NO_BORDER);
nesCell81.setBorder(PdfPCell.NO_BORDER);
nestedTable11.addCell(nesCell51);
nestedTable11.addCell(nesCell61);
nestedTable11.addCell(nesCell71);
nestedTable11.addCell(nesCell81);
nestedTable11.setSpacingBefore(3f);
nestedTable11.setSpacingAfter(3f);
cell1.addElement(nestedTable11);
PdfPTable nestedTable12 = new PdfPTable(4);
nestedTable12.setWidthPercentage(100f);
PdfPCell nesCell52 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell62 = new PdfPCell(new Paragraph(ImageListPath.get(2).getParStudID()));
PdfPCell nesCell72 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell82 = new PdfPCell(new Paragraph(ImageListPath.get(2).getParStuClass()));
nesCell52.setBorder(PdfPCell.NO_BORDER);
nesCell62.setBorder(PdfPCell.NO_BORDER);
nesCell72.setBorder(PdfPCell.NO_BORDER);
nesCell82.setBorder(PdfPCell.NO_BORDER);
nestedTable12.addCell(nesCell52);
nestedTable12.addCell(nesCell62);
nestedTable12.addCell(nesCell72);
nestedTable12.addCell(nesCell82);
nestedTable12.setSpacingBefore(3f);
nestedTable12.setSpacingAfter(3f);
cell1.addElement(nestedTable12);
}
else if(ImageListPath.size()==4)
{
PdfPTable nestedTable1 = new PdfPTable(4);
nestedTable1.setWidthPercentage(100f);
PdfPCell nesCell5 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell6 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStudID()));
PdfPCell nesCell7 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell8 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStuClass()));
nesCell5.setBorder(PdfPCell.NO_BORDER);
nesCell6.setBorder(PdfPCell.NO_BORDER);
nesCell7.setBorder(PdfPCell.NO_BORDER);
nesCell8.setBorder(PdfPCell.NO_BORDER);
nestedTable1.addCell(nesCell5);
nestedTable1.addCell(nesCell6);
nestedTable1.addCell(nesCell7);
nestedTable1.addCell(nesCell8);
nestedTable1.setSpacingBefore(3f);
nestedTable1.setSpacingAfter(3f);
cell1.addElement(nestedTable1);
PdfPTable nestedTable11 = new PdfPTable(4);
nestedTable11.setWidthPercentage(100f);
PdfPCell nesCell51 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell61 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStudID()));
PdfPCell nesCell71 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell81 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStuClass()));
nesCell51.setBorder(PdfPCell.NO_BORDER);
nesCell61.setBorder(PdfPCell.NO_BORDER);
nesCell71.setBorder(PdfPCell.NO_BORDER);
nesCell81.setBorder(PdfPCell.NO_BORDER);
nestedTable11.addCell(nesCell51);
nestedTable11.addCell(nesCell61);
nestedTable11.addCell(nesCell71);
nestedTable11.addCell(nesCell81);
nestedTable11.setSpacingBefore(3f);
nestedTable11.setSpacingAfter(3f);
cell1.addElement(nestedTable11);
PdfPTable nestedTable12 = new PdfPTable(4);
nestedTable12.setWidthPercentage(100f);
PdfPCell nesCell52 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell62 = new PdfPCell(new Paragraph(ImageListPath.get(2).getParStudID()));
PdfPCell nesCell72 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell82 = new PdfPCell(new Paragraph(ImageListPath.get(2).getParStuClass()));
nesCell52.setBorder(PdfPCell.NO_BORDER);
nesCell62.setBorder(PdfPCell.NO_BORDER);
nesCell72.setBorder(PdfPCell.NO_BORDER);
nesCell82.setBorder(PdfPCell.NO_BORDER);
nestedTable12.addCell(nesCell52);
nestedTable12.addCell(nesCell62);
nestedTable12.addCell(nesCell72);
nestedTable12.addCell(nesCell82);
nestedTable12.setSpacingBefore(3f);
nestedTable12.setSpacingAfter(3f);
cell1.addElement(nestedTable12);
PdfPTable nestedTable13 = new PdfPTable(4);
nestedTable13.setWidthPercentage(100f);
PdfPCell nesCell53 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell63 = new PdfPCell(new Paragraph(ImageListPath.get(3).getParStudID()));
PdfPCell nesCell73 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell83 = new PdfPCell(new Paragraph(ImageListPath.get(3).getParStuClass()));
nesCell53.setBorder(PdfPCell.NO_BORDER);
nesCell63.setBorder(PdfPCell.NO_BORDER);
nesCell73.setBorder(PdfPCell.NO_BORDER);
nesCell83.setBorder(PdfPCell.NO_BORDER);
nestedTable13.addCell(nesCell53);
nestedTable13.addCell(nesCell63);
nestedTable13.addCell(nesCell73);
nestedTable13.addCell(nesCell83);
nestedTable13.setSpacingBefore(3f);
nestedTable13.setSpacingAfter(3f);
cell1.addElement(nestedTable13);
}
else if(ImageListPath.size()==5)
{
PdfPTable nestedTable1 = new PdfPTable(4);
nestedTable1.setWidthPercentage(100f);
PdfPCell nesCell5 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell6 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStudID()));
PdfPCell nesCell7 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell8 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParStuClass()));
nesCell5.setBorder(PdfPCell.NO_BORDER);
nesCell6.setBorder(PdfPCell.NO_BORDER);
nesCell7.setBorder(PdfPCell.NO_BORDER);
nesCell8.setBorder(PdfPCell.NO_BORDER);
nestedTable1.addCell(nesCell5);
nestedTable1.addCell(nesCell6);
nestedTable1.addCell(nesCell7);
nestedTable1.addCell(nesCell8);
nestedTable1.setSpacingBefore(3f);
nestedTable1.setSpacingAfter(3f);
cell1.addElement(nestedTable1);
PdfPTable nestedTable11 = new PdfPTable(4);
nestedTable11.setWidthPercentage(100f);
PdfPCell nesCell51 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell61 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStudID()));
PdfPCell nesCell71 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell81 = new PdfPCell(new Paragraph(ImageListPath.get(1).getParStuClass()));
nesCell51.setBorder(PdfPCell.NO_BORDER);
nesCell61.setBorder(PdfPCell.NO_BORDER);
nesCell71.setBorder(PdfPCell.NO_BORDER);
nesCell81.setBorder(PdfPCell.NO_BORDER);
nestedTable11.addCell(nesCell51);
nestedTable11.addCell(nesCell61);
nestedTable11.addCell(nesCell71);
nestedTable11.addCell(nesCell81);
nestedTable11.setSpacingBefore(3f);
nestedTable11.setSpacingAfter(3f);
cell1.addElement(nestedTable11);
PdfPTable nestedTable12 = new PdfPTable(4);
nestedTable12.setWidthPercentage(100f);
PdfPCell nesCell52 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell62 = new PdfPCell(new Paragraph(ImageListPath.get(2).getParStudID()));
PdfPCell nesCell72 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell82 = new PdfPCell(new Paragraph(ImageListPath.get(2).getParStuClass()));
nesCell52.setBorder(PdfPCell.NO_BORDER);
nesCell62.setBorder(PdfPCell.NO_BORDER);
nesCell72.setBorder(PdfPCell.NO_BORDER);
nesCell82.setBorder(PdfPCell.NO_BORDER);
nestedTable12.addCell(nesCell52);
nestedTable12.addCell(nesCell62);
nestedTable12.addCell(nesCell72);
nestedTable12.addCell(nesCell82);
nestedTable12.setSpacingBefore(3f);
nestedTable12.setSpacingAfter(3f);
cell1.addElement(nestedTable12);
PdfPTable nestedTable13 = new PdfPTable(4);
nestedTable13.setWidthPercentage(100f);
PdfPCell nesCell53 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell63 = new PdfPCell(new Paragraph(ImageListPath.get(3).getParStudID()));
PdfPCell nesCell73 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell83 = new PdfPCell(new Paragraph(ImageListPath.get(3).getParStuClass()));
nesCell53.setBorder(PdfPCell.NO_BORDER);
nesCell63.setBorder(PdfPCell.NO_BORDER);
nesCell73.setBorder(PdfPCell.NO_BORDER);
nesCell83.setBorder(PdfPCell.NO_BORDER);
nestedTable13.addCell(nesCell53);
nestedTable13.addCell(nesCell63);
nestedTable13.addCell(nesCell73);
nestedTable13.addCell(nesCell83);
nestedTable13.setSpacingBefore(3f);
nestedTable13.setSpacingAfter(3f);
cell1.addElement(nestedTable13);
PdfPTable nestedTable14 = new PdfPTable(4);
nestedTable14.setWidthPercentage(100f);
PdfPCell nesCell54 = new PdfPCell(new Paragraph("Student ID:"));
PdfPCell nesCell64 = new PdfPCell(new Paragraph(ImageListPath.get(4).getParStudID()));
PdfPCell nesCell74 = new PdfPCell(new Paragraph("Student Class:"));
PdfPCell nesCell84 = new PdfPCell(new Paragraph(ImageListPath.get(4).getParStuClass()));
nesCell54.setBorder(PdfPCell.NO_BORDER);
nesCell64.setBorder(PdfPCell.NO_BORDER);
nesCell74.setBorder(PdfPCell.NO_BORDER);
nesCell84.setBorder(PdfPCell.NO_BORDER);
nestedTable14.addCell(nesCell54);
nestedTable14.addCell(nesCell64);
nestedTable14.addCell(nesCell74);
nestedTable14.addCell(nesCell84);
nestedTable14.setSpacingBefore(3f);
nestedTable14.setSpacingAfter(3f);
cell1.addElement(nestedTable14);
}
PdfPTable nestedTable2 = new PdfPTable(4);
nestedTable2.setWidthPercentage(100f);
PdfPCell nesCell9 = new PdfPCell(new Paragraph("Phone number:"));
PdfPCell nesCell10 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParPhoneNo()));
PdfPCell nesCell11 = new PdfPCell(new Paragraph("Email ID:"));
PdfPCell nesCell12 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParEmail()));
nesCell9.setBorder(PdfPCell.NO_BORDER);
nesCell10.setBorder(PdfPCell.NO_BORDER);
nesCell11.setBorder(PdfPCell.NO_BORDER);
nesCell12.setBorder(PdfPCell.NO_BORDER);
nestedTable2.addCell(nesCell9);
nestedTable2.addCell(nesCell10);
nestedTable2.addCell(nesCell11);
nestedTable2.addCell(nesCell12);
nestedTable2.setSpacingBefore(3f);
nestedTable2.setSpacingAfter(3f);
cell1.addElement(nestedTable2);
PdfPTable nestedTable3 = new PdfPTable(4);
nestedTable3.setWidthPercentage(100f);
PdfPCell nesCell13 = new PdfPCell(new Paragraph("Relation:"));
PdfPCell nesCell14 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParentRelation()));
PdfPCell nesCell15 = new PdfPCell(new Paragraph("Parent ID:"));
PdfPCell nesCell16 = new PdfPCell(new Paragraph(ImageListPath.get(0).getParParentID()));
nesCell13.setBorder(PdfPCell.NO_BORDER);
nesCell14.setBorder(PdfPCell.NO_BORDER);
nesCell15.setBorder(PdfPCell.NO_BORDER);
nesCell16.setBorder(PdfPCell.NO_BORDER);
nestedTable3.addCell(nesCell13);
nestedTable3.addCell(nesCell14);
nestedTable3.addCell(nesCell15);
nestedTable3.addCell(nesCell16);
nestedTable3.setSpacingBefore(3f);
nestedTable3.setSpacingAfter(3f);
cell1.addElement(nestedTable3);
PdfPTable nestedTable9 = new PdfPTable(4);
nestedTable9.setWidthPercentage(100f);
PdfPCell nesCell33 = new PdfPCell(new Paragraph());
PdfPCell nesCell34 = new PdfPCell(new Paragraph());
PdfPCell nesCell35 = new PdfPCell(new Paragraph("Photo"));
String tempdate = ft.format(ImageListPath.get(0).getParPathDate());
String imageLocation = paths.getString("sms.parents.photo") + tempdate + "/"
+ ImageListPath.get(0).getParfilePath();
//Image image = Image.getInstance(imageLocation);
//image.scaleAbsolute(100, 100);
//PdfPCell nesCell36 = new PdfPCell(image, false);
nesCell33.setBorder(PdfPCell.NO_BORDER);
nesCell34.setBorder(PdfPCell.NO_BORDER);
nesCell35.setBorder(PdfPCell.NO_BORDER);
//nesCell36.setBorder(PdfPCell.NO_BORDER);
nestedTable9.addCell(nesCell35);
//nestedTable9.addCell(nesCell36);
nestedTable9.addCell(nesCell33);
nestedTable9.addCell(nesCell34);
nestedTable9.setSpacingBefore(3f);
nestedTable9.setSpacingAfter(3f);
cell1.addElement(nestedTable9);
table.addCell(cell1);
table.addCell(cell2);
document.add(table);
document.close();
file.close();
/*
* //PDF open Windows and MAC File pdfFile = new
* File(files+paths.getString("path_context").toString()+parentsDataBean2.getParUsername()+".pdf")
* ; if(pdfFile.exists()){ if (Desktop.isDesktopSupported())
* { Desktop.getDesktop().open(pdfFile); } else {
* logger.debug("Awt Desktop is not supported!"); }
*
* } else { logger.debug("File is not exists!"); }
*/
logger.debug("Done");
status = "Success";
}
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
return status;
}
private void copyFile(String fileName, InputStream inputstream, String n) {
try {
// Create Directory
File files = new File(paths.getString("sms.parents.photo") + ft.format(now));
if (!files.exists()) {
files.mkdirs();
} else {
logger.debug("Alreday Found");
}
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(files + paths.getString("path_context").toString() + fileName + "." + n));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputstream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputstream.close();
out.flush();
out.close();
logger.debug("New file created!");
} catch (IOException e) {
logger.debug(e.getMessage());
}
}
public boolean validate1(boolean flag) {
boolean valid = true;
String fieldName;
FacesContext fc = FacesContext.getCurrentInstance();
if(parentsBean.size()==0)
{
if (parentsDataBean.getParStuClass().equalsIgnoreCase("Choose")) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parClassID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.select")));
}
valid = false;
}
if (StringUtils.isBlank(parentsDataBean.getParStudID())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parStudentID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.studentID")));
}
valid = false;
} else if (!StringUtils.isBlank(parentsDataBean.getParStudID())) {
if (parentsDataBean.getParStudID().length() < 3) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parStudentID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vstudentID")));
}
valid = false;
}
}
}
if (StringUtils.isEmpty(parentsDataBean.getParFirstName())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parFName").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.fname")));
}
valid = false;
} else if (!StringUtils.isEmpty(parentsDataBean.getParFirstName())) {
if (!CommonValidate.validateName(parentsDataBean.getParFirstName())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parFName").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vfname")));
}
valid = false;
} else if (parentsDataBean.getParFirstName().length() < 3) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parFName").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vfname")));
}
valid = false;
}
}
/*if (StringUtils.isEmpty(parentsDataBean.getParLastName())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parLName").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.lname")));
}
valid = false;
} else if (!StringUtils.isEmpty(parentsDataBean.getParLastName())) {
if (!CommonValidate.validateName(parentsDataBean.getParLastName())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parLName").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vlame")));
}
valid = false;
} else if (parentsDataBean.getParLastName().length() < 3) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parLName").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vlame")));
}
valid = false;
}
}
*/
if (StringUtils.isEmpty(parentsDataBean.getCountryCode())) {
/*if (flag) {
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.teacher.CountryCode")));
}
valid = false;*/
}
else{
if (StringUtils.isEmpty(parentsDataBean.getParPhoneNo())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.phno")));
}
valid = false;
} else if (!StringUtils.isEmpty(parentsDataBean.getParPhoneNo())) {
if(!CommonValidate.validateNumberOnly(parentsDataBean.getParPhoneNo())){
if (flag) {
System.out.println("----->inside number format val----->");
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.teacher.phonenumberinvalid")));
}
valid = false;
}
else if(!CommonValidate.countryValidateNumber(parentsDataBean.getParPhoneNo(),parentsDataBean.getCountryCode().split("-")[1])){
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
if (parentsDataBean.getCountryCode().split("-")[1].equalsIgnoreCase("INDIA")) {
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.india.phonevalidation")));
}
else if (parentsDataBean.getCountryCode().split("-")[1].equalsIgnoreCase("UAE")) {
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.uae.phonevalidation")));
}
else if (parentsDataBean.getCountryCode().split("-")[1].equalsIgnoreCase("INDONESIA")) {
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.indonesia.phonevalidation")));
}
else if (parentsDataBean.getCountryCode().split("-")[1].equalsIgnoreCase("MALAYSIA")) {
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.malaysia.phonevalidation")));
}
valid = false;
}
}
}
if (StringUtils.isEmpty(parentsDataBean.getParentRelation())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parRelation").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.relation")));
}
valid = false;
} else if (!StringUtils.isEmpty(parentsDataBean.getParentRelation())) {
if (!CommonValidate.validateName(parentsDataBean.getParentRelation())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parRelation").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vrelation")));
}
valid = false;
} else if (parentsDataBean.getParentRelation().length() < 3) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parRelation").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vrelation")));
}
valid = false;
}
}
if (StringUtils.isEmpty(parentsDataBean.getParParentID())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parParentID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.parentId")));
}
valid = false;
} else if (!StringUtils.isEmpty(parentsDataBean.getParParentID())) {
if (parentsDataBean.getParParentID().length() < 3) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parParentID").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vparentID")));
}
valid = false;
}
}
/*if (StringUtils.isEmpty(parentsDataBean.getParEmail())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parE-mail").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.email")));
}
valid = false;
} else*/ if (!StringUtils.isEmpty(parentsDataBean.getParEmail())) {
if (!CommonValidate.validateEmail(parentsDataBean.getParEmail())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parE-mail").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.vemail")));
}
valid = false;
}
}
/*if (StringUtils.isEmpty(parentsDataBean.getParPhoneNo())) {
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.parent.phno")));
}
valid = false;
} else if (!StringUtils.isEmpty(parentsDataBean.getParPhoneNo())) {
if(!CommonValidate.validateNumber(parentsDataBean.getParPhoneNo())){
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.teacher.phonenumberinvalid")));
}
valid = false;
}else if(Integer.parseInt(parentsDataBean.getParPhoneNo() <= 0){
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.teacher.phonenumberinvalid")));
}
valid = false;
}
else if(parentsDataBean.getParPhoneNo().length() < 11){
if (flag) {
fieldName = CommonValidate.findComponentInRoot("parPhone").getClientId(fc);
fc.addMessage(fieldName, new FacesMessage(text.getString("sms.teacher.phonenumberinvalid")));
}
valid = false;
}
}*/
return valid;
}
public void preProcessPDF(Object document) throws BadElementException, DocumentException, IOException {
String schoolID=(String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("schoolID");
int schoolid=Integer.parseInt(schoolID);
String logo ="";
Document pdf = (Document) document;
pdf.open();
pdf.setPageSize(PageSize.A4);
if(schoolid==1 || schoolid==2 || schoolid==3 || schoolid==4 || schoolid==5 || schoolid==6){
logo = paths.getString(schoolID+"_LOGO");
pdf.add(Image.getInstance(getClass().getClassLoader().getResource(logo)));
}else{
logo=MailSendJDBC.pdfProcess(schoolid);
logger.debug("logo "+logo);
pdf.add(Image.getInstance(logo));
}
pdf.add(new Paragraph(
"------------------------------------------------------------------------------------------------------------------------"));
}
public void view() {
SmsController controller = null;
try {
parentList = new ArrayList<ParentsDataBean>();
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
logger.debug("-----Inside call Parents view method ------" + parentsDataBean.getParParentID());
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
if (personID != null) {
parentList = controller.getParentDetilsList(personID, parentsDataBean);
if (parentList.size() > 0) {
if (parentList.get(0).getParentList().size() > 0) {
parentsDataBean.setParParentID(parentList.get(0).getParentList().get(0).getRollNumber());
} else {
parentsDataBean.setParParentID("");
}
if (parentList.get(0).getParentDetailsList().size() > 0) {
parentsDataBean.setName(parentList.get(0).getParentDetailsList().get(0).getFirstName() + " "
+ parentList.get(0).getParentDetailsList().get(0).getLastName());
parentsDataBean.setParEmail(parentList.get(0).getParentDetailsList().get(0).getEmaiId());
parentsDataBean
.setParentRelation(parentList.get(0).getParentDetailsList().get(0).getRelation());
parentsDataBean.setParPhoneNo(parentList.get(0).getParentDetailsList().get(0).getPhoneNumber());
//parentsDataBean.setCountryCode(parentList.get(0).getParentDetailsList().get(0).getCountryCode());
parentsDataBean.setCountryCode(parentList.get(0).getParentDetailsList().get(0).getCountrycode());
} else {
parentsDataBean.setName("");
parentsDataBean.setParEmail("");
parentsDataBean.setParentRelation("");
parentsDataBean.setParPhoneNo("");
}
if (parentList.get(0).getParentImageList().size() > 0) {
parentsDataBean.setParfilePath(parentList.get(0).getParentImageList().get(0).getPath());
parentsDataBean.setParPathDate(parentList.get(0).getParentImageList().get(0).getDate());
} else {
parentsDataBean.setParfilePath("");
parentsDataBean.setParPathDate(null);
}
if (parentList.get(0).getParentdetails().size() > 0) {
for (int i = 0; i < parentList.get(0).getParentdetails().size(); i++) {
logger.debug("id "+
parentList.get(0).getParentdetails().get(i).getName());
if(parentList.get(0).getParentdetails().size()==1) parentsDataBean.setParStudID(
parentList.get(0).getParentdetails().get(0).getName());
else if(parentList.get(0).getParentdetails().size()==2) parentsDataBean.setParStudID(
parentList.get(0).getParentdetails().get(0).getName()+" , "+
parentList.get(0).getParentdetails().get(1).getName());
else if(parentList.get(0).getParentdetails().size()==3) parentsDataBean.setParStudID(
parentList.get(0).getParentdetails().get(0).getName()+" , "+
parentList.get(0).getParentdetails().get(1).getName()+" , "+
parentList.get(0).getParentdetails().get(2).getName());
else if(parentList.get(0).getParentdetails().size()==4) parentsDataBean.setParStudID(
parentList.get(0).getParentdetails().get(0).getName()+" , "+
parentList.get(0).getParentdetails().get(1).getName()+" , "+
parentList.get(0).getParentdetails().get(2).getName()+" , "+
parentList.get(0).getParentdetails().get(3).getName());
else if(parentList.get(0).getParentdetails().size()==5) parentsDataBean.setParStudID(
parentList.get(0).getParentdetails().get(0).getName()+" , "+
parentList.get(0).getParentdetails().get(1).getName()+" , "+
parentList.get(0).getParentdetails().get(2).getName()+" , "+
parentList.get(0).getParentdetails().get(3).getName()+" , "+
parentList.get(0).getParentdetails().get(4).getName());
}
logger.debug("student ID "+parentsDataBean.getParStudID());
} else {
parentsDataBean.setParStudID("");
}
} else {
parentsDataBean.setParParentID("");
parentsDataBean.setParStudID("");
parentsDataBean.setParfilePath("");
parentsDataBean.setParPathDate(null);
parentsDataBean.setName("");
parentsDataBean.setParEmail("");
parentsDataBean.setParentRelation("");
parentsDataBean.setParPhoneNo("");
}
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
}
public String edit() {
SmsController controller = null;
studentIDList = null;
classSectionList = null;
try {
parentList = new ArrayList<ParentsDataBean>();
studentIDList = new ArrayList<String>();
classSectionList = new ArrayList<String>();
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
controller = (SmsController) ctx.getBean("controller");
logger.debug("-----Inside call Parents view method ------" + parentsDataBean.getParParentID());
String personID = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("LogID");
if (personID != null) {
parentList = controller.getParentDetilsList(personID, parentsDataBean);
if (parentList.size() > 0) {
if (parentList.get(0).getParentList().size() > 0) {
parentsDataBean.setParParentID(parentList.get(0).getParentList().get(0).getRollNumber());
} else {
parentsDataBean.setParParentID("");
}
if (parentList.get(0).getParentDetailsList().size() > 0) {
parentsDataBean.setName(parentList.get(0).getParentDetailsList().get(0).getFirstName() + " "
+ parentList.get(0).getParentDetailsList().get(0).getLastName());
parentsDataBean.setParEmail(parentList.get(0).getParentDetailsList().get(0).getEmaiId());
parentsDataBean
.setParentRelation(parentList.get(0).getParentDetailsList().get(0).getRelation());
parentsDataBean.setParPhoneNo(parentList.get(0).getParentDetailsList().get(0).getPhoneNumber());
parentsDataBean.setParFirstName(parentList.get(0).getParentDetailsList().get(0).getFirstName());
parentsDataBean.setParLastName(parentList.get(0).getParentDetailsList().get(0).getLastName());
parentsDataBean.setCountryCode(CommonValidate.phonenumbercode(parentList.get(0).getParentDetailsList().get(0).getCountrycode()));
} else {
parentsDataBean.setName("");
parentsDataBean.setParEmail("");
parentsDataBean.setParentRelation("");
parentsDataBean.setParPhoneNo("");
parentsDataBean.setCountryCode("");
}
if (parentList.get(0).getParentImageList().size() > 0) {
parentsDataBean.setParfilePath(parentList.get(0).getParentImageList().get(0).getPath());
parentsDataBean.setParPathDate(parentList.get(0).getParentImageList().get(0).getDate());
} else {
parentsDataBean.setParfilePath("");
parentsDataBean.setParPathDate(null);
}
if (parentList.get(0).getParentdetails().size() > 0) {
parentsBean=new ArrayList<ParentsDataBean>();
for (int i = 0; i < parentList.get(0).getParentdetails().size(); i++) {
ParentsDataBean students=new ParentsDataBean();
students.setParStudID(parentList.get(0).getParentdetails().get(i).getName());
students.setParStuClass(parentList.get(0).getStudentClass().get(i));
parentsBean.add(students);
}
parentsDataBean.setParStuClass("");
logger.debug(parentsBean.size());
} else {
parentsDataBean.setParStudID("");
parentsDataBean.setParStuClass("");
}
} else {
parentsDataBean.setParParentID("");
parentsDataBean.setParStudID("");
parentsDataBean.setParfilePath("");
parentsDataBean.setParPathDate(null);
parentsDataBean.setName("");
parentsDataBean.setParEmail("");
parentsDataBean.setParentRelation("");
parentsDataBean.setParPhoneNo("");
}
logger.debug("----->" + parentsDataBean.getParStuClass());
classSectionList = controller.getClassSection(personID);
studentIDList = controller.getStudentRollNumber(personID, parentsDataBean.getParStuClass());
}
} catch (Exception e) {
logger.warn("Exception -->"+e.getMessage());
}
return "parentEditPage";
}
public void phonenumberclear(ValueChangeEvent v){
parentsDataBean.setParPhoneNo("");
}
}
| true
|
803405197e6559a54284b8d202f2a5d8c06616cd
|
Java
|
mast-group/codemining-core
|
/src/main/java/codemining/js/codeutils/binding/AbstractJavascriptNameBindingsExtractor.java
|
UTF-8
| 5,807
| 2.1875
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
/**
*
*/
package codemining.js.codeutils.binding;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import org.apache.commons.io.FileUtils;
import org.eclipse.wst.jsdt.core.dom.ASTNode;
import codemining.js.codeutils.JavascriptASTExtractor;
import codemining.js.codeutils.JavascriptTokenizer;
import codemining.languagetools.bindings.AbstractNameBindingsExtractor;
import codemining.languagetools.bindings.ResolvedSourceCode;
import codemining.languagetools.bindings.TokenNameBinding;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* A name bindings extractor interface for Javascript.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public abstract class AbstractJavascriptNameBindingsExtractor extends
AbstractNameBindingsExtractor {
public static Set<String> getFeatures(final Set<ASTNode> boundAstNodes) {
// TODO
return Collections.emptySet();
}
public static ResolvedSourceCode getResolvedSourceCode(
final String sourceCode, final Set<Set<ASTNode>> nodeBindings) {
final JavascriptTokenizer tokenizer = new JavascriptTokenizer();
final SortedMap<Integer, String> tokenPositions = tokenizer
.tokenListWithPos(sourceCode.toCharArray());
final SortedMap<Integer, Integer> positionToIndex = getTokenIndexForPostion(tokenPositions);
final List<String> tokens = Lists.newArrayList(tokenPositions.values());
final ArrayListMultimap<String, TokenNameBinding> bindings = ArrayListMultimap
.create();
for (final Set<ASTNode> boundName : nodeBindings) {
if (boundName.isEmpty()) {
continue;
}
final List<Integer> boundPositions = Lists.newArrayList();
for (final ASTNode name : boundName) {
// Convert position to token index and add
final int tokenIdx = positionToIndex.get(name
.getStartPosition());
boundPositions.add(tokenIdx);
}
bindings.put(tokens.get(boundPositions.get(0)),
new TokenNameBinding(Sets.newTreeSet(boundPositions),
tokens, getFeatures(boundName)));
}
return new ResolvedSourceCode(tokens, bindings);
}
/**
* Get the token bindings given the ASTNode bindings and the source code
* positions.
*
* @param sourceCode
* @param nodeBindings
* @return
*/
public static List<TokenNameBinding> getTokenBindings(
final String sourceCode, final Set<Set<ASTNode>> nodeBindings) {
final JavascriptTokenizer tokenizer = new JavascriptTokenizer();
final SortedMap<Integer, String> tokenPositions = tokenizer
.tokenListWithPos(sourceCode.toCharArray());
final SortedMap<Integer, Integer> positionToIndex = getTokenIndexForPostion(tokenPositions);
final List<String> tokens = Lists.newArrayList(tokenPositions.values());
final List<TokenNameBinding> bindings = Lists.newArrayList();
for (final Set<ASTNode> boundName : nodeBindings) {
final List<Integer> boundPositions = Lists.newArrayList();
for (final ASTNode name : boundName) {
// Convert position to token index and add
final int tokenIdx = positionToIndex.get(name
.getStartPosition());
boundPositions.add(tokenIdx);
}
bindings.add(new TokenNameBinding(Sets.newTreeSet(boundPositions),
tokens, getFeatures(boundName)));
}
return bindings;
}
/**
* Return the token index for the given position.
*
* @param sourceCode
* @return
*/
protected static SortedMap<Integer, Integer> getTokenIndexForPostion(
final SortedMap<Integer, String> tokenPositions) {
final SortedMap<Integer, Integer> positionToIndex = Maps.newTreeMap();
int i = 0;
for (final int position : tokenPositions.keySet()) {
positionToIndex.put(position, i);
i++;
}
return positionToIndex;
}
protected JavascriptASTExtractor createExtractor() {
return new JavascriptASTExtractor(false);
}
/**
* Return a set of sets of SimpleName ASTNode objects that are bound
* together
*
* @param node
* @return
*/
public abstract Set<Set<ASTNode>> getNameBindings(final ASTNode node);
/**
* Get the name bindings for the given ASTNode. This assumes that the
* ASTNode has been produced by the sourceCode, code with no variation.
*
* @param node
* the ASTNode where bindings will be computed.
* @param sourceCode
* the sourceCode from which the ASTNode has been extracted.
* @return
*/
public final List<TokenNameBinding> getNameBindings(final ASTNode node,
final String sourceCode) {
final Set<Set<ASTNode>> nodeBindings = getNameBindings(node);
return getTokenBindings(sourceCode, nodeBindings);
}
@Override
public List<TokenNameBinding> getNameBindings(final File f)
throws IOException {
final JavascriptASTExtractor ex = createExtractor();
return getNameBindings(ex.getAST(f), FileUtils.readFileToString(f));
}
@Override
public List<TokenNameBinding> getNameBindings(final String code) {
final JavascriptASTExtractor ex = createExtractor();
try {
return getNameBindings(ex.getCompilationUnitAstNode(code), code);
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
}
@Override
public ResolvedSourceCode getResolvedSourceCode(final File f)
throws IOException {
final JavascriptASTExtractor ex = createExtractor();
return getResolvedSourceCode(FileUtils.readFileToString(f),
getNameBindings(ex.getAST(f)));
}
@Override
public ResolvedSourceCode getResolvedSourceCode(final String code) {
final JavascriptASTExtractor ex = createExtractor();
try {
return getResolvedSourceCode(code,
getNameBindings(ex.getCompilationUnitAstNode(code)));
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
}
}
| true
|
c01de7bf45caddb42c300ad4df281b570d0d24c4
|
Java
|
farvher/tam
|
/src/main/java/co/com/tam/dto/GenerosDto.java
|
UTF-8
| 1,007
| 2.109375
| 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 co.com.tam.dto;
import java.util.List;
/**
*
* @author geotor
*/
public class GenerosDto {
private Integer generoid;
private String genero;
private List<UsuariosDto> usuariosList;
public GenerosDto() {
}
public GenerosDto(Integer generoid) {
this.generoid = generoid;
}
public Integer getGeneroid() {
return generoid;
}
public void setGeneroid(Integer generoid) {
this.generoid = generoid;
}
public String getGenero() {
return genero;
}
public void setGenero(String genero) {
this.genero = genero;
}
public List<UsuariosDto> getUsuariosList() {
return usuariosList;
}
public void setUsuariosList(List<UsuariosDto> usuariosList) {
this.usuariosList = usuariosList;
}
}
| true
|
f89096292254f19a99156cbcbc80d468add566f8
|
Java
|
xiaoqiangOB/translage
|
/src/main/java/edu/ahut/MainController.java
|
UTF-8
| 1,543
| 1.953125
| 2
|
[] |
no_license
|
package edu.ahut;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import edu.ahut.entity.Enwords;
import edu.ahut.service.EnwordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @Author wengxiaofeng
* @Description:英译汉controller
* @Data create in 15:00 2018/3/2.
* @Modified by:
*/
@RestController
@RequestMapping(value = "/eng")
public class MainController {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private EnwordsService enwordsService;
//@ResponseBody
@RequestMapping(value="/ETC",method = RequestMethod.POST)
String queryFromEnglishToChinese(){
List<Map<String,Object>> list = jdbcTemplate.queryForList("select *from enwords where word like 'abandon%'");
return JSONArray.toJSONString(list);
}
@RequestMapping(value = "/search",method = RequestMethod.POST)
String test(@RequestBody Enwords enwords){
List<Enwords> list = enwordsService.translateETC(enwords);
return JSONArray.toJSONString(list);
}
@RequestMapping(value = "/tips",method = RequestMethod.POST)
String queryById(@RequestBody Enwords enwords){
List<Enwords> result = enwordsService.tips(enwords);
return JSONArray.toJSONString(result);
}
}
| true
|
600cb0a0a33e2861fd4847e52fb7738c2060eee7
|
Java
|
bilelkhalsi/ioServices
|
/service-oidc-autoconfigure/src/main/java/io/services/autoconfigure/GrantedRolesExtractor.java
|
UTF-8
| 1,420
| 2.1875
| 2
|
[] |
no_license
|
package io.services.autoconfigure;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import java.util.*;
import java.util.stream.Collectors;
/**
* Jwt to user granted roles converter.
*/
public final class GrantedRolesExtractor implements Converter<Jwt, Collection<GrantedAuthority>> {
private static final String AUTHORITY_PREFIX = "ROLE_";
private static final List<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("realm_access");
private static final String WELL_KNOWN_ROLES_FIELD_NAME = "roles";
public Collection<GrantedAuthority> convert(Jwt jwt) {
List<String> claimRoles = WELL_KNOWN_AUTHORITIES_CLAIM_NAMES.stream()
.filter(name -> jwt.getClaims().containsKey(name))
.map(name -> (Map<String, Object>) jwt.getClaims().get(name))
.map(claimAuthorities -> (List<String>) claimAuthorities.getOrDefault(WELL_KNOWN_ROLES_FIELD_NAME, Collections.emptyList()))
.findFirst()
.orElse(Collections.emptyList());
return claimRoles
.stream()
.map(role -> new SimpleGrantedAuthority(AUTHORITY_PREFIX + role))
.collect(Collectors.toList());
}
}
| true
|
a15e8ff465d568bdc8bae40eedd3333d78f35edb
|
Java
|
myorganizationqq/cole-project
|
/src/test/java/com/test/PrivilegeTest.java
|
UTF-8
| 3,359
| 2.0625
| 2
|
[] |
no_license
|
/*
package com.test;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.cole.bean.Page;
import com.cole.project.web.dao.demo.DynamicSqlMapper;
import com.cole.project.web.entity.Logs;
import com.cole.project.web.service.authorization.LogsService;
import com.cole.project.web.service.authorization.ResourceService;
import com.cole.project.web.service.authorization.UserService;
import com.cole.project.web.service.demo.DynamicSqlService;
import com.cole.project.web.service.demo.TransactionFunService;
import com.cole.util.StringUtils;
import com.cole.util.timecategories.TimePoints;
import com.cole.web.bean.AjaxResult;
//首先指定Junit的Runner
@RunWith(SpringJUnit4ClassRunner.class)
// 指明配置文件所在
@ContextConfiguration(locations = "classpath:config/application.xml")
// 指定事务管理器
@Transactional(value = "commonTransactionManager")
// 继承AbstractTransactionalJUnit4SpringContextTests来获取Spring上下文环境来获取Bean
public class PrivilegeTest extends AbstractTransactionalJUnit4SpringContextTests {
// @Autowired
// PrivilegeManagementController privilegeManagementController;
@Autowired
ResourceService resourceService;
@Autowired
TransactionFunService transactionFunService;
@Autowired
DynamicSqlService dynamicSqlService;
@Autowired
UserService userService;
@Autowired
LogsService logsService;
// JUnit注解 ,表明这是一个需要运行的测试方法
@Test
public void test0(){
logsService.getDataList(new Logs(), null, null, new Page());
}
@Test
public void test() {
// AjaxResult ajaxResult=AjaxResult.getFailResult();
// System.out.println(ajaxResult.toJsonString());
// resourceService.findAllResource();
Date startTime = new Date(2017 - 1900, 01, 14, 17, 00, 0);
Date endTime = new Date(2017 - 1900, 01, 14, 18, 00, 00);
// AjaxResult ajaxResult =
// transactionFunService.findTransactionFun(startTime,endTime);
AjaxResult ajaxResult = dynamicSqlService.findAllDataListPage("Redis GET", startTime, endTime);
System.out.println(ajaxResult.toJsonString());
List<Date> categories = TimePoints.getTimePoints(startTime, endTime);
System.out.println(categories.toString());
}
@Test
public void test1() {
// AjaxResult ajaxResult=AjaxResult.getFailResult();
// System.out.println(ajaxResult.toJsonString());
// resourceService.findAllResource();
Date startTime = new Date(2017 - 1900, 01, 14, 17, 00, 0);
Date endTime = new Date(2017 - 1900, 01, 14, 18, 00, 00);
// AjaxResult ajaxResult =
// transactionFunService.findTransactionFun(startTime,endTime);
AjaxResult ajaxResult = dynamicSqlService.findAllData("Redis GET", startTime, endTime);
System.out.println(ajaxResult.toJsonString());
List<Date> categories = TimePoints.getTimePoints(startTime, endTime);
System.out.println(categories.toString());
}
}
*/
| true
|
2c3a38bd8607b5553b2c561a01c8e5a99bb0f440
|
Java
|
woodspring/SpringHeight
|
/TT-ADAPTOR/.svn/pristine/69/69d9b267865797703827535dc7a50cf4151f1811.svn-base
|
UTF-8
| 133
| 1.625
| 2
|
[] |
no_license
|
package com.tts.mde.support;
public interface IMasGlobolSequenceProvider {
long getNewSequence();
long getCurrentSequence();
}
| true
|
275bbaa8fbe0f1489f4a75f95d4ec94991daf5ec
|
Java
|
strawhatcode/springboot-study
|
/09_spring_cloud_config/spring-cloud-config-client/src/main/java/com/example/configclient/controller/TestController.java
|
UTF-8
| 725
| 1.960938
| 2
|
[] |
no_license
|
package com.example.configclient.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.ProtectionDomain;
@RestController
@RefreshScope //刷新注解,使用http://127.0.0.1:8202/actuator/bus-refresh可以刷新
public class TestController {
@Value("${test}") //引用配置文件中的test属性
String test;
@Value("${server.port}")
String port;
@GetMapping("/gettest")
public String gettest(){
return "端口号【"+ port +"】"+test;
}
}
| true
|
f354c574bc788c1e9bc2410d5a192e8c6e832193
|
Java
|
dz-forever/baidu-image
|
/src/main/java/com/dzforever/webmagic/ImageProcessor.java
|
UTF-8
| 3,229
| 1.984375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.dzforever.webmagic;
import com.dzforever.pojo.ImageSrc;
import com.dzforever.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.scheduler.QueueScheduler;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
@Transactional
public class ImageProcessor implements PageProcessor {
private List<ImageSrc> imageSrcs = new ArrayList<>();
@Autowired
private IdWorker idWorker;
public void process(Page page) {
String context = page.getHtml().xpath("//*[@id=\"content\"]/div/div[2]/div/div[2]").toString();
String regexString = "src=\"https://cdn.pixabay.com/photo/[0-9]{4}/[0-9]{2}/[0-9]{2}/[0-9]+/[0-9]+/[a-z]+-[0-9]{7}__340\\.[a-z]{3}\"\\s+alt=\"[\\s\\S]*?\"";
Pattern compile = Pattern.compile(regexString);
Matcher matcher = compile.matcher(context);
// System.out.println(matcher.find());
while (matcher.find()) {
// System.out.println(matcher.toString());
// System.out.println(matcher.group());
String strAll = matcher.group();
String[] split = strAll.split("src=\"");
String[] split1 = split[1].split("\" alt=\"");
String[] split2 = split1[1].split("\"");
// System.out.println(split1[0]);
// System.out.println(split2[0]);
ImageSrc imageSrc = new ImageSrc();
imageSrc.setId(idWorker.nextId()+"");
imageSrc.setImageStr(split1[0]);
imageSrc.setImagealt(split1[1]);
imageSrcs.add(imageSrc);
// System.out.println(split[1]);
}
// if (matcher.find()) {
// System.out.println(matcher.find());
// }
// System.out.println(context);
// page.putField("图片",context);
}
public List<ImageSrc> getImageSrc() {
return this.imageSrcs;
}
@Override
public Site getSite() {
return Site.me().setSleepTime(300).setRetryTimes(3);
}
public static void main(String[] args) {
// String url = "%E4%B8%AD%E5%9B%BD%E4%BA%BA";
// String name = "中国人";
// String url = "";
// try {
// name = URLDecoder.decode(url, "utf-8");
// url = URLEncoder.encode(name, "utf-8");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// System.out.println(url);
// System.out.println();
Spider.create(new ImageProcessor())
.addUrl("https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&fm=index&pos=history&word=无敌")
// .addPipeline(new FilePipeline("D:/image"))
.setScheduler(new QueueScheduler())
.run();
}
}
| true
|
2b7f3510cd944df2022333fd808c44ce2a2ca8c0
|
Java
|
CazauxAdrien/PI
|
/src/main/java/courbe/Connexion_influxDB.java
|
ISO-8859-1
| 5,292
| 2.109375
| 2
|
[] |
no_license
|
package courbe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Pong;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.joda.time.DateTime;
public class Connexion_influxDB {
public InfluxDB influxDB;
public XYSeries series;
public XYSeries series1;
public XYSeriesCollection DatasetTest;
double max = 0.23;
double min = 0.03;
public void connect_influx(String IP, int port){
influxDB = InfluxDBFactory.connect("http://" + IP + ":" + port, "root", "root");
Pong response = this.influxDB.ping();
System.out.println(response);
DatasetTest = new XYSeriesCollection();
series = new XYSeries("Import");
series1 = new XYSeries("Query");
}
public void createDatabase(String dbName, String rpName){
influxDB.deleteDatabase(dbName);
influxDB.dropRetentionPolicy(rpName, dbName);
influxDB.createDatabase(dbName);
influxDB.setDatabase(dbName);
influxDB.createRetentionPolicy(rpName, dbName, "1825d", "30m", 2, true);
influxDB.setRetentionPolicy(rpName);
}
public void insertMasse(String dbName, String rpName,String Grandeur_ref, String valeur, int n){
BatchPoints batchPoints = BatchPoints.database(dbName).retentionPolicy(rpName).build();
Map<String, String> data = new HashMap<String, String>();
DateTime t = new DateTime(2017,1,1,0,0);
long respondtime = 0;
long totaltime = 0;
long time_init = t.getMillis();
long timelong = time_init;
for(int i=1;i<n;i++){ //nb de clients
for (int j=1;j<2;j++) {
for(int a=0;a<1440*6;a++){ // nb de points dans un mois
timelong = time_init + 1000*60*30*a;
double random = min + Math.random() * (max - min);
Point point1 = Point
.measurement("consommation")
.tag("idClient", String.valueOf(i))
.tag(Grandeur_ref, "352447")
.addField(valeur, random)
.time(timelong, TimeUnit.MILLISECONDS)
.build();
data.put("idClient", String.valueOf(i));
batchPoints.setTags(data);
batchPoints.point(point1);
System.out.println(a + ";" + timelong + ";" + ";" + i);
System.out.println(batchPoints.getTags());
}
System.out.println("avant");
long bfins = System.currentTimeMillis();
this.influxDB.write(batchPoints);
long afins = System.currentTimeMillis();
System.out.println("aprs");
//long afins = System.currentTimeMillis()-bfins;
respondtime += afins-bfins;
}
series.add(n*i,respondtime+0.0001);
}
/*
for(int i=0;i<n;i++){
for(int j=0;j<2;j++){
Point[] points = new Point[1440];
for(int m=0;m<1440;m++){ // BatchPoint contient la consommation d'un mois
double random = min + Math.random() * (max - min);
points[m]= Point
.measurement("consommation")
.tag(Grandeur_ref, "352447")
.time(timelong+m*1000*60*30, TimeUnit.MILLISECONDS)
.addField(valeur, random)
.build();
}
for (int m = 0; m < 1440; m++) {
batchPoints.point(points[m]);
}
System.out.println("avant");
long bfins = System.currentTimeMillis();
this.influxDB.write(batchPoints);
long afins = System.currentTimeMillis();
System.out.println("aprs");
//long afins = System.currentTimeMillis()-bfins;
respondtime = afins-bfins;
totaltime += afins - bfins;
System.out.println("Temps d'criture : " + respondtime);
series.add(n*i,respondtime+0.0001);
}
}
*/
System.out.println("Temps d'criture total : " + respondtime);
DatasetTest.addSeries(series);
}
public class TestThread extends Thread{
int nbclients;
int nb ;
int trac;
int nbconnexions;
public TestThread(int clients, int trace, int nbconnex){
nbclients=clients;
nb= (int) (Math.random()*(clients-1));
trac = trace;
nbconnexions=nbconnex;
}
}
public void acces_concurrent(int n, int clients){
int trace = (int) (clients*17280)/(n-1);
List<TestThread> ThreadList = new ArrayList<TestThread>();
for (int i=0;i<n;i++){
ThreadList.add(new TestThread(clients, trace , i ));
}
for (int i=0;i<ThreadList.size();i++){
ThreadList.get(i).start();
}
System.out.println(series1);
DatasetTest.addSeries(series1);
}
}
| true
|
f632bfecea35b44d310d03888ab3220845dd9ca7
|
Java
|
17bq1a12e0/Nagalakshmi-Tirupatamma-Putta-Newyear_Present-2
|
/Choco_analisys.java
|
UTF-8
| 1,918
| 3.15625
| 3
|
[] |
no_license
|
package epam.com.maven;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Choco_analisys {
public static int tw_choco = 0;
public static int tc_choco = 0;
@SuppressWarnings("resource")
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
Fivestar f = new Fivestar();
Perk p = new Perk();
System.out.println("Enter quantity of Fivestar: ");
int fq = scan.nextInt();
System.out.println("Enter quantity of Perk: ");
int pq = scan.nextInt();
System.out.println("Enter size of Fivestar ");
f.getsize(scan.nextInt());
System.out.println("Enter size of Perk");
p.getsize(scan.nextInt());
System.out.println("Enter price of Fivestar: ");
f.price = scan.nextInt();
System.out.println("Enter price of Perk: ");
p.price = scan.nextInt();
System.out.println("Sort By Option:");
System.out.println("1.Size\n2.Name\nEnter your choice: ");
int op = scan.nextInt();
int dm = f.display();
int ss = p.display();
ArrayList<String> ch = new ArrayList<String>();
if(op==1) {
if(dm>ss){
ch.add("Fivestar");
ch.add("Perk");
}
else{
ch.add("Perk");
ch.add("Fivestar");
}
System.out.println(ch+"\n\n");
}
else if(op==2) {
ch.add("Perk");
ch.add("Fivestar");
Collections.sort(ch);
System.out.println(ch);
}
else {
System.out.println("Invalid Input!Please Enter valid input");
return;
}
tw_choco = f.t_weight(fq) + p.t_weight(pq);
System.out.println(tw_choco +" Grms");
tc_choco = f.t_price(fq) + p.t_price(pq);
System.out.println(tc_choco +" Rc.");
}
}
| true
|
13a1d6d12337f99a2b9c2d21568c2aa6cdb4c0ad
|
Java
|
johnnybarden/bank_cinema
|
/src/main/java/com/moskalenko/bankcinema/controller/UserController.java
|
UTF-8
| 2,313
| 2.1875
| 2
|
[] |
no_license
|
package com.moskalenko.bankcinema.controller;
import com.moskalenko.bankcinema.api.client.UserClient;
import com.moskalenko.bankcinema.api.entity.Movie;
import com.moskalenko.bankcinema.service.UserService;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
@RestController
@RequestMapping("/users")
public class UserController implements UserClient {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@Override
@PostMapping("/{userId}/add/{movieId}")
public void addToUserMoviesList(@PathVariable Long userId,@PathVariable Long movieId) {
userService.addToUserMoviesList(userId, movieId);
}
@Override
@DeleteMapping ("/{userId}/delete/{movieId}")
public void deleteFromUserMoviesList(@PathVariable Long userId,@PathVariable Long movieId) {
userService.deleteFromUserMoviesList(userId, movieId);
}
@Override
@PutMapping("/{userId}/movies/{movieId}/rate/{rate}")
public void rateTheMovie(@PathVariable Long userId,
@PathVariable Long movieId,
@PathVariable Integer rate) {
userService.rateTheMovie(userId, movieId, rate);
}
@Override
@PutMapping("/{userId}/view/{movieId}")
public void updateMovieViewInfo(@PathVariable Long userId,@PathVariable Long movieId) {
userService.updateMovieViewInfo(userId, movieId);
}
@Override
@GetMapping("/{userId}/all")
public Collection<Movie> getAllMoviesFromUserMoviesList(@PathVariable Long userId) {
return userService.getAllMoviesFromUserMoviesList(userId);
}
@Override
@GetMapping("/{userId}/unseen")
public Collection<Movie> getAllUnseenMoviesFromUserMoviesList(@PathVariable Long userId) {
return userService.getAllUnseenMoviesFromUserMoviesList(userId);
}
}
| true
|
309922f025b25a998a12918cedca6cbe33e50ad6
|
Java
|
truongngodang/ExcerciseFirst
|
/src/Main.java
|
UTF-8
| 908
| 2.84375
| 3
|
[] |
no_license
|
public class Main {
public static void main(String[] args) {
System.out.println("___________________Bài tập lần 1___________________\n");
//Khoi tao
HinhTamGiac hinhTamGiac = new HinhTamGiac(5);
HinhChuNhat hinhChuNhat = new HinhChuNhat(4, 5);
BangCuuChuong bangCuuChuong = new BangCuuChuong();
SoNgauNhien soNgauNhien = new SoNgauNhien();
System.out.println("Bài 1 \n");
hinhChuNhat.fillFull("*");
System.out.println("\nBài 2 \n");
hinhChuNhat.fillBorder("*");
System.out.println("\nBài 3 \n");
hinhTamGiac.fillTamGiacCan("*");
System.out.println("\nBài 4 \n");
hinhTamGiac.fillTamGiacPascal();
System.out.println("\nBài 5 \n");
bangCuuChuong.display();
System.out.println("\nBài 5 \n");
soNgauNhien.checkSoNgauNhien(10, 99, 24);
}
}
| true
|
909e3e43c449a6d655e31558c768b7477c622bda
|
Java
|
i2863CookieZJ/KenLi
|
/WebTvRebuild_KenLi/Library/src/main/java/com/higgses/griffin/core/entity/GinViewHolder.java
|
UTF-8
| 733
| 1.84375
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package com.higgses.griffin.core.entity;
import com.higgses.griffin.annotation.app.GinInjector;
import android.view.View;
/**
* 适配器中的视图实体
* Created by higgses on 14-4-21.
*/
public abstract class GinViewHolder
{
public GinViewHolder(View view)
{
GinInjector.manualInjectView(this, view);
}
}
| true
|
116c43137c19729c92ab579c593199aec1bc1776
|
Java
|
huybinh1994/HTTTHienDai
|
/src/java/services/src/main/java/service/MasterServiceImpl.java
|
UTF-8
| 658
| 2.125
| 2
|
[] |
no_license
|
package service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.MasterDAO;
import model.MasterDTO;
@Service
public class MasterServiceImpl implements MasterService{
MasterDAO master;
public MasterDAO getMaster() {
return master;
}
@Autowired
public void setMaster(MasterDAO master) {
this.master = master;
}
@Override
public List<MasterDTO> getAll() {
// TODO Auto-generated method stub
return master.getAll();
}
@Override
public List<MasterDTO> getbyid(int id){
// TODO Auto-generated method stub
return master.getbyid(id);
}
}
| true
|
67ebf2fbdca3de047c5791345b5f1b9d4c894e8e
|
Java
|
Aztyu/SupApi
|
/src/main/java/com/supinfo/supapi/entity/Line.java
|
UTF-8
| 2,701
| 2.484375
| 2
|
[
"MIT"
] |
permissive
|
package com.supinfo.supapi.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import org.codehaus.jackson.annotate.JsonManagedReference;
import com.supinfo.supapi.entity.association.StationLineAssociation;
@Entity
//@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "id")
public class Line {
@Id
private long id;
private String reference;
private String name;
private Double avg_speed;
private double price;
@JsonManagedReference
@OneToMany(mappedBy="line", cascade = CascadeType.ALL)
private List<StationLineAssociation> stations;
public Line(){
this.id = -1;
this.name = new String();
this.reference = new String();
this.avg_speed = 0.0;
this.stations = new ArrayList<StationLineAssociation>();
}
public Line(int id, String reference, String name, double avg_speed, double price){
this.id = id;
this.name = name;
this.reference = reference;
this.avg_speed = avg_speed;
this.price = price;
this.stations = new ArrayList<StationLineAssociation>();
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getAvg_speed() {
return avg_speed;
}
public void setAvg_speed(Double avg_speed) {
this.avg_speed = avg_speed;
}
public List<StationLineAssociation> getStations() {
return stations;
}
public void setStations(List<StationLineAssociation> stations) {
this.stations = stations;
}
public void addStation(Station station, int station_order, long distance){
StationLineAssociation sla = new StationLineAssociation();
sla.setLine(this);
sla.setStation(station);
sla.setStation_order(station_order);
sla.setDistance(distance);
this.stations.add(sla);
station.getLines().add(sla);
}
@Override
public boolean equals(Object arg0) {
// TODO Auto-generated method stub
if(arg0 instanceof Line){
Line other = (Line)arg0;
return other.getId() == this.id;
}
return false;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
| true
|
fe97ab26aed67310014b65acb2f41f764d152fb8
|
Java
|
ShaneRich5/ui_prototype
|
/app/src/main/java/com/shane/demo/activities/videos/ShowVideoActivity.java
|
UTF-8
| 1,345
| 2
| 2
|
[] |
no_license
|
package com.shane.demo.activities.videos;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.shane.demo.R;
import com.shane.demo.adapters.ViewPagerAdapter;
import com.shane.demo.fragments.CommentFragment;
import com.shane.demo.fragments.InfoFragment;
import com.shane.demo.fragments.ListVideoFragment;
import butterknife.Bind;
import butterknife.ButterKnife;
public class ShowVideoActivity extends AppCompatActivity {
@Bind(R.id.toolbar) Toolbar toolbar;
@Bind(R.id.tabs) TabLayout tabs;
@Bind(R.id.pager) ViewPager pager;
ViewPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_video);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(CommentFragment.newInstance(), "Comments");
adapter.addFragment(InfoFragment.newInstance(), "Info");
adapter.addFragment(ListVideoFragment.newInstance(), "Related");
pager.setAdapter(adapter);
tabs.setupWithViewPager(pager);
}
}
| true
|
1f2d655fce7ff290deb8b1d2f63c641c59e8303e
|
Java
|
omirobarcelo/visualTableaux
|
/visualTableaux/src/main/java/ver1/NonDeterministicOperation.java
|
UTF-8
| 2,818
| 2.6875
| 3
|
[
"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 ver1;
import ownapi.OWNAxiom;
import ver1.Operation.OPERATOR;
import ver1.util.StringAxiomConstants;
/**
* A non deterministic operation is characterized by the node on which
* is performed, the operation applied (operator), which is the operand,
* and which is the result in this specific case
*/
public class NonDeterministicOperation {
private Node n;
private OPERATOR operator;
private OWNAxiom operand;
private OWNAxiom result;
/**
* Non null arguments assumed
* @param n
* @param op Assumed that the operation represents a type of NDO (i.e.: OR)
*/
public NonDeterministicOperation(Node n, Operation op) {
this.n = n;
this.operator = op.getOperator();
this.operand = op.getOperand1();
this.result = op.getResult();
}
/**
* Non null arguments assumed
* @param n
* @param operator
* @param operand
* @param result
*/
public NonDeterministicOperation(Node n, OPERATOR operator,
OWNAxiom operand, OWNAxiom result) {
this.n = n;
this.operator = operator;
this.operand = operand;
this.result = result;
}
public Node getNode() {
return n;
}
public OPERATOR getOperator() {
return operator;
}
public OWNAxiom getOperand() {
return operand;
}
public OWNAxiom getResult() {
return result;
}
/**
* As per right now, toString() returns always OR format
*/
@Override
public String toString() {
return StringAxiomConstants.OP_DISJUNCTION + "(" + operand + ", " + result + ")" +
" " + StringAxiomConstants.ARROW_RIGHT + " " +
"L(" + n.getId() + ") " + StringAxiomConstants.UNION + " {" + result + "}";
}
@Override
public int hashCode() {
return n.hashCode() ^ operator.hashCode() ^ operand.hashCode() ^ result.hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof NonDeterministicOperation) {
NonDeterministicOperation ndo = (NonDeterministicOperation)other;
return n.equals(ndo.n) && operator == ndo.operator &&
operand.equals(ndo.operand) && result.equals(ndo.result);
}
return false;
}
}
| true
|
3aea0d81cc356d7c862782f8459aa1285ab1ef0b
|
Java
|
hafsamohamed/software1_project
|
/src/controller/interactioncontroller/PostManager.java
|
UTF-8
| 538
| 2.03125
| 2
|
[] |
no_license
|
package controller.interactioncontroller;
import system.interaction.Post;
import java.util.Vector;
public class PostManager {
private Vector<Post> posts;
PostManager(){}
public boolean createPost(Post post){
return true;
}
public boolean editPost(Post post){
return true;
}
public int updateNumOfLikes(Post post){
return 1;
}
public int updateNumOfComments(Post post){
return 1;
}
public int updateNumOfShares(Post post){
return 1;
}
}
| true
|
9cf2925d41b26be08c373c887fa7ec929e6c0627
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/9/9_627d9d18fac963f306bf4ff36bbd4d42c7be65d6/JFreeChartFactoryEngine/9_627d9d18fac963f306bf4ff36bbd4d42c7be65d6_JFreeChartFactoryEngine_s.java
|
UTF-8
| 9,631
| 2.015625
| 2
|
[] |
no_license
|
package org.pentaho.experimental.chart.plugin.jfreechart;
import java.io.Serializable;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.IntervalBarRenderer;
import org.jfree.chart.renderer.category.StackedBarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.pentaho.experimental.chart.core.ChartDocument;
import org.pentaho.experimental.chart.core.ChartElement;
import org.pentaho.experimental.chart.css.keys.ChartStyleKeys;
import org.pentaho.experimental.chart.css.styles.ChartBarStyle;
import org.pentaho.experimental.chart.data.ChartTableModel;
import org.pentaho.experimental.chart.plugin.api.IOutput;
import org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine;
import org.pentaho.experimental.chart.plugin.jfreechart.utils.CylinderRenderer;
import org.pentaho.experimental.chart.plugin.jfreechart.utils.JFreeChartUtils;
import org.pentaho.reporting.libraries.css.values.CSSValue;
public class JFreeChartFactoryEngine implements ChartFactoryEngine, Serializable {
private static final long serialVersionUID = -1079376910255750394L;
public JFreeChartFactoryEngine(){
}
public ChartFactoryEngine getInstance() {
return this;
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeAreaChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeAreaChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeBarChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeBarChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) throws Exception {
String title = JFreeChartUtils.getTitle(chartDocument);
String valueCategoryLabel = JFreeChartUtils.getValueCategoryLabel(chartDocument);
String valueAxisLabel = JFreeChartUtils.getValueAxisLabel(chartDocument);
PlotOrientation orientation = JFreeChartUtils.getPlotOrientation(chartDocument);
boolean legend = JFreeChartUtils.getShowLegend(chartDocument);
boolean toolTips = JFreeChartUtils.getShowToolTips(chartDocument);
boolean urls = JFreeChartUtils.getShowUrls(chartDocument);
JFreeChart chart = createBarChartSubType(chartDocument, data, title, valueCategoryLabel, valueAxisLabel, orientation, legend, toolTips, urls);
JFreeChartUtils.setPlotAttributes(chart.getCategoryPlot(), chartDocument, data);
outHandler.setChart(chart);
outHandler.persist();
}
private JFreeChart createBarChartSubType(ChartDocument chartDocument, ChartTableModel data, String title, String valueCategoryLabel, String valueAxisLabel, PlotOrientation orientation, boolean legend, boolean toolTips, boolean urls) {
boolean stacked = false;
boolean stackedPct = false;
boolean cylinder = false;
boolean interval = false;
ChartElement[] elements = chartDocument.getRootElement().findChildrenByName(ChartElement.TAG_NAME_SERIES);
for (ChartElement element : elements) {
CSSValue value = element.getLayoutStyle().getValue(ChartStyleKeys.BAR_STYLE);
stacked = value.equals(ChartBarStyle.STACKED) ? true : stacked;
stackedPct = value.equals(ChartBarStyle.STACK_PERCENT) ? true : stackedPct;
cylinder = value.equals(ChartBarStyle.CYLINDER) ? true : cylinder;
interval = value.equals(ChartBarStyle.INTERVAL) ? true : interval;
}
JFreeChart chart = null;
if (stacked || stackedPct) {
chart = ChartFactory.createStackedBarChart(title, valueAxisLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data), orientation, legend, toolTips, urls);
((StackedBarRenderer)chart.getCategoryPlot().getRenderer()).setRenderAsPercentages(stackedPct);
return chart;
} else {
if (cylinder) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data), orientation, legend, toolTips, urls);
CylinderRenderer renderer = new CylinderRenderer();
chart.getCategoryPlot().setRenderer(renderer);
return chart;
} else if (interval) {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultIntervalCategoryDataset(data), orientation, legend, toolTips, urls);
chart.getCategoryPlot().setRenderer(new IntervalBarRenderer());
} else {
chart = ChartFactory.createBarChart(title, valueCategoryLabel, valueAxisLabel, JFreeChartUtils.createDefaultCategoryDataset(data), orientation, legend, toolTips, urls);
}
}
return chart;
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeBarLineChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeBarLineChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeBubbleChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeBubbleChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeDialChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeDialChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeDifferenceChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeDifferenceChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeLineChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeLineChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeMultiPieChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeMultiPieChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makePieChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makePieChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeScatterPlotChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeScatterPlotChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeStepAreaChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeStepAreaChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeStepChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeStepChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
/* (non-Javadoc)
* @see org.pentaho.experimental.chart.plugin.api.engine.ChartFactoryEngine#makeWaterfallChart(org.pentaho.experimental.chart.data.ChartTableModel, org.pentaho.experimental.chart.core.ChartDocument, org.pentaho.experimental.chart.plugin.api.IOutput)
*/
public void makeWaterfallChart(ChartTableModel data, ChartDocument chartDocument, IOutput outHandler) {
}
}
| true
|
764a36e950b3eff109bb2d97b12193bc114a090e
|
Java
|
elisabethgombkoto/workspace
|
/Hausuebungen/src/oo/ego8769/hue08/bsp3/Zip/GzipUtil.java
|
UTF-8
| 3,225
| 2.8125
| 3
|
[] |
no_license
|
package oo.ego8769.hue08.bsp3.Zip;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class GzipUtil {
public void gzip(File in_file, File out_archiv, String extension) throws IOException {
System.out.println(out_archiv.getAbsolutePath());
if (!out_archiv.exists()) {
out_archiv.createNewFile();
}
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(out_archiv));
gzipDirectory(in_file, gzipOutputStream, extension);
gzipOutputStream.flush();
gzipOutputStream.close();
}
private void gzipDirectory(File file, GZIPOutputStream zipOutputStream, String extension) throws IOException {
if (file.isDirectory() == true) {
for (File content : file.listFiles()) {
// if (content.isDirectory() == true) {
// zipDirectory(file, zipOutputStream);
// } else {
if (!content.isDirectory()) {
if (extension != null) {
if (getExtension(content).equals(extension)) {
gzipFile(content, zipOutputStream);
// }
}
} else {
gzipFile(content, zipOutputStream);
}
}
}
}
}
private String getExtension(File file) {
System.out.println(file.getName());
return file.getName().split("\\.")[1];
}
private void gzipFile(File file, GZIPOutputStream gzipOutputStream) throws IOException {
System.out.println(file.getAbsolutePath());
FileInputStream fileInputStream = new FileInputStream(file);
ZipEntry gzipEntry = new ZipEntry(file.getName());
// gzipOutputStream.putNextEntry(gzipEntry);
byte[] buffer = new byte[4096];
int returnValue = 0;
while (returnValue != -1) {
returnValue = fileInputStream.read(buffer);
gzipOutputStream.write(buffer);
gzipOutputStream.flush();
}
fileInputStream.close();
}
public void enZip(File archive, File directori) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(archive)));
if (!directori.exists()) {
directori.mkdir();
}
// enGzipArcive(directori, zipInputStream);
}
private void enGzipArcive(File directori, GZIPInputStream gzipInputStream) throws IOException {
/*
* ZipEntry entry = gzipInputStream.getNextEntry();
*
* while (entry != null) { File enZipFile = new
* File(directori.getAbsolutePath() + File.separator + entry.getName());
* System.out.println(enZipFile.getAbsolutePath());
* enZipFile.createNewFile(); FileOutputStream fileOutputStream = null;
*
* try { fileOutputStream = new FileOutputStream(enZipFile); byte[]
* buffer = new byte[4096]; int returnValue = 0; while (returnValue !=
* -1) { returnValue = gzipInputStream.read(buffer);// ich lese //
* hinaus
*
* fileOutputStream.write(buffer);// ich schreibe hinein } } catch
* (FileNotFoundException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } finally { fileOutputStream.flush();
* fileOutputStream.close(); }
*
* // entry = gzipInputStream.getNextEntry(); }
*/}
}
| true
|
7bb8924c9316ba7c78fcdd021a6440ca1c1b2367
|
Java
|
jordana98/Backup
|
/InventarioTiendaUdem/src/java/udem/edu/co/controller/IndexController.java
|
UTF-8
| 2,237
| 2.125
| 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 udem.edu.co.controller;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.Dependent;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import udem.edu.co.entity.Usuarios;
import udem.edu.co.facade.UsuariosFacade;
/**
*
* @author Maritza
*/
@Named(value = "indexController")
@ViewScoped
public class IndexController implements Serializable{
private Usuarios current;
@EJB
private udem.edu.co.facade.UsuariosFacade ejbFacade;
/**
* Creates a new instance of IndexController
*/
public IndexController() {
}
@PostConstruct
public void init (){
current = new Usuarios();
}
public String iniciarSesion(){
String redireccion = null;
Usuarios logeo;
try {
logeo = ejbFacade.iniciarSesion(current);
//Acceso a pagina despues de logearse
if (logeo != null) {
//almacenar en la sesión JSF
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("usuario", logeo);
redireccion = "/protegido/FaceLetPrincipal?faces-redirect=true";
}
else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Aviso","Datos incorrectos"));
}
}
catch (Exception e){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(redireccion));
}
return redireccion;
}
public Usuarios getCurrent() {
return current;
}
public void setCurrent(Usuarios current) {
this.current = current;
}
public UsuariosFacade getEjbFacade() {
return ejbFacade;
}
public void setEjbFacade(UsuariosFacade ejbFacade) {
this.ejbFacade = ejbFacade;
}
}
| true
|
3c952112509c17e1a665d81c2bfd4ee936af95cc
|
Java
|
topcoder-platform/tc-website
|
/src/main/com/topcoder/dde/persistencelayer/bean/DDEUserRoleBean.java
|
UTF-8
| 3,002
| 2.171875
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2006 TopCoder, Inc. All rights reserved.
*/
package com.topcoder.dde.persistencelayer.bean;
import com.topcoder.dde.persistencelayer.interfaces.LocalDDECompVersions;
import com.topcoder.dde.persistencelayer.interfaces.LocalDDERoles;
import com.topcoder.dde.persistencelayer.interfaces.LocalDDEUserMaster;
import javax.ejb.CreateException;
/**
* The bean implementation class representing the CMP bean for the user_role table.
*
* Version 1.0.1 Change notes:
* <ol>
* <li>
* Description attribute was added.
* </li>
* <li>
* tcsrating attribute was eliminated.
* </li>
* </ol>
*
* @version 1.0.1
* @author Timur Zambalayev, pulky
*/
public abstract class DDEUserRoleBean extends DDEBaseCompVersionsBean {
/**
* Creates a new instance.
*/
public DDEUserRoleBean() {
}
/**
* Gets the userMaster (CMR).
*
* @return userMaster.
*/
public abstract LocalDDEUserMaster getUserMaster();
/**
* Sets the userMaster (CMR).
*
* @param userMaster userMaster.
*/
public abstract void setUserMaster(LocalDDEUserMaster userMaster);
/**
* Gets the role addition description.
*
* @return role addition description.
* @since 1.0.1
*/
public abstract String getDescription();
/**
* Sets the role addition description.
*
* @param description role addition description.
* @since 1.0.1
*/
public abstract void setDescription(String description);
/**
* Gets the roles (CMR).
*
* @return roles.
*/
public abstract LocalDDERoles getRoles();
/**
* Sets the roles (CMR).
*
* @param roles roles.
*/
public abstract void setRoles(LocalDDERoles roles);
/**
* Creates an entity object.
*
* @param description role addition description.
* @param userMaster userMaster.
* @param compVersions compVersions.
* @param roles roles.
* @return the entity bean's primary key (should be null for CMP bean implementations).
* @throws CreateException an application level error occurred during the create operation.
*/
public Long ejbCreate(String description, LocalDDEUserMaster userMaster,
LocalDDECompVersions compVersions, LocalDDERoles roles)
throws CreateException {
setPrimaryKey();
setDescription(description);
return null;
}
/**
* Creates an entity object.
*
* @param description role addition description.
* @param userMaster userMaster.
* @param compVersions compVersions.
* @param roles roles.
*/
public void ejbPostCreate(String description, LocalDDEUserMaster userMaster,
LocalDDECompVersions compVersions, LocalDDERoles roles) {
setUserMaster(userMaster);
setCompVersions(compVersions);
setRoles(roles);
}
}
| true
|
3e8e847d5ff490c3d077abd760d8f2c04359e9f9
|
Java
|
Justaslol/psp-2
|
/Extension/src/CargoCar.java
|
UTF-8
| 463
| 3.25
| 3
|
[] |
no_license
|
public class CargoCar extends Vehicle{
private final int DAY_PRICE = 50;
private int capacity;
public CargoCar(Gearbox gearbox, int capacity) {
super(gearbox);
this.capacity = capacity;
}
@Override
public double price(int days) {
double price = DAY_PRICE * days;
if (capacity > 5) {
price = price * 1.3;
}
for (Extension extension : getExtensions().values()) {
price += extension.priceWithInsurance(days);
}
return price;
}
}
| true
|
ee22381dd305930269ebbcfaf26d1290e95e895d
|
Java
|
inthiyazbasha9876/obs_v2
|
/zuul-auth-ojas-parent/ojas-obs-calendarholidays/src/main/java/com/ojas/obs/calendarholidays/facadeimpl/CalendarHolidaysFacadeImpl.java
|
UTF-8
| 5,757
| 2.484375
| 2
|
[
"MIT"
] |
permissive
|
package com.ojas.obs.calendarholidays.facadeimpl;
import static com.ojas.obs.calendarholidays.constants.Constants.DELETE;
import static com.ojas.obs.calendarholidays.constants.Constants.UPDATE;
import static com.ojas.obs.calendarholidays.constants.Constants.SAVE;
import static com.ojas.obs.calendarholidays.constants.Constants.GETBYID;
import static com.ojas.obs.calendarholidays.constants.Constants.GETALL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ojas.obs.calendarholidays.facade.CalendarHolidaysFacade;
import com.ojas.obs.calendarholidays.model.CalendarHolidays;
import com.ojas.obs.calendarholidays.repository.CalendarHolidaysRepository;
import com.ojas.obs.calendarholidays.request.CalendarHolidaysRequest;
import com.ojas.obs.calendarholidays.response.CalendarHolidaysResponse;
@Service
public class CalendarHolidaysFacadeImpl implements CalendarHolidaysFacade{
@Autowired
private CalendarHolidaysRepository holidaysRepo;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public ResponseEntity<Object> saveHolidays(CalendarHolidaysRequest holidaysRequestObject) {
CalendarHolidaysResponse response=null;
logger.debug("request coming to the facade");
if(holidaysRequestObject.getTransactionType().equalsIgnoreCase(SAVE)) {
response = new CalendarHolidaysResponse();
List<CalendarHolidays> holidays = holidaysRequestObject.getHolidayslist();
for (CalendarHolidays calender : holidays) {
CalendarHolidays save = holidaysRepo.save(calender);
if (save.getHolidayId() != null) {
logger.debug("save method");
response.setStatusCode("200");
response.setMessage("holiday saved successfully");
return new ResponseEntity<>(response, HttpStatus.OK);
} else {
logger.debug("save method");
response.setStatusCode("422");
response.setMessage("failed to save");
return new ResponseEntity<>(response, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
}
if (holidaysRequestObject.getTransactionType().equalsIgnoreCase(UPDATE)) {
response = new CalendarHolidaysResponse();
List<CalendarHolidays> holidays = holidaysRequestObject.getHolidayslist();
CalendarHolidays calendar = holidays.get(0);
Integer id = calendar.getHolidayId();
Optional<CalendarHolidays> findById = holidaysRepo.findById(id);
if (findById.isPresent() &&findById.get().getHolidayId() != null) {
holidaysRepo.save(calendar);
response.setStatusCode("200");
response.setMessage("holiday updated successfully");
return new ResponseEntity<>(response, HttpStatus.OK);
}
response.setStatusCode("409");
response.setMessage("failed to update");
return new ResponseEntity<>(response, HttpStatus.CONFLICT);
}
if (holidaysRequestObject.getTransactionType().equalsIgnoreCase(DELETE)) {
response = new CalendarHolidaysResponse();
Integer id = holidaysRequestObject.getHolidayslist().get(0).getHolidayId();
CalendarHolidays status = holidaysRepo.getOne(id);
status.setStatus(!status.getStatus());
CalendarHolidays data = holidaysRepo.save(status);
if (data.getHolidayId() != null) {
response.setStatusCode("200");
response.setMessage("holiday deleted successfully");
return new ResponseEntity<>(response, HttpStatus.OK);
}
response.setStatusCode("409");
response.setMessage("failed to delete");
return new ResponseEntity<>(response, HttpStatus.CONFLICT);
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
@Override
public ResponseEntity<Object> getHolidays(CalendarHolidaysRequest holidaysRequestObject) {
List<CalendarHolidays> list = holidaysRequestObject.getHolidayslist();
logger.debug(" getAll holidays details");
CalendarHolidaysResponse response = null;
List<CalendarHolidays> getAll = null;
if (holidaysRequestObject.getTransactionType().equalsIgnoreCase(GETALL)) {
getAll = holidaysRepo.findAll();
if (getAll.isEmpty()) {
response = new CalendarHolidaysResponse();
response.setHolidayslist(new ArrayList<CalendarHolidays>());
response.setMessage("No records found");
response.setStatusCode("409");
return new ResponseEntity<>(response, HttpStatus.CONFLICT);
}
response = new CalendarHolidaysResponse();
response.setHolidayslist(getAll);
response.setMessage("success");
response.setStatusCode("200");
return new ResponseEntity<>(response, HttpStatus.OK);
}
if (holidaysRequestObject.getTransactionType().equalsIgnoreCase(GETBYID)
&& list.get(0).getHolidayId() != null) {
for (CalendarHolidays details : list) {
if (details.getHolidayId() != null) {
Integer id = holidaysRequestObject.getHolidayslist().get(0).getHolidayId();
ArrayList<CalendarHolidays> holidayslist = new ArrayList<>();
CalendarHolidays getById = holidaysRepo.findById(id).orElse(new CalendarHolidays());
holidayslist.add(getById);
if (getById != null && getById.getHolidayId() != null) {
response = new CalendarHolidaysResponse();
response.setHolidayslist(holidayslist);
response.setStatusCode("200");
response.setMessage("success");
return new ResponseEntity<>(response, HttpStatus.OK);
}
response = new CalendarHolidaysResponse();
response.setStatusCode("409");
response.setMessage("please provide valid id");
return new ResponseEntity<>(response, HttpStatus.CONFLICT);
}
}
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
| true
|
8d0bc57547438c9f1fe3d2d77216837e713ffba8
|
Java
|
yqyzxd/ui-skin
|
/skinview-lib/src/main/java/com/wind/ui/skinview/view/SkinnableTextView.java
|
UTF-8
| 3,309
| 2.109375
| 2
|
[] |
no_license
|
package com.wind.ui.skinview.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatTextView;
import com.wind.ui.skinview.R;
import com.wind.ui.skinview.SkinAttributes;
import com.wind.ui.skinview.Skinnable;
import com.wind.ui.skinview.Skins;
/**
* Created By wind
* on 2020-02-25
*/
public class SkinnableTextView extends AppCompatTextView implements Skinnable {
private SkinAttributes mSkinAttributes;
public SkinnableTextView(Context context) {
this(context,null);
}
public SkinnableTextView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public SkinnableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//获取attrs中设置的可以换肤的属性
TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.SkinnableTextView,defStyleAttr,0);
mSkinAttributes=new SkinAttributes(typedArray,R.styleable.SkinnableTextView);
String typefacePath=typedArray.getString(R.styleable.SkinnableTextView_skin_typeface);
if (!TextUtils.isEmpty(typefacePath)) {
setTypeface(Typeface.createFromAsset(getResources().getAssets(), typefacePath));
}
typedArray.recycle();
}
@Override
public void skin() {
//日间/夜间模式 使用以下方式获取background
/* int backgroundKey=R.styleable.SkinableTextView[R.styleable.SkinableTextView_android_background];
int backgroundResourceId=mSkinAttributes.getResourceId(backgroundKey);
if (backgroundResourceId>0){
Drawable drawable=ContextCompat.getDrawable(getContext(),backgroundResourceId);
setBackground(drawable);
}
//获取textColor
int textColorId=R.styleable.SkinableTextView[R.styleable.SkinableTextView_android_textColor];
int textColorResourceId=mSkinAttributes.getResourceId(textColorId);
if (textColorResourceId>0){
ColorStateList color=ContextCompat.getColorStateList(getContext(),textColorResourceId);
setTextColor(color);
}*/
// 根据自定义属性,获取styleable中的background属性
int key = R.styleable.SkinnableTextView[R.styleable.SkinnableTextView_android_background];
// 根据styleable获取控件某属性的resourceId
int backgroundResourceId = mSkinAttributes.getResourceId(key);
Skins.getInstance().setBackground(this,backgroundResourceId);
// 根据自定义属性,获取styleable中的textColor属性
key = R.styleable.SkinnableTextView[R.styleable.SkinnableTextView_android_textColor];
int textColorResourceId = mSkinAttributes.getResourceId(key);
Skins.getInstance().setTextColor(this,textColorResourceId);
// 根据自定义属性,获取styleable中的字体 skin_typeface 属性
key = R.styleable.SkinnableTextView[R.styleable.SkinnableTextView_skin_typeface];
int textTypefaceResourceId = mSkinAttributes.getResourceId(key);
Skins.getInstance().setTypeface(this,textTypefaceResourceId);
}
}
| true
|
dfe9a278c512a385b487d7328e1e50cd2b8ea84a
|
Java
|
RJ-4/EmployeeServer
|
/EmployeeServer1/src/main/java/com/nagarro/java/training/employee/api/EmployeeAPI.java
|
UTF-8
| 2,244
| 2.46875
| 2
|
[] |
no_license
|
package com.nagarro.java.training.employee.api;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.nagarro.java.training.employee.model.Employee;
import com.nagarro.java.training.employee.service.AddEmployeeService;
import com.nagarro.java.training.employee.service.FetchAllEmployeesService;
import com.nagarro.java.training.employee.service.FetchSelectedEmployeeService;
import com.nagarro.java.training.employee.service.UpdateEmployeeService;
import com.nagarro.java.training.employee.service.impl.AddEmployeeServiceImpl;
import com.nagarro.java.training.employee.service.impl.FetchAllEmployeesServiceImpl;
import com.nagarro.java.training.employee.service.impl.FetchSelectedEmployeeServiceImpl;
import com.nagarro.java.training.employee.service.impl.UpdateEmployeeServiceImpl;
@Path("/employees")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class EmployeeAPI {
AddEmployeeService addEmployeeService;
FetchAllEmployeesService fetchAllEmployees;
UpdateEmployeeService updateEmployeeService;
FetchSelectedEmployeeService fetchSelectedEmployeeService;
@POST
public Employee addEmployee(Employee employee) throws Exception{
addEmployeeService = new AddEmployeeServiceImpl();
return addEmployeeService.addEmployee(employee);
}
@GET
public List<Employee> getEmployeeList() {
fetchAllEmployees = new FetchAllEmployeesServiceImpl();
return fetchAllEmployees.getEmployeeList();
}
@PUT
@Path("/{employeeCode}")
public Employee updateEmployee(Employee employee, @PathParam("employeeCode") int employeeCode){
updateEmployeeService = new UpdateEmployeeServiceImpl();
employee.setEmployeeCode(employeeCode);
return updateEmployeeService.updateEmployee(employee);
}
@GET
@Path("/{employeeCode}")
public Employee getSelectedEmployee(@PathParam("employeeCode") int employeeCode) {
fetchSelectedEmployeeService = new FetchSelectedEmployeeServiceImpl();
return fetchSelectedEmployeeService.fetchSelectedEmployee(employeeCode);
}
}
| true
|
b711e9c7dfe0c48f36b386325edc5213cfb29692
|
Java
|
jodie8869/Graffiti-1
|
/app/src/main/java/org/linccy/graffiti_sample/GraffitiFragment.java
|
UTF-8
| 6,232
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.linccy.graffiti_sample;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import org.linccy.graffiti.GraffitiView;
import org.linccy.graffiti.GraffitiConfig;
import java.io.File;
import java.io.FileOutputStream;
/**
* Created by lcx on 12/21/16.
* 画图fragment
*/
public class GraffitiFragment extends android.support.v4.app.Fragment implements GraffitiView.OnLoadFinishListener {
public static final int REDO = 0;
public static final int UNDO = 1;
public static final int CLEAR = 2;
public static final int ROTATE = 3;
public static int ROTATE_ANGLE = 90;
public static final int RED_PEN = 1;
public static final int YELLOW_PEN = 2;
public static final int BLUE_PEN = 3;
private FrameLayout checkView;
private GraffitiView mGraffitiView;
private GraffitiView.OnGraffitiViewOnClickListener onGraffitiViewOnClickListener;
private String img;
private String local;
private View mRootView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
Bundle arguments = getArguments();
img = arguments.getString("url");
local = arguments.getString("local");
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(getContentLayout(), container, false);
mGraffitiView = new GraffitiView(getContext());
mGraffitiView.setOnLoadFinishListener(this);
mGraffitiView.setOnGraffitiViewOnClick(onGraffitiViewOnClickListener);
mGraffitiView.setId(R.id.graffitiview); //setId,当页面被移除后恢复时GraffitiView调用保存状态
mGraffitiView.setSaveEnabled(true);
checkView = (FrameLayout) mRootView.findViewById(R.id.graffiti);
return mRootView;
}
public int getContentLayout() {
return R.layout.fragment_graffiti;
}
public void setPenColor(int penType) {
switch (penType) {
case RED_PEN:
mGraffitiView.setPenType_1();
break;
case YELLOW_PEN:
mGraffitiView.setPenType_2();
break;
case BLUE_PEN:
mGraffitiView.setPenType_3();
break;
default:
break;
}
}
public void action(int action) {
switch (action) {
case REDO:
mGraffitiView.redo();
break;
case UNDO:
mGraffitiView.undo();
break;
case CLEAR:
mGraffitiView.clear();
break;
case ROTATE:
mGraffitiView.rotate(ROTATE_ANGLE);
break;
default:
break;
}
}
/**
* 设置画图View的背景图
* 通过rxJava下载图片
*
* @param url 图片的地址
*/
private void setImage(String path, String url) {
//优先使用本地文件
if (mGraffitiView == null) {
mGraffitiView = new GraffitiView(getContext());
mGraffitiView.setOnLoadFinishListener(this);
mGraffitiView.setOnGraffitiViewOnClick(onGraffitiViewOnClickListener);
}
if (!TextUtils.isEmpty(path)) {
mGraffitiView.setImageUri("file://" + path);
} else {
mGraffitiView.setImageUri(url);
}
}
@Override
public void onResume() {
super.onResume();
setImage(local, img);
}
public String saveAndClear() {
if (mGraffitiView != null && mGraffitiView.isChanged()) {
if (!TextUtils.isEmpty(local)) {
//如果上一次有图片保存,则把上一次的图片删除
File f = new File(local);
if (f.exists()) f.delete();
local = "";
}
local = saveEditPic(mGraffitiView.getResultBitmap());
setChangedOver();
}
return local;
}
public boolean graffitiIsChanged() {
return mGraffitiView != null && mGraffitiView.isChanged();
}
private void setChangedOver() {
mGraffitiView.setChangedOver();
}
/**
* 保存图片,图片必须为png->bitmap->png或者jpg->bitmap->jpg否则保存的图片将无法打开
*
* @param bitmap 要保存的bitmap
*/
private String saveEditPic(Bitmap bitmap) {
String path = "";
File f = new File(GraffitiConfig.APP_TEMP_FILE_PATH + System.currentTimeMillis() + ".jpg");
if (f.exists()) f.delete();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
if (null != fOut) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
}
path = f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fOut.close();
bitmap.recycle();
} catch (Exception e) {
}
}
return path;
}
public void setOnGraffitiViewOnClickListener(GraffitiView.OnGraffitiViewOnClickListener onGraffitiViewOnClickListener) {
this.onGraffitiViewOnClickListener = onGraffitiViewOnClickListener;
}
@Override
public void OnLoadFinish() {
if (null == getActivity()) {
return;
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
checkView.removeAllViews();
checkView.addView(mGraffitiView);
}
});
}
@Override
public void onDestroy() {
if (null != mGraffitiView) {
mGraffitiView.release();
mGraffitiView.removeAllViews();
}
super.onDestroy();
}
}
| true
|
140dc4ea086e3488afca7e2fdc94624e7279168a
|
Java
|
triplezhao/driver
|
/app/src/main/java/potato/driver/ui/map/MapActivity.java
|
UTF-8
| 8,522
| 1.96875
| 2
|
[] |
no_license
|
package potato.driver.ui.map;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.potato.library.net.RequestManager;
import com.potato.library.net.RequestWraper;
import com.potato.library.util.L;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import potato.driver.R;
import potato.driver.chips.base.BaseActivity;
import potato.driver.chips.util.UIUtils;
import potato.driver.data.bean.DriverBean;
import potato.driver.data.db.DriverBeanDao;
import potato.driver.data.request.DriverRequestBuilder;
/**
* AMapV1地图中简单介绍显示定位小蓝点
*/
public class MapActivity extends BaseActivity implements LocationSource,
AMapLocationListener {
private AMap aMap;
private MapView mapView;
private OnLocationChangedListener mListener;
private AMapLocationClient mlocationClient;
private AMapLocationClientOption mLocationOption;
//司机实体
DriverBean mDriver;
@InjectView(R.id.bt_start)
View bt_start;
@InjectView(R.id.bt_stop)
View bt_stop;
//开始统计坐标,默认不统计
public static boolean isStarted = false;
DriverBeanDao dao;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.inject(this);
mapView = (MapView) findViewById(R.id.map);
mapView.onCreate(savedInstanceState);// 此方法必须重写
init();
}
/**
* 初始化AMap对象
*/
private void init() {
if (aMap == null) {
aMap = mapView.getMap();
setUpMap();
}
dao = new DriverBeanDao(getApplication());
}
/**
* 设置一些amap的属性
*/
private void setUpMap() {
// 自定义系统定位小蓝点
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationIcon(BitmapDescriptorFactory
.fromResource(R.drawable.car_y));// 设置小蓝点的图标
myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
// myLocationStyle.anchor(int,int)//设置小蓝点的锚点
myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
aMap.setMyLocationStyle(myLocationStyle);
aMap.setLocationSource(this);// 设置定位监听
aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false
CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(15);
aMap.moveCamera(cameraUpdate);
float mZoom = aMap.getCameraPosition().zoom;
L.d("mZoom=" + mZoom);
// aMap.setMyLocationType()
}
/**
* 方法必须重写
*/
@Override
public void onResume() {
super.onResume();
mapView.onResume();
mDriver = dao.getLoginedDiver();
}
/**
* 方法必须重写
*/
@Override
public void onPause() {
super.onPause();
// mapView.onPause();
// deactivate();
}
/**
* 方法必须重写
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
/**
* 方法必须重写
*/
@Override
public void onDestroy() {
super.onDestroy();
deactivate();
mapView.onDestroy();
}
/**
* 定位成功后回调函数
*/
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (mListener != null && amapLocation != null) {
if (amapLocation != null
&& amapLocation.getErrorCode() == 0) {
mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
String errText = "定位成功," + amapLocation.getLatitude() + "," + amapLocation.getLongitude();
L.d(errText);
/**
* 调用animateCamera方法或moveCamera方法来改变可视区域
*/
CameraUpdate cameraUpdate = CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude()));
aMap.animateCamera(cameraUpdate, 1000, null);
aMap.moveCamera(cameraUpdate);
if (isStarted) {
updateLocation(amapLocation);
}
} else {
String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
L.d(errText);
}
}
}
/**
* @param amapLocation 向服务器上报位置信息
*/
private void updateLocation(AMapLocation amapLocation) {
String errText = "统计坐标信息," + amapLocation.getLatitude() + "," + amapLocation.getLongitude();
L.d(errText);
RequestWraper requestWraper = DriverRequestBuilder.location(mDriver.getLogin_id(), (amapLocation.getLatitude() + ""), (amapLocation.getLongitude() + ""));
RequestManager.requestData(requestWraper, RequestManager.CACHE_TYPE_NOCACHE, new RequestManager.DataLoadListener() {
@Override
public void onCacheLoaded(String content) {
}
@Override
public void onSuccess(int statusCode, String content) {
L.d("上传统计坐标信息成功," + content);
}
@Override
public void onFailure(Throwable error, String errMsg) {
L.d(errMsg);
}
});
}
/**
* 激活定位
*/
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
if (mlocationClient == null) {
mlocationClient = new AMapLocationClient(this);
mLocationOption = new AMapLocationClientOption();
//设置定位监听
mlocationClient.setLocationListener(this);
//设置为高精度定位模式
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
mLocationOption.setInterval(1000 * 5);
//设置定位参数
mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,
// 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后,在合适的生命周期调用onDestroy()方法
// 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除
mlocationClient.startLocation();
}
}
/**
* 停止定位
*/
@Override
public void deactivate() {
mListener = null;
if (mlocationClient != null) {
mlocationClient.stopLocation();
mlocationClient.onDestroy();
}
mlocationClient = null;
}
@OnClick(R.id.bt_start)
public void clickStart(View view) {
if (mDriver == null) {
UIUtils.toast(mContext, "请先登录");
return;
}
bt_stop.setVisibility(View.VISIBLE);
bt_start.setVisibility(View.GONE);
isStarted = true;
}
@OnClick(R.id.bt_stop)
public void clickStop(View view) {
bt_stop.setVisibility(View.GONE);
bt_start.setVisibility(View.VISIBLE);
isStarted = false;
}
}
| true
|
e42115e7ffa9fa34283482d24249c43c661e2c69
|
Java
|
jakeswenson/dropwizard
|
/dropwizard-hibernate/src/main/java/io/dropwizard/hibernate/UnitOfWorkApplicationListener.java
|
UTF-8
| 4,794
| 2.328125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package io.dropwizard.hibernate;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.server.internal.process.MappableException;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.glassfish.jersey.server.monitoring.ApplicationEvent;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
import org.hibernate.SessionFactory;
/**
* An application event listener that listens for Jersey application initialization to
* be finished, then creates a map of resource method that have metrics annotations.
*
* Finally, it listens for method start events, and returns a {@link RequestEventListener}
* that updates the relevant metric for suitably annotated methods when it gets the
* request events indicating that the method is about to be invoked, or just got done
* being invoked.
*/
@Provider
public class UnitOfWorkApplicationListener implements ApplicationEventListener {
private Map<Method, UnitOfWork> methodMap = new HashMap<>();
private Map<String, SessionFactory> sessionFactories = new HashMap<>();
public UnitOfWorkApplicationListener() {
}
/**
* Construct an application event listener using the given name and session factory.
*
* <p/>
* When using this constructor, the {@link UnitOfWorkApplicationListener}
* should be added to a Jersey {@code ResourceConfig} as a singleton.
*
* @param name a name of a Hibernate bundle
* @param sessionFactory a {@link SessionFactory}
*/
public UnitOfWorkApplicationListener(String name, SessionFactory sessionFactory) {
registerSessionFactory(name, sessionFactory);
}
/**
* Register a session factory with the given name.
*
* @param name a name of a Hibernate bundle
* @param sessionFactory a {@link SessionFactory}
*/
public void registerSessionFactory(String name, SessionFactory sessionFactory) {
sessionFactories.put(name, sessionFactory);
}
private static class UnitOfWorkEventListener implements RequestEventListener {
private final Map<Method, UnitOfWork> methodMap;
private final UnitOfWorkAspect unitOfWorkAspect;
UnitOfWorkEventListener(Map<Method, UnitOfWork> methodMap,
Map<String, SessionFactory> sessionFactories) {
this.methodMap = methodMap;
unitOfWorkAspect = new UnitOfWorkAspect(sessionFactories);
}
@Override
public void onEvent(RequestEvent event) {
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) {
UnitOfWork unitOfWork = methodMap.get(event.getUriInfo()
.getMatchedResourceMethod().getInvocable().getDefinitionMethod());
unitOfWorkAspect.beforeStart(unitOfWork);
} else if (event.getType() == RequestEvent.Type.RESP_FILTERS_START) {
try {
unitOfWorkAspect.afterEnd();
} catch (Exception e) {
throw new MappableException(e);
}
} else if (event.getType() == RequestEvent.Type.ON_EXCEPTION) {
unitOfWorkAspect.onError();
}
}
}
@Override
public void onEvent(ApplicationEvent event) {
if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) {
for (Resource resource : event.getResourceModel().getResources()) {
for (ResourceMethod method : resource.getAllMethods()) {
registerUnitOfWorkAnnotations(method);
}
for (Resource childResource : resource.getChildResources()) {
for (ResourceMethod method : childResource.getAllMethods()) {
registerUnitOfWorkAnnotations(method);
}
}
}
}
}
@Override
public RequestEventListener onRequest(RequestEvent event) {
return new UnitOfWorkEventListener(methodMap, sessionFactories);
}
private void registerUnitOfWorkAnnotations(ResourceMethod method) {
UnitOfWork annotation = method.getInvocable().getDefinitionMethod().getAnnotation(UnitOfWork.class);
if (annotation == null) {
annotation = method.getInvocable().getHandlingMethod().getAnnotation(UnitOfWork.class);
}
if (annotation != null) {
this.methodMap.put(method.getInvocable().getDefinitionMethod(), annotation);
}
}
}
| true
|
c20a3335d56a577f1e6767899fd74bdf9f5728a5
|
Java
|
HassenBenSlima/Mini-Project-Java
|
/workspaceJava/Try/src/Tp/App3.java
|
ISO-8859-1
| 889
| 3.453125
| 3
|
[] |
no_license
|
package Tp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class App3 {
/*
* Lire et crire sur un fichier texte ligne par ligne : Streams de
* traitement : BufferedReader et BufferedWriter
*/
@SuppressWarnings("resource")
public static void main(String[] args) {
try {
File f = new File("notes.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
double somme = 0;
int nb = 0;
while ((s = br.readLine()) != null)// null parce que une chaine de
// caractere
{
++nb;
String[] tab = s.split(";");
double note = Double.parseDouble(tab[2]);
somme = somme + note;
}
System.out.println("Moyenne=" + somme / nb);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
48e733503db46c70ee08ef352340e60356688d03
|
Java
|
AnanichRoman/OrganizeRemains
|
/organize/UserActivity.java
|
UTF-8
| 3,802
| 1.984375
| 2
|
[] |
no_license
|
package com.appsrox.remindme;
import java.util.Date;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import com.appsrox.remindme.model.Alarm;
import com.appsrox.remindme.model.AlarmMsg;
public class UserActivity extends Activity {
// private static final String TAG = "UserActivity";
private TypedArray icons;
private TimePicker picker;
private TextView tv;
private TextView timeText;
private long alarmMsgId, alarmId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_user);
icons = getResources().obtainTypedArray(R.array.icon_arr);
tv = (TextView) findViewById(R.id.textView1);
timeText = (TextView) findViewById(R.id.time_tv);
picker = (TimePicker) findViewById(R.id.timePicker1);
picker.setIs24HourView(true);
int hr = RemindMe.getSnoozeTime() / 60;
int min = RemindMe.getSnoozeTime() - hr*60;
picker.setCurrentHour(hr);
picker.setCurrentMinute(min);
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
alarmMsgId = intent.getLongExtra(AlarmMsg.COL_ID, -1);
alarmId = intent.getLongExtra(AlarmMsg.COL_ALARMID, -1);
Alarm alarm = new Alarm(alarmId);
alarm.load(RemindMe.db);
tv.setText(alarm.getName());
String _tagName = alarm.getTag();
Alarm.TAG _tag = !TextUtils.isEmpty(_tagName) ? Alarm.TAG.valueOf(_tagName) : null;
if (_tag!=null) {
tv.setCompoundDrawablesWithIntrinsicBounds(icons.getResourceId(_tag.ordinal()+1, -1), 0, 0, 0);
}
AlarmMsg alarmMsg = new AlarmMsg(alarmMsgId);
alarmMsg.load(RemindMe.db);
Date dt = new Date(alarmMsg.getDateTime());
timeText.setText(Util.getActualTime(dt.getHours(), dt.getMinutes()));
doCancel(intent);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("hour", picker.getCurrentHour());
}
@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
picker.setCurrentHour(state.getInt("hour"));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
finish();
break;
case R.id.button2:
long when = System.currentTimeMillis() + (picker.getCurrentHour()*60 + picker.getCurrentMinute())*60*1000;
AlarmMsg alarmMsg = new AlarmMsg(alarmMsgId);
alarmMsg.setStatus(AlarmMsg.ACTIVE);//TODO DEFERRED
alarmMsg.setDateTime(when);
alarmMsg.persist(RemindMe.db);
Intent service = new Intent(this, AlarmService.class);
service.putExtra(AlarmMsg.COL_ID, String.valueOf(alarmMsgId));
service.setAction(AlarmService.CREATE);
startService(service);
finish();
break;
}
}
private void doCancel(Intent intent) {
Intent i = new Intent(this, AlarmReceiver.class);
i.putExtra(AlarmMsg.COL_ID, intent.getLongExtra(AlarmMsg.COL_ID, -1));
i.putExtra(AlarmMsg.COL_ALARMID, intent.getLongExtra(AlarmMsg.COL_ALARMID, -1));
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
}
}
| true
|
f555df21e1fb01514a10556c24009795b884ab8b
|
Java
|
kanyuxia/oldStudyJava
|
/src/io/StudyFile.java
|
UTF-8
| 1,378
| 2.9375
| 3
|
[] |
no_license
|
package io;
import java.io.File;
import java.io.IOException;
/**
* Created by kanyuxia on 2017/3/2.
*/
public class StudyFile {
public static void main(String[] args) throws IOException {
File file = new File("E:\\java\\America.java");
boolean canExecute = file.canExecute();
System.out.println(canExecute);
boolean canRead = file.canRead();
System.out.println(canRead);
boolean canWrite = file.canWrite();
System.out.println(canWrite);
int compareTo = file.compareTo(new File("E:\\java\\People.java"));
System.out.println(compareTo);
boolean createNewFile = file.createNewFile();
System.out.println(createNewFile);
// boolean delete = file.delete();
// System.out.println(delete);
boolean exists = file.exists();
System.out.println(exists);
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);
System.out.println(file.getName());
System.out.println(file.getParent());
System.out.println(file.getPath());
System.out.println(file.isAbsolute());
System.out.println(file.isDirectory());
System.out.println(file.isFile());
System.out.println(file.lastModified());
System.out.println(file.length());
System.out.println(file.toURI());
}
}
| true
|
ccce33a9a81d6667cf421a4e92f72afa65689f48
|
Java
|
stepbystepspringboot/coronavirus02_server
|
/src/main/java/com/aikiinc/coronavirus/data/CoronaVirusRemoteData.java
|
UTF-8
| 2,166
| 2.421875
| 2
|
[] |
no_license
|
package com.aikiinc.coronavirus.data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aikiinc.coronavirus.exception.CoronaVirusException;
import com.aikiinc.coronavirus.utility.CoronaVirusUtil;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class CoronaVirusRemoteData extends CoronaVirusCommon implements CornaVirusData {
private Logger log = LoggerFactory.getLogger(CoronaVirusRemoteData.class);
public final static String SOURCE_URL_PREFIX = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/";
private static String sourceUrlPrefix;
private URL remoteUrl;
private CoronaVirusRemoteData() {
}
private CoronaVirusRemoteData(String sourceUrlPrefix) throws CoronaVirusException {
CoronaVirusRemoteData.sourceUrlPrefix = sourceUrlPrefix;
log.debug(CoronaVirusRemoteData.sourceUrlPrefix);
}
/**
* Create a CoronaVirusLocalData instance and process loading the data
*
* @return
* @throws CoronaVirusException
*/
public static final CoronaVirusRemoteData getInstance() throws CoronaVirusException {
CoronaVirusRemoteData CoronaVirusRemoteData = new CoronaVirusRemoteData(sourceUrlPrefix);
return CoronaVirusRemoteData;
}
public void process() throws CoronaVirusException {
setRemoteConnection();
setURL();
readData();
extractData();
CoronaVirusUtil.closeBuffer();
}
void setURL() {
super.coroSiteURL = remoteUrl;
}
void setRemoteConnection() throws CoronaVirusException {
// String sdate =
// LocalDate.now().format(DateTimeFormatter.ofPattern("MM-dd-yyyy"));
/**
* Get prior date
*/
String sdate = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("MM-dd-yyyy"));
log.debug("Load coronavirus data for date: " + sdate);
String sourceUrl = SOURCE_URL_PREFIX + sdate + ".csv";
try {
this.remoteUrl = new URL(sourceUrl);
remoteUrl.getContent();
log.debug("\tLoading data from: " + remoteUrl);
} catch (Exception e) {
log.warn("\tCould not load data from: " + sourceUrl);
log.warn("\tException: " + e.getMessage());
}
}
}
| true
|
4c967075a56f91f6bac4974db30adcc450484748
|
Java
|
SplendidSky/Distributed-Computing
|
/food store阶段三/src/main/java/com/zhtian/services/OrderLineServiceImpl.java
|
UTF-8
| 1,135
| 2.328125
| 2
|
[] |
no_license
|
package com.zhtian.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhtian.entities.Food;
import com.zhtian.entities.OrderLine;
import com.zhtian.dao.OrderLineDao;
import com.zhtian.dao.FoodDao;
@Service
@Transactional
public class OrderLineServiceImpl implements OrderLineService {
@Autowired
private OrderLineDao orderLineDao;
@Autowired
private FoodDao foodDao;
public OrderLineServiceImpl() {
super();
}
public List<OrderLine> findByOrderId(Integer orderId) {
List<OrderLine> orderLines = orderLineDao.findByOrderId(orderId);
for (OrderLine orderLine : orderLines) {
orderLine.setFood(foodDao.findById(orderLine.getFoodId()));
}
return orderLines;
}
public OrderLine addOrderLineDao(Food food, Integer amount, Integer orderId, boolean isCheaper) {
orderLineDao.addOrderLineDao(food, amount, orderId, isCheaper);
OrderLine orderLine = new OrderLine(food, food.getId(), amount, orderId, isCheaper);
return orderLine;
}
}
| true
|
d46102bab6340cc9fb0cbc1ef37e025d5d214000
|
Java
|
prompto/prompto-java
|
/Standalone/src/main/java/prompto/runtime/Standalone.java
|
UTF-8
| 14,997
| 1.679688
| 2
|
[] |
no_license
|
package prompto.runtime;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.esotericsoftware.yamlbeans.document.YamlMapping;
import prompto.code.ICodeStore;
import prompto.code.ImmutableCodeStore;
import prompto.code.MutableCodeStore;
import prompto.compiler.PromptoClassLoader;
import prompto.config.CmdLineConfigurationReader;
import prompto.config.IConfigurationReader;
import prompto.config.IDebugConfiguration;
import prompto.config.IDebugEventAdapterConfiguration;
import prompto.config.IDebugRequestListenerConfiguration;
import prompto.config.IRuntimeConfiguration;
import prompto.config.IStandaloneConfiguration;
import prompto.config.IStoreConfiguration;
import prompto.config.StandaloneConfiguration;
import prompto.config.TempDirectories;
import prompto.config.YamlConfigurationReader;
import prompto.debug.IDebugEventAdapter;
import prompto.debug.IDebugEventAdapterFactory;
import prompto.debug.IDebugRequestListener;
import prompto.debug.IDebugRequestListenerFactory;
import prompto.debug.IDebugger;
import prompto.debug.ProcessDebugger;
import prompto.debug.ProcessDebugger.DebuggedWorker;
import prompto.debug.ProcessStatus;
import prompto.debug.WorkerDebugger;
import prompto.debug.WorkerStatus;
import prompto.debug.event.ConnectedDebugEvent;
import prompto.declaration.AttributeDeclaration;
import prompto.declaration.IDeclaration;
import prompto.error.PromptoError;
import prompto.error.TerminatedError;
import prompto.expression.ValueExpression;
import prompto.expression.IExpression;
import prompto.grammar.Identifier;
import prompto.intrinsic.PromptoDict;
import prompto.intrinsic.PromptoDocument;
import prompto.intrinsic.PromptoVersion;
import prompto.java.JavaIdentifierExpression;
import prompto.libraries.Libraries;
import prompto.reader.YAMLReader;
import prompto.store.AttributeInfo;
import prompto.store.DataStore;
import prompto.store.IStore;
import prompto.store.IStoreFactory;
import prompto.store.memory.MemStore;
import prompto.type.DictType;
import prompto.type.IType;
import prompto.type.ListType;
import prompto.type.TextType;
import prompto.utils.CmdLineParser;
import prompto.utils.IdentifierList;
import prompto.utils.Logger;
import prompto.utils.TypeUtils;
import prompto.value.DictionaryValue;
import prompto.value.IValue;
import prompto.value.TextValue;
import prompto.writer.YAMLWriter;
public abstract class Standalone {
private static Logger logger = new Logger();
private static PromptoClassLoader classLoader;
private static IDebugRequestListener debugRequestListener;
private static IDebugEventAdapter debugEventAdapter;
public static IRuntimeConfiguration configuration;
public static void main(String[] args) throws Throwable {
IStandaloneConfiguration config = loadConfiguration(args);
main(config, null, null);
}
public static void main(IStandaloneConfiguration config, ICodeStore codeStore, IStore dataStore) throws Throwable {
initialize(config, codeStore, dataStore);
run(config);
}
public static void run(IStandaloneConfiguration config) throws Throwable {
IDebugConfiguration debug = config.getDebugConfiguration();
String testMethod = config.getTestMethod();
if(testMethod!=null) {
if(debug!=null)
debugTest(debug, testMethod);
else
runTest(testMethod);
} else {
String mainMethod = config.getMainMethod();
IExpression argsValue = argsToArgValue(config.getArguments());
if(debug!=null)
debugApplication(debug, mainMethod, argsValue);
else
runApplication(mainMethod, argsValue);
}
}
private static IStandaloneConfiguration loadConfiguration(String[] args) throws IOException {
Map<String, String> argsMap = CmdLineParser.read(args);
IConfigurationReader reader = readerFromArgs(argsMap);
IStandaloneConfiguration config = new StandaloneConfiguration(reader, argsMap);
return config.withRuntimeLibs(()->Libraries.getPromptoLibraries(Libraries.class));
}
public static IConfigurationReader readerFromArgs(Map<String, String> argsMap) throws IOException {
if(argsMap.containsKey("yamlConfigFile")) {
try(InputStream input = loadYamlData(argsMap.get("yamlConfigFile"))) {
return new YamlConfigurationReader(input);
}
} else
return new CmdLineConfigurationReader(argsMap);
}
private static InputStream loadYamlData(String path) throws FileNotFoundException {
File file = new File(path);
if(file.exists())
return new FileInputStream(file);
InputStream resource = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
if(resource!=null)
return resource;
else
throw new FileNotFoundException(path);
}
public static PromptoDocument<String, Object> getApplicationConfiguration() {
try {
YamlMapping mapping = configuration.toYaml();
String yaml = YAMLWriter.write(mapping);
List<PromptoDocument<String, Object>> docs = YAMLReader.read(yaml);
return docs.get(0);
} catch(Throwable t) {
throw new InternalError("getApplicationConfiguration failed!", t);
}
}
public static void initialize(IRuntimeConfiguration config) throws Throwable {
initialize(config, null, null);
}
public static void initialize(IRuntimeConfiguration config, ICodeStore codeStore, IStore dataStore) throws Throwable {
configuration = config;
Mode.set(config.getRuntimeMode());
TempDirectories.create();
if(codeStore==null)
codeStore = initializeCodeStore(config);
if(dataStore==null)
dataStore = initializeDataStore(config);
synchronizeSchema(codeStore, dataStore);
}
public static ICodeStore initializeCodeStore(IRuntimeConfiguration config) throws Throwable {
// in SEED scenario, cfg from store is null to ensure latest code from resource is always used
// so we use MemStore to stay consistent, but its content will never be persisted
IStore store = null;
IStoreConfiguration cfg = config.getCodeStoreConfiguration();
if(cfg!=null)
store = IStoreFactory.newStoreFromConfig(cfg);
if(store==null)
store = new MemStore();
boolean isMemStore = store instanceof MemStore;
logger.debug(()->"Using " + ( isMemStore ? "MemStore" : cfg.toString()) + " as code store");
return bootstrapCodeStore(store, config);
}
public static IStore initializeDataStore(IRuntimeConfiguration config) throws Throwable {
IStoreConfiguration cfg = config.getDataStoreConfiguration();
logger.debug(()->"Using " + (cfg==null ? "MemStore" : cfg.toString()) + " as data store");
IStore store = IStoreFactory.newStoreFromConfig(cfg);
return bootstrapDataStore(store);
}
public static PromptoClassLoader getClassLoader() {
return classLoader;
}
private static void runTest(String testMethod) {
runTest(ApplicationContext.get(), testMethod);
}
private static void runTest(Context context, String testMethod) {
try {
if("all".equals(testMethod))
Interpreter.interpretTests(context);
else
Interpreter.interpretTest(context, new Identifier(testMethod), true);
} finally {
context.notifyCompleted();
}
}
private static void debugTest(IDebugConfiguration debug, String testMethod) throws Throwable {
Context local = null;
try {
ProcessDebugger debugger = startProcessDebugger(debug);
local = ApplicationContext.get().newLocalContext();
wireProcessDebugger(debugger, local);
runTest(local, testMethod);
} catch(TerminatedError e) {
if(local!=null)
local.notifyCompleted();
} finally {
stopProcessDebugger();
}
}
private static void runApplication(String mainMethod, IExpression args) {
runApplication(ApplicationContext.get(), mainMethod, args);
}
private static void runApplication(Context context, String mainMethod, IExpression args) {
try {
// TODO use args
Interpreter.interpretMethod(context, new Identifier(mainMethod), "");
} finally {
context.notifyCompleted();
}
}
private static void debugApplication(IDebugConfiguration debug, String mainMethod, IExpression args) throws Throwable {
Context local = null;
try {
ProcessDebugger debugger = startProcessDebugger(debug);
local = ApplicationContext.get().newLocalContext();
wireProcessDebugger(debugger, local);
runApplication(local, mainMethod, args);
} catch(TerminatedError e) {
if(local!=null)
local.notifyCompleted();
} finally {
stopProcessDebugger();
}
}
public static IDebugEventAdapter getDebugEventAdapter() {
return debugEventAdapter;
}
public static IDebugRequestListener getDebugRequestListener() {
return debugRequestListener;
}
public static ProcessDebugger startProcessDebugger(IDebugConfiguration config) throws Throwable {
// wire adapter which will send events to client
debugEventAdapter = createDebugEventAdapter(config);
ProcessDebugger processDebugger = ProcessDebugger.createInstance(ApplicationContext.get());
processDebugger.setListener(debugEventAdapter);
// wire listener which will receive requests from client
debugRequestListener = createDebugRequestListener(config, processDebugger);
ConnectedDebugEvent connected = debugRequestListener.startListening();
debugEventAdapter.onConnectedEvent(connected);
return processDebugger;
}
public static void wireProcessDebugger(ProcessDebugger processDebugger, Context context) {
logger.info(()->"Wiring process debugger...");
// wire context to debugger
WorkerDebugger workerDebugger = startWorkerDebugger(Thread.currentThread(), context);
processDebugger.setProcessStatus(ProcessStatus.PROCESS_RUNNING);
// step in start method by default
// TODO: make this configurable
workerDebugger.stepInto();
logger.info(()->"Process debugger wired.");
}
public static void stopProcessDebugger() {
ProcessDebugger processDebugger = ProcessDebugger.getInstance();
processDebugger.setProcessStatus(ProcessStatus.PROCESS_TERMINATING);
debugEventAdapter.onProcessTerminatedEvent();
processDebugger.setProcessStatus(ProcessStatus.PROCESS_TERMINATED);
debugRequestListener.stopListening();
}
public static WorkerDebugger startWorkerDebugger(Thread thread, Context context) {
WorkerDebugger workerDebugger = new WorkerDebugger();
ProcessDebugger.getInstance().register(Thread.currentThread(), workerDebugger);
debugEventAdapter.onWorkerStartedEvent(DebuggedWorker.wrap(Thread.currentThread()));
workerDebugger.setListener(debugEventAdapter);
context.setDebugger(workerDebugger);
workerDebugger.setWorkerStatus(WorkerStatus.WORKER_RUNNING);
return workerDebugger;
}
public static IDebugRequestListener createDebugRequestListener(IDebugConfiguration cfg, IDebugger debugger) throws Throwable {
IDebugRequestListenerConfiguration config = cfg.getRequestListenerConfiguration();
if(config==null)
throw new RuntimeException("Missing requestListener in debug config!");
return IDebugRequestListenerFactory.newListenerFromConfig(config, debugger);
}
public static IDebugEventAdapter createDebugEventAdapter(IDebugConfiguration cfg) throws Throwable {
IDebugEventAdapterConfiguration config = cfg.getEventAdapterConfiguration();
if(config==null)
throw new RuntimeException("Missing eventAdapter in debug config!");
return IDebugEventAdapterFactory.newAdapterFromConfig(config);
}
public static IExpression argsToArgValue(Map<String, String> args) {
PromptoDict<TextValue, IValue> dict = new PromptoDict<>(true);
for(Map.Entry<String, String> e : args.entrySet())
dict.put(new TextValue(e.getKey()),new TextValue(e.getValue()));
return new ValueExpression(new DictType(TextType.instance()), new DictionaryValue(TextType.instance(), dict));
}
public static void showHelp(String application, String test, PromptoVersion version) {
if(application==null && test==null)
logger.info(()->"Missing argument: -application or -test");
if(version.equals(PromptoVersion.LATEST))
logger.info(()->"Additional argument: -version (optional)");
}
public static IStore bootstrapDataStore(IStore store) throws Exception {
DataStore.setGlobal(store);
DataStore.useGlobal();
return store;
}
public static void synchronizeSchema(ICodeStore codeStore, IStore dataStore) throws PromptoError {
logger.info(()->"Initializing schema...");
Map<String, AttributeDeclaration> columns = getMinimalDataColumns(dataStore);
codeStore.collectStorableAttributes(columns);
Function<Identifier, IDeclaration> locator = id->{
Iterable<IDeclaration> found = codeStore.fetchDeclarations(id.toString());
if(found==null)
return null;
Iterator<IDeclaration> decls = found.iterator();
return decls.hasNext() ? decls.next() : null;
};
Context context = Context.newGlobalsContext();
List<AttributeInfo> infos = columns.values().stream()
.map((c)->c.getAttributeInfo(context, locator))
.filter(Objects::nonNull)
.collect(Collectors.toList());
dataStore.createOrUpdateAttributes(infos);
logger.info(()->"Schema successfully initialized.");
}
public static ICodeStore bootstrapCodeStore(IStore store, IRuntimeConfiguration config) throws Exception {
logger.info(()->"Initializing class loader " + ( Mode.get()==Mode.UNITTEST ? "in test mode" : "") + "...");
classLoader = PromptoClassLoader.initialize(ApplicationContext.init());
JavaIdentifierExpression.registerAddOns(config.getAddOnURLs(), classLoader);
logger.info(()->"Class loader initialized.");
logger.info(()->"Bootstrapping prompto...");
ICodeStore runtime = config.getRuntimeLibs() == null ? null : ImmutableCodeStore.bootstrapRuntime(config.getRuntimeLibs());
ICodeStore codeStore = newQueryableCodeStore(store, runtime, config);
codeStore.upgradeIfRequired();
ICodeStore.setInstance(codeStore);
logger.info(()->"Bootstrapping successful.");
codeStore.setMainModule(config.getApplicationName(), config.getApplicationVersion());
return codeStore;
}
private static ICodeStore newQueryableCodeStore(IStore store, ICodeStore runtime, IRuntimeConfiguration config) {
return new MutableCodeStore(store,
runtime,
config.getApplicationName(),
config.getApplicationVersion(),
config.getAddOnURLs(),
config.getResourceURLs());
}
public static Map<String, AttributeDeclaration> getMinimalDataColumns(IStore dataStore) {
Map<String, AttributeDeclaration> columns = new HashMap<String, AttributeDeclaration>();
// attributes with reserved names, the below declarations will be used
IType dbIdIType = TypeUtils.typeToIType(dataStore.getNativeDbIdClass());
columns.put(IStore.dbIdName, new AttributeDeclaration(new Identifier(IStore.dbIdName), dbIdIType).withStorable(true));
columns.put("category", new AttributeDeclaration(new Identifier("category"),
new ListType(TextType.instance()), new IdentifierList(new Identifier("key"))));
return columns;
}
}
| true
|
5b5cf71fc0628b8ce92414228d361ae7adc72f25
|
Java
|
aholzapfel/ECC
|
/ECC/src/main/java/at/fhhagenberg/sqe/ecc/controllers/ElevatorControlCenterController.java
|
UTF-8
| 7,025
| 2.265625
| 2
|
[] |
no_license
|
package at.fhhagenberg.sqe.ecc.controllers;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import at.fhhagenberg.sqe.ecc.Main;
import at.fhhagenberg.sqe.ecc.viewmodels.Elevator;
import at.fhhagenberg.sqe.ecc.viewmodels.Floor;
import at.fhhagenberg.sqe.ecc.views.ElevatorsListViewCell;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
import sqelevator.IElevator;
public class ElevatorControlCenterController {
@FXML
private ListView<Floor> floors;
@FXML
private FloorsController floorsController;
@FXML
private ListView<Elevator> lvElevators;
protected List<Elevator> elevators = new ArrayList<>();
protected ListProperty<Elevator> listPropertyElevators = new SimpleListProperty<>();
private List<ElevatorsListViewCell> cells = new ArrayList<>();
private IElevator elevatorSystem;
private long clockTime;
private List<Integer> requestTargetQueue = new ArrayList<>();
private List<Integer> elevatorTargetQueue = new ArrayList<>();
public void init(IElevator elevatorSystem) {
try {
this.elevatorSystem = elevatorSystem;
floorsController.init(elevatorSystem);
for (int i = 0; i <= elevatorSystem.getElevatorNum() - 1; i++) {
elevators.add(initElevatorFromSystem(new Elevator(i)));
}
lvElevators.itemsProperty().bind(listPropertyElevators);
lvElevators.setCellFactory(new Callback<ListView<Elevator>, ListCell<Elevator>>() {
@Override
public ListCell<Elevator> call(ListView<Elevator> param) {
ElevatorsListViewCell cell = new ElevatorsListViewCell(elevatorSystem);
cells.add(cell);
return cell;
}
});
listPropertyElevators.set(FXCollections.observableArrayList(elevators));
} catch (RemoteException e) {
e.printStackTrace();
}
}
public Runnable updateRunnable = new Runnable() {
public void run() {
try {
if (clockTime != elevatorSystem.getClockTick()) {
// Go throw all elevators and reload their data from elevator system
// Refreshes GUI automatically through binding
for (Elevator elevator : elevators) {
initElevatorFromSystem(elevator);
}
// Refresh floor list
floorsController.refreshFloors();
// Refresh elevator floor lists
for (ElevatorsListViewCell cell : cells) {
cell.refreshFloors();
}
}
clockTime = elevatorSystem.getClockTick();
// check if new targets were pressed, elevators or floors
for (int i = 0; i < elevatorSystem.getFloorNum(); i++) {
// floor button was pressed
if (elevatorSystem.getFloorButtonDown(i) || elevatorSystem.getFloorButtonUp(i)) {
if (!requestTargetQueue.contains(i)) {
// floors to send elevator to
requestTargetQueue.add(i);
}
}
for (int j = 0; j < elevators.size(); j++) {
if (elevatorSystem.getElevatorButton(j, i)) {
insertIntoTargetQueue(j, i);
}
}
}
// setting target
for (Elevator elevator : elevators) {
if (elevator.getAutomatic()) {
// no elevator targets -> take element from floor queue
if (elevator.getNextTarget() == -1) {
if (!requestTargetQueue.isEmpty()) {
for (int i = 0; i < requestTargetQueue.size(); i++) {
if (!elevatorTargetQueue.contains(requestTargetQueue.get(i))) {
elevator.insertTarget(-1, requestTargetQueue.get(i));
elevatorTargetQueue.add(requestTargetQueue.get(i));
elevatorSystem.setTarget(elevator.getNumber(), elevator.getNextTarget());
break;
}
}
}
} else {
if (elevatorSystem.getTarget(elevator.getNumber()) != elevator.getNextTarget()) {
elevatorSystem.setTarget(elevator.getNumber(), elevator.getNextTarget());
}
}
if (elevatorSystem.getElevatorFloor(elevator.getNumber()) == elevatorSystem
.getTarget(elevator.getNumber())
&& elevatorSystem.getElevatorDoorStatus(elevator.getNumber()) == 1) {
if (elevator.getNextTarget() == -1) {
if (elevatorTargetQueue.contains(elevatorSystem.getTarget(elevator.getNumber()))) {
int toRemove = elevatorTargetQueue
.indexOf(elevatorSystem.getTarget(elevator.getNumber()));
elevatorTargetQueue.remove(toRemove);
toRemove = requestTargetQueue.indexOf(elevator.getNextTarget());
if (toRemove != -1) {
requestTargetQueue.remove(toRemove);
}
}
} else {
if (requestTargetQueue.contains(elevator.getNextTarget())) {
int toRemove = requestTargetQueue.indexOf(elevator.getNextTarget());
requestTargetQueue.remove(toRemove);
}
if (elevatorTargetQueue.contains(elevator.getNextTarget())) {
int toRemove = elevatorTargetQueue.indexOf(elevator.getNextTarget());
elevatorTargetQueue.remove(toRemove);
} else {
elevator.removeTargetFromList();
}
}
}
}
}
} catch (RemoteException e) {
Main.pollingExecutor.shutdown();
Main.showConnectionLostDialog();
}
}
};
private Elevator initElevatorFromSystem(Elevator elevator) throws RemoteException {
int number = elevator.getNumber();
int payload = elevatorSystem.getElevatorWeight(number);
int speed = elevatorSystem.getElevatorSpeed(number);
int doorStatus = elevatorSystem.getElevatorDoorStatus(number);
int currentFloor = elevatorSystem.getElevatorPosition(number);
elevator.setPayload(payload);
elevator.setSpeed(speed);
elevator.setDoorStatus(doorStatus);
elevator.setCurrentFloor(currentFloor);
return elevator;
}
private void insertIntoTargetQueue(int elevatorNum, int target) throws RemoteException {
if (elevators.get(elevatorNum).getNextTarget() != -1) {
// elevator goes down
if (elevatorSystem.getElevatorFloor(elevatorNum) > elevators.get(elevatorNum).getNextTarget()) {
// requested floor is between target and current position -> stop on the way
if (target < elevatorSystem.getElevatorFloor(elevatorNum)
&& target > elevators.get(elevatorNum).getNextTarget()) {
elevators.get(elevatorNum).insertTarget(0, target);
// targetQueue.add(0, target);
} else {
// giving index -1 appends the target as last element
elevators.get(elevatorNum).insertTarget(-1, target);
}
// elevator goes up
} else {
// requested floor is between target and current position -> stop on the way
if (target > elevatorSystem.getElevatorFloor(elevatorNum)
&& target < elevators.get(elevatorNum).getNextTarget()) {
elevators.get(elevatorNum).insertTarget(0, target);
} else {
// giving index -1 appends the target as last element
elevators.get(elevatorNum).insertTarget(-1, target);
}
}
} else {
elevators.get(elevatorNum).insertTarget(-1, target);
}
}
}
| true
|
aa20449306acfe232b5b2e61ba28208a538c4bf1
|
Java
|
bulentrahimkazanci/ByteCode-ControlFlowGraph
|
/src/cfgparser/TestData.java
|
UTF-8
| 2,082
| 3.296875
| 3
|
[] |
no_license
|
package cfgparser;
public class TestData {
public void test1(){
int x = 3;
int y = 5;
if(x <= 2){
if(y >= 4){
System.out.println("x <=2 and y >= 4");
}else{
System.out.println("x <= 2 and y < 4");
}
}else{
if(y >= 4){
System.out.println("x > 2 and y >= 4");
}else{
System.out.println("x < 2 and y < 4");
}
}
}
public void test2(){
int x = 4;
int y = 4;
if(x < y){
System.out.println("x < y");
}else
if(y < x){
System.out.println("y < x");
}else{
System.out.println("x = y");
}
}
public void test3(){
int x = 5;
int y = 5;
while(x < y){
System.out.println("x < y");
++x;
}
}
public void test4(){
int x = 4;
int y = 5;
while(x < y){
System.out.println("x < y");
++x;
}
}
public void test5(){
int x = 3;
int y = 5;
while(x < y){
System.out.println("x < y");
++x;
}
}
public void IfElse(int x) {
if (x < 3) {
x = 6;
} else {
x = 7;
}
}
public int IfElseIf(int y) {
int x = 1;
if (x == y) {
y = 6;
} else
if (x == 8) {
System.out.println("x == 7");
} else {
y = 1;
}
return x;
}
public int ManyIfElse(int y) {
int x = 1;
if (x == y) {
y = 6;
} else
if (x == 8) {
y = 7;
} else
if (x == 6) {
y = 1;
} else
if (x == 5) {
y = 4;
}
return x;
}
public void ForLoopExample() {
int x = 3;
for(int i = 0; i < x; i++)
System.out.print("i: " + i);
}
}
| true
|
eb132be829404439c8f0aa50dff0a4ecfae7275e
|
Java
|
Yamane/lhz_enemy_builder
|
/src/lhz/enemy/model/narrow/Troll1.java
|
UTF-8
| 2,765
| 2.6875
| 3
|
[] |
no_license
|
package lhz.enemy.model.narrow;
import java.util.Arrays;
import java.util.List;
import lhz.enemy.model.Enemy;
import lhz.enemy.model.EnemySkill;
import lhz.enemy.model.EnemyType;
import lhz.enemy.model.NarrowRace;
import lhz.enemy.model.Race;
public class Troll1 extends NarrowRace {
public static final NarrowRace instance = new Troll1();
private Troll1() {
super(Race.DEMI_HUMAN, "灰色大鬼 (トロウル)");
tags = Arrays.asList("巨人", "暗視");
}
@Override
public List<EnemyType> getApplyTypes() {
return Arrays.asList(EnemyType.FENCER);
}
@Override
public List<EnemySkill> getDefaultSkills(Enemy enemy) {
EnemySkill skill = new EnemySkill("灰色大鬼の生命力", "クリンナップ");
skill.createFunction("このエネミーは【HP】を%d点回復する。この特技はエネミーがこのラウンドに[火炎][光輝]タグを持つダメージを受けていた場合は使用できない。", enemy.getStubborn(0.25));
return Arrays.asList(skill);
}
@Override
public List<EnemySkill> getArrangeSkills(Enemy enemy) {
EnemySkill skill1 = createMajorMeleeSkill(enemy, "捕獲する腕");
Integer arg1 = new Float(getDamageFix(enemy) * 0.9).intValue();
skill1.createFunction("対象に[%d+2D]の物理ダメージと[硬直]を与える。この[硬直]は通常の方法では解除されず、対象とこのエネミーが別のSqに離れた時のみ解除される。〔対象:硬直〕このエネミーの攻撃に対する対象の【物理防御力】は、対象の【STR】の値に等しいものとして扱う。", arg1);
EnemySkill skill2 = createMajorMeleeSkill(enemy, "引き裂く豪腕");
Integer arg2 = getDamageFix(enemy);
Integer arg3 = enemy.getAttackRole() + 9;
Integer arg4 = enemy.getParameter(4, 1, 10);
skill2.createFunction("対象に[%d+2D]の物理ダメージを与える。〔達成値:%d〕対象に[硬直]と[追撃:%d]を与える。このふたつのBSはひとつとして扱い、どちらかを解除すれば両方解除される。〔対象:硬直〕この特技の[攻撃判定]に+2。", arg2, arg3, arg4);
return Arrays.asList(skill1, skill2);
}
@Override
public Integer getAvoid(Enemy enemy) {
Integer def = super.getAvoid(enemy);
return def > 2 ? def - 2 : 0;
}
@Override
public Integer getResist(Enemy enemy) {
Integer def = super.getResist(enemy);
return def > 2 ? def - 2 : 0;
}
@Override
public Integer getHitPoint(Enemy enemy, Integer defaultValue) {
Integer cr = enemy.getCharacterRank();
Float param = cr > 4 ? 0.6f : cr * 20 / 100f;
return defaultValue + new Float(defaultValue * param).intValue();
}
}
| true
|
585d6b132d2e4925fe5b2497d96076cd3fb3b8bc
|
Java
|
juancsosap/javatraining
|
/JavaApps/src/GenericDAO/Storable.java
|
UTF-8
| 235
| 1.765625
| 2
|
[] |
no_license
|
package GenericDAO;
public interface Storable<T, K> extends Gettable<K>,
Updatable<T>,
Listable,
Selectable {}
| true
|
a80806a86bb0fbb3b2539a34bd63eb0964c451f2
|
Java
|
omarabdillah91/coachingapplication
|
/app/src/main/java/dao/CoachingQuestionAnswerDAO.java
|
UTF-8
| 4,284
| 2.375
| 2
|
[] |
no_license
|
package dao;
import android.util.Log;
import android.util.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import entity.CoachingQuestionAnswerEntity;
import io.realm.Realm;
import io.realm.RealmResults;
/**
* Created by adrianch on 15/08/2016.
*/
public class CoachingQuestionAnswerDAO {
private static final String TAG = "CoachingQuestionAnswer";
public static void getCoachingQA(String coachingSessionID, GetCoachingQAListener listener) {
Realm realm = Realm.getDefaultInstance();
RealmResults<CoachingQuestionAnswerEntity> coachingQuestionAnswerEntities =
realm.where(CoachingQuestionAnswerEntity.class)
.equalTo("coachingSessionID", coachingSessionID).findAll();
listener.onQuestionAnswerReceived(coachingQuestionAnswerEntities);
}
public static void getCoachingQA(String coachingSessionID, GetCoachingQAMapListener listener){
Realm realm = Realm.getDefaultInstance();
RealmResults<CoachingQuestionAnswerEntity> coachingQuestionAnswerEntities =
realm.where(CoachingQuestionAnswerEntity.class)
.equalTo("coachingSessionID", coachingSessionID).findAll();
Map<Pair<String, String>, CoachingQuestionAnswerEntity> map = new HashMap<>();
Log.d(TAG, "size : " + coachingQuestionAnswerEntities.size());
for(CoachingQuestionAnswerEntity entity: coachingQuestionAnswerEntities){
map.put(new Pair<>(entity.getQuestionID(), entity.getColumnID()), entity);
}
/*for(int i = 0; i < map.size(); i++){
Pair<String, String> temp = (Pair)map.keySet().toArray()[i];
Log.d(TAG, "MAP size : " + temp.first + temp.second);
}*/
listener.onQAMapReceived(map);
}
public static List<CoachingQuestionAnswerEntity> filterQAByQuestionID(Collection<CoachingQuestionAnswerEntity> entityList,
String questionID){
List<CoachingQuestionAnswerEntity> result = new ArrayList<>();
for(CoachingQuestionAnswerEntity entity : entityList){
if(entity.getQuestionID() == questionID){
result.add(entity);
}
}
return result;
}
public static List<CoachingQuestionAnswerEntity> filterQAByColumnID(Collection<CoachingQuestionAnswerEntity> entityList,
String columnID){
List<CoachingQuestionAnswerEntity> result = new ArrayList<>();
for(CoachingQuestionAnswerEntity entity : entityList){
if(entity.getColumnID() == columnID){
result.add(entity);
}
}
return result;
}
public static String[] uniqueColumnID(Collection<CoachingQuestionAnswerEntity> entityList){
Set<String> result = new HashSet<>();
for(CoachingQuestionAnswerEntity entity : entityList){
if(entity.getColumnID().contentEquals("")){
continue;
}
result.add(entity.getColumnID());
}
return Arrays.copyOf(result.toArray(), result.size(), String[].class);
}
public static void insertCoachingQA(List<CoachingQuestionAnswerEntity> coachingQuestionAnswerEntities,
InsertCoachingQAListener listener) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(coachingQuestionAnswerEntities);
realm.commitTransaction();
listener.onInsertQuestionAnswerCompleted(true);
}
public interface GetCoachingQAListener {
void onQuestionAnswerReceived(List<CoachingQuestionAnswerEntity>
coachingQuestionAnswerEntityList);
}
public interface GetCoachingQAMapListener {
void onQAMapReceived(Map<Pair<String, String>, CoachingQuestionAnswerEntity> qaMap);
}
public interface InsertCoachingQAListener {
void onInsertQuestionAnswerCompleted(boolean isSuccess);
}
}
| true
|
faf343785d1e0aa92ed2bcaa299333c0388b9eb4
|
Java
|
sanrentai/manyi
|
/trunk/CallCenterSystem/src/com/ecpss/mp/controller/MainController.java
|
UTF-8
| 1,247
| 1.976563
| 2
|
[] |
no_license
|
package com.ecpss.mp.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.ecpss.mp.BaseController;
import com.ecpss.mp.Global;
import com.ecpss.mp.entity.Employee;
import com.ecpss.mp.uc.service.MainService;
@Controller
@SessionAttributes(Global.SESSION_UID_KEY)
public class MainController extends BaseController {
@Autowired
@Qualifier("mainService")
private MainService mainService;
@RequestMapping(value = "/index")
@SuppressWarnings("rawtypes")
public String index(HttpServletRequest request) {
//判断用户是否登录
Employee loginEmployee = (Employee) request.getSession().getAttribute("loginEmployee");
if(loginEmployee != null){
return "index";
}else{
return "login";
}
}
public MainService getMainService() {
return mainService;
}
public void setMainService(MainService mainService) {
this.mainService = mainService;
}
}
| true
|
573404fbb8498380e6fc5f1a42adccb02f637b9c
|
Java
|
MyMoneyForWho/fenqipai
|
/src/com/fenqipai/fenqipaiandroid/ServiceEvaluationActivity.java
|
UTF-8
| 2,642
| 2.046875
| 2
|
[] |
no_license
|
package com.fenqipai.fenqipaiandroid;
import com.fenqipai.fenqipaiandroid.base.BaseActivity;
import com.fenqipai.fenqipaiandroid.base.BaseApplication;
import com.fenqipai.fenqipaiandroid.util.StringUtils;
import com.fenqipai.fenqipaiandroid.util.ToastUtils;
import com.fenqipai.fenqipaiandroid.view.TitleBarView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
/**
* @Description:服务评分界面
* @author hunaixin
* @date 2016年11月25日 下午2:06:37
*/
public class ServiceEvaluationActivity extends BaseActivity {
// 标题栏
@ViewInject(R.id.service_evaluation_titleBar)
private TitleBarView titleBarView;
// 确认提交
@ViewInject(R.id.confirm_btn)
private Button confirmBtn;
// 评分条
@ViewInject(R.id.ratingbar)
private RatingBar mRatingBar;
// 反馈内容
@ViewInject(R.id.feedback_et)
private EditText feedbackEt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_evaluation);
// 注入view和事件
ViewUtils.inject(this);
initView();
initEvent();
}
/**
* @Description:初始化视图
* @author hunaixin
* @parame
* @return
*/
public void initView() {
application = (BaseApplication) getApplication();
titleBarView.setCommonTitle(View.VISIBLE, View.GONE, View.VISIBLE, View.GONE, View.GONE);
titleBarView.setBtnLeft(R.drawable.btn_back);
titleBarView.setTitleText(R.string.service_evaluation);
}
/**
* @Description:初始化事件
* @author hunaixin
* @parame
* @return
*/
public void initEvent() {
titleBarView.setBtnLeftOnclickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mRatingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
}
});
confirmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (StringUtils.isEmpty(feedbackEt.getText().toString())) {
ToastUtils.show(ServiceEvaluationActivity.this, "反馈内容不得为空", ToastUtils.TOAST_SHORT);
}else {
ToastUtils.show(ServiceEvaluationActivity.this, "提交成功", ToastUtils.TOAST_SHORT);
finish();
}
}
});
}
}
| true
|
a86919a71e072592df17aba0992e786856e832cd
|
Java
|
Tikitoo/DaggerExample
|
/app/src/main/java/com/antonioleiva/daggerexample/app/samples/CoffeeApp.java
|
UTF-8
| 1,909
| 2.9375
| 3
|
[] |
no_license
|
package com.antonioleiva.daggerexample.app.samples;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Component;
import dagger.Lazy;
import dagger.Module;
import dagger.Provides;
public class CoffeeApp {
@Singleton
@Component(modules = { DripCoffeeModule.class })
public interface Coffee {
CoffeeMaker maker();
}
public static void main(String[] args) {
Coffee coffee = DaggerCoffeeApp_Coffee.builder().build();
coffee.maker().brew();
}
}
class CoffeeMaker {
private final Lazy<Heater> heater;
private final Pump pump;
@Inject
public CoffeeMaker(Lazy<Heater> heater, Pump pump) {
this.heater = heater;
this.pump = pump;
}
public void brew() {
heater.get().on();
pump.pump();
System.out.println("pump ==> coffee ==> pump");
heater.get().off();
}
}
interface Heater {
void on();
void off();
boolean isHot();
}
class ElectricHeater implements Heater {
boolean isHot = false;
@Override
public void on() {
System.out.println("~~~~ isHoting ~~~~");
isHot = true;
}
@Override
public void off() {
isHot = true;
}
@Override
public boolean isHot() {
return isHot;
}
}
interface Pump {
void pump();
}
class Thermosiphon implements Pump {
private final Heater mHeater;
@Inject
public Thermosiphon(Heater heater) {
mHeater = heater;
}
@Override
public void pump() {
if (mHeater.isHot()) {
System.out.println("==> pumping ==>");
}
}
}
@Module(includes = PumpModule.class)
class DripCoffeeModule {
@Provides @Singleton
Heater provideHeater() {
return new ElectricHeater();
}
}
@Module
class PumpModule {
@Provides Pump providePump(Thermosiphon pump) {
return pump;
}
}
| true
|
557e6cca06570155e0a00000410b8bb6fa7d4b58
|
Java
|
Merray/ProjetVolSpring
|
/src/main/java/repositories/VilleRepository.java
|
UTF-8
| 183
| 1.78125
| 2
|
[] |
no_license
|
package repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import model.Ville;
public interface VilleRepository extends JpaRepository<Ville, Integer>{
}
| true
|
c861a8a22cf4cd773b60f5bc594158fea8c3950a
|
Java
|
lixuan789/guli_admin
|
/guli_java/service/service_edu/src/main/java/com/lixuan/service/edu/client/OssClient.java
|
UTF-8
| 492
| 1.710938
| 2
|
[] |
no_license
|
package com.lixuan.service.edu.client;
import com.lixuan.common.base.result.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient("service-oss")
@Component
public interface OssClient {
@DeleteMapping("/api/oss/detele")
Result deleteOssFile(@RequestParam("filename") String filename);
}
| true
|
910e69a9c1175773a824aefbd214c1296efe9176
|
Java
|
elflautero/FiscalizacaoSRH2
|
/src/main/java/controllers/TabNavegadorController.java
|
UTF-8
| 18,911
| 1.875
| 2
|
[] |
no_license
|
package controllers;
import java.awt.List;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javax.swing.text.TableView;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.web.PopupFeatures;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TabNavegadorController implements Initializable{
//-- Link de entrada do navegador WebView --//
String link = "https://sei.df.gov.br/sip/login.php?sigla_orgao_sistema=GDF&sigla_sistema=SEI";
int contDocSei;
//-- Array de Strings - Documentos Capturados --//
String[] docsSei; // = new String [contDocSei];
static String html;
// array list para a captura de dados dos documentos --//
ArrayList<String> docsList = new ArrayList<String>();
@FXML Pane pBrowser;
@FXML AnchorPane tabNavegador = new AnchorPane();
@FXML
Button btnSEI = new Button();
@FXML
Button btnCapturarDocs = new Button();
@FXML
Button btnMostrarDocs = new Button();
@FXML
Button btnGo = new Button();
@FXML
Button btnGoogle = new Button();
WebView wv1;
// table view de documentos capturados do sei
ObservableList<String []> numDosObservable;
TableView tv;
WebView wv2;
//-- botão Google --//
public void btnGoogleHab (ActionEvent event) {
link = "https://www.google.com.br/search?q=googlr&oq=googlr&aqs=chrome..69i57j0l5.2588j0j7&sourceid=chrome&ie=UTF-8";
navegarWeb();
System.out.println("btn google clicado");
}
//-- botão SEI --//
public void btnSEIHab (ActionEvent event) {
link = "http://treinamento3.sei.df.gov.br/sip/login.php?sigla_orgao_sistema=GDF&sigla_sistema=SEI";
navegarWeb();
System.out.println("btn sei treinamento clicado");
}
//-- botão capturar --//
public void btnCapturarDocsHab (ActionEvent event) {
// adicionar execeção https://github.com/Microsoft/ClearScript/issues/16
wv1.getEngine().executeScript(
"var doc;"
+ "$(function() {"
+ "$( '#ifrArvore' ).load(function(){"
//+ "alert('iframe carregado');"
//+ "alert($(this).contents().find('span'));"
+ "$(this).contents().find( 'span' ).css( 'background-color', '#BADA55' );"
+ "doc = ($(this).contents().find('span'));"
//+ "alert(doc);"
+ "for (var i = 0; i < doc.length; i++) {"
//+ "alert (doc[i].textContent);"
+ "}"
+ "});"
+ "});"
);
}
public void btnMostrarDocsHab (ActionEvent event ) {
// adicionar execeção https://github.com/Microsoft/ClearScript/issues/16
contDocSei = (int) wv1.getEngine().executeScript("doc.length"); // quantidade de docs capturados
docsSei = new String [contDocSei]; // para limitar a quantidade de strings na array
for (int i = 0; i < contDocSei; i++ ) {
String strDocSei = (String) wv1.getEngine().executeScript("doc[" + i + "].textContent");
docsSei [i] = strDocSei;
}
for (int z = 0; z < contDocSei; z++) {
docsList.add(docsSei[z]);
}
ObservableList<String> documentos = FXCollections.observableArrayList(docsSei);
ListView<String> listView = new ListView<String>(documentos);
TableColumn<List, String> tc = new TableColumn<List, String> ("Documentos");
tc.setCellValueFactory(new Callback<CellDataFeatures<List, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<List, String> p) {
return new SimpleStringProperty(p.getValue().toString());
}
});
//TableView tv = new TableView(listView);
Scene scene = new Scene(listView);
Stage stage = new Stage(); // StageStyle.UTILITY - tirei para ver como fica, se aparece o minimizar
stage.setWidth(400);
stage.setHeight(300);
stage.setScene(scene);
stage.setMaximized(false);
stage.setResizable(false);
stage.setX(1030.0);
stage.setY(550.0);
stage.setAlwaysOnTop(true);
stage.show();
//-- https://docs.oracle.com/javafx/2/ui_controls/ListViewSample.java.html --//
listView.getSelectionModel().selectedItemProperty().addListener(
new ChangeListener<String>() {
public void changed(ObservableValue<? extends String>
ov, String old_val, String new_val) {
Clipboard clip = Clipboard.getSystemClipboard();
ClipboardContent conteudo = new ClipboardContent();
conteudo.putString(new_val);
clip.setContent(conteudo);
}
});
}
//-- botão Go - atualizar navegador --//
public void bntGoHab (ActionEvent event) {
link = "https://www.google.com.br/search?q=googlr&oq=googlr&aqs=chrome..69i57j0l5.2588j0j7&sourceid=chrome&ie=UTF-8";
navegarWeb();
System.out.println("Botão go clicado!");
}
//-- método navegar --//
public void navegarWeb() {
wv1 = new WebView();
wv1.setPrefSize(1117.0,571.0);
//wv1.setLayoutY(78);
wv1.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {
public WebEngine call(PopupFeatures p) {
wv2 = new WebView();
wv2.setPrefHeight(645.0); // wv2, 1140.0, 650.0
wv2.setPrefWidth(1140.0);
wv2.setLayoutY(35);
Button btnIframe = new Button ("Incluir");
btnIframe.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
/*
File file = new File("../FiscalizacaoSRH/src/main/resources/html/autodeinfracao.html");
Document docHtml = null;
try {
docHtml = Jsoup.parse(file, "UTF-8"); // retirei o .clone()
} catch (IOException e1) {
System.out.println("Erro na leitura do documento e Jsoup!!!");
e1.printStackTrace();
}
docHtml.select("nomeus").prepend("Fabrício José Barrozo");
String html = docHtml.toString();
html = html.replace("\"", "'");
html = html.replace("\n", "");
html = "\"" + html + "\"";
*/
//-- imprimir o relatório ou tn no editor do SEI --//
wv2.getEngine().executeScript(
"var x = document.getElementsByTagName('iframe')[1];"
+ "var y = x.contentDocument;"
+ "y.body.innerHTML = " + html + ";"
);
}
});
btnIframe.setLayoutY(8);
btnIframe.setLayoutX(502);
Group group = new Group();
group.getChildren().addAll(btnIframe, wv2);
Stage stage = new Stage(); // StageStyle.UTILITY
stage.setScene(new Scene(group));
stage.show();
return wv2.getEngine();
}
});
//-- para imprimir no console java os alerts do javascript --//
wv1.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {
@Override
public void handle(WebEvent<String> event) {
System.out.println(event.getData());
//-- Alerta de senha ou usuário errado --//
Alert aLogin = new Alert (Alert.AlertType.ERROR);
aLogin.setTitle("Atenção!!!");
aLogin.setContentText(event.getData().toString());
aLogin.setHeaderText(null);
aLogin.show();
}
});
StackPane root = new StackPane();
root.getChildren().add(wv1);
//-- habilitar javascript --//
wv1.getEngine().setJavaScriptEnabled(true);
wv1.getEngine().load(link);
//tabNavegador.getChildren().add(wv1);
pBrowser.getChildren().add(wv1);
}
//-- INITIALIZE --//
@Override
public void initialize(URL url, ResourceBundle rb) {
// -- inicitalizar o mapa -- //
Platform.runLater(() ->{
navegarWeb();
});
}
}
/*
Object html = (Object) wv1.getEngine().executeScript("document.getElementsByTagName('a')[" + i + "].innerHTML");
Object htmlOuter = (Object) wv1.getEngine().executeScript("document.getElementsByTagName('a')[" + i + "].outerHTML");
Object htmlSpan = (Object) wv1.getEngine().executeScript("document.getElementsByTagName('span')[" + i + "].innerHTML");
Object htmlSpanOuter = (Object) wv1.getEngine().executeScript("document.getElementsByTagName('span')[" + i + "].outerHTML");
// [" + i + "].innerHTML"
//String htmlOuter = (String) wv1.getEngine().executeScript("document.getElementsById('*')[" + i + "].outerHTML");
//"for (var i = 0; i<5; i++){document.getElementsByTagName('span')[i].innerHTML;}");
System.out.println("inner: " + html);
System.out.println("outer: " + htmlOuter);
System.out.println("innerSpan: " + htmlSpan);
System.out.println("outerSpan: " + htmlSpanOuter);
*/
/*
"var doc;"
+ "$(function() {"
+ "$( '#ifrArvore' ).load(function(){"
+ "alert('iframe carregado');"
+ "alert($(this).contents().find('span'));"
+ "$(this).contents().find( 'span' ).css( 'background-color', '#BADA55' );"
+ "doc = ($(this).contents().find('span'));"
+ "alert(doc);"
+ "for (var i = 0; i < doc.length; i++) {"
+ "alert (doc[i].textContent);"
+ "}"
+ "});"
+ "});"
*/
//link = "http://gis.adasa.df.gov.br/portal/home/index.html";
//navegarWeb();
//System.out.println(wv1.getEngine().getDocument());
//for (int i = 0; i < 10; i++ ) {
//List<?> varOne = (List<?>) wv1.getEngine().executeScript("document.getElementsByTagName('*')[0]");
/*
wv1.getEngine().executeScript("var pro = document.querySelectorAll('span');" +
" for (var y=0; y<pro.length;y++){ " +
" var one = pro[y].innerHTML; " +
" console.log (one);" +
" console.log (y);" +
"}"
);*/
//}
/*
var el = document.getElementsByTagName('*')[0];
console.log(el);
el.addEventListener('click', function() {
alert(el.innerHTML);
});
*/
/* NÃO DEU CERTO
String varOne = (String) wv1.getEngine().executeScript("var el = document.getElementsByTagName('*')[" + i + "].addEventListener('mouseover', function(event) { console.log(event.target.innerHTML); });");
String varTwo = (String) wv1.getEngine().executeScript("el");
System.out.println("one: " + varOne);
String varThree = (String)wv1.getEngine().executeScript("event.target.innerHTML");
System.out.println("two: " + varTwo);
System.out.println("three: " + varThree);
*/
/* FUNCIONANDO BEM, PARA VER SE UMA VARIÁVEL JS PODE SER CHAMADA...
String[] span = new String [10];
span [i] = (String) wv1.getEngine().executeScript("document.getElementsByTagName('span')[" + i + "].innerHTML;"
+ "var oneJS = document.getElementsByTagName('span')[0].innerHTML");
System.out.println("String " + i + " = " + span [i]);
String zero = (String) wv1.getEngine().executeScript("oneJS");
System.out.println("String zero: " + zero);;
*/
//}
//outerHTML não pega o que eu quero
//"
//
//wv1.getEngine().executeScript("alert('Quantidade de querys encontradas abaixo:')");
//wv1.getEngine().executeScript("alert (pro.lenght)");
/*
int count = (int) wv1.getEngine().executeScript("pro.length");
for (int i = 0; i<count; i++) {
String html = (String) wv1.getEngine().executeScript("pro[ " + i + "].innerHTML;");
System.out.println(html);
}
*/
/*
// -- Conexão e pesquisa de denúncias -- //
private DenunciaDao denunciaDao = new DenunciaDao(); //passar classe
private List<Denuncia> denunciaList; // = denunciaDao.listDenuncia(strPesquisa); //passar string de pesquisar
private ObservableList<DenunciaTabela> obsListDenunciaTabela = FXCollections.observableArrayList(); //chamar observable list e outra classe
// --- método listarDenuncias --- //
public void listarDenuncias () {
if (!obsListDenunciaTabela.isEmpty()) {
obsListDenunciaTabela.clear();
}
for (Denuncia denuncia : denunciaList) {
DenunciaTabela denTab = new DenunciaTabela(
denuncia.getCod_Denuncia(),
denuncia.getDoc_Denuncia(),
denuncia.getDoc_SEI_Denuncia(),
denuncia.getProc_SEI_Denuncia(),
denuncia.getDesc_Denuncia(),
// adicionao o ojeto enderecoFK na DenunciaTabela
denuncia.getEnderecoFK()
);
obsListDenunciaTabela.add(denTab);
}
tcDocumento.setCellValueFactory(new PropertyValueFactory<DenunciaTabela, String>("Doc_Denuncia"));
tcDocSEI.setCellValueFactory(new PropertyValueFactory<DenunciaTabela, String>("Doc_SEI_Denuncia"));
tcProcSEI.setCellValueFactory(new PropertyValueFactory<DenunciaTabela, String>("Proc_SEI_Denuncia"));
tvLista.setItems(obsListDenunciaTabela);
*/
/*
// -- Tabela -- //
@FXML private TableView <DenunciaTabela> tvLista;
// -- Colunas -- //
@FXML private TableColumn<DenunciaTabela, String> tcDocumento;
@FXML private TableColumn<DenunciaTabela, String> tcDocSEI;
@FXML private TableColumn<DenunciaTabela, String> tcProcSEI;
*/
/*
StackPane root = new StackPane();
ObservableList<String[]> data = FXCollections.observableArrayList();
data.addAll(Arrays.asList(docsSei));
//data.remove(0);//remove titles from data
TableView<String[]> table = new TableView<>();
for (int a = 0; a < docsSei[0].length; a++) {
TableColumn tc = new TableColumn(docsSei [0][a]);
final int colNo = a;
tc.setCellValueFactory(new Callback<CellDataFeatures<String[], String>, ObservableValue<String>() {
@Override
public ObservableValue<String> call(CellDataFeatures<String[], String> p) {
return new SimpleStringProperty((p.getValue()[colNo]));
}
});
tc.setPrefWidth(90);
table.getColumns().add(tc);
}
Stage stage = new Stage(); // StageStyle.UTILITY - tirei para ver como fica, se aparece o minimizar
Scene scene = new Scene(table);
stage.setWidth(1250);
stage.setHeight(750);
stage.setScene(scene);
stage.setMaximized(false);
stage.setResizable(false);
*/
/*
table.setItems(data);
root.getChildren().add(table);
stage.setScene(new Scene(root, 300, 250));
stage.show();
*/
/*
List<String[]> numDocsList;
ObservableList<String []> numDocsObservable = FXCollections.observableArrayList();
if (!numDocsObservable.isEmpty()) {
numDocsObservable.clear();
}
numDocsObservable.addAll(docsSei);
TableColumn<Integer, Integer> docsTabCol = new TableColumn ();
docsTabCol.setCellValueFactory(new PropertyValueFactory<DenunciaTabela, String>(docsSei [0][0]));
//tcDocumento.setCellValueFactory(new PropertyValueFactory<DenunciaTabela, String>("Doc_Denuncia"));
/*
ObservableList<String> numDosObservable = FXCollections.observableArrayList(docsSei);
TableView<String []> tvNumerosDocs = new TableView<String []>();
for (int z = 0; z < docsSei.length; z++) {
TableColumn tc = new TableColumn<docsSei [z]>();
}
*/
/*
///
//btnIframe.setLayoutY(8);
//btnIframe.setLayoutX(502);
//btnIframe.setGraphic(new ImageView(imgGetCoord));
*/
/*
public String pegarBuf () {
String FILENAME = "../FiscalizacaoSRH/src/main/resources/html/autodeinfracao.html";
// "../FiscalizacaoSRH/src/main/resources/html/autodeinfracao.html"
// "../json/src/main/resources/html/relatorio.html"
BufferedReader br = null;
FileReader fr = null;
String leitorRelatorio = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
while ((leitorRelatorio = br.readLine()) != null) {
System.out.println(leitorRelatorio);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println(leitorRelatorio);
return leitorRelatorio;
}
*/
/*
String FILENAME = "../FiscalizacaoSRH/src/main/resources/html/autodeinfracao.html";
BufferedReader br = null;
FileReader fr = null;
String leitorRelatorio = null;
StringBuilder strBuilder = new StringBuilder();
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
// passa linha por linha do relatorio e adiciona uma por uma na strBuilder
while ((leitorRelatorio = br.readLine()) != null) {
strBuilder.append(leitorRelatorio);
}
} catch (IOException eIO) {
eIO.printStackTrace();
}
leitorRelatorio = " \" " + strBuilder + " \" " ; // adiciona aspas duplas no html final
*/
| true
|
b32e14d754b09cdf50313b8b4c56611008a09c96
|
Java
|
alberti-tu/DSA
|
/DSA_Android/app/src/main/java/eetac/dsa/juego/vista/JuegoView.java
|
UTF-8
| 2,690
| 2.546875
| 3
|
[] |
no_license
|
package eetac.dsa.juego.vista;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import eetac.dsa.juego.root.Mundo;
/**
* Created by oscar on 24/12/2017.
*/
public class JuegoView extends SurfaceView implements Runnable{
Context context;
SurfaceHolder holder;
Thread gameThread = null;
Paint paint;
Resources mResources;
volatile boolean playing;
Mundo mundo;
int direccion;
MundoDraw mundoDraw;
public Resources getmResources() {
return mResources;
}
public void setmResources(Resources mResources) {
this.mResources = mResources;
mundoDraw = new MundoDraw(mResources);
}
public void setDireccion(int direccion) {
this.direccion = direccion;
}
public JuegoView(Context context, AttributeSet attrs) {
super(context,attrs);
this.context = context;
holder = getHolder();
paint = new Paint();
playing = true;
mundo = Mundo.getIns();
}
@Override
public void run() {
while(playing)
{
update();
draw();
}
}
public void update() {
if(mundo.getEstado()== Mundo.FSM.combate)
{
Mundo.getIns().getCombate().step(1/15f);
}
}
public synchronized void draw() {
if (holder.getSurface().isValid()) {
if(mundo.getEstado()== Mundo.FSM.play)
{
Canvas canvas = holder.lockCanvas();
canvas.drawColor(Color.WHITE);
mundoDraw.drawMapa(canvas,paint,getWidth(),getHeight(), direccion);
holder.unlockCanvasAndPost(canvas);
}
if(mundo.getEstado()== Mundo.FSM.combate)
{
Canvas canvas = holder.lockCanvas();
canvas.drawColor(Color.WHITE);
mundoDraw.drawCombate(canvas,paint,getWidth(),getHeight());
holder.unlockCanvasAndPost(canvas);
}
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
Log.e("Error:", "joining thread");
}
}
// If SimpleGameEngine Activity is started theb
// start our thread.
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
}
| true
|
598e2f2845da39e557982f510421ea565ac0355a
|
Java
|
JustMeFlex/ResidenceSigns-2.0
|
/ResidenceSigns2/src/Flex/ResidenceSigns2/ResidenceListener.java
|
UTF-8
| 1,260
| 2.328125
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Flex.ResidenceSigns2;
import com.bekvon.bukkit.residence.Residence;
import com.bekvon.bukkit.residence.economy.rent.RentManager;
import com.bekvon.bukkit.residence.event.ResidenceOwnerChangeEvent;
import com.bekvon.bukkit.residence.event.ResidenceRentEvent;
import com.bekvon.bukkit.residence.protection.ClaimedResidence;
import org.bukkit.event.CustomEventListener;
import org.bukkit.event.Event;
/**
*
* @author Flex
*/
public class ResidenceListener extends CustomEventListener {
public ResidenceSigns2 plugin;
public ResidenceListener(ResidenceSigns2 instance)
{
plugin = instance;
}
@Override
public void onCustomEvent(Event event)
{
//This just listens for residence events and passes them on to the main class
if(event instanceof ResidenceOwnerChangeEvent)
{
ResidenceOwnerChangeEvent e = (ResidenceOwnerChangeEvent) event;
plugin.updateAllSigns(e);
}
else if(event instanceof ResidenceRentEvent)
{
ResidenceRentEvent e = (ResidenceRentEvent) event;
plugin.updateAllSigns(e);
}
}
}
| true
|
811a6ba32c2902fad1394e99da4059693a0d9bef
|
Java
|
google-code/androtext
|
/xtext_1.x/hu.bme.mit.androtext.data/src-gen/hu/bme/mit/androtext/androDataLang/util/AndroDataLangSwitch.java
|
UTF-8
| 9,313
| 2.421875
| 2
|
[] |
no_license
|
/**
* <copyright>
* </copyright>
*
*/
package hu.bme.mit.androtext.androDataLang.util;
import hu.bme.mit.androtext.androDataLang.*;
import java.util.List;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see hu.bme.mit.androtext.androDataLang.AndroDataLangPackage
* @generated
*/
public class AndroDataLangSwitch<T>
{
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static AndroDataLangPackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AndroDataLangSwitch()
{
if (modelPackage == null)
{
modelPackage = AndroDataLangPackage.eINSTANCE;
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
public T doSwitch(EObject theEObject)
{
return doSwitch(theEObject.eClass(), theEObject);
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(EClass theEClass, EObject theEObject)
{
if (theEClass.eContainer() == modelPackage)
{
return doSwitch(theEClass.getClassifierID(), theEObject);
}
else
{
List<EClass> eSuperTypes = theEClass.getESuperTypes();
return
eSuperTypes.isEmpty() ?
defaultCase(theEObject) :
doSwitch(eSuperTypes.get(0), theEObject);
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(int classifierID, EObject theEObject)
{
switch (classifierID)
{
case AndroDataLangPackage.ANDRO_DATA_ROOT:
{
AndroDataRoot androDataRoot = (AndroDataRoot)theEObject;
T result = caseAndroDataRoot(androDataRoot);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AndroDataLangPackage.TYPE:
{
Type type = (Type)theEObject;
T result = caseType(type);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AndroDataLangPackage.ENTITY:
{
Entity entity = (Entity)theEObject;
T result = caseEntity(entity);
if (result == null) result = caseType(entity);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AndroDataLangPackage.FEATURE:
{
Feature feature = (Feature)theEObject;
T result = caseFeature(feature);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AndroDataLangPackage.TYPE_REF:
{
TypeRef typeRef = (TypeRef)theEObject;
T result = caseTypeRef(typeRef);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AndroDataLangPackage.ENTITY_TYPE_REF:
{
EntityTypeRef entityTypeRef = (EntityTypeRef)theEObject;
T result = caseEntityTypeRef(entityTypeRef);
if (result == null) result = caseTypeRef(entityTypeRef);
if (result == null) result = defaultCase(theEObject);
return result;
}
case AndroDataLangPackage.DATA_TYPE_REF:
{
DataTypeRef dataTypeRef = (DataTypeRef)theEObject;
T result = caseDataTypeRef(dataTypeRef);
if (result == null) result = caseTypeRef(dataTypeRef);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Andro Data Root</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Andro Data Root</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseAndroDataRoot(AndroDataRoot object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Type</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Type</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseType(Type object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Entity</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Entity</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseEntity(Entity object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Feature</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Feature</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseFeature(Feature object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Type Ref</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Type Ref</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseTypeRef(TypeRef object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Entity Type Ref</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Entity Type Ref</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseEntityTypeRef(EntityTypeRef object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Data Type Ref</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Data Type Ref</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseDataTypeRef(DataTypeRef object)
{
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
public T defaultCase(EObject object)
{
return null;
}
} //AndroDataLangSwitch
| true
|