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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
38ab53f812b1bb8765483337ec1a55691065fdd0 | Java | Palenoff/Parking | /Parking_Project/src/ParkRunnable.java | UTF-8 | 668 | 2.90625 | 3 | [] | no_license | import java.util.Random;
import Entities.*;
public class ParkRunnable implements Runnable {
public ParkRunnable(int i) {
this.i = i;
}
private int i;
@Override
public void run() {
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
char letter1 = letters.charAt(rnd.nextInt(letters.length()));
char letter2 = letters.charAt(rnd.nextInt(letters.length()));
StringBuilder sb = new StringBuilder();
sb.append(letter1);
sb.append(letter2);
sb.append(Integer.toString(i));
String sign = sb.toString();
Parking.park(new Car(sign));
}
}
| true |
aa234a3af1fcd7f63f2e8f36081d505fc4306c0c | Java | liqian008/foundation | /foundation-mcap/src/main/java/com/bruce/foundation/macp/api/service/impl/McpCacheManagerImpl.java | UTF-8 | 804 | 1.820313 | 2 | [] | no_license | /**
* $Id $
* Copyright 2009-2011 Oak Pacific Interactive. All rights reserved.
*/
package com.bruce.foundation.macp.api.service.impl;
import java.util.HashMap;
import java.util.Map;
/*
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;*/
import com.bruce.foundation.macp.api.service.McpCacheManager;
/**
* @author liqian
*
*/
public class McpCacheManagerImpl implements McpCacheManager {
private Map<String, Object> sigCache = new HashMap<String, Object>();
private Map<String, Object> userSecretKeyCache = new HashMap<String, Object>();
@Override
public Map<String, Object> getSigCache() {
return sigCache;
}
@Override
public Map<String, Object> getUserSecretKeyCache() {
return userSecretKeyCache;
}
}
| true |
3af13bcc82b392bf2264cd3635b63c33f85a6da7 | Java | huguodong/Cloud-4 | /cloudbusinessservice_mobile/src/main/java/com/ssitcloud/business/mobile/service/RegionService.java | UTF-8 | 1,630 | 2.171875 | 2 | [] | no_license | package com.ssitcloud.business.mobile.service;
import java.util.List;
import com.ssitcloud.common.entity.ResultEntity;
import com.ssitcloud.mobile.entity.RegionEntity;
/**
* 地区服务
* @author LXP
*
*/
public interface RegionService {
/**
* 区域Region实体单个查询
* @param regionEntity
* @return
*/
public abstract ResultEntity selRegionByRegionIdx(RegionEntity regionEntity);
/**
* 区域Region实体多个查询
* @param regionEntity
* @return
*/
ResultEntity selRegionsByRegionCode(RegionEntity regionEntity);
/**
* 区域Region实体多个查询,根据地区码查询地区码符合及其地区码下级地区
* @param regionEntity
* @return
*/
ResultEntity selRegionsOnRegionCode(RegionEntity regionEntity);
/**
* 区域RegionEntity多个查询 可查所有省、省对应的市、对应的区
* 根据传入参数的长度来查不同的实体,长度为0时查出所有省,长度为4时查出对应市,长度为6时查出对应区
* @param regionEntity
* @return
*/
ResultEntity selProCityAreaByRegionCode(RegionEntity regionEntity);
/**
* 根据地区码列表查询地区
* @param regi_codes 地区码列表
* @return 查询到的地区
*/
List<RegionEntity> selRegions(List<String> regi_codes);
/**
* 区域Region实体多个查询(通过regionIdxs)
* @param regionEntity
* @return
*/
ResultEntity selRegionsByRegionIdxs(List l);
/**
* 区域Region实体多个查询,根据地区码查询地区码符合及其地区码下级地区
* @param req
* @return
*/
ResultEntity selRegionsForNormal(String req);
}
| true |
6b9fc604b8556fa6ad5ba68f4d40a9a2d11e1aab | Java | agrawalk9/NAGP-Microservices-Assn | /service-provider/src/main/java/com/nagp/serviceprovider/services/Services.java | UTF-8 | 169 | 1.625 | 2 | [] | no_license | package com.nagp.serviceprovider.services;
public interface Services {
String serviceResponse(String receiverId, String providerId, String reqType, String status);
} | true |
0cec8e6d4e04e3bca4900b8d74b977df4874e824 | Java | TestAkforFun/Second | /TestGT/src/test/java/TestS1.java | UTF-8 | 1,274 | 1.953125 | 2 | [] | no_license | import Base.TestBase;
import helpers.Listner;
import org.openqa.selenium.By;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import pages.FormationChangesRequestPage;
import pages.LoginPage;
import pages.MainPage;
/**
* Created by Администратор on 18.07.2015.
*/
@Listeners(Listner.class)
public class TestS1 extends TestBase{
@Test
public void testSuite1() throws InterruptedException {
LoginPage.inputLogin(driver, user);
LoginPage.inputPassword(driver, password);
LoginPage.clickEnter(driver);
MainPage.goToCreationGroupForm(driver);
MainPage.chooseReconciliationProcess(driver, MainPage.ReconciliationProcess.Etl_10);
MainPage.inputShortName(driver, testShortName);
MainPage.inputFullName(driver, testFullName);
MainPage.pushSaveButton(driver);
MainPage.goToFormationChangesRequestPage(driver);
Thread.sleep(1000);
FormationChangesRequestPage.checkAddedGroup(driver, testShortName);
Thread.sleep(1000);
FormationChangesRequestPage.editAddedGroup(driver, testShortName);
Thread.sleep(1000);
FormationChangesRequestPage.checkFieldsOnCreationGroupForm(driver,testShortName,testFullName);
}
}
| true |
fc6422df1f6a1d0e57dbcd590ba1102824f165c3 | Java | xufengjun/personal_blog_event | /src/controller/MessageAction.java | WINDOWS-1252 | 1,781 | 2.296875 | 2 | [] | no_license | package controller;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import dao.Mysql;
import model.Message;
import model.User;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MessageAction extends ActionSupport implements ModelDriven<Message> {
private User user = new User();
private ResultSet rs = null;
private int id;
private Map<String,Object> session;
private Message message=new Message();
public String send() throws Exception{
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String sql = "insert into themessage(username,message) values('"+message.getName()+"','"+message.getMessage()+"')";
System.out.println(sql);
int flag = Mysql.executeUpdate(sql);
if (flag == 1){
// out.print("<script>alert('ͳɹ')</script>");
// out.print("<script>window.location.href='blogartical.jsp'</script>");
// out.close();
return "success";
}
else {
// out.print("<script>alert('ʧܣ')</script>");
// out.print("<script>window.location.href='blogartical.jsp'</script>");
// out.close();
return "error";
}
}
private int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public Message getModel() {
return message;
}
}
| true |
f39ffe637fd59a01a441c2913d3724f02395ab2b | Java | imsks/Java-Basics | /Basics/HashSet/base.java | UTF-8 | 385 | 2.9375 | 3 | [
"MIT"
] | permissive | /*
@Author - Sachin Kr. Shukla
@Date - 19 Jan, 2019
About - Implimenting HashSet
*/
import java.util.*;
public class base{
public static void main(String[] args) {
HashSet<String> name = new HashSet<String>();
name.add("A");
name.add("B");
name.add("C");
name.add("D");
Iterator<String> itr = name.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
} | true |
b72d15437e5d300eb85da8b50919c9a35357daf0 | Java | coinninjadev/dropbit-android | /app/src/main/java/com/coinninja/coinkeeper/ui/dropbit/me/verified/VerifiedDropbitMeDialog.java | UTF-8 | 4,276 | 1.726563 | 2 | [
"MIT"
] | permissive | package com.coinninja.coinkeeper.ui.dropbit.me.verified;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import com.coinninja.android.helpers.Resources;
import com.coinninja.coinkeeper.CoinKeeperApplication;
import com.coinninja.coinkeeper.R;
import com.coinninja.coinkeeper.ui.dropbit.me.DropBitMeDialog;
import com.coinninja.coinkeeper.ui.dropbit.me.DropbitMeConfiguration;
import com.coinninja.coinkeeper.util.android.LocalBroadCastUtil;
import com.coinninja.coinkeeper.util.android.ServiceWorkUtil;
import com.coinninja.coinkeeper.util.android.activity.ActivityNavigationUtil;
import com.squareup.picasso.Picasso;
import javax.inject.Inject;
import static com.coinninja.coinkeeper.util.DropbitIntents.ACTION_DROPBIT_ME_ACCOUNT_DISABLED;
public class VerifiedDropbitMeDialog extends DropBitMeDialog {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION_DROPBIT_ME_ACCOUNT_DISABLED.equals(intent.getAction())) {
renderAccount();
}
}
};
IntentFilter intentFilter;
@Inject
LocalBroadCastUtil localBroadCastUtil;
@Inject
ActivityNavigationUtil activityNavigationUtil;
@Inject
ServiceWorkUtil serviceWorkUtil;
@Inject
DropbitMeConfiguration dropbitMeConfiguration;
@Inject
Picasso picasso;
public static DropBitMeDialog newInstance() {
return new VerifiedDropbitMeDialog();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intentFilter = new IntentFilter(ACTION_DROPBIT_ME_ACCOUNT_DISABLED);
}
@Override
public void onResume() {
super.onResume();
View view = getView();
if (view == null) return;
Button button = findViewById(R.id.dropbit_me_url);
button.setText(dropbitMeConfiguration.getShareUrl());
localBroadCastUtil.registerReceiver(receiver, intentFilter);
setupAvatarUI();
}
@Override
protected int getContentViewLayoutId() {
return R.layout.dialog_verified_dropbit_me_account;
}
@Override
protected void configurePrimaryCallToAction(Button button) {
button.setText(R.string.dropbit_me_verified_account_button);
Drawable drawable = Resources.INSTANCE.getDrawable(getContext(), R.drawable.twitter_icon);
button.setCompoundDrawables(drawable, null, null, null);
button.setCompoundDrawablePadding(Math.round(getResources().getDimension(R.dimen.button_vertical_padding_small)));
button.setOnClickListener(v -> onPrimaryButtonClick());
}
@Override
protected void configureSecondaryButton(Button button) {
button.setText(getString(R.string.dropbit_me_disable_account_button_label));
button.setOnClickListener(v -> onDisableAccount());
}
@Override
public void onPause() {
super.onPause();
localBroadCastUtil.unregisterReceiver(receiver);
}
private void setupAvatarUI() {
String avatar = dropbitMeConfiguration.getAvatar();
if (avatar == null) {
findViewById(R.id.twitter_profile_picture).setVisibility(View.GONE);
} else {
findViewById(R.id.twitter_profile_picture).setVisibility(View.VISIBLE);
picasso.invalidate(avatar);
picasso.get().load(avatar).transform(CoinKeeperApplication.appComponent.provideCircleTransform()).into(((ImageView) getView().findViewById(R.id.twitter_profile_picture)));
}
}
private void onDisableAccount() {
serviceWorkUtil.disableDropBitMe();
}
private String getShareMessage() {
return getString(R.string.dropbit_me_share_on_twitter, dropbitMeConfiguration.getShareUrl());
}
private void onPrimaryButtonClick() {
activityNavigationUtil.shareWithTwitter(getActivity(), getShareMessage());
dismiss();
}
}
| true |
eb613ef3db5cf826aac3811c3ecf6ac728482743 | Java | dengjiaping/hn-apos | /apos/apos-enterprise-android2.5/src/me/andpay/apos/tqrm/action/QueryCouponAction.java | UTF-8 | 1,535 | 1.898438 | 2 | [
"Apache-2.0"
] | permissive | package me.andpay.apos.tqrm.action;
import java.util.List;
import me.andpay.ac.term.api.pas.CouponRedeemList;
import me.andpay.ac.term.api.pas.CouponService;
import me.andpay.ac.term.api.pas.QueryCouponRedeemListCond;
import me.andpay.apos.common.action.SessionKeepAction;
import me.andpay.apos.tqrm.form.QueryCouponCondForm;
import me.andpay.timobileframework.mvc.ModelAndView;
import me.andpay.timobileframework.mvc.action.ActionMapping;
import me.andpay.timobileframework.mvc.action.ActionRequest;
import me.andpay.timobileframework.util.BeanUtils;
@ActionMapping(domain = QueryCouponAction.DOMAIN_NAME)
public class QueryCouponAction extends SessionKeepAction {
public static final String DOMAIN_NAME = "/tqrm/queryCoupon.action";
public static final String QUERY_COUPON = "queryCouponList";
public CouponService couponService;
// @Inject
// public OrderInfoDao orderInfoDao;
/**
* 查询订单
*
* @param request
* @return
*/
public ModelAndView queryCouponList(ActionRequest request)
throws RuntimeException {
QueryCouponCondForm condForm = (QueryCouponCondForm) request
.getParameterValue("couponQueryForm");
QueryCouponRedeemListCond queryCond = new QueryCouponRedeemListCond();
BeanUtils.copyProperties(condForm, queryCond);
List<CouponRedeemList> couponResult = couponService
.queryCouponRedeemLists(queryCond, 0, 10);
ModelAndView mav = new ModelAndView();
mav.addModelValue("couponResult", couponResult);
mav.addModelValue("couponQueryForm", condForm);
return mav;
}
}
| true |
6a3b8ed3e9c59657b1dc1b279270f9beed9208c9 | Java | Al-vish/DIS-Project | /New DIS Project/src/main/java/client/MasterCommand.java | UTF-8 | 4,094 | 2.546875 | 3 | [] | no_license | package client;
import fileserver.Command;
import utils.AESUtils;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
public class MasterCommand {
private Map<String, Map<String,String>> serverMap;
private String clientId;
public void setServerMap(Map<String, Map<String, String>> serverMap) {
this.serverMap = serverMap;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String ls(){
String answer = "";
for(Map.Entry<String, Map<String,String>> entry: serverMap.entrySet()){
Integer portServer = Integer.parseInt(entry.getValue().get("port"));
String sessionKey = entry.getValue().get("sessionKey");
try {
Command command = (Command) Naming.lookup("rmi://localhost:"+portServer+"/command");
String encAns = command.commandOperation(AESUtils.encrypt("ls",sessionKey), clientId);
answer += AESUtils.decrypt(encAns, sessionKey);
} catch (NotBoundException | MalformedURLException | RemoteException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
}
return answer;
}
public String pwd(){
return "System\n";
}
public String cat(String name){
String result;
for(Map.Entry<String, Map<String,String>> entry: serverMap.entrySet()){
Integer portServer = Integer.parseInt(entry.getValue().get("port"));
String sessionKey = entry.getValue().get("sessionKey");
try {
Command command = (Command) Naming.lookup("rmi://localhost:"+portServer+"/command");
String encresult = command.commandOperation(AESUtils.encrypt("cat " + name, sessionKey),clientId);
result = AESUtils.decrypt(encresult, sessionKey);
if(!result.equals("null")) {
return result;
}
} catch (NotBoundException | MalformedURLException | RemoteException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
}
return null;
}
public Boolean cp(String name, String des){
String data = cat(name);
if(data==null){
return false;
}
for(Map.Entry<String, Map<String,String>> entry: serverMap.entrySet()){
Integer portServer = Integer.parseInt(entry.getValue().get("port"));
String sessionKey = entry.getValue().get("sessionKey");
try {
Command command = (Command) Naming.lookup("rmi://localhost:"+portServer+"/command");
String encResult = command.commandOperation(AESUtils.encrypt("is "+des,sessionKey),clientId);
if(AESUtils.decrypt(encResult, sessionKey).equals("true")){
String encresult = command.createAndAdd(AESUtils.encrypt(data, sessionKey), AESUtils.encrypt(des, sessionKey),
AESUtils.encrypt(name, sessionKey), clientId);
if(AESUtils.decrypt(encResult, sessionKey).equals("true"))
return true;
}
} catch (NotBoundException | MalformedURLException | RemoteException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
}
return false;
}
}
| true |
fc4e638430630534434d41e7446be0d061aff97d | Java | HevilH/ExerMate-Backend | /src/main/java/ExerMate/ExerMate/Biz/Controller/Params/ExerPostParams/In/CreateInParams.java | UTF-8 | 1,563 | 2.03125 | 2 | [] | no_license | package ExerMate.ExerMate.Biz.Controller.Params.ExerPostParams.In;
import ExerMate.ExerMate.Base.Annotation.BizType;
import ExerMate.ExerMate.Base.Annotation.Required;
import ExerMate.ExerMate.Biz.BizTypeEnum;
import ExerMate.ExerMate.Biz.Controller.Params.CommonInParams;
@BizType(BizTypeEnum.EXERPOST_CREATE)
public class CreateInParams extends CommonInParams {
@Required
private String exerName;
@Required
private String exerPlace;
@Required
private String exerTime;
@Required
private int maxNum;
@Required
private String contents;
@Required
private String chatRoomName;
public String getExerName() {
return exerName;
}
public void setExerName(String exerName) {
this.exerName = exerName;
}
public String getExerPlace() {
return exerPlace;
}
public void setExerPlace(String exerPlace) {
this.exerPlace = exerPlace;
}
public String getExerTime() {
return exerTime;
}
public void setExerTime(String exerTime) {
this.exerTime = exerTime;
}
public int getMaxNum() {
return maxNum;
}
public void setMaxNum(int maxNum) {
this.maxNum = maxNum;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public String getChatRoomName() {
return chatRoomName;
}
public void setChatRoomName(String chatRoomName) {
this.chatRoomName = chatRoomName;
}
}
| true |
0d43870458acfcce164e63135b055b9da4a2c94c | Java | tsuzcx/qq_apk | /com.tencent.mobileqqi/classes.jar/NS_MOBILE_FEEDS/cell_pic.java | UTF-8 | 7,185 | 1.679688 | 2 | [] | no_license | package NS_MOBILE_FEEDS;
import com.qq.taf.jce.JceInputStream;
import com.qq.taf.jce.JceOutputStream;
import com.qq.taf.jce.JceStruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public final class cell_pic
extends JceStruct
{
static Map cache_busi_param;
static ArrayList cache_facemans;
static s_user cache_friendinfo;
static ArrayList cache_picdata;
public int actiontype = 18;
public String actionurl = "";
public String albumanswer = "";
public String albumid = "";
public String albumname = "";
public int albumnum = 0;
public String albumquestion = "";
public int albumrights = 0;
public int albumtype = 0;
public int allow_access = 0;
public int anonymity = 0;
public boolean balbum = true;
public Map busi_param = null;
public String desc = "";
public int faceman_num = 0;
public ArrayList facemans = null;
public s_user friendinfo = null;
public boolean isSubscribe = true;
public int lastupdatetime = 0;
public String news = "";
public ArrayList picdata = null;
public String qunid = "";
public long uin = 0L;
public int unread_count = 0;
public int uploadnum = 0;
public cell_pic() {}
public cell_pic(ArrayList paramArrayList1, String paramString1, String paramString2, int paramInt1, int paramInt2, int paramInt3, String paramString3, String paramString4, String paramString5, long paramLong, boolean paramBoolean1, int paramInt4, Map paramMap, String paramString6, int paramInt5, int paramInt6, int paramInt7, int paramInt8, String paramString7, boolean paramBoolean2, s_user params_user, String paramString8, int paramInt9, ArrayList paramArrayList2, int paramInt10)
{
this.picdata = paramArrayList1;
this.albumname = paramString1;
this.albumid = paramString2;
this.albumnum = paramInt1;
this.uploadnum = paramInt2;
this.albumrights = paramInt3;
this.albumquestion = paramString3;
this.albumanswer = paramString4;
this.desc = paramString5;
this.uin = paramLong;
this.balbum = paramBoolean1;
this.lastupdatetime = paramInt4;
this.busi_param = paramMap;
this.qunid = paramString6;
this.allow_access = paramInt5;
this.anonymity = paramInt6;
this.albumtype = paramInt7;
this.actiontype = paramInt8;
this.actionurl = paramString7;
this.isSubscribe = paramBoolean2;
this.friendinfo = params_user;
this.news = paramString8;
this.unread_count = paramInt9;
this.facemans = paramArrayList2;
this.faceman_num = paramInt10;
}
public void readFrom(JceInputStream paramJceInputStream)
{
Object localObject;
if (cache_picdata == null)
{
cache_picdata = new ArrayList();
localObject = new s_picdata();
cache_picdata.add(localObject);
}
this.picdata = ((ArrayList)paramJceInputStream.read(cache_picdata, 0, false));
this.albumname = paramJceInputStream.readString(1, false);
this.albumid = paramJceInputStream.readString(2, false);
this.albumnum = paramJceInputStream.read(this.albumnum, 3, false);
this.uploadnum = paramJceInputStream.read(this.uploadnum, 4, false);
this.albumrights = paramJceInputStream.read(this.albumrights, 5, false);
this.albumquestion = paramJceInputStream.readString(6, false);
this.albumanswer = paramJceInputStream.readString(7, false);
this.desc = paramJceInputStream.readString(8, false);
this.uin = paramJceInputStream.read(this.uin, 9, false);
this.balbum = paramJceInputStream.read(this.balbum, 10, false);
this.lastupdatetime = paramJceInputStream.read(this.lastupdatetime, 11, false);
if (cache_busi_param == null)
{
cache_busi_param = new HashMap();
cache_busi_param.put(Integer.valueOf(0), "");
}
this.busi_param = ((Map)paramJceInputStream.read(cache_busi_param, 12, false));
this.qunid = paramJceInputStream.readString(13, false);
this.allow_access = paramJceInputStream.read(this.allow_access, 14, false);
this.anonymity = paramJceInputStream.read(this.anonymity, 15, false);
this.albumtype = paramJceInputStream.read(this.albumtype, 16, false);
this.actiontype = paramJceInputStream.read(this.actiontype, 17, false);
this.actionurl = paramJceInputStream.readString(18, false);
this.isSubscribe = paramJceInputStream.read(this.isSubscribe, 19, false);
if (cache_friendinfo == null) {
cache_friendinfo = new s_user();
}
this.friendinfo = ((s_user)paramJceInputStream.read(cache_friendinfo, 20, false));
this.news = paramJceInputStream.readString(21, false);
this.unread_count = paramJceInputStream.read(this.unread_count, 22, false);
if (cache_facemans == null)
{
cache_facemans = new ArrayList();
localObject = new s_user();
cache_facemans.add(localObject);
}
this.facemans = ((ArrayList)paramJceInputStream.read(cache_facemans, 23, false));
this.faceman_num = paramJceInputStream.read(this.faceman_num, 24, false);
}
public void writeTo(JceOutputStream paramJceOutputStream)
{
if (this.picdata != null) {
paramJceOutputStream.write(this.picdata, 0);
}
if (this.albumname != null) {
paramJceOutputStream.write(this.albumname, 1);
}
if (this.albumid != null) {
paramJceOutputStream.write(this.albumid, 2);
}
paramJceOutputStream.write(this.albumnum, 3);
paramJceOutputStream.write(this.uploadnum, 4);
paramJceOutputStream.write(this.albumrights, 5);
if (this.albumquestion != null) {
paramJceOutputStream.write(this.albumquestion, 6);
}
if (this.albumanswer != null) {
paramJceOutputStream.write(this.albumanswer, 7);
}
if (this.desc != null) {
paramJceOutputStream.write(this.desc, 8);
}
paramJceOutputStream.write(this.uin, 9);
paramJceOutputStream.write(this.balbum, 10);
paramJceOutputStream.write(this.lastupdatetime, 11);
if (this.busi_param != null) {
paramJceOutputStream.write(this.busi_param, 12);
}
if (this.qunid != null) {
paramJceOutputStream.write(this.qunid, 13);
}
paramJceOutputStream.write(this.allow_access, 14);
paramJceOutputStream.write(this.anonymity, 15);
paramJceOutputStream.write(this.albumtype, 16);
paramJceOutputStream.write(this.actiontype, 17);
if (this.actionurl != null) {
paramJceOutputStream.write(this.actionurl, 18);
}
paramJceOutputStream.write(this.isSubscribe, 19);
if (this.friendinfo != null) {
paramJceOutputStream.write(this.friendinfo, 20);
}
if (this.news != null) {
paramJceOutputStream.write(this.news, 21);
}
paramJceOutputStream.write(this.unread_count, 22);
if (this.facemans != null) {
paramJceOutputStream.write(this.facemans, 23);
}
paramJceOutputStream.write(this.faceman_num, 24);
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mobileqqi\classes2.jar
* Qualified Name: NS_MOBILE_FEEDS.cell_pic
* JD-Core Version: 0.7.0.1
*/ | true |
da15da27e0fab9b1e742255b28e306b7806c2fb9 | Java | jackchow621/DesignPatterns | /creational/simple-factory/src/main/java/ghost/designpatterns/ProductB.java | UTF-8 | 167 | 2.15625 | 2 | [] | no_license | package ghost.designpatterns;
public class ProductB implements Product {
public String getName() {
// TODO Auto-generated method stub
return "productB";
}
}
| true |
8dcbfd67c1e58e7fd239abf4f42ad72ba80d2e8a | Java | zafar1246/PMS_web | /src/main/java/com/omaisss/pms/restcontrollers/GuestRestController.java | UTF-8 | 9,011 | 2.109375 | 2 | [] | no_license | package com.omaisss.pms.restcontrollers;
import java.util.List;
import org.springframework.web.bind.annotation.RestController;
import com.omaisss.pms.restdomainobjects.GuestProfileVO;
import com.omaisss.pms.restentity.GuestAddress;
import com.omaisss.pms.restentity.GuestMembership;
import com.omaisss.pms.restentity.GuestPaymentCard;
import com.omaisss.pms.restentity.GuestPreferences;
import com.omaisss.pms.restentity.GuestProfile;
import com.omaisss.pms.restservices.GuestAddressService;
import com.omaisss.pms.restservices.GuestMembershipService;
import com.omaisss.pms.restservices.GuestPaymentCardService;
import com.omaisss.pms.restservices.GuestPreferencesService;
import com.omaisss.pms.restservices.GuestProfileService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
@RestController
@CrossOrigin
@RequestMapping("/api/pms/guestController")
public class GuestRestController {
@Autowired
private GuestProfileService guestProfileService;
@Autowired
private GuestAddressService guestAddressService;
@Autowired
private GuestMembershipService guestMembershipService;
@Autowired
private GuestPaymentCardService guestPaymentCardService;
@Autowired
private GuestPreferencesService guestPreferencesService;
/*
@Autowired
private RoomMasterService roomMasterService;
*/
// --------------------Guest Address------------------------//
@GetMapping("/getGuestAddresses")
public List<GuestAddress> getGuestAddress() {
//System.out.println("GuestAddress Customers Get Mapping Method");
return guestAddressService.getGuestAddress();
}
@GetMapping("/getGuestAddress/{guestAddressId}")
public GuestAddress getGuestAddress(@PathVariable String guestAddressId) {
//System.out.println("GuestAddress Get Mapping Method using Room Number");
GuestAddress guestAddress = guestAddressService.getGuestAddress(guestAddressId);
return guestAddress;
}
@PostMapping("/postGuestAddress")
public GuestAddress addGuestAddress(@RequestBody GuestAddress guestAddress) {
//System.out.println("GuestAddress Post Mapping Method");
guestAddressService.saveGuestAddress(guestAddress);
return guestAddress;
}
@PutMapping("/updateGuestAddress")
public GuestAddress updateGuestAddress(@RequestBody GuestAddress guestAddress) {
//System.out.println("GuestAddress Put Mapping Method");
guestAddressService.saveGuestAddress(guestAddress);
return guestAddress;
}
@DeleteMapping("/deleteGuestAddress/{guestAddressId}")
public String deleteGuestAddress(@PathVariable String guestAddressId) {
//System.out.println("GuestAddress Delete Mapping Method");
guestAddressService.deleteGuestAddress(guestAddressId);
return "Delete Guest Address id :" + guestAddressId;
}
//--------------------Guest Membership------------------------//
@GetMapping("/getGuestMemberships")
public List<GuestMembership> getGuestMembership() {
//System.out.println("Customers Get Mapping Method");
return guestMembershipService.getGuestMembership();
}
@GetMapping("/getGuestMembership/{guestMembershipId}")
public GuestMembership getGuestMembership(@PathVariable String guestMembershipId) {
//System.out.println("GuestMembership Get Mapping Method using Id");
GuestMembership guestMembership = guestMembershipService.getGuestMembership(guestMembershipId);
return guestMembership;
}
@PostMapping("/postGuestMembership")
public GuestMembership addGuestMembership(@RequestBody GuestMembership guestMembership) {
//System.out.println("GuestMembership Post Mapping Method");
guestMembershipService.saveGuestMembership(guestMembership);
return guestMembership;
}
@PutMapping("/updateGuestMembership")
public GuestMembership updateGuestMembership(@RequestBody GuestMembership guestMembership) {
//System.out.println("GuestMembership Put Mapping Method");
guestMembershipService.saveGuestMembership(guestMembership);
return guestMembership;
}
@DeleteMapping("/deleteGuestMembership/{guestMembershipId}")
public String deleteGuestMembership(@PathVariable String guestMembershipId) {
//System.out.println("GuestMembership Delete Mapping Method");
guestMembershipService.deleteGuestMembership(guestMembershipId);
return "Deleted Guest Membership id :" + guestMembershipId;
}
// --------------------Guest PaymentCard------------------------//
@GetMapping("/getGuestPaymentCard")
public List<GuestPaymentCard> getGuestPaymentCard() {
//System.out.println("GuestPaymentCard Get Mapping Method");
return guestPaymentCardService.getGuestPaymentCard();
}
@GetMapping("/getGuestPaymentCard/{guesPaymentCardId}")
public GuestPaymentCard getGuestPaymentCard(@PathVariable String guestPaymentCardId) {
//System.out.println("GuestPaymentCard Get Mapping Method using Id");
GuestPaymentCard guestPaymentCard = guestPaymentCardService.getGuestPaymentCard(guestPaymentCardId);
return guestPaymentCard;
}
@PostMapping("/postGuestPaymentCard")
public GuestPaymentCard addGuestPaymentCard(@RequestBody GuestPaymentCard guestPaymentCard) {
//System.out.println("GuestPaymentCard Post Mapping Method");
guestPaymentCardService.saveGuestPaymentCard(guestPaymentCard);
return guestPaymentCard;
}
@PutMapping("/updateGuestPaymentCard")
public GuestPaymentCard updateGuestPaymentCard(@RequestBody GuestPaymentCard guestPaymentCard) {
//System.out.println("GuestPaymentCard Put Mapping Method");
guestPaymentCardService.saveGuestPaymentCard(guestPaymentCard);
return guestPaymentCard;
}
@DeleteMapping("/deleteGuestPaymentCard/{guestPaymentCardId}")
public String deleteGuestPaymentCard(@PathVariable String guestPaymentCardId) {
//System.out.println("GuestPaymentCard Delete Mapping Method");
guestPaymentCardService.deleteGuestPaymentCard(guestPaymentCardId);
return "Delete Guest Payment Card id :" + guestPaymentCardId;
}
// --------------------Guest Preferences------------------------//
@GetMapping("/getGuestPreferences")
public List<GuestPreferences> getGuestPreferences() {
//System.out.println("GuestPreferences Get Mapping Method");
return guestPreferencesService.getGuestPreferences();
}
@GetMapping("/getGuestPreferences/{guestPreferencesId}")
public GuestPreferences getGuestPreferences(@PathVariable String guestPreferencesId) {
//System.out.println("Guest Preferences Get Mapping Method using Id");
GuestPreferences guestPreferences = guestPreferencesService.getGuestPreferences(guestPreferencesId);
return guestPreferences;
}
@PostMapping("/postGuestPreferences")
public GuestPreferences addGuestPreferences(@RequestBody GuestPreferences guestPreferences) {
//System.out.println("GuestPreferences Post Mapping Method");
guestPreferencesService.saveGuestPreferences(guestPreferences);
return guestPreferences;
}
@PutMapping("/updateGuestPreferences")
public GuestPreferences updateGuestPreferences(@RequestBody GuestPreferences guestPreferences) {
//System.out.println("GuestPreferences Put Mapping Method");
guestPreferencesService.saveGuestPreferences(guestPreferences);
return guestPreferences;
}
@DeleteMapping("/deleteGuestPreferences/{guestPreferencesId}")
public String deleteGuestPreferences(@PathVariable String guestPreferencesId) {
//System.out.println("GuestPreferences Delete Mapping Method");
guestPreferencesService.deleteGuestPreferences(guestPreferencesId);
return "Delete Guest Preferences id :" + guestPreferencesId;
}
// --------------------Guest Profile------------------------//
@GetMapping("/getGuestProfiles")
public List<GuestProfile> getGuestProfile() {
System.out.println("Guest Profile Page");
return guestProfileService.getGuestProfile();
}
@GetMapping("/getGuestProfile/{guestProfileId}")
public GuestProfile getGuestProfile(@PathVariable int guestProfileId) {
GuestProfile guestProfile = guestProfileService.getGuestProfile(guestProfileId);
return guestProfile;
}
@PostMapping("/postGuestProfile")
public String addGuestProfile(@RequestBody GuestProfileVO guestProfileVO) {
guestProfileService.saveGuestProfile(guestProfileVO);
return "created successfully";
}
@PutMapping("/updateGuestProfile")
public String updateGuestProfile(@RequestBody GuestProfileVO guestProfileVO) {
guestProfileService.saveGuestProfile(guestProfileVO);
return "Updated successfully";
}
@DeleteMapping("/deleteGuestProfile/{guestProfileId}")
public String deleteGuestProfile(@PathVariable int guestProfileId) {
guestProfileService.deleteGuestProfile(guestProfileId);
return "Delete Guest Profile id :" + guestProfileId;
}
} | true |
2bed0b41ad9c1e532e204f7b1ab101b7787c39f1 | Java | yuntian0215/spring_cloud | /spring_cloud/parent-project/spring-shiro/src/main/java/com/yuntian/service/impl/RoleServiceImpl.java | UTF-8 | 574 | 1.835938 | 2 | [] | no_license | package com.yuntian.service.impl;
import com.yuntian.Role;
import com.yuntian.mapper.RoleMapper;
import com.yuntian.service.IRoleService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>内容</p>
* 2019/3/8/0008 15:49
*
* @author lvjie
*/
@Service
public class RoleServiceImpl implements IRoleService {
@Resource
private RoleMapper roleMapper;
public List<Role> findRoleByUserId(Integer userId){
List<Role> list = roleMapper.findRoleByUserId(userId);
return list;
}
}
| true |
ccf2f96782e7256dc126d6f118b011a191678063 | Java | ankitsingh4004/Clear-Safe | /app/src/main/java/com/workorder/app/pojo/GetWorkOrderDetailPojo.java | UTF-8 | 8,054 | 1.679688 | 2 | [] | no_license | package com.workorder.app.pojo;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class GetWorkOrderDetailPojo implements Serializable {
@SerializedName("AssesmentId")
@Expose
private Integer assesmentId;
@SerializedName("WorkOrderNo")
@Expose
private String workOrderNo;
@SerializedName("ClientWorkOrder")
@Expose
private String clientWorkOrder;
@SerializedName("ClientName")
@Expose
private String clientName;
@SerializedName("ClientContact")
@Expose
private String clientContact;
@SerializedName("TraderCategoryId")
@Expose
private Integer traderCategoryId;
@SerializedName("TradeCategory")
@Expose
private String tradeCategory;
@SerializedName("AssesmentType")
@Expose
private String assesmentType;
@SerializedName("WorkScope")
@Expose
private String workScope;
@SerializedName("AssesmentDate")
@Expose
private String assesmentDate;
@SerializedName("ProjectName")
@Expose
private String projectName;
@SerializedName("IsSurveyAttached")
@Expose
private String isSurveyAttached;
@SerializedName("IsSurveySigned")
@Expose
private String IsSurveySigned;
@SerializedName("SurveyId")
@Expose
private Integer surveyId;
@SerializedName("AssesmentNo")
@Expose
private String assesmentNo;
@SerializedName("SiteName")
@Expose
private String siteName;
@SerializedName("BuildingName")
@Expose
private String buildingName;
@SerializedName("Floor")
@Expose
private Object floor;
@SerializedName("Room")
@Expose
private Object room;
@SerializedName("Address1")
@Expose
private String address1;
@SerializedName("Address2")
@Expose
private String address2;
@SerializedName("City")
@Expose
private String city;
@SerializedName("PostCode")
@Expose
private String postCode;
@SerializedName("Country")
@Expose
private String country;
@SerializedName("State")
@Expose
private String state;
@SerializedName("Lat")
@Expose
private Double lat;
@SerializedName("Lon")
@Expose
private Double lon;
@SerializedName("status")
@Expose
private String status;
@SerializedName("SWMSStatus")
@Expose
private String sWMSStatus;
@SerializedName("SWMSWarningLevel")
@Expose
private String sWMSWarningLevel;
@SerializedName("PrevStatus")
@Expose
private Boolean PrevStatus;
public Integer getAssesmentId() {
return assesmentId;
}
public Boolean getPrevStatus() {
return PrevStatus;
}
public void setPrevStatus(Boolean prevStatus) {
PrevStatus = prevStatus;
}
public void setAssesmentId(Integer assesmentId) {
this.assesmentId = assesmentId;
}
public String getWorkOrderNo() {
return workOrderNo;
}
public void setWorkOrderNo(String workOrderNo) {
this.workOrderNo = workOrderNo;
}
public String getClientWorkOrder() {
return clientWorkOrder;
}
public void setClientWorkOrder(String clientWorkOrder) {
this.clientWorkOrder = clientWorkOrder;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientContact() {
return clientContact;
}
public void setClientContact(String clientContact) {
this.clientContact = clientContact;
}
public Integer getTraderCategoryId() {
return traderCategoryId;
}
public void setTraderCategoryId(Integer traderCategoryId) {
this.traderCategoryId = traderCategoryId;
}
public String getTradeCategory() {
return tradeCategory;
}
public void setTradeCategory(String tradeCategory) {
this.tradeCategory = tradeCategory;
}
public String getAssesmentType() {
return assesmentType;
}
public void setAssesmentType(String assesmentType) {
this.assesmentType = assesmentType;
}
public String getWorkScope() {
return workScope;
}
public void setWorkScope(String workScope) {
this.workScope = workScope;
}
public String getAssesmentDate() {
return assesmentDate;
}
public void setAssesmentDate(String assesmentDate) {
this.assesmentDate = assesmentDate;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getIsSurveyAttached() {
return isSurveyAttached;
}
public void setIsSurveyAttached(String isSurveyAttached) {
this.isSurveyAttached = isSurveyAttached;
}
public Integer getSurveyId() {
return surveyId;
}
public void setSurveyId(Integer surveyId) {
this.surveyId = surveyId;
}
public String getAssesmentNo() {
return assesmentNo;
}
public void setAssesmentNo(String assesmentNo) {
this.assesmentNo = assesmentNo;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(String buildingName) {
this.buildingName = buildingName;
}
public Object getFloor() {
return floor;
}
public void setFloor(Object floor) {
this.floor = floor;
}
public Object getRoom() {
return room;
}
public void setRoom(Object room) {
this.room = room;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSWMSStatus() {
return sWMSStatus;
}
public void setSWMSStatus(String sWMSStatus) {
this.sWMSStatus = sWMSStatus;
}
public String getSWMSWarningLevel() {
return sWMSWarningLevel;
}
public void setSWMSWarningLevel(String sWMSWarningLevel) {
this.sWMSWarningLevel = sWMSWarningLevel;
}
public String getIsSurveySigned() {
return IsSurveySigned;
}
public void setIsSurveySigned(String isSurveySigned) {
IsSurveySigned = isSurveySigned;
}
public String getsWMSStatus() {
return sWMSStatus;
}
public void setsWMSStatus(String sWMSStatus) {
this.sWMSStatus = sWMSStatus;
}
public String getsWMSWarningLevel() {
return sWMSWarningLevel;
}
public void setsWMSWarningLevel(String sWMSWarningLevel) {
this.sWMSWarningLevel = sWMSWarningLevel;
}
}
| true |
bb0441c4002ad1e337388e60b645b46cc18b231d | Java | devcase/dwf | /dwf/dwf-web-view-integration-test/src/test/java/test/dwf/web/mail/JspBasedMailBuilderITCase.java | UTF-8 | 1,544 | 2.078125 | 2 | [] | no_license | package test.dwf.web.mail;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.context.WebApplicationContext;
import test.dwf.web.application.DwfWebRestTestApplication;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {DwfWebRestTestApplication.class})
@WebIntegrationTest()
public class JspBasedMailBuilderITCase {
@Value("${local.server.port}")
private int serverPort;
@Autowired
private WebApplicationContext wac;
@Test
public void testBuildMail() {
TestRestTemplate restTemplate = new TestRestTemplate();
ResponseEntity<String> responseEn = restTemplate.getForEntity("http://localhost:" + serverPort + "/jspBasedMailBuilder?locale=en_US", String.class);
Assert.assertTrue(responseEn.getBody().contains("English"));
Assert.assertTrue(responseEn.getBody().contains("SUPER STRING"));
ResponseEntity<String> responsePt = restTemplate.getForEntity("http://localhost:" + serverPort + "/jspBasedMailBuilder?locale=pt_BR", String.class);
Assert.assertTrue(responsePt.getBody().contains("Português"));
}
}
| true |
f10f59704b85deea062dfbf97763c207170ced4c | Java | swacademy/JavaSE | /Chapter 7. Methods/OverLoadingTest2.java | UTF-8 | 248 | 2.9375 | 3 | [] | no_license | public class OverLoadingTest2{
public static void main(String[] args) {
add(4, 8);
add(4,6);
}
static void add(int su, int num){
System.out.println(su+num);
}
static void add(int a, int b){
System.out.println(a+b);
}
}
| true |
ae86f618c222d730cba895c68140389e865975fd | Java | ukyo99999/pipimy | /app/src/main/java/com/macrowell/pipimy/bean/CartBean.java | UTF-8 | 1,815 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | package com.macrowell.pipimy.bean;
import java.io.Serializable;
public class CartBean implements Serializable {
private static final long serialVersionUID = 1L;
private int groupNo; // 臨時的分組編號
private int itemno; // 商品編號
private String itemName; // 商品名稱
private String itemPicUrl; // 商品圖片路徑
private int buyerPrice; // 議價後決定的價格
private int ownerUid; // 賣家會員編號
private String ownerName; // 賣家會員名稱
private String ownerPicUrl; // 賣家會員顯示圖路徑
public void setGroupNo(int groupNo) {
this.groupNo = groupNo;
}
public int getGroupNo() {
return groupNo;
}
public void setItemno(int itemno) {
this.itemno = itemno;
}
public int getItemno() {
return itemno;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemName() {
return itemName;
}
public void setItemPicUrl(String itemPicUrl) {
this.itemPicUrl = itemPicUrl;
}
public String getItemPicUrl() {
return itemPicUrl;
}
public void setBuyerPrice(int buyerPrice) {
this.buyerPrice = buyerPrice;
}
public int getBuyerPrice() {
return buyerPrice;
}
public void setOwnerUid(int ownerUid) {
this.ownerUid = ownerUid;
}
public int getOwnerUid() {
return ownerUid;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerPicUrl(String ownerPicUrl) {
this.ownerPicUrl = ownerPicUrl;
}
public String getOwnerPicUrl() {
return ownerPicUrl;
}
}
| true |
a88f4ec77730d22620af2d0e251428022ca8ba25 | Java | Spark-Liang/SalarySystem | /SalarySystem/src/ittest/java/com/lzh/salarysystem/ittest/environment/WebAppTestEnv.java | UTF-8 | 862 | 1.773438 | 2 | [] | no_license | package com.lzh.salarysystem.ittest.environment;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.lzh.salarysystem.test.envirnoment.DBUnitTestEnv;
@WebAppContextEnvironmentPlugin
public class WebAppTestEnv extends DBUnitTestEnv{
@Autowired
private WebApplicationContext webContext;
private MockMvc mockMvc;
@Before
public void setUpMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webContext).build();
}
@Test
public void loadWebContext() {
}
protected WebApplicationContext getWebContext() {
return webContext;
}
protected MockMvc getMockMvc() {
return mockMvc;
}
}
| true |
e5eeaca0bfc218d4d1d93cef0f459ff997baaca4 | Java | wongjessica/TicTacToe | /Board.java | UTF-8 | 2,781 | 3.453125 | 3 | [] | no_license | public class Board {
private char[] board = new char[9];
public Board(){ }
public void displayBoard(){
System.out.println("[ " + board[0] + " ]" + "[ " + board[1] + " ]" + "[ " + board[2] + " ]");
System.out.println("[ " + board[3] + " ]" + "[ " + board[4] + " ]" + "[ " + board[5] + " ]");
System.out.println("[ " + board[6] + " ]" + "[ " + board[7] + " ]" + "[ " + board[8] + " ]");
System.out.println();
}
public void setSpace(int space, char letter){
board[space] = letter;
}
public char getSpace(int space){
return this.board[space];
}
public boolean notOccupied(int space){
return (board[space] == '-'); //true if space contains "-"
}
public void clear(){
//clear the board
for(int i = 0; i < 9; i++){
board[i] = '-';
}
}
public boolean checkGame(Board board){ //check when game over
int total = 0;
//Check rows for 3 X or O in a row
for(int i = 0; i < 3; i++){ //row 1
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
for(int i = 3; i < 6; i++){ //row 2
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
for(int i = 6; i < 9; i++){ //row 3
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
//Check columns for 3 X or O in a row
for(int i = 0; i < 7; i += 3){ //column 1
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
for(int i = 1; i < 8; i += 3){ //column 2
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
for(int i = 2; i < 10; i += 3){ //column 3
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
//check diagonal-right for 3 X or O in a row
for(int i = 0; i < 10; i += 4){
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
//check diagonal-left for 3 X or O in a row
for(int i = 2; i < 7; i += 2){
total += (int)board.getSpace(i);
if(total == 237 || total == 264)
return true;
}
total = 0;
return false; //Default
}
}
| true |
ba8e210442830f1a06b142ada96f72a7088b16b0 | Java | Lemmmy/NuclearMC | /src/main/java/net/teamdentro/nuclearmc/ConsoleFormatter.java | UTF-8 | 791 | 2.734375 | 3 | [] | no_license | package net.teamdentro.nuclearmc;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class ConsoleFormatter extends Formatter {
@Override
public String format(LogRecord rec) {
Level level = rec.getLevel();
String msg = rec.getMessage();
long tid = rec.getThreadID();
long ms = rec.getMillis();
return "[" + formatDate(ms) + (tid != NuclearMC.MAIN_THREAD_ID ? " @ " + tid + "] " : "] ") + "[" + level.toString() + "] " + msg + "\n";
}
private String formatDate(long ms) {
SimpleDateFormat f = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date d = new Date(ms);
return f.format(d);
}
}
| true |
8b11d3651730c42700abd29c6db56267a0174ceb | Java | Wechat-Group/WxJava | /weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/entpay/EntPayRedpackQueryResult.java | UTF-8 | 3,439 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package com.github.binarywang.wxpay.bean.entpay;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.w3c.dom.Document;
import java.io.Serializable;
/**
* 红包发送记录查询返回
*
* @author wuyong
* created on 2019-12-01 17:23
*/
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@XStreamAlias("xml")
public class EntPayRedpackQueryResult extends BaseWxPayResult implements Serializable {
private static final long serialVersionUID = 3127509905347445197L;
/**
* 商户订单号
* 商户使用查询API填写的商户单号的原路返回
*/
@XStreamAlias("mch_billno")
protected String mchBillNo;
/**
* 红包单号
* 使用API发放现金红包时返回的红包单号
*/
@XStreamAlias("detailId")
private String detailId;
/**
* 红包状态
* SENDING:发放
* SENT:
* 已发放待领取
* FAILED:发放失败
* RECEIVED:已领取
* RFUND_ING:退款中 REFUND:已退款
*/
@XStreamAlias("status")
private String status;
/**
* 发放类型
* API:通过API接口发放
*/
@XStreamAlias("send_type")
private String sendType;
/**
* 红包金额
* 红包总金额(单位分)
*/
@XStreamAlias("total_amount")
private Integer totalAmount;
/**
* 失败原因
* 发送失败原因
*/
@XStreamAlias("reason")
private String reason;
/**
* 红包发送时间
*/
@XStreamAlias("send_time")
private String sendTime;
/**
* 红包的退款时间
*/
@XStreamAlias("refund_time")
private String refundTime;
/**
* 红包退款金额
*/
@XStreamAlias("refund_amount")
private Integer refundAmount;
/**
* 祝福语
*/
@XStreamAlias("wishing")
private String wishing;
/**
* 备注
*/
@XStreamAlias("remark")
private String remark;
/**
* 活动名称
*/
@XStreamAlias("act_name")
private String actName;
/**
* 领取红包的Openid
*/
@XStreamAlias("openid")
private String openid;
/**
* 金额
*/
@XStreamAlias("amount")
private Integer amount;
/**
* 接收时间
*/
@XStreamAlias("rcv_time")
private String rcvTime;
/**
* 发送者名称
*/
@XStreamAlias("sender_name")
private String senderName;
/**
* 发送者头像
* 通过企业微信开放接口上传获取
*/
@XStreamAlias("sender_header_media_id")
private String senderHeaderMediaId;
@Override
protected void loadXml(Document d) {
mchBillNo = readXmlString(d, "mch_billno");
detailId = readXmlString(d, "detailId");
status = readXmlString(d, "status");
sendType = readXmlString(d, "send_type");
totalAmount = readXmlInteger(d, "total_amount");
reason = readXmlString(d, "reason");
sendTime = readXmlString(d, "send_time");
refundTime = readXmlString(d, "refund_time");
refundAmount = readXmlInteger(d, "refund_amount");
wishing = readXmlString(d, "wishing");
remark = readXmlString(d, "remark");
actName = readXmlString(d, "act_name");
openid = readXmlString(d, "openid");
amount = readXmlInteger(d, "amount");
rcvTime = readXmlString(d, "rcv_time");
senderName = readXmlString(d, "sender_name");
senderHeaderMediaId = readXmlString(d, "sender_header_media_id");
}
}
| true |
f28313462f317969ca2ef3eb888f16301951098d | Java | clebersimm/store | /src/io/clebersimm/store/budget/DomainException.java | UTF-8 | 248 | 1.898438 | 2 | [
"MIT"
] | permissive | package io.clebersimm.store.budget;
public class DomainException extends RuntimeException {
private static final long serialVersionUID = -3391280071390542200L;
public DomainException(String exception) {
System.out.println(exception);
}
}
| true |
923d86b020ca4b9ed7d8d61ee3b30d69c71fb4ee | Java | marchalvincent/knomarcar | /src/backup/Operator.java | UTF-8 | 309 | 1.507813 | 2 | [] | no_license | /**
*/
package backup;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Operator</b></em>'.
* <!-- end-user-doc -->
*
*
* @see metamodel.MetamodelPackage#getOperator()
* @model abstract="true"
* @generated
*/
public interface Operator extends Condition {
} // Operator
| true |
82ed5d8336710051cc8fbfcaaa7000a888aac26e | Java | srigandhi98/sample-socket-server | /src/main/java/org/gandhi/sample/socket/server/run/ServerLauncher.java | UTF-8 | 278 | 1.898438 | 2 | [] | no_license | package org.gandhi.sample.socket.server.run;
import org.gandhi.sample.socket.server.Server;
public class ServerLauncher {
public static void main(String args[]) throws Exception{
Server s = new Server(8080);
s.start();
//Thread.sleep(10000);
//s.stopServer();
}
} | true |
6346a434ced2b912de01f1d9be7561fbf7753141 | Java | SurajChoudhary/coding-challenge-master | /src/main/java/com/newrelic/codingchallenge/clienthandler/ServerListener.java | UTF-8 | 1,552 | 3.203125 | 3 | [] | no_license | package com.newrelic.codingchallenge.clienthandler;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import com.newrelic.codingchallenge.ThreadPool;
/**
* @author uchousu
* this is the main server socket listener thread.
*
* It accepts connection request from the clients and invokes client handler threads.
*
* It also invokes RefuseConnectionHandler thread if the application has
* five active clients connected to it.
*
* Terminates the server socket when application is shutting down.
*/
public class ServerListener implements Runnable {
private ServerSocket server;
private ThreadPool clientConnectionPool;
public ServerListener(ServerSocket server, ThreadPool clientConnectionPool) {
this.clientConnectionPool = clientConnectionPool;
this.server = server;
}
@Override
public void run() {
Socket clientSocket;
try {
while (true) {
clientSocket = this.server.accept();
if (ClientSocketHandler.acceptMoreclients.get()) {
// String clientAddress = clientSocket.getInetAddress().getHostAddress();
// System.out.println("\nNew connection from " + clientAddress);
clientConnectionPool.createClientHandler(clientSocket);
} else {
clientConnectionPool.createRefuseConnectionHandler(clientSocket);
}
}
} catch (IOException e) {
}
}
public void terminate() {
try {
// stop listening, close the socket
this.server.close();
} catch (IOException e) {
}
}
}
| true |
7efdf53fce73c11b112a5ef86d438063915b0a1f | Java | pengMaster/Mvp-Rxjava-Retrofit-dagger2 | /app/src/main/java/vip/retail/testmvp/mvp/model/UserDataModel.java | UTF-8 | 418 | 1.570313 | 2 | [
"Apache-2.0"
] | permissive | package vip.retail.testmvp.mvp.model;
import android.os.Handler;
import com.zhy.http.okhttp.callback.Callback;
import vip.retail.testmvp.mvp.base.BaseModel;
/**
* <pre>
* author : Wp
* e-mail : 18141924293@163.com
* time : 2018/07/03
* desc :
* version: 1.0
* </pre>
*/
public class UserDataModel extends BaseModel {
@Override
public void execute(Callback<String> callback) {
}
}
| true |
010d440bf3f059f28a7fe1faf51524e87105d6b1 | Java | ezralangat98/IfElseIfLadderExampleJava | /src/IfElseIfLadderExample.java | UTF-8 | 690 | 3.265625 | 3 | [] | no_license | public class IfElseIfLadderExample{
public static void main(String[] args) {
int score=91;
if(score<55){
System.out.println("fail");
}
else if(score>=55 && score<65){
System.out.println("C grade");
}
else if(score>=65 && score<75){
System.out.println("C+ grade");
}
else if(score>=75 && score<80){
System.out.println("B+ grade");
}
else if(score>=80 && score<85){
System.out.println("A- grade");
}else if(score>=86 ){
System.out.println("A grade");
}else{
System.out.println("Invalid!");
}
}
}
| true |
68295c9c507682ad9c2c25a885c1a09d76715316 | Java | AleksanderKarbowiak/project-IO | /Aplikacja/src/Classes/WidmoPanel.java | UTF-8 | 3,234 | 2.65625 | 3 | [] | no_license | package Classes;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
/**
* Klasa okna widma
*/
public class WidmoPanel extends JFrame{
private JComboBox comboBox1;
private JButton okButton;
private JLabel name;
private JPanel text;
public JPanel WidmoPanel;
private JTextField textField1;
private JSpinner FrequencySpinner;
private JTextField textField3;
private Baza_danych baza;
private int iloscProbek;
private int czestotliwosc;
private int amplituda;
/**
* Konstruktor panelu widma
* @param text
* @param baza
*/
public WidmoPanel(String text, Baza_danych baza) {
super(text);
this.baza = baza;
for(Nagranie nagranie : baza.nagrania) {
comboBox1.addItem(nagranie.nazwa);
}
SpinnerModel model = new SpinnerNumberModel(20, 20, 8000, 1);
FrequencySpinner.setModel(model);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
czestotliwosc = (Integer) FrequencySpinner.getValue();
wyswietlWidmo();
}
});
}
/**
Metoda wyświetla widmo DTFT
*/
public void wyswietlWidmo() {
Ramka Okno;
DTFT Transformata;
double fs; //Parametry próbkowania
double f_max; //Parametry DTFT
double f_min;
double f_krok;
widmo[] wynik = new widmo[2048];
String file = (String) comboBox1.getSelectedItem();
PlikWave plik = new PlikWave( file + ".wav");
plik.OtwórzIstniejącyPlik();
fs = plik.getCzęstotliwośćPróbkowania();
f_max = fs/2;
f_min = czestotliwosc;
f_krok = fs/2048;
Transformata = new DTFT(f_min, f_max, f_krok, fs);
int ileProbek = 4096;
int indexProbki = 0;
double[] probkiSuma = new double[2048];
while (indexProbki + ileProbek < plik.getLiczbęPróbek())
{
byte[] probki = plik.PobierzKilkaPróbek(indexProbki, ileProbek);
indexProbki += ileProbek;
double[] probkiL = new double[ileProbek/2];
int licznikL = 0;
for (int i = 0; i < probkiL.length; i++)
{
if (i % 2 == 0)
{
probkiL[licznikL++] = probki[i];
}
}
for (int i = 0; i < probkiSuma.length; i++)
{
probkiSuma[i] += probkiL[i];
}
}
wynik = Transformata.ObliczDTFT(probkiSuma);
/*Okno = new Ramka(600,600,"Wykres widma",10,10, wynik);
Okno.UstawMnieNaŚrodku();
Okno.setVisible(true);
*/
WykresWidma wykres = new WykresWidma(wynik, "Widmo");
wykres.setSize(800, 400);
wykres.setLocationRelativeTo(null);
wykres.setVisible(true);
//WyprowadźWidmo(wynik);
}
}
| true |
bcb5b59265b582353bffbcecf51a4478acce3e51 | Java | craxyabc/initial_html | /gfg/matrix/snakePrint.java | UTF-8 | 1,020 | 3.65625 | 4 | [] | no_license | package gfg.matrix;
import java.util.*;
public class snakePrint {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = s.nextInt();
}
}
ArrayList<Integer> list = snakePrint(arr);
for (int li : list) {
System.out.print(li + " ");
}
}
private static ArrayList<Integer> snakePrint(int[][] arr) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
for (int j = 0; j < arr.length; j++) {
list.add(arr[i][j]);
}
} else {
for (int j = arr.length - 1; j >= 0; j--) {
list.add(arr[i][j]);
}
}
}
return list;
}
}
| true |
ed2a433b82bc6eaf035f3269a71193c01e21c784 | Java | fupengfei0201/inov | /src/inov/fpf/model/vo/Empcontent.java | UTF-8 | 522 | 2.171875 | 2 | [] | no_license | package inov.fpf.model.vo;
public class Empcontent {
private String assessment;
private String empcontent;
private int marks;
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public String getAssessment() {
return assessment;
}
public void setAssessment(String assessment) {
this.assessment = assessment;
}
public String getEmpcontent() {
return empcontent;
}
public void setEmpcontent(String empcontent) {
this.empcontent = empcontent;
}
}
| true |
cea6272d5a1d4db92d2fcbbfbf3fa845f34739c9 | Java | Hl4p3x/L2J_Sunrise_Official | /Untouched/sunrisedata/branches/L2J_SunriseProject_Data/dist/game/data/scripts/handlers/effecthandlers/DispelBySlotProbability.java | UTF-8 | 2,692 | 2.375 | 2 | [
"Unlicense"
] | permissive | /*
* Copyright (C) L2J Sunrise
* This file is part of L2J Sunrise.
*/
package handlers.effecthandlers;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import l2r.gameserver.model.actor.L2Character;
import l2r.gameserver.model.effects.EffectTemplate;
import l2r.gameserver.model.effects.L2Effect;
import l2r.gameserver.model.effects.L2EffectType;
import l2r.gameserver.model.stats.Env;
import l2r.gameserver.model.stats.Formulas;
/**
* @author vGodFather
*/
public class DispelBySlotProbability extends L2Effect
{
private final String _dispel;
private final Map<String, Short> _dispelAbnormals;
private final int _rate;
public DispelBySlotProbability(Env env, EffectTemplate template)
{
super(env, template);
_dispel = template.getParameters().getString("dispel", null);
_rate = template.getParameters().getInt("rate", 0);
if ((_dispel != null) && !_dispel.isEmpty())
{
_dispelAbnormals = new ConcurrentHashMap<>();
for (String ngtStack : _dispel.split(";"))
{
String[] ngt = ngtStack.split(",");
_dispelAbnormals.put(ngt[0].toLowerCase(), (ngt.length > 1) ? Short.parseShort(ngt[1]) : Short.MAX_VALUE);
}
}
else
{
_dispelAbnormals = Collections.<String, Short> emptyMap();
}
}
@Override
public L2EffectType getEffectType()
{
return L2EffectType.DISPEL;
}
@Override
public boolean isInstant()
{
return true;
}
@Override
public boolean onStart()
{
if (_dispelAbnormals.isEmpty())
{
return false;
}
L2Character target = getEffected();
if ((target == null) || target.isDead())
{
return false;
}
for (Entry<String, Short> value : _dispelAbnormals.entrySet())
{
String stackType = value.getKey();
float stackOrder = value.getValue();
int skillCast = getSkill().getId();
// final boolean result = Formulas.calcStealSuccess(getEffector(), target, getSkill(), _rate);
// if (Rnd.get(100) < _rate)
{
for (L2Effect e : target.getAllEffects())
{
if (!e.getSkill().canBeDispeled())
{
continue;
}
if (!Formulas.calcStealSuccess(getEffector(), target, getSkill(), _rate))
{
continue;
}
// Fist check for stacktype
if (stackType.equalsIgnoreCase(e.getAbnormalType()) && (e.getSkill().getId() != skillCast))
{
if (e.getSkill() != null)
{
if (stackOrder == -1)
{
target.stopSkillEffects(e.getSkill().getId());
}
else if (stackOrder >= e.getAbnormalLvl())
{
target.stopSkillEffects(e.getSkill().getId());
}
}
}
}
}
}
return true;
}
}
| true |
48de4c6814c94785a6a0a8e4f5d3b06a032b68b0 | Java | devil13th/javatest-root | /javatest-json/src/main/java/com/thd/json/jackson/User.java | UTF-8 | 1,047 | 2.84375 | 3 | [] | no_license | package com.thd.json.jackson;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
public class User {
private String name;
private Date birthday;
private LocalDateTime createTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(this.birthday);
return "User{" +
"name='" + name + '\'' +
", birthday=" + birthday +
", createTime=" + dateStr +
'}';
}
}
| true |
87b7a8fb2ef0901d0e47c1ae83c7b11c74c37f3b | Java | mr-xkf/api-wechat | /web-service/api-service/src/main/java/com/example/thread/Demo3.java | UTF-8 | 1,807 | 3.359375 | 3 | [] | no_license | /**
* FileName: Demo3
* Author: 13235
* Date: 2019/4/7 18:48
* Description:
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.example.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
/**
* 〈一句话功能简述〉<br>
* 〈〉
*
* @author 13235
* @create 2019/4/7
* @since 1.0.0
*/
public class Demo3 extends RecursiveTask<Integer> {
private Integer start;
private Integer end;
public Demo3(Integer start, Integer end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
Integer sum=0;
if (end - start <= 10) {
for (int i = start; i <= end; i++) {
sum += i;
}
}else{
Demo3 d1 = new Demo3(start, (start+end) / 2);
Demo3 d2 = new Demo3((end + start) / 2 + 1, end);
d1.fork();
d2.fork();
Integer join = d1.join();
Integer join2 = d2.join();
sum=join + join2;
}
return sum;
}
public static void main(String[] args) {
Demo3 demo3 = new Demo3(1, 100);
ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
ForkJoinTask<Integer> submit = pool.submit(demo3);
System.out.println(".....");
try {
System.out.println("结果是:" + submit.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
| true |
e7fed1210f67d8c60707bea45050eaf0f29adfd4 | Java | S3lfie1/SUL-Simple-User-List | /build/generated-sources/ap-source-output/com/jList/model/Users_.java | UTF-8 | 575 | 1.546875 | 2 | [] | no_license | package com.jList.model;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-10-17T20:06:50")
@StaticMetamodel(Users.class)
public class Users_ {
public static volatile SingularAttribute<Users, String> firstname;
public static volatile SingularAttribute<Users, String> dob;
public static volatile SingularAttribute<Users, Integer> id;
public static volatile SingularAttribute<Users, String> lastname;
} | true |
3387b01eff1da86beaa1fe0332efe062f2675c98 | Java | oktolab/netty-jersey-starter | /src/main/java/br/com/oktolab/netflixoss/nettyrest/provider/HealthCheckRest.java | UTF-8 | 216 | 1.71875 | 2 | [] | no_license | package br.com.oktolab.netflixoss.nettyrest.provider;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/healthcheck")
public class HealthCheckRest {
@GET
public String healthCheck() {
return "OK";
}
}
| true |
49d2c3ac30c720652302f41a00c781aea271670d | Java | gk141988/trending_hashtag | /src/Tester.java | UTF-8 | 673 | 3.0625 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Tester {
public static void main(String[] args) throws IOException {
final TrendingHashTagObservable observable = new TrendingHashTagObservable();
final TrendingHashTagObserver observer = new TrendingHashTagObserver();
observable.addObserver(observer);
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Enter your tweet here : \n");
String tweet = br.readLine();
observable.setHashTagFromTweet(tweet);
}
}
}
| true |
bdfc1a194839ccf2258de3786a3b5ced9c4d24a2 | Java | SJU-CUS-1194-Mobile-Health-Analytics/Ronald-McDonald-Android-App | /app/src/main/java/com/example/jsung721/ronaldmcdonald_prototype1/SettingsActivity.java | UTF-8 | 1,742 | 2.109375 | 2 | [] | no_license | package com.example.jsung721.ronaldmcdonald_prototype1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Button settingsBackButton = (Button) findViewById(R.id.button_settings_to_menu);
settingsBackButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent settingsToMenuIntent = new Intent(SettingsActivity.this, StrideMainMenuActivity.class);
startActivity(settingsToMenuIntent);
}
});
Button signOutButton = (Button) findViewById(R.id.button_settings_log_out);
signOutButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent settingsLogOutIntent = new Intent(SettingsActivity.this, SignInSignOutActivity.class);
startActivity(settingsLogOutIntent);
}
});
Button editProfileButton = (Button) findViewById(R.id.button_settings_edit_user);
editProfileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent settingsEditProfileIntent = new Intent(SettingsActivity.this, EditProfileActivity.class);
startActivity(settingsEditProfileIntent);
}
});
}
}
| true |
6867d80efeed9a4ff3381d79942f8ba2a49a8040 | Java | badayosi/MovieProject | /src/main/java/movie/dao/TimetableDao.java | UTF-8 | 432 | 1.921875 | 2 | [] | no_license | package movie.dao;
import java.util.List;
import movie.dto.Timetable;
public interface TimetableDao {
public List<Timetable> selectAll();
public List<Timetable> selectByMovie(int no);
public List<Timetable> selectByTheater(int no);
public List<Timetable> selectByDate(int theaterNo, String date);
public Timetable selectByNo(int no);
public void deleteByNo(int no);
public void insert(Timetable timetable);
}
| true |
3ff94e55a08f284ac1755af258f6e3e03f5fa228 | Java | mdtofayel/shadowhite | /src/main/java/com/threeD/service/DigitalItemCommentsService.java | UTF-8 | 384 | 1.945313 | 2 | [] | no_license | package com.threeD.service;
import com.threeD.domain.DigitalItemComments;
public interface DigitalItemCommentsService {
Iterable<DigitalItemComments> listAllDigitalItemComments();
DigitalItemComments getDigitalItemCommentsById(Integer id);
DigitalItemComments saveDigitalItemComments(DigitalItemComments digitalItems);
void deleteDigitalItemComments(Integer id);
}
| true |
bd2fa496086b85c94d8496474936543a022aecaa | Java | EduarRamos2020/tareas | /src/help/Honduras.java | UTF-8 | 491 | 1.96875 | 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 help;
/**
*
* @author Pc
*/
public class Honduras extends Hospital {
@Override
public String getpais() {
return "Hospital Mario Catarino Rivas";
}
@Override
public String getdirector() {
return "Director General: Dra Ledy Brizzio";
}
}
| true |
3e5cd8c772af661015d8cb850047584a13dd6021 | Java | heartzz/DealseRetailer | /app/src/main/java/com/dealse/dealsepartner/Objects/StoreTypeApiModel.java | UTF-8 | 502 | 1.9375 | 2 | [] | no_license | package com.dealse.dealsepartner.Objects;
public class StoreTypeApiModel {
private String storeTypeId;
private String storeTypeName;
public String getStoreTypeId() {
return storeTypeId;
}
public void setStoreTypeId(String storeTypeId) {
this.storeTypeId = storeTypeId;
}
public String getStoreTypeName() {
return storeTypeName;
}
public void setStoreTypeName(String storeTypeName) {
this.storeTypeName = storeTypeName;
}
}
| true |
7ceb705f6c265bdcfffa29674747a13c066fa026 | Java | pattrie/estudos-apostila-fj21-jsp-caelum | /fj21-agenda/src/main/java/br/com/caelum/servlet/MinhaServlet.java | UTF-8 | 1,045 | 2.484375 | 2 | [] | no_license | package br.com.caelum.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/minhaServlet")
public class MinhaServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
log("Iniciando a servlet.");
}
@Override
public void destroy() {
super.destroy();
log("Destruindo a servlet.");
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("Primeira Servlet");
out.println("</body>");
out.println("</html>");
}
}
| true |
ef4592bf2218b79717084fa0d20147ca3c7351af | Java | iscomX/Android_proj | /app/src/main/java/is/com/RandomGame.java | UTF-8 | 1,423 | 2.296875 | 2 | [] | no_license | package is.com;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.iscom.sharedprefs.R;
import java.util.Random;
public class RandomGame extends AppCompatActivity {
Integer randInt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_game);
randInt = new Random().nextInt(100) + 1;
}
public void generate(View view) {
Log.i("info", "" + randInt);
EditText editText = (EditText) findViewById(R.id.editText_RG);
TextView textView = (TextView) findViewById(R.id.textView_RG);
Integer numEdit = Integer.parseInt(editText.getText().toString());
if (randInt == numEdit) {
randInt = new Random().nextInt(100) + 1;
toastMessage("Good");
textView.setText("Good");
} else if (randInt > numEdit) {
toastMessage("Great than");
textView.setText("Great than");
} else {
toastMessage("Less than");
textView.setText("Less than");
}
}
public void toastMessage(String string) {
Toast.makeText(this, "" + string, Toast.LENGTH_LONG).show();
}
}
| true |
754ed69d678808de1242d0324bdad6d916a4fa28 | Java | jackyzonewen/JocCheji_master | /src/com/icalinks/mobile/ui/fragment/SvcsRecordFragment.java | UTF-8 | 3,257 | 2 | 2 | [] | no_license | package com.icalinks.mobile.ui.fragment;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.icalinks.jocyjt.R;
import com.icalinks.mobile.GlobalApplication;
import com.icalinks.mobile.db.dal.NaviDal;
import com.icalinks.mobile.db.dal.NaviInfo;
import com.icalinks.mobile.ui.NaviActivity;
import com.icalinks.mobile.ui.adapter.SvcsRecordAdapter;
import com.icalinks.mobile.util.ToastShow;
import com.provider.net.tcp.GpsWorker;
public class SvcsRecordFragment extends BaseFragment implements
OnItemClickListener {
public static final String TAG = SvcsRecordFragment.class.getSimpleName();
public SvcsRecordFragment(int resId) {
super(resId);
}
public SvcsRecordFragment(Activity activity, int resId) {
super(resId);
setActivity(activity);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.svcs_record, null);
init(v);
return v;
}
private TextView mMainTextView;
private ListView mMainListView;
private SvcsRecordAdapter mSvcsRecordAdapter;
private void init(View v) {
mMainTextView = (TextView) v.findViewById(R.id.svcs_record_item_none);
mMainListView = (ListView) v.findViewById(R.id.svcs_record_item_list);
mMainListView.setOnItemClickListener(this);
}
@Override
public void onResume() {
super.onResume();
check();
}
private void check() {
List<NaviInfo> lstItem = NaviDal.getInstance(getActivitySafe()).select(
null);
if (lstItem != null && lstItem.size() > 0) {
mMainListView.setVisibility(View.VISIBLE);
mMainTextView.setVisibility(View.GONE);
mSvcsRecordAdapter = new SvcsRecordAdapter(getActivitySafe(),
lstItem);
mMainListView.setAdapter(mSvcsRecordAdapter);
} else {
mMainTextView.setVisibility(View.VISIBLE);
mMainListView.setVisibility(View.GONE);
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Location location = GlobalApplication.getLocation();
if (location == null) {
ToastShow.show(getActivitySafe(), "无法获取当前位置,请稍后再试!");
return;
}
NaviInfo info = (NaviInfo) mSvcsRecordAdapter.getItem(position);
NaviDal.getInstance(getActivitySafe()).update(info.get_id());// 更新最后时间,影响排序
Intent intent = new Intent();
{
intent.setClass(getActivitySafe(), NaviActivity.class);
String strData = String.format("false,%s,%s,%s;false,%s,%s,%s", 0,
0, "X", info.getEndPoint().getLongitudeE6() / 1000000.0,
info.getEndPoint().getLatitudeE6() / 1000000.0,
info.getEndAddrs());
intent.putExtra(NaviActivity.ARGS_NAVI_DATA_STRING, strData);
intent.putExtra(NaviActivity.ARGS_IS_BAIDU_POINT, false);// 不是百度坐标
}
getActivitySafe().startActivity(intent);
}
}
| true |
9829835508a9703b283f93d75337380637deae76 | Java | florin-postelnicu/releasejar | /Jprograms/Rectangle.java | UTF-8 | 1,313 | 4.3125 | 4 | [] | no_license | package com.exam.bicycle;
/*
this keyword is used to represent the current object. As in the previous example,
since method1 has the object of class as parameter, so when it was called inside method2,
we passed this keyword as its argument in place of the object of the class.
Similarly, we can return this keyword instead of returning object of any class.
Here, we returned this in getObj() method.
Now, since object r1 called the 'getObj' method and this keyword represents the current object,
here this keyword is used to represent the object r1. Thus by writing return this,
we are returning object r1 and by writing r2 = r1.getObj(), we are assigning object r1 to object r2.
Thus, the length and breadth of r2 also become 15 and 20 respectively.
*/
public class Rectangle {
int length, breadth;
Rectangle(int l, int b){
length = l;
breadth = b;
}
Rectangle getObj(){
return this;
}
}
class This5{
public static void main(String[] args) {
Rectangle r1 = new Rectangle(15, 20);
Rectangle r2 ;
r2 = r1.getObj();
System.out.println("length : " + r1.length + " breadth : " + r1.breadth);
System.out.println("Length : " + r2.length + " breadth : " + r2.breadth);
}
}
| true |
70a5d5f8658793480f077202429da6facd353d4f | Java | Ninise/SmartHelper | /app/src/main/java/com/ninise/smarthelper/db/RealmAccessor.java | UTF-8 | 289 | 2.09375 | 2 | [] | no_license | package com.ninise.smarthelper.db;
import java.util.List;
/**
* @author Nikita Nikita
*/
public interface RealmAccessor<T> {
T readItem(String name);
List<T> readAllItems();
void createItem(T item);
void updateItem(T item);
void deleteItem(T item);
void clear();
}
| true |
fa2b81a734760bc344a14468c805deb2649f55bf | Java | ThomasvanBommel/java | /CSMClient1.6/src/com/cekeh/utility/Vector2i.java | UTF-8 | 356 | 2.71875 | 3 | [] | no_license | // Last edit: 06/04/2018 - TvB
package com.cekeh.utility;
/**
* Cekeh's Vector2i object
* Created 06/04/2018
* @author Thomas vanBommel (TvB)
*/
public class Vector2i {
public int x;
public int y;
/**
* Create a new Vector2i object
* @param x The x value
* @param y The y value
*/
public Vector2i(int x, int y) {
this.x = x;
this.y = y;
}
}
| true |
0c63dd1c4cd635ff63977e0e1d7bcff468a0b64e | Java | zhangqunshi/java_study | /java_basic/day9_arrays_collections/ArrayList1.java | UTF-8 | 2,135 | 3.71875 | 4 | [] | no_license | import java.util.ArrayList;
class Apple {
private static long count;
private final long id = count++;
private String name;
public Apple() {
}
public Apple(String name) {
this.name = name;
}
public long id() {
return id;
}
public String getName() {
return name;
}
public boolean equals(Object other) {
if (other == null) {
return false;
}
Apple another = (Apple) other;
if (this.name != null && this.name.equals(another.getName())) {
return true;
}
return false;
}
}
class Orange {
}
public class ArrayList1 {
public static void main(String[] args) {
ArrayList<Apple> appleList = new ArrayList<>(); // 新建
for (int i = 0; i < 3; i++) {
appleList.add(new Apple()); // 添加
}
// appleList.add(1, new Orange()); // 带index的插入
// appleList.add(1.01); // 自动装箱
// Apple apple = (Applet) appleList.get(0); // 获取,需要强制转型
Apple apple = appleList.get(0); // 获取
// System.out.println((Double)appleList.get(4) + 2); // 自动拆箱
// appleList.remove(0);
// appleList.clear();
// ArrayList orangeList = new ArrayList();
// orangeList.add(new Orange());
// orangeList.add(new Orange());
// appleList.addAll(orangeList);
// Object[] arr = appleList.toArray();
appleList.add(null);
appleList.add(null);
System.out.println("size = " + appleList.size());
boolean exist = appleList.contains(null);
System.out.println("exist = " + exist);
appleList.add(new Apple("big"));
exist = appleList.contains(new Apple("big"));
System.out.println("exist big = " + exist);
System.out.println("is empty = " + appleList.isEmpty());
for (int i = 0; i < appleList.size(); i++) {
System.out.println(appleList.get(i));
}
for (Apple x : appleList) {
System.out.println(x);
}
}
} | true |
de6ee67872e989fd838dcb5dec7418bb25e87963 | Java | Yuditskiy-o/2GIS-test-task | /src/test/java/ru/gis/test/QueryPageSizeTest.java | UTF-8 | 7,522 | 2.390625 | 2 | [] | no_license | package ru.gis.test;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.basePath;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
public class QueryPageSizeTest {
private final RequestSpecification requestSpec = new RequestSpecBuilder()
.setBaseUri("https://regions-test.2gis.com")
.setBasePath("/1.0/regions")
.setUrlEncodingEnabled(false)
.setAccept(ContentType.JSON)
.setContentType(ContentType.JSON)
.log(LogDetail.ALL)
.build();
@Nested
class PageSizeWithNoArgs {
@Test
void shouldCheckIfGetErrorWhenOnlyPageSize() {
given()
.spec(requestSpec)
.queryParam("page_size")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' должен быть целым числом"));
}
@Test
void shouldCheckIfGetErrorWhenPageSizeAndSign() {
given()
.spec(requestSpec)
.queryParam("page_size=")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' должен быть целым числом"));
}
}
@Nested
class PageSizeWithIncorrectArgs {
@Test
void shouldCheckIfGetErrorWhenPageSizeSignMinus1() {
given()
.spec(requestSpec)
.queryParam("page_size=-1")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15"));
}
@Test
void shouldCheckIfGetErrorWhenPageSizeSign0() {
given()
.spec(requestSpec)
.queryParam("page_size=0")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15"));
}
@Test
void shouldCheckIfGetErrorWhenPageSizeSignFloat() {
given()
.spec(requestSpec)
.queryParam("page_size=1.1")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15"));
}
@Test
void shouldCheckIfGetErrorWhenPageSizeSignLetters() {
given()
.spec(requestSpec)
.queryParam("page_size=акт")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15"));
}
@Test
void shouldCheckIfGetErrorWhenPageSizeSignSpecialCharacters() {
given()
.spec(requestSpec)
.queryParam("page_size=$$$$")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15"));
}
}
@Nested
class PageSizeWithSizeFilterAndDefaultCountTest {
@Test
void shouldCheckIfSearchWorksWithExact5Cities() {
given()
.spec(requestSpec)
.queryParam("page_size=5")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("items", hasSize(5));
}
@Test
void shouldCheckIfSearchWorksWithExact10Cities() {
given()
.spec(requestSpec)
.queryParam("page_size=10")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("items", hasSize(10));
}
@Test
void shouldCheckIfSearchWorksWithExact15Cities() {
given()
.spec(requestSpec)
.queryParam("page_size=15")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("items", hasSize(15));
}
@Test
void shouldCheckIfGetErrorWhenPageSizeMoreWhen15() {
given()
.spec(requestSpec)
.queryParam("page_size=20")
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("error.message", equalTo("Параметр 'page_size' может быть одним из следующих значений: 5, 10, 15"));
}
@Test
void shouldCheckIfDefaultCountOfRegionsIs15() {
given()
.spec(requestSpec)
// Выполняемые действия
.when()
.get(basePath)
// Проверки
.then().assertThat().statusCode(200)
.and().body("items", hasSize(15));
}
}
}
| true |
4799cee22c14128eb1a2000564266b0d9d7b9c15 | Java | SanaNasar/Intro-to-JAVA | /HelloSantaClaus.java | UTF-8 | 811 | 4.03125 | 4 | [
"MIT"
] | permissive | import java.util.*;
class SantaClaus
{
String greeting = "Ho! Ho! Ho!";
}
class HelloSantaClaus
{
public static void main(String[] args)
{
SantaClaus sc = new SantaClaus();
System.out.println("You do not want to pay taxes, right? Say 'yes'.");
Scanner myScanner = new Scanner(System.in);
String userAnswer = myScanner.nextLine();
System.out.println("You said " + userAnswer);
System.out.println(sc.greeting + " now let's add two integers.");
System.out.println("Type in an integer, that is, a whole number.");
int myFirstInt = myScanner.nextInt();
System.out.println("Type in an second integer.");
int mySecondInt = myScanner.nextInt();
System.out.println("The sum is: " + (myFirstInt + mySecondInt));
}
} | true |
027f9a3c536dcf669f7fc8289eb65ebfda9b7323 | Java | 0xshaikat/CrispyPotatoes | /RapLyrics2.java | UTF-8 | 3,009 | 2.71875 | 3 | [] | no_license | ///takes the top 10 lyrics from genius.com and inputs them into a .txt file separated by newline
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.parser.Tag;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.util.*;
import java.lang.Character;
public class RapLyrics2{
public final String access_token = "QD3MzatG7kXDSzm2WF9VXOQLqZzA2IOZRkWRzNQUk-mppG3ifUVsd33RmYB3fbM4"; //access token for api requests
public final String base_URL = "http://api.genius.com";
public static String links_rough = "";
public static void main(String[] args) {
try {
PrintWriter writer = new PrintWriter("lyrics.txt", "UTF-8");
PrintWriter writer1 = new PrintWriter("lyrics1.txt", "UTF-8");
// fetch the document over HTTP
Document doc = Jsoup.connect("https://genius.com/").get();
// get all dem links and add them to one string?
Elements links = doc.select("a[href]");
ArrayList<String> linksrough = new ArrayList<String>();
ArrayList<Document> docs = new ArrayList<Document>();
for (Element link : links) {
if(link.attr("href").contains("lyrics")){
linksrough.add(link.attr("href")) ;
}
}
Document docs1 = Jsoup.connect(linksrough.get(0)).get();
docs.add(docs1);
Document docs2 = Jsoup.connect(linksrough.get(1)).get();
docs.add(docs2);
Document docs3 = Jsoup.connect(linksrough.get(2)).get();
docs.add(docs3);
Document docs4 = Jsoup.connect(linksrough.get(3)).get();
docs.add(docs4);
Document docs5 = Jsoup.connect(linksrough.get(4)).get();
docs.add(docs5);
Document docs6 = Jsoup.connect(linksrough.get(5)).get();
docs.add(docs6);
Document docs7 = Jsoup.connect(linksrough.get(6)).get();
docs.add(docs7);
Document docs8 = Jsoup.connect(linksrough.get(7)).get();
docs.add(docs8);
Document docs9 = Jsoup.connect(linksrough.get(8)).get();
docs.add(docs9);
Document docs10 = Jsoup.connect(linksrough.get(9)).get();
docs.add(docs10);
ArrayList<String> el = new ArrayList<String>();
String lyrics="";
//get em lyrics
for(Document d : docs){
Elements ex1 = d.getAllElements();
for(Element e: ex1){
if (e.tagName().equalsIgnoreCase("lyrics")){
if (e.hasText()){
lyrics = e.text();
}
}
}
el.add(lyrics);
}
for (String s1 : el){
writer1.println(s1);
writer1.println("\n");
}
writer1.close();
for (String s : el){
String[] y = s.split("(?=[A-Z])");
for(String s1: y){
writer.println(s1);
}
writer.println("\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
0f5522e7059f91c1e9c56d9ecbd1a15e86c73c41 | Java | ravisharma007/DSA_SheetByLoveBabbar | /Arrays/src/NextPermutaion.java | UTF-8 | 1,061 | 3.140625 | 3 | [] | no_license | /*
import java.util.*;
class Solution {
public void nextPermutation(int[] nums) {
int idx=-1;
for(int i= nums.length-1; i>0; i--)
{
if(nums[i] > nums[i-1])
{
idx=i;
break;
}
}
if(idx == -1)
{
reverse(nums,0,nums.length-1);
}
else
{
int prev=idx;
for(int i=idx+1; i<nums.length;i++)
{
if(nums[i] <= nums[prev] && nums[i] > nums[idx-1])
{
prev=i;
}
}
//swap
int temp=nums[prev];
nums[prev]=nums[idx-1];
nums[idx-1]=temp;
reverse(nums,idx,nums.length-1);
}
}
public void reverse(int [] arr,int start, int end)
{
while(start < end)
{
int temp= arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
}
}*/
| true |
22e7d984a2444ef7cde3953de0d4c4d507a4b943 | Java | KenyRim/restapp | /AppDevTest/app/src/main/java/com/kenyrim/appdevtest/fragments/ListFragmentA.java | UTF-8 | 2,333 | 2.109375 | 2 | [] | no_license | package com.kenyrim.appdevtest.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.kenyrim.appdevtest.R;
import com.kenyrim.appdevtest.adapter.AdapterRecycler;
import com.kenyrim.appdevtest.model.Model;
import java.util.ArrayList;
public class ListFragmentA extends Fragment {
private int scrollPos;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("scrollPos", scrollPos);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
scrollPos = savedInstanceState.getInt("scrollPos");
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_list_layout, container, false);
Bundle b = getArguments();
assert b != null;
ArrayList<Model> myArray = b.getParcelableArrayList("MY_ARRAY");
RecyclerView recyclerView = v.findViewById(R.id.recyclerView);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView,int dx,int dy) {
super.onScrolled(recyclerView,dx,dy);
scrollPos = dy;
}
});
AdapterRecycler adapter = new AdapterRecycler(getActivity(),getContext(), myArray);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null){
recyclerView.scrollTo(0,scrollPos);
}
return v;
}
}
| true |
553a726de062c6330e1864dcfb8e7e23e06e4044 | Java | ssriha0/sl-b2b-platform | /MarketBackend/src/com/newco/marketplace/inhomeoutboundnotification/beans/SendMessageResponse.java | UTF-8 | 1,356 | 1.914063 | 2 | [] | no_license | package com.newco.marketplace.inhomeoutboundnotification.beans;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
/**
* This is a bean class for storing response information for
* the In Home Out bound Message Service
* @author Infosys
*/
@XStreamAlias("SendMessageResponse")
public class SendMessageResponse {
@XStreamAlias("CorrelationId")
private String correlationId;
@XStreamAlias("ResponseCode")
private String responseCode;
@XStreamAlias("ResponseMessage")
private String responseMessage;
@XStreamAlias("messages")
private ErrorMessage messages;
public String getCorrelationId() {
return correlationId;
}
public void setCorrelationId(String correlationId) {
this.correlationId = correlationId;
}
public String getResponseCode() {
return responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
public String getResponseMessage() {
return responseMessage;
}
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
public ErrorMessage getMessages() {
return messages;
}
public void setMessages(ErrorMessage messages) {
this.messages = messages;
}
} | true |
852c3ad096bb392c15f3f5aee466fe68911a7441 | Java | nasingfaund/egrul_java | /import/src/main/java/ru/nyrk/egrul/imprt/TestService.java | UTF-8 | 1,723 | 2 | 2 | [] | no_license | package ru.nyrk.egrul.imprt;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.nyrk.egrul.database.entity.ArchiveFile;
import ru.nyrk.egrul.database.entity.LoadedFileError;
import ru.nyrk.egrul.database.entity.LoadedFileStatus;
import ru.nyrk.egrul.database.entity.XmlFile;
import ru.nyrk.egrul.imprt.repo.ArchiveFileRepository;
import ru.nyrk.egrul.imprt.repo.XmlFileRepository;
import java.util.Date;
/**
* todo:java doc
*/
@Service
public class TestService {
@Autowired
ArchiveFileRepository archiveFileRepository;
@Autowired
XmlFileRepository xmlFileRepository;
@Transactional
public void test() {
ArchiveFile archiveFile = new ArchiveFile();
archiveFile.setDateFile(new Date());
archiveFile.setDateLoad(new Date());
archiveFile.setFileId(111);
archiveFile.setFileName("gdffds");
archiveFile.setStatus(LoadedFileStatus.LOADED);
LoadedFileError loadedFileError = new LoadedFileError();
loadedFileError.setArchiveFile(archiveFile);
archiveFile.setErrors(Lists.newArrayList(loadedFileError));
XmlFile xmlFile = XmlFile
.newBuilder()
.withArchiveFile(archiveFile)
.withDate(new Date())
.withErrorMessage("text")
.build();
XmlFile save = xmlFileRepository.save(xmlFile);
archiveFile.setXmlFiles(Lists.newArrayList(save));
archiveFileRepository.save(archiveFile);
System.out.println(archiveFileRepository.findOne(0L));
}
}
| true |
35a2240f107546ed1f76a9ba4a4a22e447d99014 | Java | cabajian/web-checkers | /src/test/java/com/webcheckers/ui/WebServerTest.java | UTF-8 | 561 | 1.882813 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.webcheckers.ui;
import com.google.gson.Gson;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import spark.TemplateEngine;
import static org.mockito.Mockito.mock;
@Tag("UI-tier")
public class WebServerTest {
@Test
void webserverTest() {
TemplateEngine engine = mock(TemplateEngine.class);
Gson gson = new Gson();
WebServer CuT = new WebServer(engine, gson);
try {
CuT.initialize();
} catch (IllegalStateException e) {
}
}
}
| true |
9e9641cc925ff8920d36e32fadefb5a112099fb0 | Java | lza1997/mall-admin | /src/main/java/com/mall/admin/service/activitytemplate/ActivityTemplateService.java | UTF-8 | 686 | 1.851563 | 2 | [] | no_license | package com.mall.admin.service.activitytemplate;
import java.util.List;
import java.util.Map;
import com.mall.admin.model.pagination.PaginationInfo;
import com.mall.admin.vo.activitytemplate.ActivityTemplate;
public interface ActivityTemplateService {
public List<ActivityTemplate> getActivityTemplateList(Map<String,Object> param,PaginationInfo paginationInfo);
public int addActivityTemplate(ActivityTemplate activityTemplate) throws Exception;
public int updateActivityTemplate(ActivityTemplate activityTemplate) throws Exception ;
public ActivityTemplate getActivityTemplateById(Long activityTemplateId);
public List<ActivityTemplate> getAllActivityTemplate();
}
| true |
f848f5523a44b5268434dd514fd1a4ffe95317c1 | Java | KwonJeongah/chart | /winechart/src/main/java/com/jeongah/vo/FaPhVO.java | UTF-8 | 371 | 2.03125 | 2 | [] | no_license | package com.jeongah.vo;
public class FaPhVO {
private float fixed_acidity;
private float ph;
public float getFixed_acidity() {
return fixed_acidity;
}
public void setFixed_acidity(float fixed_acidity) {
this.fixed_acidity = fixed_acidity;
}
public float getPh() {
return ph;
}
public void setPh(float ph) {
this.ph = ph;
}
}
| true |
48056b802fe36bf04c75e89c9029a209b374f24b | Java | youssefmyh/jungle-boy | /com/veritechnolohy/elements/board.java | UTF-8 | 1,956 | 2.140625 | 2 | [] | no_license | /* */ package com.veritechnolohy.elements;
/* */
/* */ import com.veritechnology.engine.Constants;
/* */ import com.veritechnology.engine.ImageLoader;
/* */ import com.veritechnology.engine.releaseObject;
/* */ import java.io.PrintStream;
/* */ import javax.microedition.lcdui.Graphics;
/* */ import javax.microedition.lcdui.Image;
/* */
/* */ public class board extends MainElement
/* */ implements releaseObject
/* */ {
/* */ private Image bazaza;
/* */ private Image levelNumberimg;
/* */
/* */ public board(int levelNumber)
/* */ {
/* 28 */ super(Constants.NONEATINGELEMENT);
/* 29 */ setFixedElement(true);
/* 30 */ this.bazaza = ImageLoader.loadImage("board");
/* 31 */ levelNumber++;
/* 32 */ if ((levelNumber > 10) && (levelNumber < 21))
/* 33 */ levelNumber -= 10;
/* 34 */ if (levelNumber > 20) {
/* 35 */ levelNumber -= 20;
/* */ }
/* 37 */ System.out.println("the level number is " + levelNumber);
/* 38 */ this.levelNumberimg = ImageLoader.loadImage("" + levelNumber);
/* */
/* 41 */ this.locationx = 200;
/* 42 */ this.locationy = 0;
/* 43 */ this.elemntWidth = this.bazaza.getWidth();
/* 44 */ this.elementHeight = this.bazaza.getHeight();
/* */ }
/* */
/* */ public void paint(Graphics g)
/* */ {
/* 52 */ g.drawImage(this.bazaza, this.locationx, this.locationy, 0);
/* 53 */ g.drawImage(this.levelNumberimg, this.locationx + 20, this.locationy + 28, 0);
/* */ }
/* */
/* */ public void freeElement()
/* */ {
/* 58 */ super.freeElement();
/* 59 */ this.bazaza = null;
/* */ }
/* */
/* */ public void freememory()
/* */ {
/* 64 */ this.bazaza = null;
/* */ }
/* */ }
/* Location: /media/youssef/Hard3/Code C/babygame.jar
* Qualified Name: com.veritechnolohy.elements.board
* JD-Core Version: 0.6.2
*/ | true |
29c1af8fccbd478305c200e60b71ec87392f5657 | Java | dheerajbutani/Wissen | /day1/classobj/src/com/bank/cust/account/Account.java | UTF-8 | 114 | 1.578125 | 2 | [] | no_license | package com.bank.cust.account;
public class Account {
public int num;
public String name;
public Account()
{
}
}
| true |
46a83b48aadfaec5deb6200502ff6db29f8e8e1c | Java | hieuh0/wifi-easy-transfer | /app/src/main/java/pucminas/br/cc/lddm/wifieasytransfer/ServerService.java | UTF-8 | 3,441 | 2.21875 | 2 | [
"MIT"
] | permissive | package pucminas.br.cc.lddm.wifieasytransfer;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import pucminas.br.cc.lddm.tp_final.R;
/**
* Created by josue on 07/06/15.
*/
public class ServerService extends IntentService {
private int port;
private File saveLocation;
public ServerService() {
super("ServerService");
}
@Override
protected void onHandleIntent(Intent intent) {
port = ((Integer) intent.getExtras().get("port")).intValue();
saveLocation = (File) intent.getExtras().get("target");
ServerSocket ss = null;
Socket s = null;
NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder.setContentTitle("Download file")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.cellphone_img);
Log.d("Wp2p", "Loading Sever..");
try {
ss = new ServerSocket(port);
// Listen for connections
s = ss.accept();
Log.d("Wp2p", "Server wating for connections");
InputStream is = s.getInputStream();
String saveAs = "wp2pfile" + System.currentTimeMillis();
File file = new File(saveLocation, saveAs);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//byte[] buffer = new byte[4096];
byte[] buffer = new byte[1024];
int bytesRead;
int c = 0;
Log.d("Wp2p", "Downloading file...");
// start notification
mBuilder.setContentTitle("Download file")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.cellphone_img);
mBuilder.setProgress(0, 0, true);
while(true) {
bytesRead = is.read(buffer, 0, buffer.length);
if(bytesRead == -1) break;
bos.write(buffer, 0, bytesRead);
bos.flush();
c++;
Log.d("Wp2p", "write part -> "+c);
}
bos.close();
s.close();
ss.close();
Log.d("Wp2p", "Download complete...");
mBuilder.setContentText("Download complete");
// Removes the progress bar
mBuilder.setProgress(0, 0, false);
mNotifyManager.notify(1, mBuilder.build());
Toast.makeText(getApplicationContext(), "Download complete", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d("Wp2p", "Error in Socket Server");
Log.d("Wp2p", e.getMessage());
e.printStackTrace();
}
}
}
| true |
5819568efac585d3a147cefe8ed55ffdd6a4344d | Java | bellmit/GistandardTransport | /transport-base/src/main/java/com/gistandard/transport/base/entity/bean/MobileWantTransport.java | UTF-8 | 4,384 | 1.671875 | 2 | [] | no_license | package com.gistandard.transport.base.entity.bean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class MobileWantTransport implements Serializable {
private static final long serialVersionUID = -1100884892408891184L;
private Integer id;
private String lineStart;
private String lineDest;
private Date departTime;
private Date arriveTime;
private Integer respondentUser;
private BigDecimal restLoad;
private BigDecimal restSpace;
private BigDecimal heavyPrice;
private BigDecimal lightPrice;
private BigDecimal lowestVote;
private BigDecimal perTicket;
private String currency;
private Integer wantType;
private Integer createUserId;
private String createUser;
private Date createTime;
private Integer updateUserId;
private String updateUser;
private Date updateTime;
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLineStart() {
return lineStart;
}
public void setLineStart(String lineStart) {
this.lineStart = lineStart;
}
public String getLineDest() {
return lineDest;
}
public void setLineDest(String lineDest) {
this.lineDest = lineDest;
}
public Date getDepartTime() {
return departTime;
}
public void setDepartTime(Date departTime) {
this.departTime = departTime;
}
public Date getArriveTime() {
return arriveTime;
}
public void setArriveTime(Date arriveTime) {
this.arriveTime = arriveTime;
}
public Integer getRespondentUser() {
return respondentUser;
}
public void setRespondentUser(Integer respondentUser) {
this.respondentUser = respondentUser;
}
public BigDecimal getRestLoad() {
return restLoad;
}
public void setRestLoad(BigDecimal restLoad) {
this.restLoad = restLoad;
}
public BigDecimal getRestSpace() {
return restSpace;
}
public void setRestSpace(BigDecimal restSpace) {
this.restSpace = restSpace;
}
public BigDecimal getHeavyPrice() {
return heavyPrice;
}
public void setHeavyPrice(BigDecimal heavyPrice) {
this.heavyPrice = heavyPrice;
}
public BigDecimal getLightPrice() {
return lightPrice;
}
public void setLightPrice(BigDecimal lightPrice) {
this.lightPrice = lightPrice;
}
public BigDecimal getLowestVote() {
return lowestVote;
}
public void setLowestVote(BigDecimal lowestVote) {
this.lowestVote = lowestVote;
}
public BigDecimal getPerTicket() {
return perTicket;
}
public void setPerTicket(BigDecimal perTicket) {
this.perTicket = perTicket;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Integer getWantType() {
return wantType;
}
public void setWantType(Integer wantType) {
this.wantType = wantType;
}
public Integer getCreateUserId() {
return createUserId;
}
public void setCreateUserId(Integer createUserId) {
this.createUserId = createUserId;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(Integer updateUserId) {
this.updateUserId = updateUserId;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
} | true |
1c18551658f99ef9a1dab45bda2c37cf533ddb64 | Java | tochange/SnapseedOld | /app/src/main/java/com/niksoftware/snapseed/controllers/touchhandlers/TouchHandler.java | UTF-8 | 1,221 | 2.359375 | 2 | [] | no_license | package com.niksoftware.snapseed.controllers.touchhandlers;
public abstract class TouchHandler {
private boolean _ignoreEvents = false;
public void layout(boolean changed, int left, int top, int right, int bottom) {
}
public boolean needGestureDetector() {
return true;
}
public void cleanup() {
}
public boolean ignoreEvents() {
return this._ignoreEvents;
}
protected void setIgnoreEvents() {
this._ignoreEvents = true;
}
public void resetIgnoreEvents() {
this._ignoreEvents = false;
}
public boolean handleTouchDown(float x, float y) {
return false;
}
public boolean handleTouchMoved(float x, float y) {
return false;
}
public void handleTouchUp(float x, float y) {
}
public void handleTouchCanceled(float x, float y) {
}
public void handleTouchAbort(boolean pinchBegins) {
}
public boolean handlePinchBegin(int x, int y, float size, float arc) {
return false;
}
public boolean handlePinch(int x, int y, float size, float arc) {
return false;
}
public void handlePinchEnd() {
}
public void handlePinchAbort() {
}
}
| true |
bebf0b3457afa45b2fd248d4ae4fafe32d963999 | Java | dougallas/blackdesert-fishbot | /src/test/java/ru/namibios/arduino/model/command/FishLootTest.java | UTF-8 | 8,657 | 2.28125 | 2 | [] | no_license | package ru.namibios.arduino.model.command;
import org.junit.Before;
import org.junit.Test;
import ru.namibios.arduino.config.Application;
import ru.namibios.arduino.config.Path;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class FishLootTest {
@Before
public void init() {
Application.getInstance();
Application.getInstance().setProperty("bot.loot.rock", "true");
Application.getInstance().setProperty("bot.loot.key", "true");
Application.getInstance().setProperty("bot.loot.fish", "true");
Application.getInstance().setProperty("bot.loot.event","true");
Application.getInstance().setProperty("bot.loot.confirm","true");
}
private String ok;
private String confirm;
private String empty;
private String trash;
@Before
public void before() {
ok = Path.TEST_RESOURCES + "parsing/loot/ok/scala/scala.jpg";
empty = Path.TEST_RESOURCES + "parsing/loot/ok/empty/empty.jpg";
confirm = Path.TEST_RESOURCES + "parsing/loot/ok/confirm/archer_seal_2.jpg";
trash = Path.TEST_RESOURCES + "parsing/loot/trash/1.jpg";
}
// ------------------------------ALL FILTER TRUE------------------------------//
// --------------------TAKE ALL--------------------//
@Test
public void testOkEmptyEmpty() throws IOException{
FishLoot fishLoot = new FishLoot(ok, empty, empty);
String key = fishLoot.getKey();
assertEquals(ShortCommand.TAKE.getKey(), key);
}
@Test
public void testOkOkEmpty() throws IOException{
FishLoot fishLoot = new FishLoot(ok, ok, empty);
String key = fishLoot.getKey();
assertEquals(ShortCommand.TAKE.getKey(), key);
}
@Test
public void testOkOkOK() throws IOException {
FishLoot fishLoot = new FishLoot(ok, ok, ok);
String key = fishLoot.getKey();
assertEquals(ShortCommand.TAKE.getKey(), key);
}
@Test
public void testOkMax() throws IOException {
FishLoot fishLoot = new FishLoot(ok, ok, ok, ok, ok, ok, ok, ok);
String key = fishLoot.getKey();
assertEquals(ShortCommand.TAKE.getKey(), key);
}
// --------------------TAKE BY INDEX--------------------//
@Test
public void testOkConfirmTrash() throws IOException {
FishLoot fishLoot = new FishLoot(ok, confirm, trash);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandLoot() +
Application.getInstance().LOOT_TOUCH()[1].toCommandConfirmLoot(), key);
}
@Test
public void testConfirmTrashOk() throws IOException {
FishLoot fishLoot = new FishLoot(confirm, trash, ok);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandConfirmLoot() +
Application.getInstance().LOOT_TOUCH()[2].toCommandLoot(), key);
}
@Test
public void testOkTrashEmpty() throws IOException{
FishLoot fishLoot = new FishLoot(ok, trash, empty);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandLoot(), key);
}
@Test
public void testTrashOkEmpty() throws IOException{
FishLoot fishLoot = new FishLoot(trash, ok, empty);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[1].toCommandLoot(), key);
}
@Test
public void testOkOkTrash() throws IOException {
FishLoot fishLoot = new FishLoot(ok, ok, trash);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandLoot()
+ Application.getInstance().LOOT_TOUCH()[1].toCommandLoot(), key);
}
@Test
public void testOkTrashTrash() throws IOException {
FishLoot fishLoot = new FishLoot(ok, trash, trash);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandLoot(), key);
}
@Test
public void testTrashOkTrash() throws IOException {
FishLoot fishLoot = new FishLoot(trash, ok, trash);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[1].toCommandLoot(), key);
}
@Test
public void testTrashTrashOk() throws IOException {
FishLoot fishLoot = new FishLoot(trash, trash, ok);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[2].toCommandLoot(), key);
}
@Test
public void testOkTrashOk() throws IOException {
FishLoot fishLoot = new FishLoot(ok, trash, ok);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandLoot() +
Application.getInstance().LOOT_TOUCH()[2].toCommandLoot(), key);
}
@Test
public void testTrashOkOk() throws IOException {
FishLoot fishLoot = new FishLoot(trash, ok, ok);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[1].toCommandLoot() +
Application.getInstance().LOOT_TOUCH()[2].toCommandLoot(), key);
}
@Test
public void testOkTrashX4() throws IOException {
FishLoot fishLoot = new FishLoot(ok, trash, ok, trash, ok, trash, ok, trash);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandLoot() +
Application.getInstance().LOOT_TOUCH()[2].toCommandLoot()+
Application.getInstance().LOOT_TOUCH()[4].toCommandLoot()+
Application.getInstance().LOOT_TOUCH()[6].toCommandLoot(), key);
}
@Test
public void testOkTrashX4Reverse() throws IOException {
FishLoot fishLoot = new FishLoot(trash, ok, trash, ok, trash, ok, trash, ok);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[1].toCommandLoot() +
Application.getInstance().LOOT_TOUCH()[3].toCommandLoot()+
Application.getInstance().LOOT_TOUCH()[5].toCommandLoot()+
Application.getInstance().LOOT_TOUCH()[7].toCommandLoot(), key);
}
@Test
public void testConfirmTrashX4() throws IOException {
FishLoot fishLoot = new FishLoot(confirm, trash, confirm, trash, confirm, trash, confirm, trash);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[0].toCommandConfirmLoot() +
Application.getInstance().LOOT_TOUCH()[2].toCommandConfirmLoot()+
Application.getInstance().LOOT_TOUCH()[4].toCommandConfirmLoot()+
Application.getInstance().LOOT_TOUCH()[6].toCommandConfirmLoot(), key);
}
@Test
public void testConfirmTrashX4Reverse() throws IOException {
FishLoot fishLoot = new FishLoot(trash, confirm, trash, confirm, trash, confirm, trash, confirm);
String key = fishLoot.getKey();
assertEquals(Application.getInstance().LOOT_TOUCH()[1].toCommandConfirmLoot() +
Application.getInstance().LOOT_TOUCH()[3].toCommandConfirmLoot()+
Application.getInstance().LOOT_TOUCH()[5].toCommandConfirmLoot()+
Application.getInstance().LOOT_TOUCH()[7].toCommandConfirmLoot(), key);
}
// --------------------IGNORE ALL--------------------//
@Test
public void testTrashEmptyEmpty() throws IOException{
FishLoot fishLoot = new FishLoot(trash, empty, empty);
String key = fishLoot.getKey();
assertEquals(ShortCommand.IGNORE.getKey(), key);
}
@Test
public void testEmptyX8() throws IOException{
FishLoot fishLoot = new FishLoot(trash, empty, empty, empty, empty, empty, empty, empty);
String key = fishLoot.getKey();
assertEquals(ShortCommand.IGNORE.getKey(), key);
}
@Test
public void testTrashTrashEmpty() throws IOException{
FishLoot fishLoot = new FishLoot(trash, trash, empty);
String key = fishLoot.getKey();
assertEquals(ShortCommand.IGNORE.getKey(), key);
}
@Test
public void testTrashTrashTrash() throws IOException {
FishLoot fishLoot = new FishLoot(trash, trash, trash);
String key = fishLoot.getKey();
assertEquals(ShortCommand.IGNORE.getKey(), key);
}
@Test
public void testTrashX8() throws IOException {
FishLoot fishLoot = new FishLoot(trash, trash, trash, trash, trash, trash, trash, trash);
String key = fishLoot.getKey();
assertEquals(ShortCommand.IGNORE.getKey(), key);
}
} | true |
a1547c730a34dec8fcb506124aa493aafc055294 | Java | ostojan/BubbleKiwi | /core/src/com/kiwi/bubblekiwi/controllers/GameplayContactListener.java | UTF-8 | 3,348 | 2.6875 | 3 | [] | no_license | package com.kiwi.bubblekiwi.controllers;
import com.badlogic.gdx.physics.box2d.*;
import com.kiwi.bubblekiwi.world.actors.bubble.Bubble;
import com.kiwi.bubblekiwi.world.elements.GameplayBoundary;
import com.kiwi.bubblekiwi.world.actors.player.Player;
public class GameplayContactListener implements ContactListener {
private Player player;
private GameplayBoundary ground;
private LevelController levelController;
public GameplayContactListener(Player player, GameplayBoundary groundBoundary, LevelController levelController) {
this.player = player;
this.ground = groundBoundary;
this.levelController = levelController;
}
@Override
public void beginContact(Contact contact) {
Body firstContactBody = contact.getFixtureA().getBody();
Body secondContactBody = contact.getFixtureB().getBody();
if (playerTouchedGround(firstContactBody, secondContactBody)) {
player.setInAir(false);
} else if (bubbleTouchedGround(firstContactBody, secondContactBody)) {
Bubble bubble = findBubbleThatTouchedGround(firstContactBody, secondContactBody);
if (bubble != null) {
bubble.destroy();
levelController.subtractLives(1);
}
} else if (playerTouchedBubble(firstContactBody, secondContactBody)) {
Bubble bubble = findBubbleThatTouchedPlayer(firstContactBody, secondContactBody);
if (bubble != null) {
bubble.destroy();
levelController.addPoints(1);
}
}
}
@Override
public void endContact(Contact contact) {
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
private boolean playerTouchedGround(Body first, Body second) {
return ((first.getUserData() == player) && (second.getUserData() == ground)) ||
((first.getUserData() == ground) && (second.getUserData() == player));
}
private boolean bubbleTouchedGround(Body first, Body second) {
return ((first.getUserData() == ground) && (second.getUserData() != player)) ||
((first.getUserData() != player) && (second.getUserData() == ground));
}
private boolean playerTouchedBubble(Body first, Body second) {
return ((first.getUserData() == player) && (second.getUserData() != ground)) ||
((first.getUserData() != ground) && (second.getUserData() == player));
}
private Bubble findBubbleThatTouchedGround(Body first, Body second) {
return findBubbleThatTouchedObject(first, second, ground);
}
private Bubble findBubbleThatTouchedPlayer(Body first, Body second) {
return findBubbleThatTouchedObject(first, second, player);
}
private Bubble findBubbleThatTouchedObject(Body first, Body second, Object userDataObject) {
try {
if (first.getUserData() == userDataObject) {
return (Bubble) second.getUserData();
}
if (second.getUserData() == userDataObject) {
return (Bubble) first.getUserData();
}
} catch (ClassCastException e) {
return null;
}
return null;
}
}
| true |
78f77671af55e6fe8defe1055c2b09ccb803385d | Java | david-alixar/daw1_programacion | /UD2/Entrega1/Tarea8_java/src/com/company/ej11.java | UTF-8 | 502 | 3.671875 | 4 | [] | no_license | package com.company;
public class ej11 {
public static void main(String[] args) {
System.out.println(" A continuación se mostrarán las tablas de multiplicar del 1 al 10 : ");
int n = 1;
int h;
int i;
for (h = 1 ; h <= 10; h++) {
System.out.println(" La tabla del " + h + " es : ");
for (i = 1; i <= 10; i++) {
System.out.println(n + " x " + i + " = " + n * i);
}
n++;
}
}
} | true |
72dafb791074aed86d865844846bf1cb35362222 | Java | MobileGuru1013/InsideCodec | /MediaCodecRcTest/app/src/main/java/com/github/piasy/mediacodecrctest/EncoderWrapper.java | UTF-8 | 7,778 | 1.757813 | 2 | [] | no_license | package com.github.piasy.mediacodecrctest;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.opengl.GLES20;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.view.Surface;
import com.tencent.mars.xlog.Log;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.webrtc.EglBase;
import org.webrtc.GlRectDrawer;
import org.webrtc.VideoRenderer;
/**
* Created by Piasy{github.com/Piasy} on 03/08/2017.
*/
public class EncoderWrapper extends MediaCodec.Callback {
private static final String TAG = "EncoderWrapper";
private static final int TIMEOUT_US = 3_000;
private static final int RC_INTERVAL = 5_000;
private final HandlerThread mHandlerThread;
private final Handler mHandler;
private final Config mConfig;
private final MediaCodec.BufferInfo mBufferInfo = new MediaCodec.BufferInfo();
private final Bundle mParams = new Bundle();
private final Handler mUiHandler = new Handler(Looper.getMainLooper());
private final RcTest.Notifier mNotifier;
private EglBase mEglBase;
private GlRectDrawer mDrawer;
private MediaCodec mEncoder;
private Surface mEncoderSurface;
private volatile boolean mRunning;
private int mRcSign = 1;
private int mCurrentBr;
private final Runnable mRcRunnable = new Runnable() {
@Override
public void run() {
if (mCurrentBr > mConfig.initBr() * 2) {
mRcSign = -1;
} else if (mCurrentBr < mConfig.initBr()) {
mRcSign = 1;
}
mCurrentBr += mRcSign * mConfig.brStep();
mParams.clear();
mParams.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, mCurrentBr * 1000);
mEncoder.setParameters(mParams);
Log.i(TAG, "update bitrate %d", mCurrentBr);
mUiHandler.postDelayed(this, RC_INTERVAL);
}
};
private volatile int mOutputBits;
private long mLastResetBitsTime;
public EncoderWrapper(final Config config, final RcTest.Notifier notifier) {
mNotifier = notifier;
Log.i(TAG, "Test config: " + config);
mConfig = config;
mHandlerThread = new HandlerThread("EncoderThread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
}
public void start(final EglBase eglBase) {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
mEglBase = EglBase.create(eglBase.getEglBaseContext(),
EglBase.CONFIG_RECORDABLE);
mEncoder = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC);
MediaFormat encodeFormat = MediaFormat.createVideoFormat(
MediaFormat.MIMETYPE_VIDEO_AVC,
mConfig.outputWidth(), mConfig.outputHeight());
encodeFormat.setInteger(MediaFormat.KEY_BIT_RATE, mConfig.initBr() * 1000);
encodeFormat.setInteger(MediaFormat.KEY_FRAME_RATE, mConfig.outputFps());
encodeFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL,
mConfig.outputKeyFrameInterval());
encodeFormat.setInteger(MediaFormat.KEY_BITRATE_MODE, mConfig.brMode());
if (mConfig.brMode() == MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ) {
encodeFormat.setInteger("quality", mConfig.quality());
}
encodeFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
if (mConfig.asyncEnc()) {
mEncoder.setCallback(EncoderWrapper.this);
}
mEncoder.configure(encodeFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
Log.i(TAG, "VideoFormat encoder " + encodeFormat);
mEncoderSurface = mEncoder.createInputSurface();
mEncoder.start();
mCurrentBr = mConfig.initBr();
mEglBase.createSurface(mEncoderSurface);
mEglBase.makeCurrent();
mDrawer = new GlRectDrawer();
mLastResetBitsTime = System.currentTimeMillis();
if (!mConfig.asyncEnc()) {
startOutputThread();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (mConfig.updateBr()) {
mUiHandler.postDelayed(mRcRunnable, RC_INTERVAL);
}
}
private void startOutputThread() {
mRunning = true;
new Thread(new Runnable() {
@Override
public void run() {
while (mRunning) {
int index = mEncoder.dequeueOutputBuffer(mBufferInfo, TIMEOUT_US);
if (index < 0) {
continue;
}
ByteBuffer buffer = mEncoder.getOutputBuffer(index);
if (buffer != null) {
reportEncodedImage(mBufferInfo, buffer);
}
mEncoder.releaseOutputBuffer(index, false);
}
}
}).start();
}
public void encodeFrame(final VideoRenderer.I420Frame frame) {
if (mEncoder == null) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
mEglBase.makeCurrent();
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
mDrawer.drawOes(frame.textureId, frame.samplingMatrix, frame.width, frame.height, 0,
0, frame.width, frame.height);
mEglBase.swapBuffers(frame.timestamp);
}
});
}
public void stop() {
mUiHandler.removeCallbacks(mRcRunnable);
mRunning = false;
mHandlerThread.quitSafely();
}
@Override
public void onInputBufferAvailable(@NonNull final MediaCodec codec, final int index) {
}
@Override
public void onOutputBufferAvailable(@NonNull final MediaCodec codec, final int index,
@NonNull final MediaCodec.BufferInfo info) {
ByteBuffer buffer = codec.getOutputBuffer(index);
if (buffer != null) {
reportEncodedImage(info, buffer);
}
codec.releaseOutputBuffer(index, false);
}
@Override
public void onError(@NonNull final MediaCodec codec,
@NonNull final MediaCodec.CodecException e) {
}
@Override
public void onOutputFormatChanged(@NonNull final MediaCodec codec,
@NonNull final MediaFormat format) {
}
private void reportEncodedImage(final MediaCodec.BufferInfo info, final ByteBuffer buffer) {
buffer.position(info.offset);
buffer.limit(info.size);
if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0) {
Log.i(TAG, "reportEncodedImage %d %d %d",
info.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME, info.size,
info.presentationTimeUs);
if (System.currentTimeMillis() - mLastResetBitsTime > 1000) {
mNotifier.reportBr(mOutputBits);
mOutputBits = 0;
mLastResetBitsTime = System.currentTimeMillis();
}
mOutputBits += info.size * 8;
}
}
}
| true |
400320d0c775db912e759b45cfcd253b37ad324c | Java | 20m613/learning | /Ranking.java | UTF-8 | 2,305 | 3.359375 | 3 | [] | no_license | import java.util.*;
public class Ranking {
ArrayList<Country> list=new ArrayList<Country>();
public static void main (String [] args){
Ranking ob=new Ranking();
Country country=ob.new Country();
country.addCountryToList("India",3,2,1);
country.addCountryToList("Aus",30,2,19);
country.addCountryToList("England",30,20,1);
country.addCountryToList("Pakistan", 0,0,16);
ArrayList<Country> sortedList=ob.sort(ob.list);
//country.print(ob.list);
}
private int size(ArrayList<Country> list){
int size=0;
return size;
}
public int[] sort(int[] unsorted){
int mid=unsorted.length/2;
if(unsorted.length<=1)
return unsorted;
int[] left=new int[unsorted.length/2];
int[] right=new int[unsorted.length-mid];
for(int i=0;i<mid;i++)
left[i]=unsorted[i];
int k=0;
for(int i=mid;i<unsorted.length;i++)
right[k++]=unsorted[i];
left=sort(left);
right=sort(right);
return merge(left,right);
}
public int[] merge(int[] left,int[] right){
int[] result=new int [left.length+right.length];
int leftIterator=0,rightIterator=0;
int mid=result.length/2;
int resultIterator=0;
while(leftIterator<left.length||rightIterator<right.length){
if(leftIterator<left.length&&rightIterator<right.length){
if(left[leftIterator]<right[rightIterator])
result[resultIterator++]=left[leftIterator++];
else
result[resultIterator++]=right[rightIterator++];
}
else if(leftIterator<left.length)
result[resultIterator++]=left[leftIterator++];
else
result[resultIterator++]=right[rightIterator++];
}
return result;
}
class Country{
String name;
MedalCount count=null;
public Country(){
}
public Country(String name,int gold,int silver,int bronze){
this.name=name;
count=new MedalCount(gold,silver,bronze);
}
public void addCountryToList(String CountryName,int gold,int silver,int bronze){
Country newCountry=new Country(CountryName,gold,silver,bronze);
list.add(newCountry);
}
}
class MedalCount{
int gold,silver,bronze;
public MedalCount(int gold,int silver,int bronze){
this.gold=gold;
this.silver=silver;
this.bronze=bronze;
}
}
}
| true |
8dce2f2bed85fc069a1790087c06765217933d84 | Java | SurbanaJurong/teamIG | /app/src/main/java/com/teamig/whatswap/utils/ImageUtil.java | UTF-8 | 3,119 | 2.390625 | 2 | [] | no_license | package com.teamig.whatswap.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by lyk on 26/5/17.
*/
public class ImageUtil {
public static File createTemporaryFile(String part, String ext) throws Exception {
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/DCIM");
if(!tempDir.exists())
{
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
public static void rotatePhoto(Uri uri, Context context, String path) throws IOException {
//get exifOrientation
int exifOrientation = new ExifInterface(path).getAttributeInt(ExifInterface.TAG_ORIENTATION,0);
int rotate;
boolean switchWH = true;
boolean need2Rotate = true;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
switchWH = false;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
switchWH = true;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
switchWH = false;
break;
default:
rotate = 0;
need2Rotate = false;
switchWH = false;
break;
}
if(need2Rotate){
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
Bitmap rotated;
Bitmap scaledBitmap = null;
if(bitmap.getWidth()==bitmap.getHeight())
switchWH = false;
if(switchWH){
scaledBitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getHeight(),bitmap.getWidth(),true);
rotated = Bitmap.createBitmap(scaledBitmap,0,0,scaledBitmap.getWidth(),scaledBitmap.getHeight(),mtx,false);
}
else
rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, false);
//write to file
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
rotated.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(scaledBitmap!=null)
scaledBitmap.recycle();
bitmap.recycle();
}
}
}
| true |
989fc9c3c46428639f09d42c83daa69a0c0daa74 | Java | m1norius/GH_10 | /src/main/java/HW_10_1/HW_10_1/Hasher.java | UTF-8 | 718 | 2.96875 | 3 | [] | no_license | package HW_10_1.HW_10_1;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Hasher {
private static MessageDigest md;
private static byte[] bytesOfMessage;
private static BigInteger bigInt;
private static String hashtext;
private static byte[] thedigest;
public static synchronized String getHashMD5(String text){
bytesOfMessage = text.getBytes();
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
thedigest = md.digest(bytesOfMessage);
bigInt = new BigInteger(1, thedigest);
hashtext = bigInt.toString(16);
return hashtext;
}
}
| true |
af4e9c31bde488bc0ef1f4d7381fe1fec28c6fcc | Java | cc86418/GfeduApp | /GfeduSchool/src/main/java/cn/jun/adapter/OverClassAdapter.java | UTF-8 | 4,658 | 2.28125 | 2 | [] | no_license | package cn.jun.adapter;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import cn.jun.bean.OverClassListBean;
import jc.cici.android.R;
public class OverClassAdapter extends BaseAdapter {
private DisplayImageOptions options;
private ImageLoader imageLoader = ImageLoader.getInstance();
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private Activity ctx;
private ArrayList<OverClassListBean> mList = new ArrayList<>();
public static class AnimateFirstDisplayListener extends
SimpleImageLoadingListener {
static final List<String> displayedImages = Collections
.synchronizedList(new LinkedList<String>());
/**
* 监听是否加载完,完成则实现动画效果
*/
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);// 动画效果
displayedImages.add(imageUri);
}
}
}
}
public OverClassAdapter(Activity context, ArrayList<OverClassListBean> mList) {
super();
this.ctx = context;
this.mList = mList;
}
@Override
public int getCount() {
return mList.get(0).getBody().getEndList().size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
convertView = LayoutInflater.from(ctx).inflate(
R.layout.over_list_items, null);
holder = new ViewHolder();
convertView.setTag(holder); // 为所须要的组件添加tag标签
holder.im = (ImageView) convertView.findViewById(R.id.im);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.time = (TextView) convertView.findViewById(R.id.time);
holder.content = (TextView) convertView.findViewById(R.id.content);
String im_s = mList.get(0).getBody().getEndList().get(position).getClassImg();
if(!"".equals(im_s) && null!= im_s){
imageLoader.displayImage(im_s, holder.im, options,
animateFirstListener);
}
String title = mList.get(0).getBody().getEndList().get(position).getClassName();
holder.title.setText(title);
String time = mList.get(0).getBody().getEndList().get(position).getClassEndTime();
try {
Date date = stringToDate(time, "yyyy-MM-dd");
time = dateToString(date, "yyyy-MM-dd");
} catch (ParseException e) {
e.printStackTrace();
}
holder.time.setText(time);
String content = mList.get(0).getBody().getEndList().get(position).getCloseType();
holder.content.setText(content);
return convertView;
}
// 视图缓存, 把view存起来
public final class ViewHolder {
public ImageView im;
public TextView title;
public TextView time;
public TextView content;
}
public static Date stringToDate(String strTime, String formatType)
throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(formatType);
Date date = null;
date = formatter.parse(strTime);
return date;
}
public static String dateToString(Date data, String formatType) {
return new SimpleDateFormat(formatType).format(data);
}
}
| true |
de4f653bb27afc7860720bdadbcee368db77683a | Java | not-fish/LeetCode | /src/main/java/com/leetcode/easy/Solution13.java | UTF-8 | 2,226 | 3.921875 | 4 | [] | no_license | package com.leetcode.easy;
import java.util.HashMap;
import java.util.Map;
/**
* @author Peko
*
* 罗马数字转整数
*
* 解题思路1:
* 从字符串的右边开始两两比较,如果倒数第二位的字符second等级小于倒数第一位的字符first等级,则相减,否则相加
* 效率:
* O(n) 7 ms 40.93%
* O(1) 39.1 MB 34.3%
*
* 解题思路2:
* 与解题思路1相同,不过是从左到右,而且把map换成switch
* 效率:
* O(n) 4 ms 99.98%
* O(1) 38.7 MB 78.23%
*/
public class Solution13 {
public int romanToInt1(String s) {
Map<Character, Integer> valueMaps = new HashMap<Character, Integer>();
valueMaps.put('I',1);
valueMaps.put('V',5);
valueMaps.put('X',10);
valueMaps.put('L',50);
valueMaps.put('C',100);
valueMaps.put('D',500);
valueMaps.put('M',1000);
int len = s.length();
int first,second;
int sum = valueMaps.get(s.charAt(len-1));
for(int i=len-1;i>=0;i--){
first = i;
second = i-1;
if(second<0){
return sum;
}
if(valueMaps.get(s.charAt(second))<valueMaps.get(s.charAt(first))){
sum = sum - valueMaps.get(s.charAt(second));
}else{
sum = sum + valueMaps.get(s.charAt(second));
}
}
return sum;
}
public int romanToInt2(String s) {
int len = s.length();
int sum = 0;
int preNum = getValue(s.charAt(0));
for(int i=1;i<s.length();i++){
int num = getValue(s.charAt(i));
if(preNum < num){
sum-=preNum;
}else{
sum+=preNum;
}
preNum = num;
}
sum+=preNum;
return sum;
}
private int getValue(char ch) {
switch(ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
}
| true |
3fe92b33d63d45dd51df8eecc86c5bb05b3ed0fc | Java | iskusnov-studentprojects/workl3 | /src/test/java/com/convetion/XMLLoaderTest.java | UTF-8 | 738 | 2.15625 | 2 | [] | no_license | package com.convetion;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Sergey on 21.05.2017.
*/
public class XMLLoaderTest {
@Test
public void testLoadUnitsType() throws Exception {
assertNotNull(XMLLoader.loadUnitsType(""));
}
@Test
public void testLoadUnitsTypeNumberRows() throws Exception {
assertTrue(XMLLoader.loadUnitsType("src/main/java/resources/units.xml").size() > 0);
}
@Test
public void testLoadUnits() throws Exception {
assertNotNull(XMLLoader.loadUnits(""));
}
@Test
public void testLoadUnitsNumberRows() throws Exception {
assertTrue(XMLLoader.loadUnits("src/main/java/resources/units.xml").size() > 0);
}
} | true |
2bd53bcc068fabe04c701b379ef02e9e61243cdc | Java | yapkolotilov/students_why_server | /tests/studentswhyserver/data/items/ItemTest.java | UTF-8 | 1,472 | 2.703125 | 3 | [] | no_license | package studentswhyserver.data.items;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class ItemTest {
@Test
public void getHeader() {
Item item = new Item();
item.setHeader("blabla");
Assert.assertEquals(item.getHeader(), "blabla");
}
@Test
public void matches() {
Item item = new Item();
Assert.assertFalse(item.matches(Integer.class));
}
@Test
public void matches1() {
Item item = new Item();
item.setHeader("blabla");
Assert.assertFalse(item.matches("blbla"));
}
@Test
public void matches2() {
Item item = new Item();
item.setHeader("blabla");
Assert.assertTrue(item.matches("blabla", Item.class));
}
@Test
public void setHeader() {
Item item = new Item();
item.setHeader("blabla");
Assert.assertEquals(item.getHeader(), "blabla");
}
@Test
public void setContent() {
Item item = new Item();
item.setContent("blabla");
}
@Test
public void setPublishDate() {
Item item = new Item();
item.setPublishDate("01.01.2019");
}
@Test
public void like() {
Item item = new Item();
item.like();
}
@Test
public void dislike() {
}
@Test
public void toString1() {
Assert.assertEquals(new Item().toString(), "header: null, content: null");
}
} | true |
58795f9393cc4ff203cc716dd8bac726db13601e | Java | LegendPotato/practice-java | /src/ac/wangyi/wangyi2.java | UTF-8 | 1,986 | 3.359375 | 3 | [] | no_license | package ac.wangyi;
//import java.util.Scanner;
//
//public class wangyi.wangyi2 {
// public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
// int n = in.nextInt();
// int[]a = new int[n];
// for (int i = 0; i < n; i++) {
// a[i] = in.nextInt();
// }
// int[]b = new int[n];
// for (int i=0;i<n;i++){
// b[i] = sum(a,i);
// }
// int questionCount = in.nextInt();
// int[] question = new int[questionCount];
// for (int i = 0; i < questionCount; i++) {
// question[i] = in.nextInt();
// count(question[i],b,n);
// }
// }
// public static int sum(int[]a,int j){
// int sum = 0;
// for (int i=0;i<=j;i++){
// sum+=a[i];
// }
// return sum;
// }
//
// public static void count(int number,int[]b,int n){
// for (int i=0;i<n;i++){
// if (number>b[i]){
// continue;
// }else {
// System.out.println(i+1);
// break;
// }
// }
//
// }
//}
import java.util.Scanner;
public class wangyi2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int questionCount = in.nextInt();
int[] question = new int[questionCount];
for (int i = 0; i < questionCount; i++) {
question[i] = in.nextInt();
count(question[i], a, n);
}
}
public static void count(int number, int[] a, int n) {
int temp = a[0];
for (int i = 0; i < n; i++) {
if (number > temp) {
temp += a[i + 1];
continue;
} else {
System.out.println(i + 1);
break;
}
}
}
}
| true |
249db92901eba839246dbcdc613ae78804d65509 | Java | fantastic-five/project | /src/edu/uwm/cs361/fantastic_five/training_tracker/servlets/InstructorAttendanceViewServlet.java | UTF-8 | 894 | 2.3125 | 2 | [] | no_license | package edu.uwm.cs361.fantastic_five.training_tracker.servlets;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import edu.uwm.cs361.fantastic_five.training_tracker.app.entities.Program;
import edu.uwm.cs361.fantastic_five.training_tracker.app.entities.Session;
import edu.uwm.cs361.fantastic_five.training_tracker.app.entities.Student;
@SuppressWarnings("serial")
public class InstructorAttendanceViewServlet extends BaseServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
PersistenceManager pm = getPersistenceManager();
long idLong = Long.parseLong(req.getParameter("id"));
req.setAttribute("program", pm.getObjectById(Program.class,idLong));
forwardToJsp("instructor_attendance_view.jsp", req, resp);
}
} | true |
da4bdb334ad2c852c4f6d356274afc45882d828d | Java | Zeoforex/JAVA-task | /Attestation2/Attestation2/DZ/tetstss/src/main/java/services/RoleService.java | UTF-8 | 590 | 2.09375 | 2 | [] | no_license | package Attestation2.Attestation2.DZ.tetstss.src.main.java.services;
import dao.Role;
import models.Role;
import java.util.List;
public class RoleService {
private Role role = new Role();
public RoleService(){}
public Role findRole(int id){
return role.findById(id);
}
public void saveRole(Role role){
role.save(role);
}
public void updateRole(Role role){
role.update(role);
}
public void deleteRole(Role role){
role.delete(role);
}
public List<Role> findAllRoles(){
return role.getAll();
}
} | true |
f0ffe3be74f219fc5f315d0f450a77600dce1a9f | Java | ZjanPreijde/Java-Programming-Masterclass | /JavaPrograms/Section-12/S12-06-CollectionsChallenge/src/com/example/collections/Basket.java | UTF-8 | 2,930 | 3.53125 | 4 | [] | no_license | package com.example.collections;
/*
Another great class by Zjan Preijde
Creation : 2019-06-03, 12:02
*/
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
public class Basket {
private final String name;
private final Map <StockItem, Integer> shoppingList;
public Basket( String name ) {
this.name = name;
this.shoppingList = new TreeMap <>( );
}
public int addToBasket(StockItem item, int quantity) {
// System.out.println("Entering addToBasket()");
if ((item != null) && (quantity > 0)) {
int inBasket = shoppingList.getOrDefault(item, 0);
shoppingList.put(item, inBasket + quantity);
if (inBasket + quantity == 0) {
System.out.println("REMOVE ITEM");
shoppingList.remove( item );
}
return inBasket;
}
return 0;
}
public int inBasket(StockItem item) {
return shoppingList.getOrDefault( item, 0);
}
public int removeFromBasket(StockItem item, int quantity, boolean clearIfZero) {
// System.out.println("Entering addToBasket()");
if ((item != null) && (quantity > 0)) {
int inBasket = shoppingList.getOrDefault(item, 0);
if (inBasket - quantity >= 0) {
shoppingList.put( item, inBasket - quantity );
if ( inBasket - quantity == 0 && clearIfZero) {
// can not do .remove() when called from loop in checkoutBasket,
// ConcurrentModificationException
System.out.println( "REMOVE ITEM" );
shoppingList.remove( item );
}
return inBasket;
} else {
return 0;
}
}
return 0;
}
public void checkoutBasket(StockList stockList) {
System.out.println("\nChecking out basket");
shoppingList.forEach( (item, qty) -> {
System.out.println("- " + item.getName());
if (stockList.sellStock( item.getName(), qty ) != 0) {
stockList.reserveStock( item.getName(), -qty );
removeFromBasket( item, qty, false) ;
}
} );
shoppingList.clear();
}
public Map<StockItem, Integer> items() {
return Collections.unmodifiableMap( shoppingList );
}
@Override
public String toString() {
String result = "\nBasket contains " + shoppingList.size() + " items\n";
double totalCost = 0;
for (Map.Entry<StockItem, Integer> item : shoppingList.entrySet()) {
result += item.getKey() + ". " + item.getValue() + " purchased\n";
totalCost += item.getKey().getPrice() * item.getValue();
}
result += "-----------\nTotal cost : " + String.format("%.2f", totalCost) + "\n===============" ;
return result;
}
}
| true |
a7f346c9a2243fe983ca6325478167518ad30ba0 | Java | Rohit-Chandiramani/Logistics-Management-System | /mainFrame.java | UTF-8 | 23,066 | 2.09375 | 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 trialapp;
/**
*
* @author ROHIT
*/
import java.awt.Component;
import javax.mail.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;
public class mainFrame extends javax.swing.JFrame {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/logistics";
ArrayList<String>userList=new ArrayList<String>();
ArrayList<String>passList=new ArrayList<String>();
ArrayList<String>cityList=new ArrayList<String>();
ArrayList<String>nameList=new ArrayList<String>();
ArrayList<String>numberList=new ArrayList<String>();
/**
* Creates new form mainFrame
*/
public mainFrame() {
initComponents();
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String query="drop table if exists booking";
stmt.executeUpdate(query);
} catch (ClassNotFoundException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
passLabel = new javax.swing.JLabel();
userText = new javax.swing.JTextField();
userLabel1 = new javax.swing.JLabel();
passText = new javax.swing.JPasswordField();
loginButton = new javax.swing.JButton();
userType = new javax.swing.JLabel();
typeBox = new javax.swing.JComboBox<>();
messageText = new javax.swing.JLabel();
userErrorLabel = new javax.swing.JLabel();
passErrorLabel = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
forgotButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("FRONT PAGE");
setAutoRequestFocus(false);
setBackground(new java.awt.Color(61, 13, 22));
setForeground(getBackground());
setMaximumSize(new java.awt.Dimension(1366, 768));
setMinimumSize(new java.awt.Dimension(1366, 768));
setPreferredSize(new java.awt.Dimension(1366, 768));
getContentPane().setLayout(null);
passLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
passLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
passLabel.setText("PASSWORD:-");
getContentPane().add(passLabel);
passLabel.setBounds(460, 340, 110, 40);
passLabel.getAccessibleContext().setAccessibleName("userLabel");
userText.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
userText.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
userTextFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
userTextFocusLost(evt);
}
});
userText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
userTextActionPerformed(evt);
}
});
getContentPane().add(userText);
userText.setBounds(690, 270, 210, 40);
userLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
userLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
userLabel1.setText("USERNAME:-");
getContentPane().add(userLabel1);
userLabel1.setBounds(460, 270, 110, 40);
passText.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
passText.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
passTextFocusLost(evt);
}
});
passText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
passTextActionPerformed(evt);
}
});
getContentPane().add(passText);
passText.setBounds(690, 340, 210, 40);
loginButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
loginButton.setText("LOGIN");
loginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginButtonActionPerformed(evt);
}
});
getContentPane().add(loginButton);
loginButton.setBounds(750, 470, 110, 50);
userType.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
userType.setText("SELECT TYPE OF USER:- ");
getContentPane().add(userType);
userType.setBounds(460, 200, 180, 50);
typeBox.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
typeBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "", "BOOKING", "MANAGEMENT", "DELIVERY" }));
typeBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
typeBoxActionPerformed(evt);
}
});
getContentPane().add(typeBox);
typeBox.setBounds(710, 210, 160, 30);
messageText.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
messageText.setForeground(new java.awt.Color(255, 0, 0));
getContentPane().add(messageText);
messageText.setBounds(960, 470, 210, 50);
userErrorLabel.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
userErrorLabel.setForeground(new java.awt.Color(255, 0, 0));
getContentPane().add(userErrorLabel);
userErrorLabel.setBounds(940, 270, 170, 40);
passErrorLabel.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
passErrorLabel.setForeground(new java.awt.Color(255, 0, 0));
getContentPane().add(passErrorLabel);
passErrorLabel.setBounds(940, 340, 170, 40);
jLabel1.setFont(new java.awt.Font("Berlin Sans FB", 0, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("USER LOGIN");
getContentPane().add(jLabel1);
jLabel1.setBounds(520, 90, 250, 80);
forgotButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
forgotButton.setText("FORGOT PASSWORD");
forgotButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
forgotButtonActionPerformed(evt);
}
});
getContentPane().add(forgotButton);
forgotButton.setBounds(473, 470, 200, 50);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/trialapp/backfirst_1366x768.jpg"))); // NOI18N
getContentPane().add(jLabel2);
jLabel2.setBounds(0, 0, 1370, 770);
pack();
}// </editor-fold>//GEN-END:initComponents
private void passTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_passTextActionPerformed
public void getData(char c)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String query="SELECT *FROM hr where type='"+c+"'";
rs=stmt.executeQuery(query);
userList.clear();
passList.clear();
nameList.clear();
numberList.clear();
cityList.clear();
while(rs.next())
{
userList.add(rs.getString("username"));
passList.add(rs.getString("password"));
nameList.add(rs.getString("name"));
numberList.add(rs.getString("number"));
cityList.add(rs.getString("city"));
}
} catch (SQLException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}
}
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
// TODO add your handling code here:
String username=userText.getText();
String password=String.valueOf(passText.getPassword());
String type=(String) typeBox.getSelectedItem();
int flag=0;
getData(type.charAt(0));
System.out.println(userList.size());
for(int i=0;i<userList.size();i++)
{
System.out.println(userList.get(i));
}
for(int i=0,j=0;i<userList.size()&&j<passList.size();i++,j++)
{
if(userList.get(i).equals(username))
{
if(passList.get(i).equals(password))
{
flag=1;
if(type.equals("BOOKING"))
{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String query;
query="Create table booking (name varchar(15),username varchar(15),number varchar(15),city varchar(15))";
stmt.executeUpdate(query);
query="Insert into booking values('"+nameList.get(i)+"','"+username+"','"+numberList.get(i)+"','"+cityList.get(i)+"')";
stmt.executeUpdate(query);
} catch (ClassNotFoundException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
this.dispose();
bookingFirst d=new bookingFirst();
d.setVisible(true);
d.setTitle("BOOKING LANDING PAGE");
break;
}
else if(type.equals("MANAGEMENT"))
{
this.dispose();
managementFront obj=new managementFront();
obj.setVisible(true);
obj.setTitle("MANAGEMENT LANDING PAGE");
break;
}
else if(type.equals("DELIVERY"))
{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String query;
query="Create table delivery (name varchar(15),username varchar(15),number varchar(15),city varchar(15))";
stmt.executeUpdate(query);
query="Insert into delivery values('"+nameList.get(i)+"','"+username+"','"+numberList.get(i)+"','"+cityList.get(i)+"')";
stmt.executeUpdate(query);
} catch (ClassNotFoundException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
this.dispose();
Delivery d=new Delivery();
d.setVisible(true);
d.setTitle("DELIVERY PAGE");
}
}
else
{
flag=1;
messageText.setText("Password does not match!");
}
}
}
if(flag==0)
messageText.setText("User does not exist!");
}//GEN-LAST:event_loginButtonActionPerformed
private void userTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_userTextActionPerformed
public int send_email( String reciever_email)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
String reciver_password="";
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String query="select * from hr where email='"+reciever_email+"'";
rs=stmt.executeQuery(query);
if(!rs.next())
return 1;
reciver_password=rs.getString("password");
} catch (SQLException | ClassNotFoundException ex) {}
//System.out.println("check5");
final String sender_username = "thelogisticsteam@gmail.com"; // enter your mail id
final String password = "logistics";// enter ur password
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session;
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender_username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender_username)); // same email id
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(reciever_email));// whome u have to send mails that person id
message.setSubject("Confidential::Sending Of Password");
message.setText("Dear, User"
+ "\n\n your password is ::->>"+reciver_password);
Transport.send(message);
//System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
return 0;
}
private void typeBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeBoxActionPerformed
String type=(String) typeBox.getSelectedItem();
if(type.equals("BOOKING"))
{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String b;
b = "'B'";
String query="SELECT *FROM hr WHERE type="+b;
rs=stmt.executeQuery(query);
while(rs.next())
{
userList.add(rs.getString("username"));
passList.add(rs.getString("password"));
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
else if(type.equals("MANAGEMENT"))
{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String m;
m = "'M'";
String query="SELECT *FROM hr WHERE type="+m;
rs=stmt.executeQuery(query);
while(rs.next())
{
userList.add(rs.getString("username"));
passList.add(rs.getString("password"));
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
else if(type.equals("DELIVERY"))
{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,"root","R30101997c");
stmt=conn.createStatement();
String d;
d = "'D'";
String query="SELECT *FROM hr WHERE type="+d;
rs=stmt.executeQuery(query);
while(rs.next())
{
userList.add(rs.getString("username"));
passList.add(rs.getString("password"));
cityList.add(rs.getString("city"));
nameList.add(rs.getString("name"));
numberList.add(rs.getString("number"));
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(mainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}//GEN-LAST:event_typeBoxActionPerformed
private void userTextFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_userTextFocusLost
if(userText.getText().equals(""))
{
userErrorLabel.setText("*Enter Username");
}
else
{
userErrorLabel.setText("");
}
}//GEN-LAST:event_userTextFocusLost
private void userTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_userTextFocusGained
}//GEN-LAST:event_userTextFocusGained
private void passTextFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_passTextFocusLost
// TODO add your handling code here:
if(String.valueOf(passText.getPassword()).equals(""))
{
passErrorLabel.setText("*Enter Password");
}
else
{
passErrorLabel.setText("");
}
}//GEN-LAST:event_passTextFocusLost
private void forgotButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgotButtonActionPerformed
String forgotemail=JOptionPane.showInputDialog("Enter your E-mail id to send password");
int res=send_email(forgotemail);
if(res==0)
JOptionPane.showMessageDialog(null,"Your password has been sent to your E-mail id");
else if(res==1)
JOptionPane.showMessageDialog(null,"ERROR OCCOURED IN SENDING E-MAIL");
}//GEN-LAST:event_forgotButtonActionPerformed
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
mainFrame mf=new mainFrame();
mf.setTitle("FRONT PAGE");
mf.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton forgotButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton loginButton;
private javax.swing.JLabel messageText;
private javax.swing.JLabel passErrorLabel;
private javax.swing.JLabel passLabel;
private javax.swing.JPasswordField passText;
private javax.swing.JComboBox<String> typeBox;
private javax.swing.JLabel userErrorLabel;
private javax.swing.JLabel userLabel1;
private javax.swing.JTextField userText;
private javax.swing.JLabel userType;
// End of variables declaration//GEN-END:variables
}
| true |
f57ff923b40e097e975b51465a9c6a39e4bbed67 | Java | tectronics/131402-explorer-quest | /Timer.java | UTF-8 | 3,377 | 4.0625 | 4 | [] | no_license | /**
* A customizable timer that allows you to keep track of in-game time.
* To use in an actor, simply declare a new Timer.
*
* Example usage:
*
* public class Player extends Actor
* {
* private Timer timer=new Timer();
* ...
*
* public Player
* {
* ...
* }
*
* act()
* {
* timer.tick();
* ...
* }
*
* ...
*
* }
*
* Since it runs along Greenfoot, your time based ineractions won't be broken when Greenfoot is
* paused nor stopped.
*
* @author Jesus Trejo
* @version 2.1, 17/May/14
*/
public class Timer
{
private boolean isWaiting;
private boolean isCounting;
private float time;
public Timer()
{
isWaiting=false;
isCounting=false;
time=0;
}
/**
* Increases the timer by a set amount (needs to be adjusted manually
* depending on your game speed). It MUST to be called in every actor's act cycle a single
* time (and only one) in order to work properly.
*/
public void tick()
{
time+=0.016;
}
/**
* Returns the actual time.
*/
public int getTime()
{
return((int)(time*1000));
}
/**
* Resets the time to 0, so it can start a new count.
*/
public void mark()
{
time=0;
}
/**
* Checks if the timer is waiting.
* Receives as parameter the time it should wait in milliseconds, it'll automatically
* mark and check if the time elapsed is minor than the time it should wait.
*
* Returns true if it's waiting (time elapsed < time it should wait) and false
* if the time elapsed is bigger or equal.
*
* Examples: if(timer.wait(1000))
* return;
*
* if(!timer.wait(50))
* turn(10);
*
* In the first example, the timer will return true for ~1 second, after that, it'll return false.
* If it was called in an Actor's act(), it'll return true for 1 second, after
* that, it'll return false for a fraction of second, then true once again since it'll be
* automatically reset.
*
* In the second example, the actor will turn 10 degrees aproximately every 50 milliseconds.
*/
public boolean wait(int t)
{
if(isWaiting==false)
{
isWaiting=true;
mark();
}
if(getTime() < t)
return(true);
else
{
isWaiting=false;
return(false);
}
}
/**
* Resets the timer.
*/
public void reset()
{
isWaiting=false;
isCounting=false;
time=0;
}
/**
* Starts a count. It can be called multiple times without being reset. Use the method reset()
* to start a new count (must to be reset manually unlike wait()).
*/
public void count()
{
if(isCounting==false)
{
time=0;
isCounting=true;
}
}
/**
* Changes the current time to a given value
*/
public void setTime(int num)
{
time=num;
}
} | true |
64800723d34bab026ce25f9358cdaf404079efa2 | Java | johnfeir/media-utils | /src/main/java/jfeir/audio/media/utils/MediaUtils.java | UTF-8 | 16,019 | 2.296875 | 2 | [] | no_license | package main.java.jfeir.audio.media.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import com.mpatric.mp3agic.ID3v1Genres;
import com.mpatric.mp3agic.Mp3File;
import com.mpatric.mp3agic.NotSupportedException;
//TODO - build unit tests
//TODO - consolidate makePlaylist method
//TODO - clean up genre playlistname props
/**
* The Class MediaUtils.
*/
class MediaUtils {
private static final String FILE_SEP = File.separator;
private static final String LINE_SEP = System.getProperty("line.separator");
static final String TAG_DELIMITER = " - ";
static final int ARTIST = 0;
static final int TITLE = 1;
/**
* Instantiates a new media utils.
*/
MediaUtils() {
}
/**
* Adjust tags. set album from filename set genre, year sort on artist and
* set track number other tag tweaks? TODO: add year patch to ja tagger -
* default to current year
*
* @param base
* the base
* @param playListSuffix
*/
public void processMedia(String base, String genre, String year, String playListSuffix, String playListName, boolean writeTag) {
List<String> sourceList;
try {
sourceList = buildFilePathArrayList(base, "*.mp3");
} catch (IOException e1) {
e1.printStackTrace();
return;
}
Collections.sort(sourceList,String.CASE_INSENSITIVE_ORDER);
// StringBuffer playList = new StringBuffer();
// playList.append("#EXTM3U");
// playList.append(LINE_SEP);
// String lastPathSegment = getLastPathSegment(base);
int trackNum = 0;
for (String path : sourceList) {
try {
trackNum++;
File file = new File(path);
if (!file.exists()) {
throw new IOException("MediaUtils:adjustTags:ERROR:File not found: " + file.getAbsolutePath());
}
AudioFile audioFile = AudioFileIO.read(file);
Tag tag = audioFile.getTag();
String fileName = file.getName();
String[] tags = fileName.split(TAG_DELIMITER);
if (tags.length < 2) {
throw new IOException("MediaUtils:adjustTags:ERROR:File tags not parsable from file name: " + file.getAbsolutePath());
}
if (tag != null && (!(tag.isEmpty()))) {
tag.setField(FieldKey.ALBUM, tags[ARTIST]);
tag.setField(FieldKey.ALBUM_ARTIST, tags[ARTIST]);
tag.setField(FieldKey.GENRE, genre);
tag.setField(FieldKey.YEAR, year);
tag.setField(FieldKey.TRACK, getTrackNum(trackNum));
if (writeTag) {
System.out.println("Writing tag for:" + fileName);
audioFile.commit();
}
else {
System.out.println("Processing:" + fileName);
}
// addPlayListEntry(playList, tag, file, lastPathSegment);
} else {
throw new IOException("MediaUtils:adjustTags:ERROR:Id3v2Tag not present: " + file.getAbsolutePath());
}
} catch (IOException | CannotReadException | TagException | ReadOnlyFileException | InvalidAudioFrameException | CannotWriteException e) {
e.printStackTrace();
}
}
System.out.println("Processed "+trackNum+ " files.");
// String playListFilePath = getParentPath(base) + FILE_SEP + playListName + playListSuffix + ".m3u";
// writePlayListFile(playList, playListFilePath);
}
private String getLastPathSegment(String base) {
File file = new File(base);
String parentPath = file.getParent();
String lastPathSegment = base.substring(parentPath.length() + 1);
return lastPathSegment;
}
private String getParentPath(String base) {
File file = new File(base);
String parentPath = file.getParent();
return parentPath;
}
private void writePlayListFile(StringBuffer playList, String filePath) {
try {
System.out.println("MediaUtils:writePlayListFile:writing playlist file:" + filePath);
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
writer.write(playList.toString());
writer.close();
} catch (IOException e) {
System.out.println("MediaUtils:writePlayListFile:could not write playlist file:"+filePath);
e.printStackTrace();
}
}
private void addPlayListEntry(StringBuffer playList, Tag tag, File file, String lastPathSegment) {
playList.append("#EXTINF:").append(getTrackLen(file));
playList.append(",");
playList.append(tag.getFirst(FieldKey.ARTIST));
playList.append(TAG_DELIMITER);
playList.append(tag.getFirst(FieldKey.TITLE));
playList.append(LINE_SEP);
playList.append(lastPathSegment);
playList.append(FILE_SEP);
playList.append(file.getName());
playList.append(LINE_SEP);
}
private String getTrackLen(File file) {
String trackLen = null;
try {
MP3File mp3File = (MP3File) AudioFileIO.read(file);
MP3AudioHeader audioHeader = (MP3AudioHeader) mp3File.getAudioHeader();
return Integer.toString(audioHeader.getTrackLength());
} catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
e.printStackTrace();
}
return trackLen;
}
private String getTrackNum(int trackNum) {
String numberAsString = String.format("%03d", trackNum);
return numberAsString;
}
public static int getGenreNumber(String genre) {
for (int i = 0; i < ID3v1Genres.GENRES.length; i++) {
if (ID3v1Genres.GENRES[i].equals(genre)) {
return i;
}
}
return -1;// not found
}
private void renameAndSaveMp3(Mp3File mp3File, File file) {
// save to tmp filename
// delete orig file
// rename tmp to orig
File tmp = new File(file.getAbsolutePath() + ".tmp");
// File bk = new File(file.getAbsolutePath()+".bk");//test
try {
if (tmp.exists()) {
throw new IOException("MediaUtils:renameAndSaveMp3:ERROR:tmp file exists");
}
mp3File.save(tmp.getAbsolutePath());
// file.renameTo(bk);//test
file.delete();
tmp.renameTo(file);
} catch (NotSupportedException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Read mp3.
*
* @param file
* the file
*/
public void readMp3(File file) {
Mp3Data mp3Data = new Mp3Data(file);
mp3Data.readMp3();
}
/**
* Empty files.
*
* @param base
* the base
*/
public void emptyFiles(String base) {
// one time use to create empty existing files to save space
File basePath = new File(base);
File[] files = basePath.listFiles(mp3Filter);
for (File file : files) {
System.out.println("Emptying: " + file.getAbsolutePath());
try {
new PrintWriter(file.getAbsolutePath()).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// List<File> fileList = new ArrayList<File>();
// fileList.addAll(Arrays.asList(files));
}
/**
* Creates the empty files.
*
* @param sourcePath
* the source path
* @param targetPath
* the target path
* @param dryRun
* the dry run
*/
public void createEmptyFiles(String sourcePath, String targetPath, boolean dryRun) {
List<String> sourceList = null;
List<String> targetList = null;
try {
sourceList = buildFileNameArrayList(sourcePath, "*.mp3");
targetList = buildFileNameArrayList(targetPath, "*.mp3");
} catch (IOException e) {
e.printStackTrace();
return;
}
int i = 0;
for (String fileName : sourceList) {
if (!targetList.contains(cleanUpFileName(fileName))) {
// create an empty file of the same name in target
createFile(targetPath + "/" + fileName, dryRun);
i++;
} else {
System.out.println("File is already present in target:" + fileName);
}
}
System.out.println("Created count:" + i);
}
/**
* Creates the file.
*
* @param fullPath
* the full path
* @param dryRun
* the dry run
*/
private void createFile(String fullPath, boolean dryRun) {
File f = new File(fullPath);
if (!f.exists() && !f.isDirectory()) {
System.out.println("Will create:" + fullPath);
if (!dryRun) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* Clean up file name.
*
* @param fileName
* the file name
* @return the string
*/
private String cleanUpFileName(String fileName) {
String cleaned = fileName.replace(" ", " ").replace(" (1)", "");
return cleaned;
}
/** The mp3 filter. */
private FilenameFilter mp3Filter = new FilenameFilter() {
public boolean accept(File file, String name) {
if (name.endsWith(".mp3")) {
return true;
} else {
return false;
}
}
};
/**
* Builds the file array list.
*
* @param base
* the base
* @param pattern
* the pattern
* @return the list
* @throws IOException
*/
private List<File> buildFileList(String base, String pattern) throws IOException {
File basePath = new File(base);
if (!basePath.exists()) {
throw new IOException("MediaUtils:buildFileList:ERROR:Base path does not exist: " + base);
}
File[] files = basePath.listFiles(mp3Filter);
List<File> fileList = Arrays.asList(files);
return fileList;
}
/**
* Builds the file array list.
*
* @param base
* the base
* @param pattern
* the pattern
* @return the list
* @throws IOException
*/
private List<String> buildFileNameArrayList(String base, String pattern) throws IOException {
File basePath = new File(base);
if (!basePath.exists()) {
throw new IOException("MediaUtils:buildFileNameArrayList:ERROR:Base path does not exist: " + base);
}
File[] files = basePath.listFiles(mp3Filter);
List<String> fileList = new ArrayList<String>();
for (int i = 0; i < files.length; ++i) {
fileList.add(files[i].getName().toLowerCase());
}
return fileList;
}
private List<String> buildFilePathArrayList(String base, String pattern) throws IOException {
File basePath = new File(base);
if (!basePath.exists()) {
throw new IOException("MediaUtils:buildFilePathArrayList:ERROR:Base path does not exist: " + base);
}
File[] files = basePath.listFiles(mp3Filter);
List<String> fileList = new ArrayList<String>();
for (int i = 0; i < files.length; ++i) {
if (validFile(files[i])) {
fileList.add(files[i].getAbsolutePath());
}
}
return fileList;
}
private boolean validFile(File file) {
if (file.getName().contains(" (1).mp3")) {
return false;
}
return true;
}
/**
* Delete duplicates.
*
* @param sourcePath
* the source path
* @param targetPath
* the target path
* @param dryRun
* the dry run
*/
public void deleteDuplicates(String sourcePath, String targetPath, boolean dryRun) {
List<String> filesToCheck = null;
List<String> existingFiles = null;
try {
filesToCheck = buildFileNameArrayList(sourcePath, "*.mp3");
existingFiles = buildFileNameArrayList(targetPath, "*.mp3");
} catch (IOException e) {
e.printStackTrace();
return;
}
System.out.println("Deleting duplicates from:" + sourcePath);
System.out.println("That exist in:" + targetPath);
int i = 0;
for (String fileName : filesToCheck) {
if (existingFiles.contains(cleanUpFileName(fileName))) {
System.out.println("Will delete existing file:" + fileName);
if (!dryRun) {
File file = new File(sourcePath + "/" + fileName);
file.delete();
}
i++;
}
}
System.out.println("Duplicate count: " + i + " Total files:" + filesToCheck.size());
}
public void makePlaylist(String base, String playListName) {
List<String> sourceList;
try {
sourceList = buildFilePathArrayList(base, "*.mp3");
} catch (IOException e1) {
e1.printStackTrace();
return;
}
Collections.sort(sourceList, String.CASE_INSENSITIVE_ORDER);
StringBuffer playList = new StringBuffer();
playList.append("#EXTM3U");
playList.append(LINE_SEP);
String lastPathSegment = getLastPathSegment(base);
for (String path : sourceList) {
try {
File file = new File(path);
if (!file.exists()) {
throw new IOException("MediaUtils:adjustTags:ERROR:File not found: " + file.getAbsolutePath());
}
System.out.println("Processing:" + file.getName());
AudioFile audioFile;
audioFile = AudioFileIO.read(file);
Tag tag = audioFile.getTag();
addPlayListEntry(playList, tag, file, lastPathSegment);
} catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String playListFilePath = getParentPath(base) + FILE_SEP + playListName + ".m3u";
writePlayListFile(playList, playListFilePath);
}
public void deleteInvalidFiles(String basePath) {
List<String> filesToCheck;
try {
filesToCheck = buildFileNameArrayList(basePath, "*.mp3");
} catch (IOException e) {
e.printStackTrace();
return;
}
System.out.println("Deleting invalid files from:" + basePath);
int i = 0;
for (String fileName : filesToCheck) {
if (fileName.contains(" (1).mp3")) {
System.out.println("Will delete file:" + fileName);
File file = new File(basePath + FILE_SEP + fileName);
file.delete();
i++;
}
}
System.out.println("Deleted count: " + i + " Total files:" + filesToCheck.size());
}
// not tested
public void addTrackNumToFileNames(String basePath) {
List<File> files;
try {
files = buildFileList(basePath, "*.mp3");
} catch (IOException e) {
e.printStackTrace();
return;
}
for (File file : files) {
AudioFile audioFile = null;
try {
audioFile = AudioFileIO.read(file);
} catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) {
e.printStackTrace();
return;
}
Tag tag = audioFile.getTag();
if (tag != null && (!(tag.isEmpty()))) {
String trackNum = tag.getFirst(FieldKey.TRACK);
if (trackNum != null && (!(trackNum.isEmpty()))) {
System.out.println("Processing filename:" + file.getName());
StringBuffer newPath = new StringBuffer();
newPath.append(basePath);
newPath.append(FILE_SEP);
newPath.append(trackNum);
newPath.append(TAG_DELIMITER);
newPath.append(file.getName());
File newFile = new File(newPath.toString());
file.renameTo(newFile);
}
else {
System.err.println("MediaUtils:addTrackNumToFileNames:ERROR:tag is empty or null");
}
}
}
}
public void removeTrackNumFromFileNames(String basePath) {
// not tested
List<File> files;
try {
files = buildFileList(basePath, "*.mp3");
} catch (IOException e) {
e.printStackTrace();
return;
}
for (File file : files) {
String[] tags = file.getName().split(TAG_DELIMITER);
if (!(tags[0].matches("[0-9]+"))) {
System.err.println("MediaUtils:removeTrackNumToFileNames:ERROR:First element is not a number: " + file.getAbsolutePath());
continue;
}
System.out.println("Processing:" + file.getName());
StringBuffer newPath = new StringBuffer();
newPath.append(basePath);
newPath.append(FILE_SEP);
for (int i = 1; i < tags.length; i++) {
newPath.append(tags[i]);
if (i < tags.length - 1) {
newPath.append(TAG_DELIMITER);
}
}
File newFile = new File(newPath.toString());
file.renameTo(newFile);
}
}
}
| true |
d59dad2e34dcfa28f7afe1772a90b7273957544e | Java | neopaper/storagerent | /message/src/main/java/storagerent/PolicyHandler.java | UTF-8 | 2,057 | 2.359375 | 2 | [] | no_license | package storagerent;
import storagerent.config.kafka.KafkaProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
@Service
public class PolicyHandler{
@Autowired MessageRepository messageRepository;
@StreamListener(KafkaProcessor.INPUT)
public void wheneverReservationConfirmed_SendConfirmMsg(@Payload ReservationConfirmed reservationConfirmed){
if(!reservationConfirmed.validate()) return;
System.out.println("\n\n##### listener SendConfirmMsg : " + reservationConfirmed.toJson() + "\n\n");
long storageId = reservationConfirmed.getStorageId();
String msgString = "예약이 완료 되었습니다. Storage 번호 : [" + storageId +"]";
// 메시지 전송
sendMsg(storageId, msgString);
}
@StreamListener(KafkaProcessor.INPUT)
public void wheneverReservationCancelled_SendCancelMsg(@Payload ReservationCancelled reservationCancelled){
if(!reservationCancelled.validate()) return;
System.out.println("\n\n##### listener SendCancelMsg : " + reservationCancelled.toJson() + "\n\n");
long storageId = reservationCancelled.getStorageId();
String msgString = "예약이 취소 되었습니다. Storage 번호 : [" + storageId +"]";
// 메시지 전송
sendMsg(storageId, msgString);
}
@StreamListener(KafkaProcessor.INPUT)
public void whatever(@Payload String eventString){}
private void sendMsg(long storageId, String msgString) {
//////////////////////////////////////////////
// roomId 룸에 대해 msgString으로 SMS를 쌓는다
//////////////////////////////////////////////
Message msg = new Message();
msg.setStorageId(storageId);
msg.setContent(msgString);
// DB Insert
messageRepository.save(msg);
}
}
| true |
e0d16f62c04e534b28691c70d0e62bb5b5eba168 | Java | SuraaKara/JavaAssigment1Day5 | /core/adapter/OutSourceManagerAdapter.java | UTF-8 | 476 | 2.171875 | 2 | [] | no_license | package javaDay5Assigment1.core.adapter;
import javaDay5Assigment1.core.abstracts.OutSourceService;
public class OutSourceManagerAdapter implements OutSourceService {
@Override
public void registerwith() {
OutSourceManagerAdapter sourceManager= new OutSourceManagerAdapter();
sourceManager.registerwith();
}
@Override
public void loginwith() {
OutSourceManagerAdapter sourceManager= new OutSourceManagerAdapter();
sourceManager.registerwith();
}
}
| true |
1f40b9a85da427f6f4649bdc64acf634ef4c5f04 | Java | xzy0508/Xiaoshixun | /xuzhiyuan_day02_lianxi1/src/main/java/com/example/xuzhiyuan_day02_lianxi1/LogInterface.java | UTF-8 | 952 | 1.90625 | 2 | [] | no_license | package com.example.xuzhiyuan_day02_lianxi1;
import com.example.xuzhiyuan_day02_lianxi1.bean.LogBean;
import com.example.xuzhiyuan_day02_lianxi1.bean.VerifyBean;
import java.util.Map;
import io.reactivex.Observable;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface LogInterface {
String baseUrl="http://yun918.cn/study/public/index.php/";
String verify = "http://yun918.cn/study/public/index.php/";
@POST("login?")
@FormUrlEncoded
Observable<LogBean> getData(@Field("username") String username, @Field("password")String password);
@POST("login?register")
@FormUrlEncoded
Observable<LogBean> getLogin(@Field("username") String username,@Field("password")String password,@Field("phone") String phone,@Field("verify") String verify);
@GET("verify")
Observable<VerifyBean> getData();
}
| true |
db52eca6943c69e75d3fbade82be90db155cca6d | Java | ralitnad/primefaces-master | /src/main/java-templates/org/primefaces/component/password/PasswordTemplate.java | UTF-8 | 1,805 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | import javax.faces.component.UIComponent;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import org.primefaces.expression.SearchExpressionFacade;
import org.primefaces.util.MessageFactory;
import org.primefaces.util.ComponentUtils;
import org.primefaces.util.LangUtils;
public final static String STYLE_CLASS = "ui-inputfield ui-password ui-widget ui-state-default ui-corner-all";
public final static String INVALID_MATCH_KEY = "primefaces.password.INVALID_MATCH";
@Override
protected void validateValue(FacesContext context, Object value) {
super.validateValue(context, value);
String match = this.getMatch();
Object submittedValue = this.getSubmittedValue();
if(isValid() && !LangUtils.isValueBlank(match)) {
Password matchWith = (Password) SearchExpressionFacade.resolveComponent(context, this, match);
if(submittedValue != null && !submittedValue.equals(matchWith.getSubmittedValue())) {
this.setValid(false);
matchWith.setValid(false);
String validatorMessage = getValidatorMessage();
FacesMessage msg = null;
if(validatorMessage != null) {
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, validatorMessage, validatorMessage);
}
else {
Object[] params = new Object[2];
params[0] = MessageFactory.getLabel(context, this);
params[1] = MessageFactory.getLabel(context, matchWith);
msg = MessageFactory.getMessage(Password.INVALID_MATCH_KEY, FacesMessage.SEVERITY_ERROR, params);
}
context.addMessage(getClientId(context), msg);
}
}
} | true |
73909b6617ab90a55a80c94faabfb894c51d31b3 | Java | Tecali/Practice_Java | /Practice/src/RevertWord.java | UTF-8 | 1,955 | 3.234375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Stack;
import java.util.stream.Collectors;
import org.junit.Test;
public class RevertWord {
public String reverseWord(String st) {
int t1 = (int) System.currentTimeMillis();
String[] words = st.split(" ");// Option 1
// Collections.reverse(Arrays.asList(words));
// String strm = Arrays.stream(words).collect(Collectors.joining(" "));
// Option 2 faster than 1
StringBuilder stb = new StringBuilder();
//
// for(String w: words){
// stb.append(w);
// stb.append(" ");
// }
// Option 4
// for(int i=words.length-1; i>=0; i--){
// stb.append(words[i]);
// stb.append(" ");
// }
// Option 4
int len = words.length;
for (int i = 0; i < len / 2; i++) {
String tmp = words[i];
words[i] = words[len - 1 - i];
words[len - 1 - i] = tmp;
// stb.append(words[i]);
// stb.append(" ");
}
int t2 = (int) System.currentTimeMillis();
int diff = t2 - t1;
System.out.println("The time Diff is : " + diff);
// return stb.toString().trim();
// System.out.println(strm);
// return strm;
String rslt = Arrays.stream(words).collect(Collectors.joining(" "));
System.out.println(rslt);
List<Integer> ins = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 7));
// int i = ins.stream().mi
Optional<Integer> r = ins.stream().min(Comparator.comparing(x -> x));
Optional<Integer> r2 = ins.stream().skip(2).max((x, y) -> x - y);
Integer r3 = ins.stream().mapToInt(x -> x).sum();
int k = 10;
Map<Integer, Integer> mr = ins.parallelStream().collect(Collectors.toMap(x -> x+k, x -> (x-k)<0?0:x));
mr.forEach((x,v) ->
System.out.println("Key :"+x+" And Vals: "+v)
);
System.out.println("The max mval is = " + r2.get());
return rslt;
}
}
| true |
3238ac3a6c25d67946105d4893afe93bc85fb4a1 | Java | VishnuGurudathan/design-patterns | /mediator-pattern/src/main/java/org/vishnu/demo/Component.java | UTF-8 | 479 | 2.921875 | 3 | [] | no_license | package org.vishnu.demo;
/**
* Abstract component class.
*
* @author : vishnu.g
* created on : 26/Jul/2020
*/
public abstract class Component {
private String name;
protected Mediator mediator;
public Component(String name, Mediator mediator) {
this.name = name;
this.mediator = mediator;
}
public abstract void send();
public abstract void receive(String message);
public String getName() {
return this.name;
}
}
| true |
fa0fba7abfe3ae7a161f248ee7ba0f2486c926d1 | Java | Michael-Bradley/Hashcow | /src/theGame/Main.java | UTF-8 | 1,440 | 2.6875 | 3 | [] | no_license | package theGame;
import gamePieces.MapInfo;
import java.io.IOException;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import resourceManager.SoundManager;
import utils.Logger;
public class Main extends StateBasedGame {
private static AppGameContainer appgc;
public static void main(String[] args){
//entry point of program
try{
appgc = new AppGameContainer(new Main("This Is The Title"));
appgc.setDisplayMode(800, 480, false);
appgc.setShowFPS(true);
appgc.setTargetFrameRate(119);
appgc.start();
}catch(SlickException se){
//Logger.logException(se)
}
}
public Main(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
/**
* Wraps the super method to provide logging and sound management between states
*/
public void enterState(int id){
Logger.logNote("Transitioning to state " + id);
SoundManager.stopAll();
super.enterState(id);
}
@Override
public void initStatesList(GameContainer container) throws SlickException {
addState(new MainMenu());
addState(new InGame(MapInfo.TEST_MAP, 0));
}
/**
* Cleanly shut down the game
*/
public static void exit(){
try {
Logger.writeOut();
} catch (IOException e) {
e.printStackTrace();
}
Logger.streamLog("Clean exit achieved.");
appgc.exit();
}
}
| true |
1e5f11b1c160d202f4111facc2349b4150569760 | Java | DumitrascuMaria/cts_lab | /seminar2/src/ro/ase/ctsseminar2/Main.java | UTF-8 | 1,884 | 3.03125 | 3 | [] | no_license | package ro.ase.ctsseminar2;
import ro.ase.ctsseminar2.exceptii.IllegalTransferException;
import ro.ase.ctsseminar2.exceptii.InsufficientFundsException;
import ro.ase.ctsseminar2.interfaces.NotificationService;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Account a=new Account(); //nu se poate instantia o clasa abstracta
CurrentAccount c=new CurrentAccount(300,"IBAN1"); //upcasting
c.setNotificationService(new SMSNotificationService());
CurrentAccount account2=new CurrentAccount(200,"IBAN2");
//dependecy inversion=modulele cele mai abstracte sa nu depinda de cele mai complexe
SaveingAccount account3=new SaveingAccount(300,"IBAN3");
System.out.println("Suma disponibila este: " +c.getBalance()); //=>0
System.out.println("Creditul maxim pentru cont curent este "+CurrentAccount.MAX_CREDIT);
c.deposit(200);
System.out.println("Suma disponibila este: " +c.getBalance()); //=>200
try {
c.withdraw(200);
c.transfer(100, account2);
c.setNotificationService(new NotificationService(){
@Override
public void sendNotification(String message) {
System.out.println("Sent PUSH notification with message"+message);
}
});
c.withdraw(100);
} catch (InsufficientFundsException | IllegalTransferException e) {
// TODO Auto-generated catch block
System.err.println(e.getMessage());
}
System.out.println("Suma disponibila este: " +c.getBalance());
System.out.println("Suma in contul2 este:" +account2.getBalance());
System.out.println("Suma in contul3 este:" +account3.getBalance());
((SaveingAccount)account3).addInterest(10);
//account3.deposit(200);
System.out.println("Suma in contul3 este:" +account3.getBalance());
Bank banca=new Bank();
BankAccount account4=banca.openBankAccount(AccountType.CURRENT); //upcasting
}
}
| true |
9edaa4625e0e8d49d06fa9b87097437bde8e7da0 | Java | ryanSiran/maven-cluster | /maven_pom_root/maven_general_study/src/main/java/cn/com/psr/general/study/utils/delegation/Event.java | UTF-8 | 2,056 | 3.03125 | 3 | [] | no_license | package cn.com.psr.general.study.utils.delegation;
import java.lang.reflect.Method;
public class Event {
// 要执行的对象
private Object object;
// 要执行的方法名
private String methodName;
// 要执行的方法参数
private Object[] params;
// 要执行方法的参数类型
private Class<?>[] paramTypes;
public Event(){}
public Event(Object object, String methodName, Object... args){
this.object = object;
this.methodName = methodName;
this.params = args;
contractParamTypes(this.params);
}
/**
* 根据参数数组生成参数类型数组
* @param params
*/
private void contractParamTypes(Object[] params){
this.paramTypes = new Class[params.length];
for(int i = 0; i < params.length; i++){
this.paramTypes[i] = params[i].getClass();
}
}
/**
* 执行该对象的方法
* @throws Exception
*/
public void invoke() throws Exception{
Method method = object.getClass().getMethod(this.getMethodName(), this.getParamTypes());
if(null == method){
return;
}
method.invoke(this.object, params);
}
/**
* @return the object
*/
public Object getObject() {
return object;
}
/**
* @param object the object to set
*/
public void setObject(Object object) {
this.object = object;
}
/**
* @return the methodName
*/
public String getMethodName() {
return methodName;
}
/**
* @param methodName the methodName to set
*/
public void setMethodName(String methodName) {
this.methodName = methodName;
}
/**
* @return the params
*/
public Object[] getParams() {
return params;
}
/**
* @param params the params to set
*/
public void setParams(Object[] params) {
this.params = params;
}
/**
* @return the paramTypes
*/
public Class<?>[] getParamTypes() {
return paramTypes;
}
/**
* @param paramTypes the paramTypes to set
*/
public void setParamTypes(Class<?>[] paramTypes) {
this.paramTypes = paramTypes;
}
}
| true |
9cf347ddd78c813f053d4f6aa15e4686c23b9090 | Java | xtaticzero/COB | /ControlObligaciones/ControlObligacionesBack/src/main/java/mx/gob/sat/siat/cob/background/service/afectaciones/AfectacionPorNotificacionService.java | UTF-8 | 819 | 1.835938 | 2 | [] | no_license | /* ****************************************************************
* Nombre de archivo: AfectacionPorNotificionService.java
* Autores: Emmanuel Estrada Gonzalez
* Bitácora de modificaciones:
* CR/Defecto Fecha Autor Descripción del cambio
* ---------------------------------------------------------------------------
* N/A 21/10/2013 <Nombre del desarrollador que está modificando el archivo>
* ---------------------------------------------------------------------------
*/
package mx.gob.sat.siat.cob.background.service.afectaciones;
import mx.gob.sat.siat.cob.seguimiento.dto.arca.SeguimientoARCA;
import mx.gob.sat.siat.cob.seguimiento.exception.SGTServiceException;
public interface AfectacionPorNotificacionService {
void actualizaEstadoDocumento(SeguimientoARCA seguimientoARCA)throws SGTServiceException;
}
| true |
98688d589259f3640e6317883c92e11d0f53a9a9 | Java | AllBinary/AllBinary-Platform | /graphics/ImageJavaLibraryM/src/main/java/org/allbinary/media/image/analysis/ImageAnalysis.java | UTF-8 | 4,620 | 2.4375 | 2 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*
* AllBinary Open License Version 1
* Copyright (c) 2011 AllBinary
*
* By agreeing to this license you and any business entity you represent are
* legally bound to the AllBinary Open License Version 1 legal agreement.
*
* You may obtain the AllBinary Open License Version 1 legal agreement from
* AllBinary or the root directory of AllBinary's AllBinary Platform repository.
*
* Created By: Travis Berthelot
*
*/
package org.allbinary.media.image.analysis;
import java.awt.Color;
import java.awt.image.BufferedImage;
import org.allbinary.logic.communication.log.LogUtil;
import org.allbinary.graphics.color.ColorCacheFactory;
import org.allbinary.graphics.color.ColorCacheable;
import org.allbinary.logic.communication.log.LogFactory;
public class ImageAnalysis
{
private ImageAnalysis()
{
}
public static ImageAnalysisResults[] process(BufferedImage[] bufferedImageArray, ColorRangeInterface colorRangeInterface) throws Exception
{
LogUtil.put(LogFactory.getInstance("Start: " + colorRangeInterface.toString(), "ImageAnalysis", "process"));
ImageAnalysisResults[] imageAnalysisResultsArray = new ImageAnalysisResults[bufferedImageArray.length];
for (int index = 0; index < bufferedImageArray.length; index++)
{
imageAnalysisResultsArray[index] = ImageAnalysis.process(bufferedImageArray[index], colorRangeInterface);
}
return imageAnalysisResultsArray;
}
public static ImageAnalysisResults process(BufferedImage bufferedImage, ColorRangeInterface colorRangeInterface) throws Exception
{
ImageAnalysisResults imageAnalysisResults = new ImageAnalysisResults();
long redTotal = 0;
long greenTotal = 0;
long blueTotal = 0;
for (int indexY = 0; indexY < bufferedImage.getHeight(); indexY++)
{
for (int indexX = 0; indexX < bufferedImage.getWidth(); indexX++)
{
Integer keyInteger = Integer.valueOf(bufferedImage.getRGB(indexX, indexY));
ColorCacheable colorCacheable = (ColorCacheable) ColorCacheFactory.getInstance().get(keyInteger);
Color color = colorCacheable.getColor();
processColorRangeResults(imageAnalysisResults, colorRangeInterface, color);
processImageColorResults(imageAnalysisResults.getImageColorResults(), colorRangeInterface, color);
redTotal += color.getRed();
greenTotal += color.getGreen();
blueTotal += color.getBlue();
}
}
long totalPixels = imageAnalysisResults.getImageColorRangeResults().getTotalPixelsChecked();
imageAnalysisResults.getImageColorResults().getColorAverage().setAvgRed((float) redTotal / totalPixels);
imageAnalysisResults.getImageColorResults().getColorAverage().setAvgGreen((float) greenTotal / totalPixels);
imageAnalysisResults.getImageColorResults().getColorAverage().setAvgBlue((float) blueTotal / totalPixels);
return imageAnalysisResults;
}
private static void processColorRangeResults(ImageAnalysisResults imageAnalysisResults, ColorRangeInterface colorRangeInterface, Color color)
{
if (colorRangeInterface.isInRange(color))
{
imageAnalysisResults.getImageColorRangeResults().addMatchingPixelsChecked();
} else
{
// LogUtil.put(LogFactory.getInstance("Invalid Color: " + color, "ImageAnalysis", "process"));
}
imageAnalysisResults.getImageColorRangeResults().addTotalPixelsChecked();
}
private static void processImageColorResults(ImageColorResults imageColorResults, ColorRangeInterface colorRangeInterface, Color color)
{
if (color.getRed() < imageColorResults.getColorRange().getMinRed())
{
imageColorResults.getColorRange().setMinRed(color.getRed());
}
if (color.getGreen() < imageColorResults.getColorRange().getMinGreen())
{
imageColorResults.getColorRange().setMinGreen(color.getGreen());
}
if (color.getBlue() < imageColorResults.getColorRange().getMinBlue())
{
imageColorResults.getColorRange().setMinBlue(color.getBlue());
}
if (color.getRed() > imageColorResults.getColorRange().getMaxRed())
{
imageColorResults.getColorRange().setMaxRed(color.getRed());
}
if (color.getGreen() > imageColorResults.getColorRange().getMaxGreen())
{
imageColorResults.getColorRange().setMaxGreen(color.getGreen());
}
if (color.getBlue() > imageColorResults.getColorRange().getMaxBlue())
{
imageColorResults.getColorRange().setMaxBlue(color.getBlue());
}
}
}
| true |
d034455742c81f765aee246fd154c6caee59b742 | Java | gyurix/ProtectionCore | /src/gyurix/protectioncore/commands/List.java | UTF-8 | 1,453 | 1.953125 | 2 | [] | no_license | package gyurix.protectioncore.commands;
import PluginReference.MC_Location;
import PluginReference.MC_Player;
import gyurix.chatapi.ChatAPI;
import gyurix.konfigfajl.KFA;
import gyurix.protectioncore.Region;
import gyurix.protectioncore.Utils;
import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
public class List
{
public List(MC_Player plr, String[] args)
{
if (Utils.hasPerm(plr, "command.list")) {
int pldim = plr == null ? 2147483647 : plr.getLocation().dimension;
if ((plr == null) && (args.length == 1)) {
ChatAPI.msg(null, "protectioncore.region.nodimension", new String[0]);
return;
}
try {
int dim = args.length > 1 ? Integer.valueOf(args[1]).intValue() : pldim;
ChatAPI.msg(plr, "protectioncore.list" + (dim == pldim ? "" : ".dimension"), new String[] { "<regions>",
StringUtils.join((Iterable)Region.regnames.get(Integer.valueOf(dim)),
KFA.l(plr, "protectioncore.list.separator")),
"<dimension>", dim });
}
catch (Throwable e) {
if (plr != null) return;
}ChatAPI.msg(null, "protectioncore.region.notnumber", new String[] { "<dimension>", args[0] });
}
else
{
ChatAPI.msg(plr, "protectioncore.noperm.list", new String[0]);
}
}
}
/* Location: D:\GitHub\ProtectionCore.jar
* Qualified Name: gyurix.protectioncore.commands.List
* JD-Core Version: 0.6.2
*/ | true |
9f71b43e197ba15870fb7cf7e2f61bcbeea73ce5 | Java | muellenborn/dictomaton | /src/main/java/eu/danieldk/dictomaton/PerfectHashDictionary.java | UTF-8 | 1,189 | 3.34375 | 3 | [
"Apache-2.0"
] | permissive | package eu.danieldk.dictomaton;
/**
* Perfect hash dictionary interface. A perfect hash dictionary provides
* the functionality of a {@link Dictionary}, plus:
* <ul>
* <li>A hash code for each sequence in the dictionary ({@link #number(String)}).</li>
* <li>The character sequence of a given hash ({@link #sequence(int)}).</li>
* </ul>
*/
public interface PerfectHashDictionary extends Dictionary {
/**
* Compute the perfect hash code of the given character sequence.
*
* @param seq The sequence to compute the perfect hash value for.
* @return The perfect hash value of the sequence or <tt>-1</tt> if the sequence is
* not in the automaton.
*/
public int number(CharSequence seq);
public StateInfo getStateInfo(CharSequence seq);
public StateInfo getStateInfo(CharSequence seq, StateInfo startInfo);
/**
* Compute the sequence corresponding to the given hash code.
*
* @param hashCode The hash code.
* @return The sequence corresponding to the hash code or <tt>null</tt> if there is
* no sequence with that code in the automaton.
*/
public String sequence(int hashCode);
}
| true |
c8b43907f8be984dcfec25d5b340b0de63884ab7 | Java | cuihongjian/Intelligent-suspected-missing-persons-tracking-system | /src/main/java/zhrk/common/model/base/BaseQxCamarea.java | UTF-8 | 1,436 | 1.851563 | 2 | [] | no_license | package zhrk.common.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings({"serial", "unchecked"})
public abstract class BaseQxCamarea<M extends BaseQxCamarea<M>> extends Model<M> implements IBean {
public M setId(java.lang.Integer id) {
set("ID", id);
return (M)this;
}
public java.lang.Integer getId() {
return getInt("ID");
}
public M setCamname(java.lang.String camname) {
set("CAMNAME", camname);
return (M)this;
}
public java.lang.String getCamname() {
return getStr("CAMNAME");
}
public M setAddress(java.lang.String address) {
set("ADDRESS", address);
return (M)this;
}
public java.lang.String getAddress() {
return getStr("ADDRESS");
}
public M setParam(java.lang.String param) {
set("PARAM", param);
return (M)this;
}
public java.lang.String getParam() {
return getStr("PARAM");
}
public M setUrl(java.lang.String url) {
set("URL", url);
return (M)this;
}
public java.lang.String getUrl() {
return getStr("URL");
}
public M setPort(java.lang.String port) {
set("PORT", port);
return (M)this;
}
public java.lang.String getPort() {
return getStr("PORT");
}
public M setRemark(java.lang.String remark) {
set("REMARK", remark);
return (M)this;
}
public java.lang.String getRemark() {
return getStr("REMARK");
}
}
| true |
4d25c6525a6a6399b70364cdda14e89604499ce8 | Java | henrik242/openiam-idm | /openiam-pojo-services/src/main/java/org/openiam/idm/srvc/meta/service/MetadataServiceImpl.java | UTF-8 | 5,022 | 2.546875 | 3 | [] | no_license | package org.openiam.idm.srvc.meta.service;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.openiam.idm.srvc.meta.dto.MetadataElement;
import org.openiam.idm.srvc.meta.dto.MetadataType;
/**
* Data service implementation for Metadata.
* @author suneet
* @version 1
*/
public class MetadataServiceImpl implements MetadataService {
MetadataTypeDAO metadataTypeDao;
MetadataElementDAO metadataElementDao;
public MetadataElement addMetadataElement(MetadataElement metadataElement) {
if (metadataElement == null) {
throw new NullPointerException("metadataElement is null");
}
metadataElementDao.add(metadataElement);
return metadataElement;
}
public MetadataType addMetadataType(MetadataType type) {
if (type == null) {
throw new NullPointerException("Metadatatype is null");
}
metadataTypeDao.add(type);
return type;
}
public void addTypeToCategory(String typeId, String categoryId) {
if (typeId == null)
throw new NullPointerException("typeId is null");
if (categoryId == null)
throw new NullPointerException("category is null");
this.metadataTypeDao.addCategoryToType(typeId, categoryId);
}
public MetadataElement getMetadataElementById(String elementId) {
if (elementId == null) {
throw new NullPointerException("elementId is null");
}
return metadataElementDao.findById(elementId);
}
public MetadataElement[] getMetadataElementByType(String typeId) {
if (typeId == null) {
throw new NullPointerException("typeId is null");
}
MetadataType type = metadataTypeDao.findById(typeId);
if (type == null )
return null;
Map<String, MetadataElement> elementMap = type.getElementAttributes();
if (elementMap == null || elementMap.isEmpty()) {
return null;
}
// convert to an array
Collection<MetadataElement> elementCollection = elementMap.values();
MetadataElement[] elementAry = new MetadataElement[elementCollection.size()];
elementCollection.toArray(elementAry);
return elementAry;
}
public MetadataType getMetadataType(String typeId) {
if (typeId == null) {
throw new NullPointerException("typeId is null");
}
return metadataTypeDao.findById(typeId);
}
public MetadataType[] getMetadataTypes() {
List<MetadataType> typeList = metadataTypeDao.findAll();
if (typeList == null || typeList.isEmpty()) {
return null;
}
int size = typeList.size();
MetadataType[] typeAry = new MetadataType[size];
typeList.toArray(typeAry);
return typeAry;
}
public MetadataType[] getTypesInCategory(String categoryId) {
if (categoryId == null) {
throw new NullPointerException("categoryId is null");
}
List<MetadataType> typeList = metadataTypeDao.findTypesInCategory(categoryId);
if (typeList == null || typeList.isEmpty()) {
return null;
}
int size = typeList.size();
MetadataType[] typeAry = new MetadataType[size];
typeList.toArray(typeAry);
return typeAry;
}
public void removeMetadataElement(String elementId) {
if (elementId == null) {
throw new NullPointerException("elementId is null");
}
MetadataElement element = new MetadataElement(elementId);
metadataElementDao.remove(element);
}
public void removeMetadataType(String typeId) {
if (typeId == null) {
throw new NullPointerException("typeId is null");
}
metadataElementDao.removeByParentId(typeId);
MetadataType type = new MetadataType();
type.setMetadataTypeId(typeId);
metadataTypeDao.remove(type);
}
public void removeTypeFromCategory(String typeId, String categoryId) {
if (typeId == null)
throw new NullPointerException("typeId is null");
if (categoryId == null)
throw new NullPointerException("category is null");
metadataTypeDao.removeCategoryFromType(typeId, categoryId);
}
public MetadataElement updateMetadataElement(MetadataElement mv) {
if (mv == null) {
throw new NullPointerException("metadataElement is null");
}
metadataElementDao.update(mv);
return mv;
}
public MetadataType updateMetdataType(MetadataType type) {
if (type == null) {
throw new NullPointerException("Metadatatype is null");
}
metadataTypeDao.update(type);
return type;
}
public List<MetadataElement> getAllElementsForCategoryType(String categoryType) {
if (categoryType == null) {
throw new NullPointerException("categoryType is null");
}
return metadataElementDao.findbyCategoryType(categoryType);
}
public MetadataTypeDAO getMetadataTypeDao() {
return metadataTypeDao;
}
public void setMetadataTypeDao(MetadataTypeDAO metadataTypeDao) {
this.metadataTypeDao = metadataTypeDao;
}
public MetadataElementDAO getMetadataElementDao() {
return metadataElementDao;
}
public void setMetadataElementDao(MetadataElementDAO metadataElementDao) {
this.metadataElementDao = metadataElementDao;
}
}
| true |
3d3f1abcadc4da16110a86f8a963497855ecff8e | Java | gbrandao07/medium-article-springboot-docker-k8s | /echoservice/src/main/java/com/microservice/echoservice/EchoRestController.java | UTF-8 | 489 | 2.328125 | 2 | [] | no_license | package com.microservice.echoservice;
import java.time.LocalDateTime;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EchoRestController {
@GetMapping("/echo")
public String echo() {
return "Hello! This is a message sent by echoservice to callerservice. \n"
+ "Info: " +
LocalDateTime.now() + "\n" +
this.toString();
}
} | true |
74363260c9873c3211ac70b144c150432951e063 | Java | besse/backcountrylog | /src/main/java/com/backcountrylog/rest/UserResource.java | UTF-8 | 1,760 | 2.34375 | 2 | [] | no_license | package com.backcountrylog.rest;
import com.backcountrylog.model.User;
import com.backcountrylog.model.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.UnknownHostException;
/**
* Created for Outdoorlog
* UserResource: jonasbirgersson
* Date: 2015-01-31
* Time: 11:47 AM
*/
@Path("user")
public class UserResource {
private final static Logger logger = LoggerFactory.getLogger(UserResource.class);
private UserDao userDao;
public UserResource() throws UnknownHostException {
userDao = new UserDao();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers() throws UnknownHostException {
logger.info("Listing all users");
//return userDao.findAll();
return Response.ok(userDao.findAll()).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{userId}")
public User getUserById(@PathParam("userId") String userId) {
return userDao.findById(userId);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void createUser(User user) throws UnknownHostException {
userDao.save(user);
logger.info("Successfully saved user: " + user.toString());
}
}
/*
curl -H "Content-Type: application/json" -d '{"firstName":"Kenneth","lastName":"Andersson"}' http://localhost:8080/webapi/user
/Product GET Hämtar en lista med alla produkter
/Product POST Skapar en ny produkt
/Product/{ProductID} GET Returnerar en produkt
/Product/{ProductID} PUT Uppdaterar en produkt
/Product/{ProductID} DELETE Tar bort en produkt
/ProductGroup/{ProductGroupID} GET Returnerar en produktgrupp
*/
| true |