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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4c11ccf9b439ca09bca6fd183f9df93d29d50124 | Java | vinesmario/huggy-bear | /industry/industry-generic/generic-business-infrastructure-parent/generic-business-infrastructure-client/src/main/java/com/vinesmario/microservice/client/immovable/dto/FacilityDTO.java | UTF-8 | 348 | 1.859375 | 2 | [] | no_license | package com.vinesmario.microservice.client.immovable.dto;
/**
* 场所
*/
public class FacilityDTO {
/**
* 租户ID
*/
private Long tenantId;
/**
* 名称
*/
private String name;
/**
* 用途:1-办公;2-会议;3-教学;4-居住;5-储物;9-其他。
*/
private Integer purpose;
}
| true |
22632c91eeced81ed6ac5ab7b598905b0eb29f63 | Java | zndroidx/APP-MenuBox | /lib_MenuBox/src/main/java/com/zndroid/menubox/core/IMenuItemClick.java | UTF-8 | 156 | 1.648438 | 2 | [] | no_license | package com.zndroid.menubox.core;
/**
* Created by lzy on 2020/5/27.
*/
public interface IMenuItemClick {
void onItemClick(MenuItem item);
}
| true |
e80f9d45f500afcddb89098908c791a86c082cdb | Java | zxc0622/llyb | /src/main/java/com/qdum/llhb/trademana/controller/RechargeOnlineController.java | UTF-8 | 2,166 | 1.992188 | 2 | [] | no_license | package com.qdum.llhb.trademana.controller;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.qdum.llhb.fund.model.Fund;
import com.qdum.llhb.sys.utils.UserUtils;
import com.qdum.llhb.trademana.Constant;
import com.qdum.llhb.trademana.model.AlipayError;
import com.qdum.llhb.trademana.model.RechargeRecord;
import com.qdum.llhb.trademana.validator.NumValidator;
import com.qdum.llhb.trademana.vo.AlipayErrorInfo;
import com.qdum.llhb.trademana.vo.RechargeInfo;
/**
* 在线充值
* Created by chao on 2016/1/15.
*/
@ControllerBind(controllerKey = "/trademana/rechargeonline")
public class RechargeOnlineController extends Controller {
/**
* 在线充值第一步
*/
public void firstStepRecharge() {
Fund fund = Fund.dao.queryUserFund(UserUtils.getUser().getId());
if (fund == null) {
setAttr("remindSum", 800.00);
} else {
setAttr("remindSum", fund.getBigDecimal("fund"));
}
render("rechargeonline.jsp");
}
/**
* 在线充值第二步
*/
@Before(NumValidator.class)
public void secondStepRecharge() {
Float rechargeAmount = Float.valueOf(getPara("rechargeAmount"));
RechargeInfo rechargeInfo = RechargeRecord.dao.handleRecharge(rechargeAmount);
setAttr("rechargeInfo", rechargeInfo);
render("rechargeonline2.jsp");
}
/**
* 支付宝支付失败,主动推送错误消息
*/
public void errorNotify() {
AlipayErrorInfo alipayErrorInfo = new AlipayErrorInfo();
alipayErrorInfo.setPartner(getPara("partner"));
alipayErrorInfo.setOutTradeNo(getPara("out_trade_no"));
alipayErrorInfo.setErrorCode(getPara("error_code"));
alipayErrorInfo.setReturnUrl(getPara("return_url"));
alipayErrorInfo.setBuyerEmail(getPara("buyer_email"));
alipayErrorInfo.setBuyerID(getPara("buyer_id"));
alipayErrorInfo.setSellerEmail(getPara("seller_email"));
alipayErrorInfo.setSellerID(getPara("seller_id"));
AlipayError.dao.createAlipayErrorLog(alipayErrorInfo);
}
}
| true |
70942f41ab4b9971791e4ceaa5b3db8a034bb3d8 | Java | LePhiHung97/springmvc | /src/main/java/com/phihung/springmvc/entities/Student.java | UTF-8 | 1,308 | 2.8125 | 3 | [] | no_license | package com.phihung.springmvc.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "masv")
private int masv;
@Column(name = "hoten")
private String hoten;
@Column(name = "namsinh")
private int namsinh;
@Column(name = "lop")
private String lop;
@Column(name = "diem")
private double diem;
public int getMasv() {
return masv;
}
public void setMasv(int masv) {
this.masv = masv;
}
public int getNamsinh() {
return namsinh;
}
public void setNamsinh(int namsinh) {
this.namsinh = namsinh;
}
public String getHoten() {
return hoten;
}
public void setHoten(String hoten) {
this.hoten = hoten;
}
public String getLop() {
return lop;
}
public void setLop(String lop) {
this.lop = lop;
}
public double getDiem() {
return diem;
}
public void setDiem(double diem) {
this.diem = diem;
}
@Override
public String toString() {
return this.masv + " - " + this.getHoten() + " - " + this.getNamsinh() + " - " + this.getLop() + " - "
+ this.getDiem();
}
}
| true |
8e2ef82643f61be76323b945dcb7fe38e3cfa801 | Java | saitxuc/hippo-java | /hippo_open/hippo.network/src/main/java/com/hippo/network/ServerFortress.java | UTF-8 | 759 | 1.835938 | 2 | [] | no_license | package com.hippo.network;
import com.hippo.common.exception.HippoException;
import com.hippo.common.lifecycle.LifeCycle;
import com.hippo.network.transport.TransportConnectionManager;
import com.hippo.network.transport.TransportServer;
/**
*
* @author saitxuc
* 2015-3-30
*/
public interface ServerFortress extends LifeCycle {
/**
*
* @return
*/
String getSchema();
/**
*
* @return
*/
TransportServer getTransportServer();
/**
*
* @throws HippoException
*/
void close() throws HippoException;
/**
*
* @param manager
*/
void setTransportConnectionManager(TransportConnectionManager manager);
/**
*
*/
TransportConnectionManager getTransportConnectionManager();
}
| true |
b1bebc8eba8b85650ec7f8c1fa340b1156b4e7c8 | Java | madhusudhan223/java | /lnd/src/DemoArrays2.java | UTF-8 | 749 | 3.4375 | 3 | [] | no_license | import java.util.Scanner;
public class DemoArrays2 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.println("enter no.of rows and columns");
int r=sc.nextInt();
int c=sc.nextInt();
int x[][]=new int[r][c];
int y[][]=new int[r][c];
int z[][]=new int[r][c];
System.out.println("enter first matrix");
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
x[i][j]=sc.nextInt();
}
}
System.out.println("enter second matrix");
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
y[i][j]=sc.nextInt();
}
}
for(int k=0;k<r;k++) {
for(int l=0;l<c;l++) {
z[k][l]=x[k][l]+y[k][l] ;
}
}
for(int k=0;k<r;k++) {
for(int l=0;l<c;l++) {
System.out.print(z[k][l]+" ");
}
System.out.println();
}
}
}
| true |
ab8dc3efe657e4a2ce781a0201da2a2f7e10544b | Java | tmphuang6/snow | /app/src/main/java/snow/music/activity/detail/DetailActivity.java | UTF-8 | 665 | 2.1875 | 2 | [
"MIT"
] | permissive | package snow.music.activity.detail;
import android.os.Bundle;
import androidx.annotation.Nullable;
import snow.music.R;
import snow.music.activity.BaseActivity;
/**
* 对 Activity 的过渡动画进行了自定义。
*/
public class DetailActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_no_transition);
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.activity_no_transition, R.anim.activity_fade_out);
}
}
| true |
e5643915b07568296c327a480452ef761aa8a9f5 | Java | EmmanuelDS/Osyris | /osyris-model/src/main/java/be/gim/tov/osyris/model/traject/NetwerkSegment.java | UTF-8 | 2,404 | 1.921875 | 2 | [] | no_license | package be.gim.tov.osyris.model.traject;
import org.conscientia.api.model.ModelPropertyType;
import org.conscientia.api.model.annotation.Edit;
import org.conscientia.api.model.annotation.Model;
import org.conscientia.api.model.annotation.ModelClassName;
import org.conscientia.api.model.annotation.ModelStore;
import org.conscientia.api.model.annotation.NotEditable;
import org.conscientia.api.model.annotation.NotSearchable;
import org.conscientia.api.model.annotation.NotViewable;
import org.conscientia.api.model.annotation.Required;
import org.conscientia.api.model.annotation.Target;
import org.conscientia.api.model.annotation.Type;
import org.conscientia.api.model.annotation.ValuesExpression;
import be.gim.commons.resource.ResourceIdentifier;
/**
*
* @author kristof
*
*/
@Model
@ModelStore("OsyrisDataStore")
public abstract class NetwerkSegment extends Traject {
// VARIABLES
@Required
@Type(value = ModelPropertyType.ENUM)
@ValuesExpression("#{osyrisModelFunctions.canonicalBoolean}")
private String enkeleRichting;
@NotEditable
@NotViewable
private Integer vanKpNr;
@NotEditable
@NotViewable
private Integer naarKpNr;
@ModelClassName("NetwerkKnooppunt")
// @NotEditable
@Edit(type = "suggestions")
@NotSearchable
@Target("_blank")
private ResourceIdentifier vanKnooppunt;
@ModelClassName("NetwerkKnooppunt")
// @NotEditable
@Edit(type = "suggestions")
@NotSearchable
@Target("_blank")
private ResourceIdentifier naarKnooppunt;
// GETTERS AND SETTERS
// @Override
// @LabelProperty
// @NotEditable
// public Long getId() {
// return (Long) super.getId();
// }
public String getEnkeleRichting() {
return enkeleRichting;
}
public void setEnkeleRichting(String enkeleRichting) {
this.enkeleRichting = enkeleRichting;
}
public Integer getVanKpNr() {
return vanKpNr;
}
public void setVanKpNr(Integer vanKpNr) {
this.vanKpNr = vanKpNr;
}
public Integer getNaarKpNr() {
return naarKpNr;
}
public void setNaarKpNr(Integer naarKpNr) {
this.naarKpNr = naarKpNr;
}
public ResourceIdentifier getVanKnooppunt() {
return vanKnooppunt;
}
public void setVanKnooppunt(ResourceIdentifier vanKnooppunt) {
this.vanKnooppunt = vanKnooppunt;
}
public ResourceIdentifier getNaarKnooppunt() {
return naarKnooppunt;
}
public void setNaarKnooppunt(ResourceIdentifier naarKnooppunt) {
this.naarKnooppunt = naarKnooppunt;
}
} | true |
44aa73e7ffb143a00a30c6650d89b066318d5002 | Java | suppermanliu/SmartService | /app/src/main/java/com/hopen/smart/base/BaseFragment.java | UTF-8 | 2,267 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | package com.hopen.smart.base;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import com.hopen.smart.R;
import com.hopen.smart.activity.MainActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Administrator on 2017/2/14.
*/
public abstract class BaseFragment extends Fragment {
@BindView(R.id.menu)
ImageButton menu;
@BindView(R.id.title)
TextView title;
@BindView(R.id.change)
ImageButton change;
@BindView(R.id.container)
FrameLayout container;
public Context context;
public BaseFragment() {
context = getActivity();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.base_fragment, null);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initTitle();
}
//初始化标题栏
public abstract void initTitle();
//设置标题栏文字
public void setTitle(String text){
title.setText(text);
}
//设置是否显示标题栏左侧菜单按钮
public void setDisplayMenu(boolean isShow){
menu.setVisibility(isShow? View.VISIBLE: View.INVISIBLE);
}
//设置是否显示标题栏右侧按钮
public void setDisplayPic(boolean isShow){
change.setVisibility(isShow? View.VISIBLE: View.INVISIBLE);
}
//初始化布局
public abstract View initView();
//为容器添加内容
public void addView(View view){
container.removeAllViews();
container.addView(view);
}
@OnClick(R.id.menu)
public void onClick() {
MainActivity mActivity = (MainActivity) getActivity();
mActivity.slidingMenu.toggle();
}
}
| true |
900cffd34bba87c490589d459bcc8a0b4d67f6a7 | Java | zhangsung/learngit | /sung-template/src/main/java/com/nssoft/controller/EasyUIGridQuery.java | UTF-8 | 10,660 | 1.90625 | 2 | [] | no_license | package com.nssoft.controller;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.caches.ehcache.LoggingEhcache;
import org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.neighborsystem.durian.exception.AbsAPIException;
import com.neighborsystem.durian.exception.AbsException;
import com.neighborsystem.durian.restapi.api.AbsAPI;
import com.neighborsystem.durian.restapi.api.CommonTag;
import com.neighborsystem.durian.restapi.api.DurianMV;
import com.neighborsystem.durian.restapi.api.HttpMethod;
import com.neighborsystem.durian.restapi.model.NFData;
import com.nssoft.exception.AbsHttpException;
import com.nssoft.exception.InvalidMustParameterException;
import com.nssoft.exception.ParamException;
import com.nssoft.exception.ServerInternalException;
import com.nssoft.model.EasyUIGridObj;
import com.nssoft.util.MD5Util;
/**
*
* @ClassName EasyUIGridQuery
* @Description
* Copyright (c) 2014 by NS Soft.
* @author xuliguo
* @date 2015年7月31日 上午10:37:06
* @version V1.0
*
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public abstract class EasyUIGridQuery extends AbsAPI<EasyUIGridObj> {
private static final Logger logger = Logger.getLogger(EasyUIGridQuery.class);
private static final String perpertyPath = "/durian.properties";
@Resource
private SqlSessionFactory sqlSessionFactory = null;
public SqlSession getSession() {
return sqlSessionFactory.openSession();
}
public SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public String getPerpertyPath() {
return perpertyPath;
}
public String getPropertyValue(String key) {
try {
Properties props = new Properties();
InputStream inputStream = this.getClass().getResourceAsStream(perpertyPath);
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
props.load(bf);
return props.getProperty(key);
} catch (Exception e) {
logger.error(e.getMessage());
return "";
}
}
public boolean removeCache (String key) {
LoggingEhcache loggingEhcache = new LoggingEhcache(key);
loggingEhcache.clear();
return true;
}
public EasyUIGridObj page(SqlSession session, Map paramMap, String queryString) {
return page(session, paramMap, queryString, null);
}
public EasyUIGridObj page(SqlSession session, Map paramMap, String queryString, Map<String, String> summary) {
int pageNum = 0;
int pageSize = 0;
EasyUIGridObj easyUIGridObj = new EasyUIGridObj();
try {
pageNum = Integer.parseInt((String) paramMap.get("page"));
pageSize = Integer.parseInt((String) paramMap.get("rows"));
} catch (Exception e) {
throw new ParamException("分页参数格式不正确.");
}
Page page = PageHelper.startPage(pageNum, pageSize);
session.selectList(queryString, paramMap);
easyUIGridObj.setRows(page.getResult());
easyUIGridObj.setTotal(page.getTotal());
if (summary != null) {
Map resultMap = new HashMap();
Set<String> set = summary.keySet();
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = summary.get(key);
resultMap.put(key, session.selectOne(value, paramMap));
}
easyUIGridObj.setSummarys(resultMap);
}
return easyUIGridObj;
}
public String getHttpSession(HttpServletRequest req, String name) {
return (String) req.getSession().getAttribute(name);
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
NFData datas = null;
String strFormat = "json";
String strTrId = null;
Map paramsMap = null;
String headerKey = "";
try {
datas = new NFData();
datas.put(CommonTag.id.name(), this.getApiId());
strTrId = createTrID(req);
datas.put(CommonTag.trId.name(), strTrId);
logger.info("START - TrID[" + strTrId + "] API[" + this.getApiId() + "]");
paramsMap = req.getParameterMap();
strFormat = _getViewType(req, res);
checkHttpMethod(req.getMethod());
checkHttpHeader(req, res, datas);
checkMustParam(paramsMap);
checkOptoinParam(paramsMap);
checkUndefineParameter(paramsMap);
//checkNullParameterValue(paramsMap);
checkAuth(req, res);
prepareExecute(req, res);
datas.put(CommonTag.errCd.name(), 0);
datas.put(CommonTag.errMsg.name(), "Success");
datas.put("ts", req.getHeader("ts"));
EasyUIGridObj resultObj = executeAPI(req, res, strTrId);
if (resultObj != null) {
datas.put(CommonTag.result.name(), resultObj);
}
successExecute(req, res, datas);
}
catch (AbsAPIException e) {
failExecute(req, res, datas);
makeError(datas, e);
logger.error("ERROR- TrID[" + strTrId + "] [" + datas.get(CommonTag.id.name()) + "] [" + e.getErrCode() + "] [" + e.getErrMessage() + "]");
return new DurianMV(strFormat, datas);
}
catch (AbsHttpException e) {
failExecute(req, res, datas);
logger.error("ERROR- TrID[" + strTrId + "] [" + datas.get(CommonTag.id.name()) + "] [" + e.getMessage() + "]");
throw e;
}
finally {
headerKey = "timeStamp:" + req.getHeader("ts") + ";errCd:" + datas.get(CommonTag.errCd.name()) + ";trId:" + datas.get(CommonTag.trId.name()) + ";";
res.setHeader("headerKey", MD5Util.toSHA256(headerKey));
afterExecute(req, res);
logger.info("END - TrID[" + strTrId + "] API[" + this.getApiId() + "]");
}
return new DurianMV(strFormat, datas);
}
public void checkMustParam(Map paramMap) throws AbsException {
Class mEnumMustRequireParamClass = getMustParameter();
if (mEnumMustRequireParamClass == null) return;
//if (paramMap == null) throw new InvalidMustParameterException("没有发现必须参数");
if (paramMap == null) throw new ParamException("没有发现必须参数");
String[] value = null;
for (Object p : mEnumMustRequireParamClass.getEnumConstants()) {
if (logger.isDebugEnabled()) {
logger.debug("------------------------------------");
logger.debug("必须参数[" + p.toString() + "]");
}
value = (String[]) paramMap.get(p.toString());
if (value == null || value[0].length() == 0) {
if (logger.isDebugEnabled()) {
logger.debug("-----------------------------------");
logger.debug("必须参数[" + p.toString() + "]为空");
}
//throw new InvalidMustParameterException("必须参数为空[" + p.toString() + "]");
throw new ParamException("必须参数[" + p.toString() + "]为空");
}
}
}
public void checkOptoinParam(Map paramMap) throws AbsException {
Class mEnumOptionParamClass = getOptionParameter();
if (mEnumOptionParamClass == null) return;
if (paramMap == null) throw new InvalidMustParameterException("没有发现必须参数");
String[] value = null;
for (Object p : mEnumOptionParamClass.getEnumConstants()) {
if (logger.isDebugEnabled()) {
logger.debug("------------------------------------");
logger.debug("可选参数[" + p.toString() + "]");
value = (String[]) paramMap.get(p.toString());
if (value == null || value[0].length() == 0) {
if (logger.isDebugEnabled()) {
logger.debug("-----------------------------------");
logger.debug("可选参数[" + p.toString() + "]为空");
}
//throw new InvalidMustParameterException("可选参数[" + p.toString() + "]为空");
//throw new ParamException("可选参数[" + p.toString() + "]为空");
}
}
}
}
public void checkUndefineParameter(Map mRequestMap) throws AbsException {
if (mRequestMap == null)
return;
Set<String> set = mRequestMap.keySet();
Iterator<String> itr = set.iterator();
while (itr.hasNext()) {
_checkUndefineParameter(itr.next());
}
}
protected void _checkUndefineParameter(String strKey) throws AbsException {
Class mEnumOtherParamClass = getOptionParameter();
Class mEnumMustRequireParamClass = getMustParameter();
if (mEnumMustRequireParamClass != null) {
try {
mEnumMustRequireParamClass.getField(strKey);
}
catch (NullPointerException e) {
e.printStackTrace();
throw new ServerInternalException("_checkUndefineParameter() NullPointerException");
}
catch (SecurityException e) {
e.printStackTrace();
throw new ServerInternalException("_checkUndefineParameter() SecurityException");
}
catch (NoSuchFieldException e) {
if (mEnumOtherParamClass != null) {
try {
mEnumOtherParamClass.getField(strKey);
}
catch (SecurityException e1) {
e1.printStackTrace();
throw new ServerInternalException("_checkUndefineParameter() NoSuchFieldException >> SecurityException");
}
catch (NoSuchFieldException e1) {
if (logger.isDebugEnabled()) {
logger.debug("==========================================");
logger.debug("不正确的参数[" + strKey + "]");
logger.debug("==========================================");
}
//throw new UndefineParameterException("未定义的参数 [" + strKey + "]");
throw new ParamException("未定义的参数 [" + strKey + "]");
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("未定义的参数[" + strKey + "]");
}
//throw new UndefineParameterException("未定义的参数 [" + strKey + "]");
throw new ParamException("未定义的参数 [" + strKey + "]");
}
}
}
}
public void checkNullParameterValue(Map mRequestMap) throws AbsException {
if(mRequestMap == null) return;
Set<String> set = mRequestMap.keySet();
Iterator<String> itr = set.iterator();
String key = null;
String[] value = null;
int count = 0, len = 0;
while (itr.hasNext()) {
key = itr.next();
value = (String[]) mRequestMap.get(key);
len = value.length;
for (count = 0; count < len; count++) {
if (value[count].length() == 0)
//throw new InvalidValueException("参数 [" + key + "] 为 NULL");
throw new ParamException("参数 [" + key + "] 为 NULL");
}
}
}
}
| true |
4f825cee00ffb5b710b374f6f16f48b45eb346e4 | Java | isibtain/WAAHotelResevationProject | /src/main/java/com/packt/webstore/domain/User.java | UTF-8 | 2,324 | 2.3125 | 2 | [] | no_license | package com.packt.webstore.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long uid;
private String userID;
@NotEmpty(message="{NotEmpty.validation}")
private String firstName;
@NotEmpty(message="{NotEmpty.validation}")
private String lastName;
@Valid
@OneToOne(cascade = CascadeType.PERSIST)
private Address address;
// @NotNull(message = "{NotNull.validation}")
// @Size(min = 4, max = 40, message="{Size.validation}")
private String userName;
// @NotNull(message = "{NotNull.validation}")
// @Size(min = 4, max = 20, message="{Size.validation}")
private String password;
public User() {}
public User(String firstName, String lastName, Address address, String userName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.userName = userName;
this.password = password;
}
public long getUid() {
return uid;
}
public void setUid(long uid) {
this.uid = uid;
}
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
| true |
10a471a7e7349af41abace066317113446449c67 | Java | PlumpMath/homework | /IST239/Week3/HandEye/NewGameListener.java | UTF-8 | 121 | 1.789063 | 2 | [] | no_license | import java.util.EventListener;
public interface NewGameListener extends EventListener {
public void newGameEvent();
}
| true |
74ecda763bb35946313c4e8561d02692b0dbd261 | Java | hanji1122/RubyChina | /app/src/main/java/com/luckyhan/rubychina/model/response/UserResponse.java | UTF-8 | 379 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | package com.luckyhan.rubychina.model.response;
import com.luckyhan.rubychina.model.Meta;
import com.luckyhan.rubychina.model.User;
public class UserResponse {
public User user;
public Meta meta;
@Override
public String toString() {
return "UserModel{" +
"user=" + user +
", meta=" + meta +
'}';
}
}
| true |
61897f97f2070da602defb1901e30b6054b705aa | Java | ConquestMC/cqmc-core | /src/main/java/com/conquestmc/core/cosmetics/EmoteCosmetic.java | UTF-8 | 232 | 2.125 | 2 | [] | no_license | package com.conquestmc.core.cosmetics;
import org.bukkit.entity.Player;
public class EmoteCosmetic implements Cosmetic {
@Override
public String getName() {
return null;
}
@Override
public void play(Player player) {
}
}
| true |
54c55b16b1803efe7c18f262b43c097b67133357 | Java | Kryspo/L2jRamsheart | /dist/gameserver/data/scripts/quests/_112_WalkOfFate.java | UTF-8 | 1,771 | 2.3125 | 2 | [
"MIT"
] | permissive | package quests;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.model.quest.Quest;
import l2f.gameserver.model.quest.QuestState;
import l2f.gameserver.scripts.ScriptFile;
public class _112_WalkOfFate extends Quest implements ScriptFile
{
//NPC
private static final int Livina = 30572;
private static final int Karuda = 32017;
//Items
private static final int EnchantD = 956;
@Override
public void onLoad()
{
}
@Override
public void onReload()
{
}
@Override
public void onShutdown()
{
}
public _112_WalkOfFate()
{
super(false);
addStartNpc(Livina);
addTalkId(Karuda);
}
@Override
public String onEvent(String event, QuestState st, NpcInstance npc)
{
String htmltext = event;
if (event.equalsIgnoreCase("karuda_q0112_0201.htm"))
{
st.addExpAndSp(112876, 5774);
st.giveItems(ADENA_ID, (long) (22308 + 6000 * (st.getRateQuestsReward() - 1)), true);
st.giveItems(EnchantD, 1, false);
st.playSound(SOUND_FINISH);
st.exitCurrentQuest(false);
}
else if (event.equalsIgnoreCase("seer_livina_q0112_0104.htm"))
{
st.setCond(1);
st.setState(STARTED);
st.playSound(SOUND_ACCEPT);
}
return htmltext;
}
@Override
public String onTalk(NpcInstance npc, QuestState st)
{
int npcId = npc.getNpcId();
String htmltext = "noquest";
int cond = st.getCond();
if (npcId == Livina)
{
if (cond == 0)
{
if (st.getPlayer().getLevel() >= 20)
htmltext = "seer_livina_q0112_0101.htm";
else
{
htmltext = "seer_livina_q0112_0103.htm";
st.exitCurrentQuest(true);
}
}
else if (cond == 1)
htmltext = "seer_livina_q0112_0105.htm";
}
else if (npcId == Karuda)
if (cond == 1)
htmltext = "karuda_q0112_0101.htm";
return htmltext;
}
}
| true |
b6a27c4455c8618ae7ebfd1504249571abbb64da | Java | TaamouliLamia/ProjetMicroService | /BillService/src/main/java/com/project/billservice/web/BillResource.java | UTF-8 | 957 | 2 | 2 | [] | no_license |
package com.project.billservice.web;
import com.project.billservice.service.BillService;
import com.project.commons.dto.BillDto;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static com.project.commons.utils.Web.API;
/**
* @author n.lamouchi
*/
@RequiredArgsConstructor
@RestController
@RequestMapping(API + "/bill")
public class BillResource {
private final BillService itemService;
@GetMapping
public List<BillDto> findAll() {
return this.itemService.findAll();
}
@GetMapping("/{id}")
public BillDto findById(@PathVariable Long id) {
return this.itemService.findById(id);
}
@PostMapping
public BillDto create(@RequestBody BillDto billDto) {
return this.itemService.create(billDto);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
this.itemService.delete(id);
}
}
| true |
b5ef68fb0452c4da224be0af2781f07c40a12376 | Java | JustTrust/news_reader | /app/src/main/java/com/belichenko/a/news/utils/NewsGenerator.java | UTF-8 | 1,516 | 2.609375 | 3 | [] | no_license | package com.belichenko.a.news.utils;
import com.belichenko.a.news.models.News;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import io.reactivex.Single;
/**
* Created by a.belichenko on 16.06.2017.
* mail: a.belichenko@gmail.com
*/
public class NewsGenerator {
@Inject
public NewsGenerator() {
}
public Single<List<News>> getListOfNewsFromServer() {
ArrayList<News> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
try {
News news = new News(i,
"News Title ".concat(String.valueOf(i)),
"text",
("Room also verifies all of your queries in Dao classes" +
" while the application is being compiled so that" +
" if there is a problem in one of the queries, you will " +
"be notified instantly").getBytes("UTF-8"));
list.add(news);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return Single.error(e);
}
}
return Single.just(list);
}
public Single<List<News>> getListOfNewsFromServerWithDelay(){
Single<List<News>> data = getListOfNewsFromServer();
return Single.zip(data, Single.timer(5, TimeUnit.SECONDS), (news, aLong) -> news);
}
}
| true |
96f9da1afbe0059cda4dca3fcb00b9e996753828 | Java | Lelis-Alves/projeto-api-resource-server | /src/main/java/com/ealves/poc/service/CategoriaService.java | UTF-8 | 1,353 | 2.40625 | 2 | [] | no_license | package com.ealves.poc.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ealves.poc.exception.EntidadeNaoEncontradaException;
import com.ealves.poc.model.Categoria;
import com.ealves.poc.repository.CategoriaRepository;
@Service
public class CategoriaService {
@PersistenceContext
private EntityManager manager;
@Autowired
private CategoriaRepository categoriaRepo;
public List<Categoria> listar() {
return categoriaRepo.findAll();
}
// -Consultar por nome....usando o like...
public List<Categoria> consultarPorNome(String nome) {
return manager.createQuery("from Categoria where nome like :nome", Categoria.class)
.setParameter("nome", "%" + nome + "%").getResultList();
}
public Categoria buscarOuFalhar(Long categoriaId) {
return categoriaRepo.findById(categoriaId).orElseThrow(() -> new EntidadeNaoEncontradaException(categoriaId));
}
public Categoria salvar(Categoria categoria) {
return categoriaRepo.save(categoria);
}
public void excluir(Long cozinhaId) {
try {
categoriaRepo.deleteById(cozinhaId);
} catch (EntidadeNaoEncontradaException e) {
throw new EntidadeNaoEncontradaException(cozinhaId);
}
}
}
| true |
c3957cd892f3f600ebdd8c2f5a180d525e1d1136 | Java | Jeimmi/SEProjectV1 | /src/GreatTemple.java | UTF-8 | 212 | 2.546875 | 3 | [] | no_license | import java.awt.image.BufferedImage;
public class GreatTemple extends Building{
BufferedImage image;
public GreatTemple(){
super(4,4,4,4);
}
public GreatTemple(BufferedImage i){
super(4,4,4,4);
}
}
| true |
a6df4b35751cfa0131292d6ec49dd48e58b1bda1 | Java | gitByCPF/JavaLearning | /src/cpf/learn/chapter17/transformation/FileReaderDiff.java | UTF-8 | 1,795 | 2.96875 | 3 | [] | no_license | package cpf.learn.chapter17.transformation;
import org.junit.jupiter.api.Test;
import sun.nio.cs.ext.GBK;
import java.io.*;
/**
* @author CPF 创建于: 2021/7/13 11:48
* @version 1.0
*/
public class FileReaderDiff{
/**
*如果仅仅使用FileReader,那么默认使用的就是UTF-8来处理读进来的字节流.
* 因此,必须使用FileReader的父类InputStreamReader来指定编码类型.
* @throws IOException
*/
@Test
public void readByDefault() throws IOException{
String path = "src/cpf/learn/chapter17/transformation/我是UTF-8编码.txt";
File gbkFile = new File(path);
FileReader fileReader = null;
try{
char[] buffer = new char[10];
int readLen;
fileReader = new FileReader(gbkFile);
while((readLen = fileReader.read(buffer)) != -1){
System.out.println(new String(buffer, 0, readLen));
}
}catch(FileNotFoundException e){
System.out.println("打开文件异常" + e);
}finally{
if(fileReader != null){
fileReader.close();
}
}
}
/**
* 使用GBK编码模式来组织读取到的字节流,自然能够正确读取GBK的文件
* @throws IOException
*/
@Test
public void readByTransform() throws IOException{
String path = "E:/IDEA_2020_2_4/IdeaProjects/hsp/src/" +
"cpf/learn/chapter17/transformation/我是GBK编码.txt";
File gbkFile = new File(path);
InputStreamReader isr = null;
try{
char[] buffer = new char[10];
int readLen;
isr = new InputStreamReader(new FileInputStream(gbkFile),new GBK());
while((readLen = isr.read(buffer)) != -1){
System.out.println(new String(buffer, 0, readLen));
}
}catch(FileNotFoundException e){
System.out.println("打开文件异常" + e);
}finally{
if(isr != null){
isr.close();
}
}
}
}
| true |
99e77dc79bedd88566c7f81b50a6bee041c1bdde | Java | whikloj/rdf-hashing-java | /src/test/java/ca/umanitoba/dam/rdfhashing/RdfHashTest.java | UTF-8 | 3,700 | 2.609375 | 3 | [
"MIT"
] | permissive | package ca.umanitoba.dam.rdfhashing;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.apache.jena.util.FileUtils.langTurtle;
import static org.apache.jena.util.FileUtils.langNTriple;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.codec.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.junit.jupiter.api.Test;
public class RdfHashTest {
@Test
public void testSuperSimple() throws Exception {
doTest("supersimple.ttl", "supersimple.txt", "http://example.org/test1", langTurtle);
}
@Test
public void testBaseGraph() throws Exception {
doTest("base_graph.ttl", "base_graph.txt", "http://example.org/test2", langTurtle);
}
@Test
public void testDoap() throws Exception {
final Model graphTurtle = getFromFile("doap.ttl", "http://example.org/test3/ttl", langTurtle);
assertNotNull(graphTurtle, "Could not get Turtle graph");
final Model graphNTriples = getFromFile("doap.nt", "http://example.org/test3/nt", langNTriple);
assertNotNull(graphNTriples, "Could not get N-Triple graph");
final String turtleHash = RdfHash.calculate(graphTurtle);
final String ntriplesHash = RdfHash.calculate(graphNTriples);
assertEquals(turtleHash, ntriplesHash, "Hashes do not match");
}
@Test
public void testLanguageTags() throws Exception {
final Model lang1 = getFromFile("language_tags1.ttl", "http://example.org/test4/ttl1", langTurtle);
final Model lang2 = getFromFile("language_tags2.ttl", "http://example.org/test4/ttl2", langTurtle);
final Model lang3 = getFromFile("language_tags3.ttl", "http://example.org/test4/ttl3", langTurtle);
assertNotNull(lang1);
assertNotNull(lang2);
assertNotNull(lang3);
final String hash1 = RdfHash.calculate(lang1);
final String hash2 = RdfHash.calculate(lang2);
final String hash3 = RdfHash.calculate(lang3);
assertEquals(hash1, hash2);
assertEquals(hash1, hash3);
}
/**
* Test runner
*
* @param source name of the source rdf file.
* @param expected name of the final string file.
* @param baseUri baseUri of the source rdf.
* @param format format name of the rdf.
* @throws IOException on error opening stream.
*/
private void doTest(final String source, final String expected, final String baseUri, final String format)
throws IOException {
final Model originalGraph = getFromFile(source, baseUri, format);
assertNotNull(originalGraph);
final String graphString = RdfHash.getGraphString(originalGraph);
final String expectedString = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(
expected),
Charsets.UTF_8.toString());
assertEquals(expectedString, graphString, "Graph String does not match expected");
}
/**
* Load Jena model from a file
*
* @param rdfFile the name of the source file.
* @param baseUri the base uri of the rdf
* @param format the format name of the rdf
* @return the Jena Model
*/
private Model getFromFile(final String rdfFile, final String baseUri, final String format) {
final InputStream graphStream = this.getClass().getClassLoader().getResourceAsStream(rdfFile);
final Model graph = ModelFactory.createDefaultModel();
graph.read(graphStream, baseUri, format);
return graph;
}
}
| true |
18ee542d419f99c68817194a32b935a6ba47c2a8 | Java | stupidcupid/algorithm | /src/main/java/com/datastructure/recursion/binarysearch/BinarySearchApp.java | UTF-8 | 1,242 | 3.65625 | 4 | [] | no_license | package com.datastructure.recursion.binarysearch;
/**
* Created by nanzhou on 2017/7/31.
*/
public class BinarySearchApp {
/**
* 递归 二分法
* @param args
*/
public static void main(String[] args) {
long[] arr = new long[]{1, 2, 4, 6, 8, 10, 12};
System.out.println(reFind(1, 0, arr.length, arr));
System.out.println(reFind(2, 0, arr.length, arr));
System.out.println(reFind(4, 0, arr.length, arr));
System.out.println(reFind(6, 0, arr.length, arr));
System.out.println(reFind(8, 0, arr.length, arr));
System.out.println(reFind(10, 0, arr.length, arr));
System.out.println(reFind(12, 0, arr.length, arr));
}
private static int reFind(long searchKey, int lowerBound, int upperBound, long[] arr) {
int curIn = (lowerBound + upperBound) / 2;
if (arr[curIn] == searchKey)
return curIn;
else if (lowerBound > upperBound)
return arr.length;
else {
if (arr[curIn] < searchKey)
return reFind(searchKey, curIn + 1, upperBound, arr);
else {
return reFind(searchKey, lowerBound, curIn - 1, arr);
}
}
}
}
| true |
18b5acedbb7783e62397216eddde8362c3818502 | Java | vintop95/dp2-RnsSystem | /src/it/polito/dp2/RNS/sol3/rnsClient/RnsClient.java | UTF-8 | 10,870 | 2.0625 | 2 | [] | no_license | package it.polito.dp2.RNS.sol3.rnsClient;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.util.JAXBSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
import it.polito.dp2.RNS.lab3.EntranceRefusedException;
import it.polito.dp2.RNS.lab3.ServiceException;
import it.polito.dp2.RNS.lab3.UnknownPlaceException;
import it.polito.dp2.RNS.lab3.WrongPlaceException;
import it.polito.dp2.RNS.sol3.jaxb.Connection;
import it.polito.dp2.RNS.sol3.jaxb.ErrorBody;
import it.polito.dp2.RNS.sol3.jaxb.Place;
import it.polito.dp2.RNS.sol3.jaxb.RnsErrorType;
import it.polito.dp2.RNS.sol3.jaxb.RnsRootResponse;
import it.polito.dp2.RNS.sol3.jaxb.Vehicle;
import it.polito.dp2.RNS.sol3.rnsClient.RnsClientException;
public class RnsClient {
Client client;
WebTarget baseTarget;
JAXBContext jc;
javax.xml.validation.Validator validator;
RnsRootResponse rnsRootResponse;
MediaType mediaType;
String authToken;
final String xsdFile = "xsd/RnsSystem.xsd";
final String jaxbPackage = "it.polito.dp2.RNS.sol3.jaxb";
////////////////////////////////////////////////////////////////////////
public RnsClient(MediaType mediaType, String authToken)
throws RnsClientException
{
initWebClasses();
if(mediaType == null)
this.mediaType = MediaType.APPLICATION_XML_TYPE;
this.mediaType = mediaType;
this.authToken = authToken;
}
private static URI getBaseURI() {
String uri = System.getProperty("it.polito.dp2.RNS.lab3.URL");
if(uri == null){
uri = "http://localhost:8080/RnsSystem/rest";
}
return UriBuilder.fromUri(uri).build();
}
public WebTarget getBaseTarget(){
return baseTarget;
}
private void initWebClasses() throws RnsClientException{
try{
// Build the JAX-RS client object and get the
// target to the base URI
client = ClientBuilder.newClient();
baseTarget = client.target(getBaseURI());
// Create validator that uses the schema
SchemaFactory sf =
SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema;
schema = sf.newSchema(new File(xsdFile));
validator = schema.newValidator();
// validator.setErrorHandler(new MyErrorHandler());
// Create JAXB context related to the classes generated
jc = JAXBContext.newInstance(jaxbPackage);
}catch(SAXException e){
throw new RnsClientException(e);
}catch(JAXBException e){
throw new RnsClientException(e);
}
}
private String getAuthToken(){
if(this.authToken == null)
return "";
return this.authToken;
}
public void setAuthToken(String authToken){
this.authToken = authToken;
}
public WebTarget buildTarget(String url){
return client.target(url);
}
////////////////////////////////////////////////////////////////////////////
/**
* It validates any kind of JAXB-Class element against the schema
* defined in the JAXBContext
* USELESS if interceptor/provider validator is registered
*/
private <T> void validateElement(T element) throws ServiceException{
//System.out.println("> Validating " + element.toString());
try {
JAXBSource jaxbsource = new JAXBSource(jc, element);
validator.validate(jaxbsource);
// System.out.println("+ Validation OK");
} catch (org.xml.sax.SAXException se) {
System.err.println("- Validation Failed. Details:");
Throwable t = se;
while (t != null) {
String message = t.getMessage();
if (message != null)
System.err.println(message);
t = t.getCause();
}
throw new ServiceException("Validation Failed", se);
} catch (IOException e) {
throw new ServiceException("Unexpected I/O Exception", e);
} catch (JAXBException e) {
throw new ServiceException("Unexpected JAXB Esception", e);
}
}
////////////////////////////////////////////////////////////////////////////
/**
* It sends a GET request to the connectionTarget and we pass
* the type of the postResponse with the second parameter
*/
public <U> U getRequest(WebTarget connectionTarget, Class<U> c)
throws ServiceException
{
U res = getRequestWithNull(connectionTarget,c);
if(res == null){
throw new ServiceException("404");
}
return res;
}
public <U> U getRequestWithNull(
WebTarget connectionTarget, Class<U> c)
throws ServiceException
{
Response response = connectionTarget
.queryParam("authToken", authToken)
.request()
.accept(mediaType)
.get();
if (response.getStatus() == 404) {
return null;
}
else if (response.getStatus() != 200) {
String errorMsg = "Error in remote operation: " +
response.getStatus() + " " + response.getStatusInfo();
System.err.println(errorMsg);
throw new ServiceException(errorMsg);
}
U bodyResponse = response.readEntity(c);
validateElement(bodyResponse);
return bodyResponse;
}
public <T> String getLocationFromRoot(Class<T> c)
throws ServiceException
{
if(rnsRootResponse == null){
rnsRootResponse =
getRequest(baseTarget.path("rns"), RnsRootResponse.class);
}
String location;
if(Vehicle.class.equals(c)){
location = rnsRootResponse.getVehicles();
}else if(Place.class.equals(c)){
location = rnsRootResponse.getPlaces();
}else if(Connection.class.equals(c)){
location = rnsRootResponse.getConnections();
}else{
throw new ServiceException("Class not available");
}
if(location == null || location.isEmpty()){
rnsRootResponse = null;
throw new ServiceException("Cannot read from service root.");
}else{
return location;
}
}
/////////////////////////////////////////////////////////////////////////////
/**
* It sends a post request to the connectionTarget with a
* body of type T (postRequest) and we pass the type of
* the postResponse with the third parameter
*/
public <T,U> U postVehicleRequest(WebTarget connectionTarget,
T postRequest, Class<U> c) throws EntranceRefusedException,
UnknownPlaceException, WrongPlaceException, ServiceException
{
Response response = connectionTarget
//useless but in future maybe not
.queryParam("authToken", getAuthToken())
.request(mediaType)
.accept(mediaType)
.post(Entity.xml(postRequest));
if (response.getStatus() == 403) {
String errorMsg = "Entrance refused: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new EntranceRefusedException(errorMsg);
}else if (response.getStatus() == 409){
ErrorBody err = response.readEntity(ErrorBody.class);
if(err.getError() == null){
throw new ServiceException();
}
String errorMsg;
if(err.getError().equals(RnsErrorType.UNKNOWN_PLACE)){
errorMsg = "Unknown origin/destination: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new UnknownPlaceException(errorMsg);
}else if(err.getError().equals(RnsErrorType.WRONG_PLACE)){
errorMsg = "Wrong input gate: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new WrongPlaceException(errorMsg);
}
}else if(response.getStatus() != 201){
String errorMsg = "Error in remote operation: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new ServiceException(errorMsg);
}
U bodyResponse = response.readEntity(c);
validateElement(bodyResponse);
return bodyResponse;
}
/**
* It sends a post request to the connectionTarget with a body of type T
* (postRequest) and we pass the type of the postResponse with the third parameter
*/
public <T,U> U putVehicleRequest(WebTarget connectionTarget,
T putRequest, Class<U> c) throws
UnknownPlaceException, WrongPlaceException, ServiceException
{
Response response = connectionTarget
.queryParam("authToken", getAuthToken())
.request(mediaType)
.accept(mediaType)
.put(Entity.xml(putRequest));
if (response.getStatus() == 204){
return null;
}
else if (response.getStatus() == 409){
ErrorBody err = response.readEntity(ErrorBody.class);
if(err.getError() == null){
throw new ServiceException();
}
String errorMsg;
if(err.getError().equals(RnsErrorType.UNKNOWN_PLACE)){
errorMsg = "Unknown place: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new UnknownPlaceException(errorMsg);
}else if(err.getError().equals(RnsErrorType.WRONG_PLACE)){
errorMsg = "Wrong place: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new WrongPlaceException(errorMsg);
}
}else if(response.getStatus() != 200){
String errorMsg = "Error in remote operation: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new ServiceException(errorMsg);
}
U bodyResponse = response.readEntity(c);
validateElement(bodyResponse);
return bodyResponse;
}
/**
* It sends a delete request to the connectionTarget
*/
public void deleteVehicleRequest(
WebTarget target, String outGateId) throws
UnknownPlaceException, WrongPlaceException, ServiceException
{
Response response = target
.queryParam("authToken", getAuthToken())
.queryParam("outGateId", outGateId)
.request()
.delete();
if (response.getStatus() == 409){
ErrorBody err = response.readEntity(ErrorBody.class);
if(err.getError() == null){
throw new ServiceException();
}
String errorMsg;
if(err.getError().equals(RnsErrorType.UNKNOWN_PLACE)){
errorMsg = "Unknown place: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new UnknownPlaceException(errorMsg);
}else if(err.getError().equals(RnsErrorType.WRONG_PLACE)){
errorMsg = "Wrong place: " +
response.getStatus() + " " + response.getStatusInfo();
System.out.println(errorMsg);
throw new WrongPlaceException(errorMsg);
}
}else if (response.getStatus() != 204) {
String errorMsg = "Error in remote operation: "+
response.getStatus() + " " + response.getStatusInfo();
System.err.println(errorMsg);
throw new ServiceException(errorMsg);
}
}
////////////////////////////////////////////////////////////////////////////
}
| true |
e9c09a8ee94baaedd5ea989761bc6ba7de5bb9e1 | Java | Team3374/Hobbs-2017 | /src/org/usfirst/frc/team3374/robot/commands/VisionGuidedCommandGroup.java | UTF-8 | 884 | 2.15625 | 2 | [
"MIT"
] | permissive | /* */ package org.usfirst.frc.team3374.robot.commands;
/* */
/* */ import edu.wpi.first.wpilibj.command.CommandGroup;
/* */ import org.usfirst.frc.team3374.robot.RobotMap;
/* */
/* */ public class VisionGuidedCommandGroup extends CommandGroup
/* */ {
/* */ public VisionGuidedCommandGroup()
/* */ {
/* 10 */ addSequential(new GearMoverCommand(1.5D, RobotMap.centergear));
/* 11 */ addSequential(new VisionGuidedCommand(10.0D));
/* 12 */ addSequential(new GearMoverCommand(1.0D, RobotMap.topgear));
/* 13 */ addSequential(new DriveForwardCommand(0.4D, 0.6D));
/* 14 */ addSequential(new GearWhackCommand(1.0D, RobotMap.placegear));
/* */
/* 16 */ addSequential(new GearMoverCommand(0.5D, RobotMap.topgear));
/* 17 */ addSequential(new DriveForwardCommand(0.75D, -0.4D));
/* */ }
/* */ }
| true |
e62105851d8244bf8fa3583b38870419175c79d4 | Java | upswp/Algorithm | /src/algorithm_gold/BOJ3190_뱀2.java | UTF-8 | 2,302 | 3.265625 | 3 | [] | no_license | package algorithm_gold;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class BOJ3190_뱀2 {
static class Snake{ // 뱀 위치
int r;
int c;
public Snake() {}
public Snake(int r, int c) {
super();
this.r = r;
this.c = c;
}
}
static class Turn{ // 방향 D = 1 L = 3
int time;
int dir;
public Turn() {}
public Turn(int time, int dir) {
super();
this.time = time;
this.dir = dir;
}
}
static int cnt;
static int N,K,L;
static int map[][];
static ArrayList<Snake> snakes = new ArrayList<>();
static ArrayList<Turn> turns = new ArrayList<>();
static int [] dr = {0,1,0,-1};
static int [] dc = {1,0,-1,0};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
K = sc.nextInt();
//테두리 때문에 +2
map = new int [N+2][N+2];
for (int i = 0; i < N+2; i++) {
Arrays.fill(map[i],2);
}
for (int i = 1; i < N+1; i++) {
for (int j = 1; j < N+1; j++) {
map[i][j] = 0;
}
}
for (int i = 0; i < K; i++) {
int r = sc.nextInt();
int c = sc.nextInt();
map[r][c] = 1; // 사과는 1
}
L = sc.nextInt();
for (int i = 0; i < L; i++) {
int x = sc.nextInt();
char cdir = sc.next().charAt(0);
int dir = cdir=='D'?1:3;
turns.add(new Turn(x,dir));
}
cnt = 0;
solve(1,1,0);
System.out.println(cnt);
}
static void solve(int cr, int cc, int cdir) {
snakes.add(new Snake(cr,cc));
int turn = 0;
for (int i = 1; i < 10000; i++) {
cnt++;
int nr = cr + dr[cdir];
int nc = cc+ dc[cdir];
if (isFinish(nr, nc)) return;
if(map[nr][nc] == 1) {
map[nr][nc] = 0;
snakes.add(new Snake(nr,nc));
}else {
snakes.add(new Snake(nr,nc));
snakes.remove(0);
}
cr = nr;
cc = nc;
if (turn < L) {
if (cnt == turns.get(turn).time) {
//방향바꾸기.
cdir = (cdir + turns.get(turn).dir) % 4;
turn++;
}
}
}
}
public static boolean isFinish(int r, int c) {
if(!isIn(r,c)) return true;
for (int i = 0; i < snakes.size(); i++) {
Snake snake = snakes.get(i);
if (snake.r == r && snake.c == c) return true;
}
return false;
}
public static boolean isIn(int r, int c) {
return r>=1 && r<=N && c>=1 && c<=N;
}
} | true |
fe354e4599f10812c48e62a8d32d9d7889e83400 | Java | Rostanxd/ProyectoRFID | /BBRFIDSampleBT_New/src/main/java/co/kr/bluebird/newrfid/app/bbrfidbtdemo/entity/ReplenishmentWareResult.java | UTF-8 | 2,324 | 2.078125 | 2 | [] | no_license | package co.kr.bluebird.newrfid.app.bbrfidbtdemo.entity;
import java.util.List;
public class ReplenishmentWareResult {
public int id;
public String items;
public String replenishmentCount;
public String sales;
public String expenses;
public String residueWarehouse;
public String residueExtern;
public List<ResidueExternDetail> residueExternDetails;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItems() {
return items;
}
public void setItems(String items) {
this.items = items;
}
public String getReplenishmentCount() {
return replenishmentCount;
}
public void setReplenishmentCount(String replenishmentCount) {
this.replenishmentCount = replenishmentCount;
}
public String getSales() {
return sales;
}
public void setSales(String sales) {
this.sales = sales;
}
public String getExpenses() {
return expenses;
}
public void setExpenses(String expenses) {
this.expenses = expenses;
}
public String getResidueWarehouse() {
return residueWarehouse;
}
public void setResidueWarehouse(String residueWarehouse) {
this.residueWarehouse = residueWarehouse;
}
public String getResidueExtern() {
return residueExtern;
}
public void setResidueExtern(String residueExtern) {
this.residueExtern = residueExtern;
}
public List<ResidueExternDetail> getResidueExternDetails() {
return residueExternDetails;
}
public void setResidueExternDetails(List<ResidueExternDetail> residueExternDetails) {
this.residueExternDetails = residueExternDetails;
}
public ReplenishmentWareResult(int id, String items, String replenishmentCount, String sales, String expenses, String residueWarehouse, String residueExtern, List<ResidueExternDetail> residueExternDetails) {
this.id = id;
this.items = items;
this.replenishmentCount = replenishmentCount;
this.sales = sales;
this.expenses = expenses;
this.residueWarehouse = residueWarehouse;
this.residueExtern = residueExtern;
this.residueExternDetails = residueExternDetails;
}
}
| true |
7ff67721a61a76fb465ed6ddbddd2ccbfa9bdd00 | Java | underminethesystem/Kugelspiel | /app/src/main/java/com/example/jules/kugelspiel/Tile.java | UTF-8 | 1,559 | 2.953125 | 3 | [] | no_license | package com.example.jules.kugelspiel;
import android.graphics.Color;
import android.util.Log;
/**
* Created by User on 27.10.2016.
*/
public class Tile {
public static final int COLOR_WALL = Color.rgb(30,30,10) ;
public static final int COLOR_FLOOR = Color.rgb(0,111,111);
public static final int COLOR_START = Color.GRAY;
public static final int COLOR_GOAL = Color.RED;
public static final int COLOR_LAVA = Color.rgb(200,50,50);
public enum TileType{Floor,Wall,Start,Goal,Lava};
public Tile(Tile.TileType t){
type=t;
if(t==TileType.Wall)
isWalkable = false;
else
isWalkable= true;
}
public TileType type;
public boolean isWalkable;
public void toggle(){
switch(type){
case Floor: type=TileType.Wall;
break;
case Wall:type=TileType.Lava;
break;
case Start:
break;
case Goal:
break;
case Lava: type=TileType.Floor;
break;
default:
Log.v("error","invalid type");
break;
}
}
public int getColor(){
switch (type){
case Floor: return COLOR_FLOOR ;
case Wall: return COLOR_WALL ;
case Start: return COLOR_START ;
case Goal: return COLOR_GOAL ;
case Lava: return COLOR_LAVA ;
default: System.out.print("Invalid Tiletype");
return COLOR_FLOOR;
}
}
}
| true |
fb688205642820264bf47d06b776f1428b1e31b5 | Java | vyshnaviyalamareddy/BearcatMarketplace | /BearcatMarketplace/app/src/main/java/com/example/s531372/bearcatmarketplace/FirstActivity.java | UTF-8 | 2,756 | 2.03125 | 2 | [] | no_license | package com.example.s531372.bearcatmarketplace;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.Parse;
import com.parse.ParseInstallation;
public class FirstActivity extends AppCompatActivity {
TextView signup;
EditText userNameET,passwordET;
public static DataBaseUtils m_dataBaseUtils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
m_dataBaseUtils = new DataBaseUtils(FirstActivity.this);
signup = (TextView) findViewById(R.id.signupTV);
userNameET = findViewById(R.id.userNameET);
passwordET = findViewById(R.id.passwordET);
signup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent init = new Intent(FirstActivity.this, SignupActivity.class);
startActivity(init);
}
});
// Parse.initialize(new Parse.Configuration.Builder(this)
// .applicationId(getString(R.string.back4app_app_id))
// // if defined
// .clientKey(getString(R.string.back4app_client_key))
// .server(getString(R.string.back4app_server_url))
// .build()
// );
// ParseInstallation.getCurrentInstallation().saveInBackground();
}
public void loginFn(View v){
String userName=userNameET.getText().toString().trim();
String passWord=passwordET.getText().toString().trim();
if(TextUtils.isEmpty(userName)){
//Toast.makeText(FirstActivity.this, "Email cannot be empty", Toast.LENGTH_SHORT).show();
Utils.setAlert("UserName/Email cannot be empty",FirstActivity.this);
return;
}
if(TextUtils.isEmpty(passWord)){
// Toast.makeText(Signup.this, "Password cannot be empty", Toast.LENGTH_SHORT).show();
Utils.setAlert("Password cannot be empty",FirstActivity.this);
return;
}
if (m_dataBaseUtils.getUserPasswordDetails(userName).equalsIgnoreCase(passWord)) {
FilterActivity.selectedItems= new boolean[]{false, false, false, false, false};
Intent init = new Intent(this, TopPickUpsActivity.class);
init.putExtra("from","First");
startActivity(init);
}else
{
Utils.setAlert("UserName and password are not matched",FirstActivity.this);
}
}
}
| true |
af8a84b6b60a2e3d4965eb6b73ab65eb7811ab7c | Java | peishanwang/pdp-Individual | /Assignment4/src/main/java/edu/neu/ccs/cs5010/ICandyContainer.java | UTF-8 | 223 | 2.4375 | 2 | [] | no_license | package edu.neu.ccs.cs5010;
import java.util.List;
/**
* Interface of CandyContainer.
*/
public interface ICandyContainer {
/**
* Returns candy list.
* @return candy list.
*/
List<ICandy> getCandyList();
}
| true |
138cd47d38a4a46bac44e864887648f8f849e761 | Java | alibaydev/test-sado-orders2 | /src/main/java/edu/sado/DocumentNumber.java | UTF-8 | 3,233 | 2.34375 | 2 | [] | no_license |
package edu.sado;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for documentNumber complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="documentNumber">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="number" type="{http://www.w3.org/2001/XMLSchema}token" minOccurs="0"/>
* <element name="date" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* <element name="RegistratorDepartment" type="{http://www.infpres.com/IEDMS}qualifiedValue" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "documentNumber", namespace = "http://www.infpres.com/IEDMS", propOrder = {
"number",
"date",
"registratorDepartment"
})
public class DocumentNumber {
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "token")
protected String number;
@XmlElementRef(name = "date", namespace = "http://www.infpres.com/IEDMS", type = JAXBElement.class, required = false)
protected JAXBElement<XMLGregorianCalendar> date;
@XmlElement(name = "RegistratorDepartment")
protected QualifiedValue registratorDepartment;
/**
* Gets the value of the number property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNumber() {
return number;
}
/**
* Sets the value of the number property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNumber(String value) {
this.number = value;
}
/**
* Gets the value of the date property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >}
*
*/
public JAXBElement<XMLGregorianCalendar> getDate() {
return date;
}
/**
* Sets the value of the date property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >}
*
*/
public void setDate(JAXBElement<XMLGregorianCalendar> value) {
this.date = value;
}
/**
* Gets the value of the registratorDepartment property.
*
* @return
* possible object is
* {@link QualifiedValue }
*
*/
public QualifiedValue getRegistratorDepartment() {
return registratorDepartment;
}
/**
* Sets the value of the registratorDepartment property.
*
* @param value
* allowed object is
* {@link QualifiedValue }
*
*/
public void setRegistratorDepartment(QualifiedValue value) {
this.registratorDepartment = value;
}
}
| true |
5859c23c277469bd333073d961429f83acc0bfe2 | Java | dreajay/jcode-filequeue | /src/main/java/com/jcode/filequeue/serializer/JDKSerializer.java | UTF-8 | 1,747 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /**
*
*/
package com.jcode.filequeue.serializer;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.jcode.filequeue.exception.SerializationException;
/**
* @Desc
*
* @Author daijunjie
* @DateTime 2016年6月12日 下午6:16:39
*
*/
public class JDKSerializer implements QueueSerializer<Object> {
public JDKSerializer() {
}
public byte[] serialize(Object obj) throws SerializationException {
ByteArrayOutputStream os = null;
ObjectOutputStream oos = null;
try {
os = new ByteArrayOutputStream();
oos = new ObjectOutputStream(os);
oos.writeObject(obj);
byte[] data = os.toByteArray();
return data;
} catch (IOException e) {
throw new SerializationException(e.getMessage(), e);
} finally {
if (os != null) {
try {
os.close();
os = null;
} catch (IOException e) {
}
}
if (oos != null) {
try {
oos.close();
oos = null;
} catch (IOException e) {
}
}
}
}
public Object deserialize(byte[] data) throws SerializationException {
ByteArrayInputStream os = null;
ObjectInputStream ois = null;
try {
os = new ByteArrayInputStream(data);
ois = new ObjectInputStream(os);
Object obj = ois.readObject();
return obj;
} catch (Exception e) {
throw new SerializationException(e.getMessage(), e);
} finally {
if (ois != null) {
try {
ois.close();
ois = null;
} catch (IOException e) {
}
}
if (os != null) {
try {
os.close();
os = null;
} catch (IOException e) {
}
}
}
}
public static JDKSerializer build() {
return new JDKSerializer();
}
} | true |
380610443f928fdd501e88b3abea2e436190fe52 | Java | apache/tuscany-sca-2.x | /modules/sca-api/src/main/java/org/oasisopen/sca/annotation/OneWay.java | UTF-8 | 673 | 1.976563 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"W3C-19980720",
"BSD-3-Clause",
"W3C",
"MIT"
] | permissive | /*
* Copyright(C) OASIS(R) 2005,2010. All Rights Reserved.
* OASIS trademark, IPR and other policies apply.
*/
package org.oasisopen.sca.annotation;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The @OneWay annotation is used on a Java interface or class method
* to indicate that invocations will be dispatched in a non-blocking
* fashion as described in the section on Asynchronous Programming.
*
* The @OneWay annotation has no attributes.
*/
@Target(METHOD)
@Retention(RUNTIME)
public @interface OneWay {
}
| true |
5c7c50f25809a686128d18a8789ab5f5bf21978e | Java | manishabshelke/WebDriverMaven | /src/test/java/testcases/LoginTest.java | UTF-8 | 1,086 | 1.984375 | 2 | [] | no_license | package testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class LoginTest {
public static WebDriver driver;
@BeforeSuite
public void setUp() {
WebDriverManager.firefoxdriver().setup();
driver=new FirefoxDriver();
}
@Test
public void doLogin() {
driver.get("http://gmail.com");
//WebDriverWait wait=new WebDriverWait(driver, 20);
System.out.println(driver.getTitle());
driver.findElement(By.id("identifierId")).sendKeys("manaliprafullpihu@gmail.com");
driver.findElement(By.xpath("//*[@id='identifierNext']/span")).click();
//driver.findElement(By.name("password")).sendKeys("9096366517");
//driver.findElement(By.xpath("//*[@id='passwordNext']/span/span")).click();
}
@AfterSuite
public void tearDown() {
driver.close();
System.out.println("Quitting Evarything !!!");
}
} | true |
da89aabeaf1d60bf3c36b3239468356cd877cc83 | Java | JonathanJR/Integracion_Cafe_DSL | /Cafe/src/cafe/ContextEnricher.java | UTF-8 | 3,635 | 2.515625 | 3 | [] | no_license | package cafe;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ContextEnricher {
Slot entryConector, entryReplicator, outEnricher;
public ContextEnricher(Slot entryConector, Slot entryReplicator, Slot outEnricher) {
this.entryConector = entryConector;
this.entryReplicator = entryReplicator;
this.outEnricher = outEnricher;
}
public void doWork() throws ParserConfigurationException, XPathExpressionException {
System.out.println("\n----------- Soy el ContextEnricher y comienzo a leer documentos que me manda el Correlator por mis dos Slots de entrada -----------");
if (entryConector.getBuffer().size() == entryReplicator.getBuffer().size()) {
while (!entryConector.getBuffer().isEmpty() && !entryReplicator.getBuffer().isEmpty()) {
Document docConector = entryConector.read();
Document docReplicator = entryReplicator.read();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document docService = builder.newDocument();
XPath xPath = XPathFactory.newInstance().newXPath();
String expressionReplicator = "/drink";
String expressionConector = "/service";
NodeList nodeListConector = (NodeList) xPath.compile(expressionConector).evaluate(docConector, XPathConstants.NODESET);
NodeList nodeListReplicator = (NodeList) xPath.compile(expressionReplicator).evaluate(docReplicator, XPathConstants.NODESET);
Node nNodeConector = nodeListConector.item(0);
Node nNodeReplicator = nodeListReplicator.item(0);
if (nNodeConector.getNodeType() == Node.ELEMENT_NODE && nNodeReplicator.getNodeType() == Node.ELEMENT_NODE) {
Element eElementConector = (Element) nNodeConector;
Element eElementReplicator = (Element) nNodeReplicator;
String tipo = eElementReplicator.getElementsByTagName("type").item(0).getTextContent();
String nombre = eElementConector.getElementsByTagName("name").item(0).getTextContent();
String stoc = eElementConector.getElementsByTagName("stock").item(0).getTextContent();
Element service = docService.createElement("service");
Element name = docService.createElement("name");
Element type = docService.createElement("type");
Element stock = docService.createElement("stock");
name.setTextContent(nombre);
type.setTextContent(tipo);
stock.setTextContent(stoc);
System.out.println("Estoy en el enricher añadiendo bebida: " + nombre + " " + tipo + ", Stock: " + stoc);
docService.appendChild(service);
service.appendChild(name);
service.appendChild(type);
service.appendChild(stock);
}
outEnricher.write(docService);
}
}
}
}
| true |
419fddbc2ede996fc212eea767a0d65163d170e8 | Java | norteksoft/iMatrix-v6.5.RC2 | /src/main/java/com/norteksoft/product/web/wf/impl/WorkflowAction.java | UTF-8 | 1,075 | 2.046875 | 2 | [] | no_license | package com.norteksoft.product.web.wf.impl;
import com.norteksoft.wf.engine.client.FormFlowable;
/**
* 工作流Action接口
* @author qiao
* @param <T>
*/
public interface WorkflowAction<T extends FormFlowable> {
/**
* 启动并提交流程
* @return
* @throws Exception
*/
public String submitProcess();
/**
* 完成任务
* @return
* @throws Exception
*/
public String completeTask();
/**
* 完成交互任务:用于选人、选环节、填意见
* @return
*/
public String completeInteractiveTask();
/**
* 取回任务
* @return
* @throws Exception
*/
public String retrieveTask();
/**
* 减签
* @return
*/
public String removeSigner();
/**
* 加签
* @return
*/
public String addSigner();
/**
* 显示流转历史
* @return
*/
public String showHistory();
/**
* 填写意见
* @return
*/
public String fillOpinion();
/**
* 流程监控中应急处理功能
*/
public String processEmergency();
/**
* 领取任务
* @return
*/
public String drawTask();
}
| true |
6494e7480ab1e636d42a310d689f0ec0427d46ff | Java | prem1982/Lockh | /Java_Projects/FASeSOA/Order.Services/src/generated/gov/gsa/fas/orderdiscrepancy/v1/Reshipment.java | UTF-8 | 9,289 | 1.765625 | 2 | [] | no_license |
package gov.gsa.fas.orderdiscrepancy.v1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Reshipment complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Reshipment">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="discrepancyKey" type="{http://www.w3.org/2001/XMLSchema}long"/>
* <element name="resubmitFlag" type="{http://www.w3.org/2001/XMLSchema}short"/>
* <element name="docIdentifierExtension" type="{http://fas.gsa.gov/Global/v1.0}string1"/>
* <element name="routingIdentifierCode" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="mediaStatus" type="{http://fas.gsa.gov/Global/v1.0}string1"/>
* <element name="discrepancyItem" type="{http://fas.gsa.gov/OrderDiscrepancy/v1.0}DiscrepancyItem"/>
* <element name="supplementAddrAAC" type="{http://fas.gsa.gov/Global/v1.0}string6"/>
* <element name="orderCodes" type="{http://fas.gsa.gov/OrderDiscrepancy/v1.0}WdcOrderCodes"/>
* <element name="requiredDeliveryDate" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="adviceCode" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="transportDispositionCode" type="{http://fas.gsa.gov/Global/v1.0}string2"/>
* <element name="createdUserCode" type="{http://fas.gsa.gov/Global/v1.0}string2"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Reshipment", propOrder = {
"discrepancyKey",
"resubmitFlag",
"docIdentifierExtension",
"routingIdentifierCode",
"mediaStatus",
"discrepancyItem",
"supplementAddrAAC",
"orderCodes",
"requiredDeliveryDate",
"adviceCode",
"transportDispositionCode",
"createdUserCode"
})
public class Reshipment {
protected long discrepancyKey;
protected short resubmitFlag;
@XmlElement(required = true)
protected String docIdentifierExtension;
@XmlElement(required = true)
protected String routingIdentifierCode;
@XmlElement(required = true)
protected String mediaStatus;
@XmlElement(required = true)
protected DiscrepancyItem discrepancyItem;
@XmlElement(required = true, nillable = true)
protected String supplementAddrAAC;
@XmlElement(required = true)
protected WdcOrderCodes orderCodes;
@XmlElement(required = true)
protected String requiredDeliveryDate;
@XmlElement(required = true)
protected String adviceCode;
@XmlElement(required = true)
protected String transportDispositionCode;
@XmlElement(required = true)
protected String createdUserCode;
/**
* Gets the value of the discrepancyKey property.
*
*/
public long getDiscrepancyKey() {
return discrepancyKey;
}
/**
* Sets the value of the discrepancyKey property.
*
*/
public void setDiscrepancyKey(long value) {
this.discrepancyKey = value;
}
/**
* Gets the value of the resubmitFlag property.
*
*/
public short getResubmitFlag() {
return resubmitFlag;
}
/**
* Sets the value of the resubmitFlag property.
*
*/
public void setResubmitFlag(short value) {
this.resubmitFlag = value;
}
/**
* Gets the value of the docIdentifierExtension property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDocIdentifierExtension() {
return docIdentifierExtension;
}
/**
* Sets the value of the docIdentifierExtension property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDocIdentifierExtension(String value) {
this.docIdentifierExtension = value;
}
/**
* Gets the value of the routingIdentifierCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRoutingIdentifierCode() {
return routingIdentifierCode;
}
/**
* Sets the value of the routingIdentifierCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRoutingIdentifierCode(String value) {
this.routingIdentifierCode = value;
}
/**
* Gets the value of the mediaStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMediaStatus() {
return mediaStatus;
}
/**
* Sets the value of the mediaStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMediaStatus(String value) {
this.mediaStatus = value;
}
/**
* Gets the value of the discrepancyItem property.
*
* @return
* possible object is
* {@link DiscrepancyItem }
*
*/
public DiscrepancyItem getDiscrepancyItem() {
return discrepancyItem;
}
/**
* Sets the value of the discrepancyItem property.
*
* @param value
* allowed object is
* {@link DiscrepancyItem }
*
*/
public void setDiscrepancyItem(DiscrepancyItem value) {
this.discrepancyItem = value;
}
/**
* Gets the value of the supplementAddrAAC property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSupplementAddrAAC() {
return supplementAddrAAC;
}
/**
* Sets the value of the supplementAddrAAC property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSupplementAddrAAC(String value) {
this.supplementAddrAAC = value;
}
/**
* Gets the value of the orderCodes property.
*
* @return
* possible object is
* {@link WdcOrderCodes }
*
*/
public WdcOrderCodes getOrderCodes() {
return orderCodes;
}
/**
* Sets the value of the orderCodes property.
*
* @param value
* allowed object is
* {@link WdcOrderCodes }
*
*/
public void setOrderCodes(WdcOrderCodes value) {
this.orderCodes = value;
}
/**
* Gets the value of the requiredDeliveryDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequiredDeliveryDate() {
return requiredDeliveryDate;
}
/**
* Sets the value of the requiredDeliveryDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequiredDeliveryDate(String value) {
this.requiredDeliveryDate = value;
}
/**
* Gets the value of the adviceCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAdviceCode() {
return adviceCode;
}
/**
* Sets the value of the adviceCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAdviceCode(String value) {
this.adviceCode = value;
}
/**
* Gets the value of the transportDispositionCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportDispositionCode() {
return transportDispositionCode;
}
/**
* Sets the value of the transportDispositionCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportDispositionCode(String value) {
this.transportDispositionCode = value;
}
/**
* Gets the value of the createdUserCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCreatedUserCode() {
return createdUserCode;
}
/**
* Sets the value of the createdUserCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreatedUserCode(String value) {
this.createdUserCode = value;
}
}
| true |
d7e2638881b3e954955fdebd755b41a384107dd9 | Java | jaypatel8110/DataStructure_Practice | /stack/RecursionStack.java | UTF-8 | 1,195 | 3.640625 | 4 | [] | 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 com.jay.stack;
import java.util.Stack;
/**
*
* @author JAY PATEL
*/
//using data structure
public class RecursionStack {
static public Stack<Character> st=new Stack<>(); //direct stack is used for push and pop
static void reverse()
{
if(st.size()>0)
{
char x=st.peek();
st.pop();
reverse(); //go upto last element
logic(x);
}
}
static void logic(char c)
{
if(st.empty()) //for first element
{
st.push(c);
}else
{ //remove all the above and enter at end
char a=st.peek();
st.pop();
logic(c);
st.push(a);
}
}
public static void main(String args[])
{
st.push('1');
st.push('2');
st.push('3');
st.push('4');
System.out.println("original stack");
System.out.println(st);
//now to reverse
reverse();
System.out.println("revresed stack");
System.out.println(st);
}
}
| true |
e33dc0ce33e0d7553b49ed396a5c4e24a33687ed | Java | tiarebalbi/sample-geocoding-api | /src/main/java/com/tiarebalbi/sample/geocodingapi/client/model/Geometry.java | UTF-8 | 2,412 | 2.21875 | 2 | [] | no_license | package com.tiarebalbi.sample.geocodingapi.client.model;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Geometry", propOrder = {
"location",
"locationType",
"viewport",
"bounds"
})
public class Geometry {
@XmlElement(required = true)
protected Location location;
@JacksonXmlProperty(localName = "location_type")
protected LocationType locationType;
@XmlElement(required = true)
protected Viewport viewport;
@XmlElement(required = true)
protected Viewport bounds;
/**
* Gets the value of the location property.
*
* @return possible object is
* {@link Location }
*/
public Location getLocation() {
return location;
}
/**
* Sets the value of the location property.
*
* @param value allowed object is
* {@link Location }
*/
public void setLocation(Location value) {
this.location = value;
}
/**
* Gets the value of the locationType property.
*
* @return possible object is
* {@link LocationType }
*/
public LocationType getLocationType() {
return locationType;
}
/**
* Sets the value of the locationType property.
*
* @param value allowed object is
* {@link LocationType }
*/
public void setLocationType(LocationType value) {
this.locationType = value;
}
/**
* Gets the value of the viewport property.
*
* @return possible object is
* {@link Viewport }
*/
public Viewport getViewport() {
return viewport;
}
/**
* Sets the value of the viewport property.
*
* @param value allowed object is
* {@link Viewport }
*/
public void setViewport(Viewport value) {
this.viewport = value;
}
/**
* Gets the value of the bounds property.
*
* @return possible object is
* {@link Viewport }
*/
public Viewport getBounds() {
return bounds;
}
/**
* Sets the value of the bounds property.
*
* @param value allowed object is
* {@link Viewport }
*/
public void setBounds(Viewport value) {
this.bounds = value;
}
public boolean hasLocation() {
return location != null;
}
}
| true |
c3b26b2a2351b5491a2313c1c609298600824db3 | Java | liupanfeng/YangQuanClien | /app/src/main/java/com/meishe/yangquan/viewhoder/MineMyPointsHolder.java | UTF-8 | 2,525 | 2.046875 | 2 | [] | no_license | package com.meishe.yangquan.viewhoder;
import android.content.Context;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.bumptech.glide.request.RequestOptions;
import com.meishe.yangquan.R;
import com.meishe.yangquan.adapter.BaseRecyclerAdapter;
import com.meishe.yangquan.bean.BaseInfo;
import com.meishe.yangquan.bean.PointRecordInfo;
import com.meishe.yangquan.bean.SheepHairInfo;
import com.meishe.yangquan.utils.FormatCurrentData;
import com.meishe.yangquan.utils.FormatDateUtil;
import com.meishe.yangquan.utils.Util;
import java.util.HashMap;
import java.util.Map;
/**
* 我的-我的积分
*
* @author 86188
*/
public class MineMyPointsHolder extends BaseViewHolder {
private final RequestOptions options;
/*积分类型*/
private TextView tv_point_type;
/*积分时间*/
private TextView tv_point_time;
/*积分值*/
private TextView tv_point_value;
private Map<String, String> dataMaps = new HashMap<>();
public MineMyPointsHolder(@NonNull View itemView, BaseRecyclerAdapter adapter) {
super(itemView);
mAdapter = adapter;
options = new RequestOptions();
options.centerCrop();
options.placeholder(R.mipmap.ic_message_list_photo_default);
dataMaps.put("SUGGEST_ACCEPT", "建议被采纳");
dataMaps.put("ADD_COMMENT", "羊吧评论");
dataMaps.put("ADD_POST", "羊吧发帖子");
dataMaps.put("SIGN_IN", "羊吧签到");
dataMaps.put("LOGIN", "每日登录");
dataMaps.put("ON_LINE", "在线超过30分钟");
}
@Override
protected void initViewHolder(View view, Object... obj) {
tv_point_type = view.findViewById(R.id.tv_point_type);
tv_point_time = view.findViewById(R.id.tv_point_time);
tv_point_value = view.findViewById(R.id.tv_point_value);
}
@Override
public void bindViewHolder(Context context, BaseInfo info, int position, View.OnClickListener listener) {
if (info instanceof PointRecordInfo) {
tv_point_type.setText(dataMaps.get(((PointRecordInfo) info).getFromType()));
tv_point_value.setText(((PointRecordInfo) info).getWealth() + "");
tv_point_time.setText(FormatDateUtil.longToString(((PointRecordInfo) info).getInitDate(), FormatDateUtil.FORMAT_TYPE_YEAR_MONTH_DAY));
}
}
}
| true |
832340bbf00b3588ea1271e5c6dce660fef53b1c | Java | kojw1017/mycgv | /spring_mycgv/src/main/java/com/spring/service/MemberService.java | UTF-8 | 378 | 1.5 | 2 | [] | no_license | package com.spring.service;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import com.mycgv.vo.CgvMemberVO;
public interface MemberService {
ModelAndView getMemberContent(String id);
ModelAndView getMemberList(String rpage);
String getResultJoin(CgvMemberVO vo);
String getResultLogin(CgvMemberVO vo, HttpSession session);
}
| true |
b35b71187cd383327ecf10e278891e67861ebf8d | Java | ilgaleanos/calculadora_spring | /src/test/java/com/leonardo/calculadora/logic/entradas/operaciones/EliminarInTest.java | UTF-8 | 1,091 | 2.34375 | 2 | [] | no_license | package com.leonardo.calculadora.logic.entradas.operaciones;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.UUID;
import static org.springframework.test.util.AssertionErrors.*;
public class EliminarInTest {
@Autowired
private EliminarIn eliminarIn;
private String sesionId;
@BeforeEach
public void setup() {
this.sesionId = UUID.randomUUID().toString();
eliminarIn = new EliminarIn();
}
@Test
public void esInValido() {
assertFalse("invalido", eliminarIn.esInValido());
eliminarIn.setSesionId(sesionId);
assertTrue("valido", eliminarIn.esInValido());
}
@Test
public void shouldEqualsConstructor() {
EliminarIn instancia = new EliminarIn(sesionId);
assertEquals("sesionId", sesionId, instancia.getSesionId());
}
@Test
public void shouldEqualsParams() {
eliminarIn.setSesionId(sesionId);
assertEquals("sesionId", sesionId, eliminarIn.getSesionId());
}
} | true |
43c53c68cb2834628eb26ff4d4e839813e4a7857 | Java | gitjguerra/Itaca | /web/src/main/java/com/csi/itaca/ItacaApplication.java | UTF-8 | 1,013 | 1.789063 | 2 | [] | no_license | package com.csi.itaca;
import com.csi.itaca.config.model.Configurator;
import com.csi.itaca.config.tools.ConfiguratorImpl;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import javax.annotation.PostConstruct;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
@EnableBatchProcessing
public class ItacaApplication {
@Autowired
private Configurator configurator;
public static void main(String[] args) {
SpringApplication.run(ItacaApplication.class, args);
}
@Bean
public Configurator configurator() {
return new ConfiguratorImpl();
}
@PostConstruct
private void registerModules() {
configurator.registerModule("config.modules");
}
}
| true |
9ba40b5f1a1faf02169caf489e660e72a24b84eb | Java | paulo01012018/res-q | /ACMERobotics/src/main/java/com/acmerobotics/library/vector/VectorIntegrator.java | UTF-8 | 645 | 3.03125 | 3 | [
"BSD-3-Clause"
] | permissive | package com.acmerobotics.library.vector;
import java.util.concurrent.TimeUnit;
public class VectorIntegrator {
private Vector sum, last;
public VectorIntegrator() {
sum = new Vector();
last = null;
}
public void add(Vector in) {
if (last == null) {
last = in;
return;
}
double timeDiff = ((double) (in.time - last.time)) / Math.pow(10.0, 9.0);
sum.x = (last.x + in.x) * timeDiff / 2.0;
sum.y = (last.y + in.y) * timeDiff / 2.0;
sum.z = (last.z + in.z) * timeDiff / 2.0;
}
public Vector getSum() {
return sum;
}
}
| true |
225f9b459c33ffad82c898640a01d5136d5f3c79 | Java | zkewal/chrome-rest-client | /RestClient/src/org/rest/client/storage/websql/AppDatabase.java | UTF-8 | 477 | 1.828125 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | package org.rest.client.storage.websql;
import com.google.code.gwt.database.client.service.Connection;
import com.google.code.gwt.database.client.service.DataService;
/**
* Main app database connection service. Any other databases services must
* extend this class.
*
* @author jarrod
*
*/
@Connection(name = "restClient", version = "", description = "Rest service database", maxsize = 10000000)
public interface AppDatabase extends DataService {
}
| true |
bfbad4833bb7ef69d7b3db350ae7a347d5273bfc | Java | dembanakh/mana-wars | /core/src/com/mana_wars/ui/widgets/item_drawer/SkillLevelDrawer.java | UTF-8 | 1,644 | 2.640625 | 3 | [
"MIT"
] | permissive | package com.mana_wars.ui.widgets.item_drawer;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Align;
import com.mana_wars.model.entity.base.Rarity;
import com.mana_wars.model.entity.skills.ReadableSkill;
import com.mana_wars.ui.widgets.base.ListItemDrawer;
import space.earlygrey.shapedrawer.ShapeDrawer;
public class SkillLevelDrawer implements ListItemDrawer<ReadableSkill> {
private TextureRegion region;
private ShapeDrawer drawer;
public SkillLevelDrawer(TextureRegion placeholderRegion) {
this.region = placeholderRegion;
}
@Override
public void draw(Batch batch, BitmapFont font, int index, ReadableSkill item, float x, float y, float width, float height) {
if (!shouldShowLevel(item)) return;
String level = String.valueOf(item.getLevel());
font.getData().setScale(3);
float halfLineHeight = font.getLineHeight() / 2;
if (drawer == null || drawer.getBatch() != batch) drawer = new ShapeDrawer(batch, region);
drawer.setColor(Color.WHITE);
drawer.filledRectangle(x - halfLineHeight, y - halfLineHeight,
2 * halfLineHeight, 2 * halfLineHeight);
font.setColor(Color.BLACK);
font.draw(batch, level, x - width, y + halfLineHeight,
0, level.length(), 2 * width, Align.center,
false, "");
}
private boolean shouldShowLevel(ReadableSkill skill) {
return skill.getRarity() != Rarity.EMPTY;
}
}
| true |
03292e7e286ee4626f5db6cfeda08c2f6177ed34 | Java | shivanshu1992/MyProjects | /JavaPrograms/src/Java_Basic/LocalGlobalVariable.java | UTF-8 | 955 | 4.03125 | 4 | [] | no_license | package Java_Basic;
public class LocalGlobalVariable {
// these are global variable or class variable
int key= 34;
int number=90;
public static void main(String[] args) {
// these are local variables of main method
int a=12;
int b=360;
System.out.println("value of a inside the main method is " + a);
LocalGlobalVariable obj1= new LocalGlobalVariable ();
obj1.newMethod(); // To access non static method make obj1 and call it with non static method
System.out.println("value of key inside the main method is " + obj1.key);
// To use global variable inside the main method create object first then use
}
public void newMethod() {
int a=55;
int b=88; // local variable of non static method
int key =34;
System.out.println("value of NUMBER inside the main method is " + number);
System.out.println("value of a inside the non static method is " + a);
}
}
| true |
700e9474077e18bed97ff70cde9260b0f8e97707 | Java | weiju-xi/RT-JAR-CODE | /com/sun/xml/internal/ws/policy/spi/PolicyAssertionCreator.java | UTF-8 | 801 | 1.554688 | 2 | [] | no_license | package com.sun.xml.internal.ws.policy.spi;
import com.sun.xml.internal.ws.policy.AssertionSet;
import com.sun.xml.internal.ws.policy.PolicyAssertion;
import com.sun.xml.internal.ws.policy.sourcemodel.AssertionData;
import java.util.Collection;
public abstract interface PolicyAssertionCreator
{
public abstract String[] getSupportedDomainNamespaceURIs();
public abstract PolicyAssertion createAssertion(AssertionData paramAssertionData, Collection<PolicyAssertion> paramCollection, AssertionSet paramAssertionSet, PolicyAssertionCreator paramPolicyAssertionCreator)
throws AssertionCreationException;
}
/* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar
* Qualified Name: com.sun.xml.internal.ws.policy.spi.PolicyAssertionCreator
* JD-Core Version: 0.6.2
*/ | true |
27c071c7d7219afafd904f949f724b88423b5d20 | Java | renchengwei/oa | /src/oa/service/PostService.java | UTF-8 | 4,979 | 2.1875 | 2 | [] | no_license | package oa.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import oa.dao.PostDao;
import oa.pojo.Post;
import oa.pojo.PostAndReply;
import oa.pojo.PostReply;
import oa.util.BeanCopyUtil;
import oa.util.DateUtil;
import oa.util.SessionUtil;
import oa.util.StaticCodeBook;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
@Component("postService")
public class PostService {
@Resource(name="postDao")
private PostDao postDao;
public PostDao getPostDao() {
return postDao;
}
public void setPostDao(PostDao postDao) {
this.postDao = postDao;
}
// public PostFile saveUploadFile(MultipartFile file) throws IOException {
// byte[] bytes = file.getBytes();
// String path = StaticCodeBook.getPostFilePath();
//
// File uploadedFile = new File(path + DateUtil.getDateString4(new Date()));
// PostFile postFile = new PostFile();
// postFile.setFilename(file.getOriginalFilename());
// postFile.setFilesize(file.getSize() / 1.0);
// postFile.setFilepath(uploadedFile.getPath());
// postDao.saveObject(postFile);
// FileCopyUtils.copy(bytes, uploadedFile);
// return postFile;
// }
/**
* 保存帖子
* @param map
* @return
*/
public Post savePost(Map<String,String> map) {
Post post = new Post();
if(StringUtils.isNotEmpty(map.get("id"))) {
post = (Post) postDao.get(Post.class, map.get("id"));
}
BeanCopyUtil.setFieldValue(post, map);
if(StringUtils.isNotEmpty(post.getId())) {
postDao.updateObject(post);
}else {
post.setIsshield("0");
post.setIsdel("0");
post.setIssueuser(SessionUtil.getUser().getId());
post.setIssuetime(DateUtil.getDateTime(new Date()));
postDao.saveObject(post);
}
return post;
}
/**
* 分页查询帖子
* @param map
* @return
*/
public Map<String, Object> getPostByPage(Map<String, String> map) {
Map<String, Object> data = new HashMap<String, Object>();
List<Post> newslist = new ArrayList<Post>();
int count = postDao.getPostCount(map);
if(count > 0) {
newslist = postDao.getPostByPage(map);
}
data.put(StaticCodeBook.PAGE_TOTAL, count);
data.put(StaticCodeBook.PAGE_ROWS, newslist);
return data;
}
/**
* 分页查询帖子回复
* @param map
* @return
*/
public Map<String, Object> getPostAndReplyByPage(Map<String, String> map) {
Map<String, Object> data = new HashMap<String, Object>();
List<PostAndReply> newslist = new ArrayList<PostAndReply>();
int count = postDao.getPostAndReplyCount(map);
if(count > 0) {
newslist = postDao.getPostAndReplyByPage(map);
}
data.put(StaticCodeBook.PAGE_TOTAL, count);
data.put(StaticCodeBook.PAGE_ROWS, newslist);
return data;
}
public Post getPostById(String id) {
Post post = (Post) postDao.get(Post.class, id);
return post;
}
/**
* 保存帖子回复
* @param map
* @return
*/
public PostReply savePostReply(Map<String, String> map) {
PostReply postreply = new PostReply();
if(StringUtils.isNotEmpty(map.get("id"))) {
postreply = (PostReply) postDao.get(PostReply.class, map.get("id"));
}
BeanCopyUtil.setFieldValue(postreply, map);
if(StringUtils.isNotEmpty(postreply.getId())) {
postDao.updateObject(postreply);
}else {
int ordernum = postDao.getPostReplyOrderNum(postreply.getPostid());
postreply.setIsshield("0");
postreply.setIsdel("0");
postreply.setOrdernum(++ordernum);
postreply.setReplyuser(SessionUtil.getUser().getId());
postreply.setReplytime(DateUtil.getDateTime(new Date()));
postDao.saveObject(postreply);
}
return postreply;
}
/**
* 置顶帖子
* @param id
*/
public void updateToptime(String id) {
Post post = (Post) postDao.get(Post.class, id);
post.setToptime(DateUtil.getDateTime(new Date()));
postDao.updateObject(post);
}
/**
* 屏蔽/取消屏蔽帖子或者回复
* @param id
*/
public void updateIsshield(String id) {
Object obj1 = postDao.get(PostReply.class, id);
Object obj2 = postDao.get(Post.class, id);
if(obj1 != null) {
PostReply reply = (PostReply) obj1;
if("0".equals(reply.getIsshield())) {
reply.setIsshield("1");
}else {
reply.setIsshield("0");
}
postDao.updateObject(reply);
}else {
Post post = (Post) obj2;
if("0".equals(post.getIsshield())) {
post.setIsshield("1");
}else {
post.setIsshield("0");
}
postDao.updateObject(post);
}
}
public void deletePost(String id) {
Post post = (Post) postDao.get(Post.class, id);
post.setIsdel("1");
post.setDeltime(DateUtil.getDateString5(new Date()));
post.setDeluser(SessionUtil.getUser().getId());
postDao.updateObject(post);
}
}
| true |
8b9e97222ed0a16b55a41f78f443696ec4f7efef | Java | zhenghan1219/demo | /src/main/java/com/zzh/exercise/tencent/TencentAdFieldConstant.java | UTF-8 | 6,633 | 2.375 | 2 | [] | no_license | package com.zzh.exercise.tencent;
/**
* 字段维护常量
* 返回参数的字段列表、过滤条件字段
* @Author: wangxiaow@nicomama.com
* @Date: 2020/12/8
*/
public interface TencentAdFieldConstant {
/**
* 广告组id,仅支持微信公众平台广告主
* integer
*/
String ADGROUP_ID = "adgroup_id";
/**
* 推广计划id,仅支持微信公众平台广告主
* integer
*/
String CAMPAIGN_ID = "campaign_id";
/**
* 推广计划名称
*/
String CAMPAIGN_NAME = "campaign_name";
/**
* 小时(0-23),仅支持微信公众平台广告主
* integer
*/
String HOUR = "hour";
/**
* 日期,日期格式:YYYY-MM-DD,仅支持微信公众平台广告主
* string
*/
String DATE = "date";
/**
* 广告主帐号 id
* integer
*/
String ACCOUNT_ID = "account_id";
/**
* 微信账号id,仅支持微信公众平台广告主
* string
*/
String WECHAT_ACCOUNT_ID = "wechat_account_id";
/**
* 微信服务商id,仅支持微信公众平台广告主
* string
*/
String WECHAT_AGENCY_ID = "wechat_agency_id";
/**
* 公众号关注次数,仅支持微信公众平台广告主
* integer
*/
String OFFICIAL_ACCOUNT_FOLLOW_COUNT = "official_account_follow_count";
/**
* 公众号关注成本(次数),仅支持微信公众平台广告主
* integer
*/
String OFFICIAL_ACCOUNT_FOLLOW_COST = "official_account_follow_cost";
/**
* 花费,仅支持微信公众平台广告主
* integer
*/
String COST = "cost";
/**
* 广告组日预算,单位为分,设置为 0 表示不设预算(即不限)
*/
String DAILY_BUDGET = "daily_budget";
/**
* 当日成本偏差;反应广告今日的实际成本与目标成本之际差异
* float
*/
String COST_DEVIATION_RATE = "cost_deviation_rate";
/**
* 赔付金额;广告超成本时的赔付金额
* integer
*/
String COMPENSATION_AMOUNT = "compensation_amount";
/**
* 曝光次数;观看广告的次数
* integer
*/
String VIEW_COUNT = "view_count";
/**
* 千次曝光成本;平均每千次曝光的次数
* Integer
*/
String THOUSAND_DISPLAY_PRICE = "thousand_display_price";
/**
* 曝光人数;观看广告独立的用户数
* integer
*/
String VIEW_USER_COUNT = "view_user_count";
/**
* 人均曝光次数;每个用户平均观看广告的次数
* integer
*/
String AVG_VIEW_PER_USER = "avg_view_per_user";
/**
* 点击次数;用户在广告区外进行点击操作的次数
* integer
*/
String VALID_CLICK_COUNT = "valid_click_count";
/**
* 点击人数
* integer
*/
String CLICK_USER_COUNT = "click_user_count";
/**
* 点击率;广告点击次数/广告曝光次数
* integer
*/
String CTR = "ctr";
/**
* 点击均价;广告花费/广告次数
* 类型:integer
*/
String CPC = "cpc";
/**
* 可转化点击次数
* 类型:integer
*/
String VALUABLE_CLICK_COUNT = "valuable_click_count";
/**
* 可转化点击率
* 类型:integer
*/
String VALUABLE_CLICK_RATE = "valuable_click_rate";
/**
* 可转化点击成本
* 类型:integer
*/
String VALUABLE_CLICK_COST = "valuable_click_cost";
/**
* 图片点击次数
* 类型:integer
*/
String CLICK_IMAGE_COUNT = "click_image_count";
/**
* 图片点击人数
* 类型:integer
*/
String IMAGE_CLICK_USER_COUNT = "image_click_user_count";
/**
* 视频点击次
* 类型:integer
*/
String VIDEO_PLAY_COUNT = "video_play_count";
/**
* 视频点击人数
* 类型:integer
*/
String VIDEO_CLICK_USER_COUNT = "video_click_user_count";
/**
* 文字链点击次
* 类型:integer
*/
String CLICK_DETAIL_COUNT = "click_detail_count";
/**
* 文字链点击人数
* 类型:integer
*/
String LINK_CLICK_USER_COUNT = "link_click_user_count";
/**
* 头像点击次数
* 类型:integer
*/
String CLICK_HEAD_COUNT = "click_head_count";
/**
* 头像点击人数
* 类型:integer
*/
String PORTRAIT_CLICK_USER_COUNT = "portrait_click_user_count";
/**
* 昵称点击次数
* 类型:integer
*/
String CLICK_NICK_COUNT = "click_nick_count";
/**
* 昵称点击人数
* 类型:integer
*/
String NICKNAME_CLICK_USER_COUNT = "nickname_click_user_count";
/**
* 推广页曝光次数
* 类型:integer
*/
String PLATFORM_PAGE_VIEW_COUNT = "platform_page_view_count";
/**
* 推广页曝光人数
* 类型:integer
*/
String PLATFORM_KEY_PAGE_VIEW_USER_COUNT = "platform_key_page_view_user_count";
/**
* 推广页曝光率
* 类型:float
*/
String PLATFORM_KEY_PAGE_VIEW_DURATION = "platform_key_page_view_duration";
/**
* 推广页按钮点击次数
* 类型:integer
*/
String CPN_CLICK_BUTTON_COUNT = "cpn_click_button_count";
/**
* 推广页按钮点击人数
* 类型:integer
*/
String CPN_CLICK_BUTTON_UV = "cpn_click_button_uv";
/**
* 点赞次数
* 类型:integer
*/
String PRAISE_COUNT = "praise_count";
/**
* 点赞人数
* 类型:integer
*/
String PRAISE_USER_COUNT = "praise_user_count";
/**
* 评论次数
* 类型:integer
*/
String COMMENT_COUNT = "comment_count";
/**
* 评论人数
* 类型:integer
*/
String COMMENT_USER_COUNT = "comment_user_count";
/**
* 转化目标量
* 类型:integer
*/
String CONVERSIONS_COUNT = "conversions_count";
/**
* 转化目标成本
* 类型:integer
*/
String CONVERSIONS_COST = "conversions_cost";
/**
* 目标转化率
* 类型:float
*/
String CONVERSIONS_RATE = "conversions_rate";
/**
* 公众号关注率
* 类型:integer
*/
String OFFICIAL_ACCOUNT_FOLLOW_RATE = "official_account_follow_rate";
/**
* 阅读粉丝量
* 类型:integer
*/
String OFFICIAL_ACCOUNT_READER_COUNT = "official_account_reader_count";
/**
* 不感兴趣点击次数
* 类型:integer
*/
String NO_INTEREST_COUNT = "no_interest_count";
}
| true |
a271fe089c4519302c45cc48c492feea4dc8c50e | Java | aalnct/Algorithms | /src/javacertification/classdesign/Person2.java | UTF-8 | 405 | 3 | 3 | [] | no_license | package javacertification.classdesign;
public class Person2 {
String name;
int age;
Person2 () {
this.age = 29;
this.name = "Virat";
}
@Override
public int hashCode() {
return super.hashCode();
}
public int hashcode () {
return 100;
}
public static void main(String[] args) {
System.out.println(new Person2());
}
}
| true |
c2a5fb1186ace788f13445403cca90ebf6bafad7 | Java | zuuraidrisova/JavaReview | /src/day53_Iterable/RemoveDuplicates.java | UTF-8 | 2,265 | 4.1875 | 4 | [] | no_license | package day53_Iterable;
import java.util.*;
public class RemoveDuplicates {
//access-modifier specifier return-type methodsName(parameter){body}
//access modifiers: public protected default private
//specifiers: static, final, abstract, synchronized
//4. how to achieve thread safety: using synchronized keyword
/*
3. what are the differences between List and Set
List: Accepts duplicates, has index numbers and keep insertion order
Set: does not accept duplicates, does not have index numbers, and does not keep insertion order
*/
public static void main(String[] args) {
//in order to make it synchronized, we can use Collections utility
List<Integer> list2 = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list2 = Collections.synchronizedList(list2);//now it will return us synchronized list
//now it became thread safe
System.out.println(list2);
System.out.println("===============================================");
Set<Integer> set = new HashSet<>(Arrays.asList(1,3,5,7,9,11));
set = Collections.synchronizedSet(set);//synchronizes and returns the set
//now it is thread safe
System.out.println(set);
System.out.println("===============================================");
String[] arr = {"A","E","B", "A","D","D","C","A"};
removeDuplicatesFromArray(arr);
List<String> list = new ArrayList<>(Arrays.asList("A","E","B", "A","D","D","C","A"));
removeDuplicatesFromArrayList((ArrayList<String>) list);
}
//2. write a program that can remove the duplicates from an arrayList of String
public static void removeDuplicatesFromArrayList(ArrayList<String> list){
Set<String> noDup = new LinkedHashSet<>(list);
System.out.println(noDup);
}
// 1. write a program that remove the duplicates from an array of String
//and keep insertion order
public static void removeDuplicatesFromArray(String [] array){
Set<String> noDup = new LinkedHashSet<>(Arrays.asList(array));
System.out.println(noDup);
}
public synchronized void append(){
//4. how to achieve thread safety: using synchronized keyword
}
}
| true |
baf1bd40b9f8406ae55392e119e4ea0d54075426 | Java | 765947965/MVVM | /app/src/main/java/com/huike/face/device/business/screen/ScreenModel.java | UTF-8 | 760 | 2.078125 | 2 | [] | no_license | package com.huike.face.device.business.screen;
import com.huike.face.device.base.mvvm.FaceBaseModel;
import com.tencent.mmkv.MMKV;
/**
* @ProjectName: HuikeFace
* @Package: com.huike.face.device.business.screen
* @ClassName: ScreenModel
* @Description: java类作用描述
* @Author: 谢文良
* @CreateDate: 2020/3/31 10:31
* @UpdateUser: 更新者
* @UpdateDate: 2020/3/31 10:31
* @UpdateRemark: 更新说明
* @Version: 1.0
*/
public class ScreenModel extends FaceBaseModel {
private static String ACTIVATION_KEY = "activation";
boolean getActivation(){
return MMKV.defaultMMKV().decodeBool(ACTIVATION_KEY, false);
}
void setActivation(boolean value){
MMKV.defaultMMKV().encode(ACTIVATION_KEY, value);
}
}
| true |
fd4fcb0de6928a7e42edcade2439c8220ca351cb | Java | jyh111/blog-inn | /blog/src/main/java/com/example/blog/controller/UserController.java | UTF-8 | 2,092 | 2.328125 | 2 | [] | no_license | package com.example.blog.controller;
import com.example.blog.bl.UserService;
import com.example.blog.po.User;
import com.example.blog.vo.ResponseVO;
import com.example.blog.vo.UserDisplayVO;
import com.example.blog.vo.UserForm;
import com.example.blog.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController()
@RequestMapping("/api/user")
public class UserController {
private final static String ACCOUNT_INFO_ERROR = "用户名或密码错误";
private final static String ACCOUNT_NOT_EXIST = "该用户不存在";
@Autowired
private UserService userService;
@PostMapping("/login")
public ResponseVO login(@RequestBody UserForm userForm) {
User user = userService.login(userForm);
if (user == null) {
return ResponseVO.buildFailure(ACCOUNT_INFO_ERROR);
}
return ResponseVO.buildSuccess(user);
}
@PostMapping("/register")
public ResponseVO registerAccount(@RequestBody UserVO userVO) {
return userService.registerAccount(userVO);
}
@GetMapping("/{id}/getUserInfo")
public ResponseVO getUserInfo(@PathVariable Integer id){
User user = userService.getUserInfo(id);
if(user==null){
return ResponseVO.buildFailure(ACCOUNT_NOT_EXIST);
}
return ResponseVO.buildSuccess(user);
}
@PostMapping("/{userId}/userInfo/update")
public ResponseVO updateUserInfo(@RequestBody UserVO userVO,@PathVariable Integer userId){
return userService.updateUserInfo(userId,userVO.getEmail(),userVO.getUsername(),userVO.getUserImg(),userVO.getPassword(),userVO.getSelf_introduction());
}
@GetMapping("/{id}/getUserDisplay")
public ResponseVO getUserDisplay(@PathVariable Integer id){
System.out.println(id);
UserDisplayVO userDisplay = userService.getUserDisplay(id);
if(userDisplay==null){
return ResponseVO.buildFailure(ACCOUNT_NOT_EXIST);
}
return ResponseVO.buildSuccess(userDisplay);
}
}
| true |
e5ca7b72e80c33eb8868e27a6c5c8ba67659ac20 | Java | Denel91/Functional-Java | /src/main/java/Laboratorio/Dynamic_programming/BottomUp.java | UTF-8 | 5,366 | 3.796875 | 4 | [
"MIT"
] | permissive | package Laboratorio.Dynamic_programming;
public class BottomUp {
// Variabile di classe
private static final int UNKNOWN = 0;
/**
* Applica la tecnica Bottom-Up di programmazione dinamica alle seguenti procedure ricorsive.
*/
//------------ Versione ricorsiva ------------//
public static long s(int n, int k) { // 1 ≤ k ≤ n
if (k == n) {
return 1;
} else {
long x = (n - 1) * s(n - 1, k);
if (k == 1) {
return x;
} else {
return x + s(n - 1, k - 1);
}
}
}
//------------ Versione Bottom-Up ------------//
public static long sDP(int n, int k) { // 1 ≤ k ≤ n
long[][] h = new long[n + 1][k + 1];
for (int v = 0; v <= k; v++) {
h[0][v] = 1;
}
for (int u = 1; u <= n; u++) {
h[u][0] = 1;
}
for (int u = 1; u <= n; u++) {
for (int v = 1; v <= k; v++) {
if (u == v) {
h[u][v] = 1;
} else {
long x = (u - 1) * h[u - 1][v];
if (v == 1) {
h[u][v] = x;
} else {
h[u][v] = x + h[u - 1][v - 1];
}
}
}
}
return h[n][k];
}
//------------ Memoization ------------//
private static long sMem(int n, int k, long[][] h) {
if (k == n) {
h[n][k] = 1;
} else {
long x = (n - 1) * sMem(n - 1, k, h);
if (k == 1) {
h[n][k] = x;
} else {
h[n][k] = x + sMem(n - 1, k - 1, h);
}
}
return h[n][k];
}
public static long sMemoization(int n, int k) {
long[][] h = new long[n + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= k; j++) {
h[i][j] = UNKNOWN;
}
}
return sMem(n, k, h);
}
//------------ Versione ricorsiva ------------//
public static long q(int i, int j, boolean b) {
if (b) {
if (i * j == 0) {
return i + j + 1;
} else {
return q(i - 1, j, b) + q(i, j - 1, b) + q(i, j, !b);
}
} else {
if (i * j == 0) {
return 1;
} else {
return q(i - 1, j, b) + q(i, j - 1, b);
}
}
}
//------------ Prima Versione Bottom-Up ------------//
public static long qDP(int i, int j, boolean b) {
long[][][] h = new long[i + 1][j + 1][2];
for (int v = 0; v <= j; v = v + 1) {
h[0][v][0] = 1;
h[0][v][1] = v + 1;
}
for (int u = 1; u <= i; u = u + 1) {
h[u][0][0] = 1;
h[u][0][1] = u + 1;
}
for (int u = 1; u <= i; u = u + 1) {
for (int v = 1; v <= j; v = v + 1) {
h[u][v][0] = h[u - 1][v][0] + h[u][v - 1][0];
h[u][v][1] = h[u - 1][v][1] + h[u][v - 1][1] + h[u][v][0];
}
}
if (b) {
return h[i][j][1];
} else {
return h[i][j][0];
}
}
//------------ Seconda Versione Bottom-Up ------------//
public static long qBottomUp(int i, int j, boolean b) {
long[][][] h = new long[i + 1][j + 1][2];
for (int u = 0; u <= i; u++) {
for (int v = 0; v <= j; v++) {
if (u * v == 0) {
h[u][v][0] = 1;
h[u][v][1] = u + v + 1;
} else {
h[u][v][0] = h[u - 1][v][0] + h[u][v - 1][0];
h[u][v][1] = h[u - 1][v][1] + h[u][v - 1][1] + h[u][v][0];
}
}
}
return h[i][j][b ? 1 : 0];
}
//------------ Memoization ------------//
private static long qMem(int i, int j, boolean b, long[][] h) {
if (b) {
if (i * j == 0) {
h[i][j] = i + j + 1;
} else {
h[i][j] = qMem(i - 1, j, b, h) + qMem(i, j - 1, b, h) + qMem(i, j, !b, h);
}
} else {
if (i * j == 0) {
h[i][j] = 1;
} else {
h[i][j] = qMem(i - 1, j, b, h) + qMem(i, j - 1, b, h);
}
}
return h[i][j];
}
public static long qMemoization(int i, int j, boolean b) {
long[][] h = new long[i + 1][j + 1];
for (int r = 0; r <= i; r++) {
for (int c = 0; c <= j; c++) {
h[r][c] = UNKNOWN;
}
}
return qMem(i, j, b, h);
}
public static void main(String[] args) {
System.out.println(s(5, 4)); // 10
System.out.println(sMemoization(5, 4)); // 10
System.out.println(sDP(5, 4)); // 10
System.out.println(q(3, 5, true)); // 504
System.out.println(qDP(3, 5, true)); // 504
System.out.println(qBottomUp(3, 5, true)); // 504
System.out.println(q(6, 7, false)); // 1716
System.out.println(qDP(6, 7, false)); // 1716
System.out.println(qMemoization(3, 5, true)); // 504
System.out.println(qMemoization(6, 7, false)); // 1716
}
}
| true |
f6f1f3d82409e24d3a105c7e947fd4c6f3ed81d3 | Java | piaoxue85/workspace | /UPnPMonitor/src/cn/ipanel/dlna/DeviceBuilder.java | UTF-8 | 7,522 | 1.632813 | 2 | [] | no_license | package cn.ipanel.dlna;
import java.util.UUID;
import org.cybergarage.upnp.device.InvalidDescriptionException;
import org.cybergarage.upnp.std.av.renderer.AVTransport;
import org.cybergarage.upnp.std.av.renderer.ConnectionManager;
import org.cybergarage.upnp.std.av.renderer.MediaRenderer;
import org.cybergarage.upnp.std.av.renderer.RenderingControl;
import org.cybergarage.upnp.std.av.server.ContentDirectory;
import org.cybergarage.upnp.std.av.server.MediaReceiverRegistrar;
import org.cybergarage.upnp.std.av.server.MediaServer;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
public class DeviceBuilder {
public final static String RENDERER_DESCRIPTION =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<root xmlns=\"urn:schemas-upnp-org:device-1-0\" xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">\n" +
" <specVersion>\n" +
" <major>1</major>\n" +
" <minor>0</minor>\n" +
" </specVersion>\n" +
" <device>\n" +
" <deviceType>urn:schemas-upnp-org:device:MediaRenderer:1</deviceType>\n" +
" <dlna:X_DLNACAP>playcontainer-0-1</dlna:X_DLNACAP>\n"+
" <dlna:X_DLNADOC>DMR-1.50</dlna:X_DLNADOC>\n"+
" <friendlyName>%1$s</friendlyName>\n" +
" <manufacturer>%2$s</manufacturer>\n" +
" <manufacturerURL>http://www.ipanel.cn</manufacturerURL>\n" +
" <modelDescription>Simple UPnP Renderer</modelDescription>\n" +
" <modelName>%3$s</modelName>\n" +
" <modelNumber>%4$s</modelNumber>\n" +
" <modelURL>http://www.ipanel.cn</modelURL>\n" +
" <UDN>uuid:%5$s</UDN>\n" +
// " <dlna:X_DLNADOC xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">DMR-1.50</dlna:X_DLNADOC>" +
" <iconList><icon><mimetype>image/png</mimetype><width>96</width><height>96</height><depth>32</depth><url>/icon/device.png</url></icon></iconList>" +
" <serviceList>\n" +
" <service>\n" +
" <serviceType>urn:schemas-upnp-org:service:RenderingControl:1</serviceType>\n" +
" <serviceId>urn:upnp-org:serviceId:RenderingControl</serviceId>\n" +
" <SCPDURL>/service/RenderingControl1.xml</SCPDURL>\n" +
" <controlURL>/service/RenderingControl_control</controlURL>\n" +
" <eventSubURL>/service/RenderingControl_event</eventSubURL>\n" +
" </service>\n" +
" <service>\n" +
" <serviceType>urn:schemas-upnp-org:service:ConnectionManager:1</serviceType>\n" +
" <serviceId>urn:upnp-org:serviceId:ConnectionManager</serviceId>\n" +
" <SCPDURL>/service/ConnectionManager1.xml</SCPDURL>\n" +
" <controlURL>/service/ConnectionManager_control</controlURL>\n" +
" <eventSubURL>/service/ConnectionManager_event</eventSubURL>\n" +
" </service>\n" +
" <service>\n" +
" <serviceType>urn:schemas-upnp-org:service:AVTransport:1</serviceType>\n" +
" <serviceId>urn:upnp-org:serviceId:AVTransport</serviceId>\n" +
" <SCPDURL>/service/AVTransport1.xml</SCPDURL>\n" +
" <controlURL>/service/AVTransport_control</controlURL>\n" +
" <eventSubURL>/service/AVTransport_event</eventSubURL>\n" +
" </service>\n" +
" </serviceList>\n" +
" </device>\n" +
"</root>";
public static MediaRenderer createRenderer(Context context, String name) {
SharedPreferences sp = context.getSharedPreferences(DeviceBuilder.class.getName(), 0);
String key = MediaRenderer.class.getSimpleName();
String uuid = sp.getString(key, UUID.randomUUID().toString());
if(!sp.contains(key)){
sp.edit().putString(key, uuid).commit();
}
String desc = String.format(RENDERER_DESCRIPTION, name, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, uuid);
try {
return new MediaRenderer(desc, RenderingControl.SCPD, ConnectionManager.SCPD, AVTransport.SCPD);
} catch (InvalidDescriptionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public final static String SERVER_DESCRIPTION =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<root xmlns=\"urn:schemas-upnp-org:device-1-0\" xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">\n" +
" <specVersion>\n" +
" <major>1</major>\n" +
" <minor>0</minor>\n" +
" </specVersion>\n" +
" <device>\n" +
" <deviceType>urn:schemas-upnp-org:device:MediaServer:1</deviceType>\n" +
" <friendlyName>%1$s</friendlyName>\n" +
" <manufacturer>%2$s</manufacturer>\n" +
" <manufacturerURL>http://www.ipanel.cn</manufacturerURL>\n" +
" <modelDescription>Provides content through UPnP ContentDirectory service</modelDescription>\n" +
" <modelName>%3$s</modelName>\n" +
" <modelNumber>%4$s</modelNumber>\n" +
" <modelURL>http://www.ipanel.cn</modelURL>\n" +
" <UDN>uuid:%5$s</UDN>\n" +
" <dlna:X_DLNADOC>DMS-1.50</dlna:X_DLNADOC>" +
" <iconList><icon><mimetype>image/png</mimetype><width>96</width><height>96</height><depth>32</depth><url>/icon/device.png</url></icon></iconList>" +
" <serviceList>\n" +
" <service>\n" +
" <serviceType>urn:schemas-upnp-org:service:ContentDirectory:1</serviceType>\n" +
" <serviceId>urn:upnp-org:serviceId:urn:schemas-upnp-org:service:ContentDirectory</serviceId>\n" +
" <SCPDURL>/service/ContentDirectory1.xml</SCPDURL>\n" +
" <controlURL>/service/ContentDirectory_control</controlURL>\n" +
" <eventSubURL>/service/ContentDirectory_event</eventSubURL>\n" +
" </service>\n" +
" <service>\n" +
" <serviceType>urn:schemas-upnp-org:service:ConnectionManager:1</serviceType>\n" +
" <serviceId>urn:upnp-org:serviceId:urn:schemas-upnp-org:service:ConnectionManager</serviceId>\n" +
" <SCPDURL>/service/ConnectionManager1.xml</SCPDURL>\n" +
" <controlURL>/service/ConnectionManager_control</controlURL>\n" +
" <eventSubURL>/service/ConnectionManager_event</eventSubURL>\n" +
" </service>\n" +
" <service>\n" +
" <serviceType>urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1</serviceType>\n" +
" <serviceId>urn:microsoft.com:serviceId:X_MS_MediaReceiverRegistrar</serviceId>\n" +
" <SCPDURL>/service/MediaReceiverRegistrar1.xml</SCPDURL>\n" +
" <controlURL>/service/MediaReceiverRegistrar_control</controlURL>\n" +
" <eventSubURL>/service/MediaReceiverRegistrar_event</eventSubURL>\n" +
" </service>\n" +
" </serviceList>\n" +
" </device>\n" +
"</root>";
public static MediaServer createServer(Context context, String name) {
SharedPreferences sp = context.getSharedPreferences(DeviceBuilder.class.getName(), 0);
String key = MediaServer.class.getSimpleName();
String uuid = sp.getString(key, UUID.randomUUID().toString());
if(!sp.contains(key)){
sp.edit().putString(key, uuid).commit();
}
String desc = String.format(SERVER_DESCRIPTION, name, Build.MANUFACTURER, Build.MODEL, Build.VERSION.RELEASE, uuid);
try {
return new MediaServer(desc, ContentDirectory.SCPD, ConnectionManager.SCPD, MediaReceiverRegistrar.SCPD);
} catch (InvalidDescriptionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| true |
24b1ebaa9c6759a91b62c127d4f8026f2de58814 | Java | gangov/JavaOOP | /MotocrossSkeletonAndBusinessLogic/src/motocrossWorldChampionship/models/motorcycles/PowerMotorcycle.java | UTF-8 | 772 | 3 | 3 | [] | no_license | package motocrossWorldChampionship.models.motorcycles;
public class PowerMotorcycle extends MotorcycleImpl{
private static final double CUBIC_CENTIMETERS = 450;
private static final int MODEL_HORSE_POWER_LOWER_LIMIT = 70;
private static final int MODEL_HORSE_POWER_UPPER_LIMIT = 100;
public PowerMotorcycle(String model, int horsePower) {
super(model, horsePower, CUBIC_CENTIMETERS);
this.setHorsePower(horsePower, MODEL_HORSE_POWER_LOWER_LIMIT, MODEL_HORSE_POWER_UPPER_LIMIT);
}
@Override
public void setHorsePower(int horsePower, int MODEL_HORSE_POWER_LOWER_LIMIT, int MODEL_HORSE_POWER_UPPER_LIMIT) {
super.setHorsePower(horsePower, this.MODEL_HORSE_POWER_LOWER_LIMIT, this.MODEL_HORSE_POWER_UPPER_LIMIT);
}
}
| true |
5de95ecb292dc765e9ccacc1fbbe67a54a9e6b20 | Java | 0xtinyuk/SearchEngineOnReuters21578 | /src/Dictionary.java | UTF-8 | 14,919 | 2.46875 | 2 | [] | no_license | import java.io.*;
import java.util.*;
import java.util.AbstractMap.SimpleEntry;
import org.tartarus.snowball.SnowballStemmer;
import org.tartarus.snowball.ext.*;
import java.math.BigDecimal;
public class Dictionary {
public HashMap<String,HashSet<Integer>> dict;
public HashSet<String> stopwords;
public HashMap<Integer, HashSet<String>> wordset;
//public ArrayList<Double> weight;
public String dictString;
private HashMap<String, ArrayList<Integer>> tf;
public HashMap<String, ArrayList<Double>> tfidf;
private HashMap<String, Integer> bigram;
public HashMap<String,ArrayList<AbstractMap.SimpleEntry<String,Integer>>> completion;
public HashMap<String,ArrayList<AbstractMap.SimpleEntry<String,Double>>> expension;
public boolean stemming,stopword,normalization;
public boolean hasExpension,hasCompletion;
private int completionThreshold = 1;//The threshold value of query completion -> suggest only when the bi-gram frequency > threshold
private int completionListLength = 10;//The max amount of options of completion for each word
private int expensionListLength = 5;//The max amount of options of completion for each word
private double expensionThreshold = 0.1;
private int knn = 5;//the k for K-NN
public Dictionary(){
dict = new HashMap<String,HashSet<Integer>>();
stopwords = new HashSet<String>();
try{
this.inputFromStopwordsFile("stopwords.txt");
}catch (Exception e) {
e.printStackTrace();
}
dictString = "";
hasExpension=false;
hasCompletion=false;
}
public void inputFromStopwordsFile(String fileName) throws IOException{
FileInputStream fin = new FileInputStream(fileName);
String currentLine;
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
currentLine = reader.readLine();
while(currentLine !=null){
stopwords.add(currentLine.replaceAll("\\n", ""));
currentLine = reader.readLine();
}
reader.close();
fin.close();
}
public void build(ArrayList<Document> docs, boolean stopword, boolean stemming, boolean normalization,boolean reuters,boolean needTopicAssign){
this.stopword = stopword;
this.stemming = stemming;
this.normalization = normalization;
String norRegex = "[\\-\\.,\\(\\)\"\'\\?\\;]";
String splitRegex = "[ \\/\\n]";
//String splitRegex = "[\\s\\S]";
//this.weight = new ArrayList<Double>();
dict = new HashMap<String,HashSet<Integer>>();
dictString = "";
tf = new HashMap<String, ArrayList<Integer>>();
bigram = new HashMap<String,Integer>();
SnowballStemmer stemmer = new englishStemmer();
for (int i = 0; i < docs.size(); i++) {
String lastWord = "";//store the last word for bi-gram
Document doc = docs.get(i);
String[] wordlist = doc.title.split(splitRegex);
for (String str : wordlist) {
str = str.toLowerCase();
if(normalization){
str = str.replaceAll(norRegex, "");
if (str.equals("")) {lastWord="";continue;}
}
if(stopword && stopwords.contains(str)) {lastWord="";continue;}
if(isNumeric(str)){lastWord= "";continue;}
if(stemming){
stemmer.setCurrent(str);
if(stemmer.stem()){
str = stemmer.getCurrent();
//System.out.println(str);
}
}
buildBiGram(lastWord,str);
lastWord = str;
if(dict.containsKey(str)){
HashSet<Integer> index = dict.get(str);
index.add(i);
dict.replace(str, index);
}
else{
HashSet<Integer> index = new HashSet<Integer>();
index.add(i);
dict.put(str, index);
dictString = dictString+" " +str;
}
}
lastWord = "";
wordlist = doc.description.split(splitRegex);
for (String str : wordlist) {
str = str.toLowerCase();
//System.out.println(str);
if(normalization){
str = str.replaceAll(norRegex, "");
if (str.equals("")) {lastWord="";continue;}
}
if(stopword && stopwords.contains(str)) {lastWord="";continue;}
if(isNumeric(str)){lastWord="";continue;}
if(stemming){
stemmer.setCurrent(str);
if(stemmer.stem()){
str = stemmer.getCurrent();
//System.out.println(str);
}
}
buildBiGram(lastWord,str);
lastWord = str;
if(dict.containsKey(str)){
HashSet<Integer> index = dict.get(str);
index.add(i);
dict.replace(str, index);
}
else{
HashSet<Integer> index = new HashSet<Integer>();
index.add(i);
dict.put(str, index);
dictString = dictString+" " +str;
}
//System.out.println(str);
}
}
wordset = new HashMap<Integer, HashSet<String>>();
for (int i = 0; i < docs.size(); i++) {
Document doc = docs.get(i);
String[] wordlist = doc.title.split(splitRegex);
HashSet<String> TempSet = new HashSet<String>();
for (String str : wordlist) {
str = str.toLowerCase();
if(normalization){
str = str.replaceAll(norRegex, "");
if (str.equals("")) {continue;}
}
if(stopword && stopwords.contains(str)) continue;
if(stemming){
stemmer.setCurrent(str);
if(stemmer.stem()){
str = stemmer.getCurrent();
//System.out.println(str);
}
}
if(isNumeric(str))continue;
TempSet.add(str);
if(tf.containsKey(str)){
ArrayList<Integer> tempArr = tf.get(str);
if(tempArr.size()<i+1)
for(int j=tempArr.size();j<i+1;j++)
tempArr.add(j,Integer.valueOf(0));
tempArr.set(i,tempArr.get(i)+1);
tf.put(str, tempArr);
}
else{
ArrayList<Integer> tempArr = new ArrayList<Integer>();
//System.out.println(docs.size());
if(tempArr.size()<i+1)
for(int j=tempArr.size();j<i+1;j++)
tempArr.add(j,Integer.valueOf(0));
tempArr.set(i, Integer.valueOf(1));
//System.out.println(tf.get(str));
tf.put(str, tempArr);
}
//System.out.println(str);
}
wordlist = doc.description.split(splitRegex);
for (String str : wordlist) {
str = str.toLowerCase();
//System.out.println(str);
if(normalization){
str = str.replaceAll(norRegex, "");
if (str.equals("")) {continue;}
}
if(stopword && stopwords.contains(str)) continue;
if(stemming){
stemmer.setCurrent(str);
if(stemmer.stem()){
str = stemmer.getCurrent();
//System.out.println(str);
}
}
if(isNumeric(str))continue;
TempSet.add(str);
if(tf.containsKey(str)){
ArrayList<Integer> tempArr = tf.get(str);
if(tempArr.size()<i+1)
for(int j=tempArr.size();j<i+1;j++)
tempArr.add(j,Integer.valueOf(0));
tempArr.set(i, tempArr.get(i)+1);
tf.put(str, tempArr);
}
else{
ArrayList<Integer> tempArr = new ArrayList<Integer>();
//System.out.println(docs.size());
if(tempArr.size()<i+1)
for(int j=tempArr.size();j<i+1;j++)
tempArr.add(j,Integer.valueOf(0));
tempArr.set(i, Integer.valueOf(1));
//System.out.println(tf.get(str));
tf.put(str, tempArr);
}
//System.out.println(str);
}
wordset.put(doc.docID, TempSet);//Store all the words the document contains
}
tfidf = new HashMap<String, ArrayList<Double>>();
String wordlist[] = dictString.split(" ");
for(String str: wordlist){
ArrayList<Double> tempArr = new ArrayList<Double>();
for(int i=0;i<docs.size();i++){
if(dict.get(str)!=null && dict.get(str).contains(i)){
try{
tempArr.add( Math.log( tf.get(str).get(i)+1)*Math.log(docs.size()/dict.get(str).size()));
}catch (Exception e){//This is for debug use. There will not be Exception normally.
System.out.println(i);
System.out.println(tf.get(str));
dict.get(str);
}
}
else{
tempArr.add(Double.valueOf(0));
}
}
tfidf.put(str, tempArr);
}
//System.out.println(dict.size());
hasExpension=false;
hasCompletion=false;
if(reuters && needTopicAssign) topicsAssign(docs);
//buildQueryCompletion();//build up query completion
//buildQueryExpension();
tf=null;
return;
}
Comparator<AbstractMap.SimpleEntry<String,Integer>> wordIntegerComparator =
new Comparator<AbstractMap.SimpleEntry<String,Integer>>() {//Comparator for suggestions, from large frequency to small
@Override
public int compare(SimpleEntry<String, Integer> o1, SimpleEntry<String, Integer> o2) {
if(o1.getValue()<o2.getValue()) return 1;
if(o1.getValue()>o2.getValue()) return -1;
return 0;
}
};
Comparator<AbstractMap.SimpleEntry<String,Double>> wordDoubleComparator =
new Comparator<AbstractMap.SimpleEntry<String,Double>>() {//Comparator for suggestions, from large frequency to small
@Override
public int compare(SimpleEntry<String, Double> o1, SimpleEntry<String, Double> o2) {
if(o1.getValue()<o2.getValue()) return 1;
if(o1.getValue()>o2.getValue()) return -1;
return 0;
}
};
Comparator<AbstractMap.SimpleEntry<HashSet<String>,Double>> wordSetDoubleComparator =
new Comparator<AbstractMap.SimpleEntry<HashSet<String>,Double>>() {
@Override
public int compare(SimpleEntry<HashSet<String>, Double> o1, SimpleEntry<HashSet<String>, Double> o2) {
if(o1.getValue()<o2.getValue()) return 1;
if(o1.getValue()>o2.getValue()) return -1;
return 0;
}
};
private double docDistance(int x,int y){//return the distance of doc x and doc y
HashSet<String> Temp = (HashSet<String>)wordset.get(x).clone();
Temp.retainAll(wordset.get(y));
int intersection = Temp.size();
Temp = (HashSet<String>)wordset.get(x).clone();
Temp.addAll(wordset.get(y));
int union=Temp.size();
return ((double)intersection)/((double)union);
}
public void topicsAssign(ArrayList<Document> docs){
for (int i = 0; i < docs.size(); i++)
if(docs.get(i).topics.size()==0){
ArrayList<AbstractMap.SimpleEntry<HashSet<String>,Double>> temp =
new ArrayList<AbstractMap.SimpleEntry<HashSet<String>,Double>>();
for (int j = 0; j < docs.size(); j++)
if(i!=j && docs.get(j).topics.size()>0){
double similarity = docDistance(i, j);
temp.add(new AbstractMap.SimpleEntry<HashSet<String>, Double>(docs.get(j).topics, similarity));
Collections.sort(temp,wordSetDoubleComparator);
if(temp.size()>knn) temp.remove(temp.size()-1);
}
HashMap<String, Integer> count = new HashMap<String, Integer>();
for(int j=0;j<temp.size();j++){
for(String str:temp.get(j).getKey()){
if(count.containsKey(str)){
count.put(str, count.get(str)+1);
}
else count.put(str, 1);
}
}
int maxAmount = 0;
for(HashMap.Entry<String, Integer> entry: count.entrySet()){
if(entry.getValue()>maxAmount){
maxAmount = entry.getValue();
}
}
for(HashMap.Entry<String, Integer> entry: count.entrySet()){
if(entry.getValue()==maxAmount){
docs.get(i).topics.add(entry.getKey());
}
}
}
wordset = null;
}
public void buildQueryExpension(){
expension = new HashMap<String,ArrayList<AbstractMap.SimpleEntry<String,Double>>>();
for(HashMap.Entry<String,HashSet<Integer>> e1 : dict.entrySet()){
for(HashMap.Entry<String,HashSet<Integer>> e2 : dict.entrySet()){
if(e1.getKey().compareTo(e2.getKey())>=0) continue;//calculate only when str1<str2 to avoid calculate twice for performance
HashSet<Integer> Temp = (HashSet<Integer>)e1.getValue().clone();
Temp.retainAll(e2.getValue());
int intersection = Temp.size();
Temp = (HashSet<Integer>)e1.getValue().clone();
Temp.addAll(e2.getValue());
int union=Temp.size();
Double jaccardDistance = ((double)intersection)/((double)union);
if(jaccardDistance>expensionThreshold){
if(expension.containsKey(e1.getKey())){
ArrayList<AbstractMap.SimpleEntry<String,Double>> tempArr = expension.get(e1.getKey());
tempArr.add(new AbstractMap.SimpleEntry<String, Double>(e2.getKey(), jaccardDistance));
Collections.sort(tempArr,wordDoubleComparator);
if(tempArr.size()>expensionListLength) tempArr.remove(tempArr.size()-1);
expension.put(e1.getKey(), tempArr);
}
else{
ArrayList<AbstractMap.SimpleEntry<String,Double>> tempArr = new ArrayList<AbstractMap.SimpleEntry<String,Double>>();
tempArr.add(new AbstractMap.SimpleEntry<String, Double>(e2.getKey(), jaccardDistance));
expension.put(e1.getKey(), tempArr);
}
if(expension.containsKey(e2.getKey())){
ArrayList<AbstractMap.SimpleEntry<String,Double>> tempArr = expension.get(e2.getKey());
tempArr.add(new AbstractMap.SimpleEntry<String, Double>(e1.getKey(), jaccardDistance));
Collections.sort(tempArr,wordDoubleComparator);
if(tempArr.size()>expensionListLength) tempArr.remove(tempArr.size()-1);
expension.put(e2.getKey(), tempArr);
}
else{
ArrayList<AbstractMap.SimpleEntry<String,Double>> tempArr = new ArrayList<AbstractMap.SimpleEntry<String,Double>>();
tempArr.add(new AbstractMap.SimpleEntry<String, Double>(e1.getKey(), jaccardDistance));
expension.put(e2.getKey(), tempArr);
}
}
}
}
hasExpension = true;
}
public void buildQueryCompletion(){
completion = new HashMap<String,ArrayList<AbstractMap.SimpleEntry<String,Integer>>>();
for(HashMap.Entry<String, Integer> entry : bigram.entrySet()){
if(entry.getValue()<completionThreshold) continue;
String[] wl = entry.getKey().split(" ");
if(wl.length!=2) continue;
if(completion.containsKey(wl[0])){
ArrayList<AbstractMap.SimpleEntry<String,Integer>> tempArr = completion.get(wl[0]);
tempArr.add(new AbstractMap.SimpleEntry<String, Integer>(wl[1], entry.getValue()));
Collections.sort(tempArr,wordIntegerComparator);
if(tempArr.size()>completionListLength) tempArr.remove(tempArr.size()-1);
completion.put(wl[0], tempArr);
}
else{
ArrayList<AbstractMap.SimpleEntry<String,Integer>> tempArr = new ArrayList<AbstractMap.SimpleEntry<String,Integer>>();
tempArr.add(new AbstractMap.SimpleEntry<String, Integer>(wl[1], entry.getValue()));
completion.put(wl[0], tempArr);
}
}
bigram=null;
hasCompletion = true;
}
public static boolean isNumeric(String str) {//check if the str is a number
try {
String bigStr = new BigDecimal(str).toString();
} catch (Exception e) {
return false;
}
return true;
}
private void buildBiGram(String lastWord,String str){
if(lastWord.equals("")) return;
String bg = lastWord + " "+str;
if(bigram.containsKey(bg)){
bigram.put(bg,bigram.get(bg)+1);
}
else{
bigram.put(bg, 1);
}
}
}
| true |
28616f6c45cf1903e043255d01ffe2de62592ed7 | Java | TinsPHP/tins-symbols | /src/ch/tsphp/tinsphp/symbols/utils/ModifierHelper.java | UTF-8 | 876 | 2.25 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /*
* This file is part of the TinsPHP project published under the Apache License 2.0
* For the full copyright and license information, please have a look at LICENSE in the
* root folder or visit the project's website http://tsphp.ch/wiki/display/TINS/License
*/
package ch.tsphp.tinsphp.symbols.utils;
import ch.tsphp.common.symbols.ISymbolWithModifier;
import ch.tsphp.tinsphp.common.gen.TokenTypes;
public final class ModifierHelper
{
private ModifierHelper() {
}
public static void addNullableModifier(ISymbolWithModifier symbol) {
symbol.addModifier(TokenTypes.QuestionMark);
}
public static void addFalseableModifier(ISymbolWithModifier symbol) {
symbol.addModifier(TokenTypes.LogicNot);
}
public static void addAlwaysCastingModifier(ISymbolWithModifier symbol) {
symbol.addModifier(TokenTypes.Cast);
}
}
| true |
ed9b89dfe4d0ae522df85d9063b7a09e589f7b93 | Java | HubertBourget/FoodApp | /app/src/main/java/com/example/myrestaurant/LoginActivity.java | UTF-8 | 1,117 | 2.15625 | 2 | [] | no_license | package com.example.myrestaurant;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity{
//shared preferences
SharedPreferences sf;
String file_name = "foodPreference";
String pref_id = "id";
String pref_total = "total";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Shared preference
sf = getSharedPreferences(file_name, MODE_PRIVATE);
SharedPreferences.Editor edit = sf.edit();
edit.putString(pref_id, 1 + "");
edit.putString(pref_total, "0.00");
edit.commit();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}, 2000);
}
}
| true |
31a0ef35937558bb39240a4e98e345395f4defbe | Java | ulyn/eos | /eos-common/src/main/java/com/sunsharing/eos/common/serialize/Serialization.java | UTF-8 | 785 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package com.sunsharing.eos.common.serialize;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public interface Serialization {
/**
* get content type id
*
* @return content type id
*/
byte getContentTypeId();
/**
* get content type
*
* @return content type
*/
String getContentType();
/**
* create serializer
*
* @param output
* @return serializer
* @throws java.io.IOException
*/
ObjectOutput serialize(OutputStream output) throws IOException;
/**
* create deserializer
*
* @param input
* @return deserializer
* @throws java.io.IOException
*/
ObjectInput deserialize(InputStream input) throws IOException;
} | true |
052ce3d4271c0fd4b43f533320a719ac75b35562 | Java | michelleADMVC/FullStackJava | /Spring/Licencia/src/main/java/com/example/app/repositories/PersonRepository.java | UTF-8 | 322 | 2.015625 | 2 | [] | no_license | package com.example.app.repositories;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.app.models.Person;
@Repository
public interface PersonRepository extends CrudRepository<Person, Long>{
List<Person>findAll();
}
| true |
9caa1fb7e4192340b18f3adf31e5494040bdef76 | Java | Zekrom64/ZEngine | /MathLib/src/com/zekrom_64/mathlib/tuple/impl/Vector4I.java | UTF-8 | 1,213 | 2.828125 | 3 | [] | no_license | package com.zekrom_64.mathlib.tuple.impl;
import com.zekrom_64.mathlib.tuple.Vector4;
public class Vector4I extends Vector3I implements Vector4<Integer> {
public int w;
public Vector4I() {}
public Vector4I(Vector4I v) {
x = v.x;
y = v.y;
z = v.z;
w = v.w;
}
public Vector4I(int x, int y, int z, int w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public Vector4I(int[] values) {
x = values[0];
y = values[1];
z = values[2];
w = values[3];
}
public void set(Vector4I v) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
this.w = v.w;
}
public void set(int x, int y, int z, int w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
@Override
public int size() {
return 4;
}
@Override
public int getInt(int i) {
switch(i) {
case 0: return x;
case 1: return y;
case 2: return z;
case 3: return w;
}
return 0;
}
@Override
public void setInt(int i, int val) {
switch(i) {
case 0: x = val; break;
case 1: y = val; break;
case 2: z = val; break;
case 3: w = val; break;
}
}
public boolean equals(Vector4I other) {
return
x == other.x &&
y == other.y &&
z == other.z &&
w == other.w;
}
}
| true |
06b1251dea0c9a3695e04c7b3f99b982074cdcaa | Java | anisha-r/Mode1-Training | /Day2/BoxingDemo/src/p1/Demo.java | UTF-8 | 360 | 2.453125 | 2 | [] | no_license | package p1;
public class Demo {
public int a=5;
private String city = "coimbatore";
protected double b = 12.5;
String name = "anisha";
public static void main(String[] args) {
Demo obj =new Demo();
System.out.println(obj.a);
System.out.println(obj.city);
System.out.println(obj.b);
System.out.println(obj.name);
}
}
| true |
8f1c081437f34d40d7b0a75cf9aaad8473886f61 | Java | VasilSokolov/TestProject | /src/com/designpatterns/behavior/strategy/StrategyPatternDemo.java | UTF-8 | 133 | 1.632813 | 2 | [] | no_license | package com.designpatterns.behavior.strategy;
public class StrategyPatternDemo {
public static void main(String[] args) {
}
}
| true |
589be8c36156b61c0e1b872dbb7ed7c02d797f14 | Java | labbeh/semestre3 | /cpoa/workspace/tp2Suite/tests/irb/PlsClassementIRBTest.java | UTF-8 | 1,013 | 2.265625 | 2 | [] | no_license | package irb;
import static org.junit.Assert.*;
import java.util.HashSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PlsClassementIRBTest
{
private PlsClassementIRB pls ;
private ClassementIRB irbMoy78910;
@Before
public void setUp() throws Exception
{
this.pls = new PlsClassementIRB();
this.irbMoy78910 = new ClassementIRB(new ClassementIRB("i2007.txt"), "moy78910");
}
@After
public void tearDown() throws Exception
{
this.pls = null;
this.irbMoy78910 = null;
}
@Test
public void testMoyPoints()
{
HashSet<String> codesPays = this.irbMoy78910.getEnsembleCodePays();
for(String code: codesPays)
assertEquals(new Double(this.irbMoy78910.getPaysByCode(code).getNbPoint()),
new Double(this.pls.moyPoints(code))
);
}
@Test
public void testAnneeMoy()
{
// test sur LUX et KOR
assertEquals(this.pls.anneeMoy("LUX"), new String("2008"));
assertEquals(this.pls.anneeMoy("KOR"), new String("2009"));
}
}
| true |
208853b706e6f57707a5f486949b4b8725c039aa | Java | stefanbugge/gesture-recogniser | /src/dk/loeschcke/matrix/helper/Action.java | UTF-8 | 240 | 1.546875 | 2 | [] | no_license | package dk.loeschcke.matrix.helper;
/**
* Created with IntelliJ IDEA.
* User: sbugge
* Date: 16/08/13
* Time: 14.49
* To change this template use File | Settings | File Templates.
*/
public enum Action {
TAP,
NONE, GESTURE
}
| true |
db2333c0b360d4f3ec6d9bdcbcfa4e5a6115a81b | Java | weltonvs/Ejemplos_DS_UDC | /Modulo1/src/paquete_a/ClaseMismoPaquete.java | UTF-8 | 539 | 3.15625 | 3 | [] | no_license |
package paquete_a;
/**
* Ejemplo de clase que pertenece al mismo paquete_a.
* @author weltonvs
*/
public class ClaseMismoPaquete {
public void metodoDeAcceso_2(){
Clase c = new Clase();
//c.privado = 1;//No es válido porque ese atributo es privado en la clase Clase.
c.protegido = 2;//Se permite porque esta en el mismo paquete.
c.paquete = 3;//Se permite porque esa clase pertenece al mismo paquete.
c.publico = 4;//Se permite porque el atributo de la clase Clase es público.
}
}
| true |
246444950f0d63a69acc2fc87bd0453fc9300a99 | Java | EricGhildyal/CS1653CryptoProject | /src/GroupServer.java | UTF-8 | 6,864 | 3.015625 | 3 | [] | no_license | /* Group server. Server loads the users from UserList.bin.
* If user list does not exists, it creates a new list and makes the user the server administrator.
* On exit, the server saves the user list to file.
*/
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
import java.security.*;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
public class GroupServer extends Server {
public static final int SERVER_PORT = 8765;
public UserList userList;
public ArrayList<Group> groupList = new ArrayList<Group>();
public String fname = "";
public static KeyRing keyRing;
public CryptoHelper crypto;
public GroupServer(String dbFileName) {
super(SERVER_PORT, "ALPHA");
crypto = new CryptoHelper();
fname = dbFileName;
keyRing = new KeyRing("GroupServer");
if(keyRing.exists()){
keyRing = crypto.loadRing(keyRing);
}else{ //create new ring
keyRing.init();
KeyPair kp = crypto.getNewKeypair();
keyRing.addKey("rsa_priv", kp.getPrivate());
keyRing.addKey("rsa_pub", kp.getPublic());
System.out.println("GS_PUBKEY: " + Base64.encodeBase64String(kp.getPublic().getEncoded()));
}
}
public GroupServer(int _port, String dbFileName) {
super(_port, "ALPHA");
crypto = new CryptoHelper();
fname = dbFileName;
keyRing = new KeyRing("GroupServer");
if(keyRing.exists()){
keyRing = crypto.loadRing(keyRing);
}else{ //create new ring
keyRing.init();
KeyPair kp = crypto.getNewKeypair();
keyRing.addKey("rsa_priv", kp.getPrivate());
keyRing.addKey("rsa_pub", kp.getPublic());
System.out.println("GS_PUBKEY: " + Base64.encodeBase64String(kp.getPublic().getEncoded()));
}
}
public void start() {
// Overwrote server.start() because if no user file exists, initial admin account needs to be created
String userFile = "UserList.bin";
String groupFile = "GroupList.bin";
Scanner console = new Scanner(System.in);
ObjectInputStream userStream;
ObjectInputStream groupStream;
//This runs a thread that saves the lists on program exit
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new ShutDownListener(this));
//Creates the authentication database, or opens it if it already exists
File authFile = new File(fname);
try{
authFile.createNewFile();
}catch(Exception e){
e.printStackTrace();
System.exit(-1);
}
UserPasswordDB authDB = new UserPasswordDB(fname);
//Open user file to get user list
try
{
FileInputStream fis = new FileInputStream(userFile);
userStream = new ObjectInputStream(fis);
userList = (UserList)userStream.readObject();
}
catch(FileNotFoundException e)
{
System.out.println("UserList File Does Not Exist. Creating UserList...");
System.out.println("No users currently exist. Your account will be the administrator.");
java.io.Console sysConsole = System.console();
String username = "";
String password = "";
String passwordConfirm = "";
do{
username = sysConsole.readLine("Username: "); //Takes in username input from user
password = new String(sysConsole.readPassword("Password: ")); //Takes in password input from user
passwordConfirm = new String(sysConsole.readPassword("Please Retype Password: ")); //Takes in password input from user
if(username.isEmpty() || password.isEmpty()){
System.out.println("Invalid username or password format, please try again!");
}else if(!password.equals(passwordConfirm)){
System.out.println("Passwords did not match, please try again!");
}
}while(username.isEmpty() || password.isEmpty() || !password.equals(passwordConfirm));
try{
authDB.add(username, password);
}catch(Exception f){
f.printStackTrace();
System.exit(-1);
}
//Create a new list, add current user to the ADMIN group. They now own the ADMIN group.
userList = new UserList();
userList.addUser(username);
userList.addGroup(username, "ADMIN");
userList.addOwnership(username, "ADMIN");
ArrayList<String> admins = new ArrayList<String>();
admins.add(username);
groupList.add(new Group(admins, "ADMIN", username));
}
catch(Exception e)
{
System.out.println("Error reading from UserList file");
System.exit(-1);
}
try
{
FileInputStream gis = new FileInputStream(groupFile);
groupStream = new ObjectInputStream(gis);
groupList = (ArrayList<Group>)groupStream.readObject();
}
catch(FileNotFoundException e)
{
System.out.println("groupList File Does Not Exist. Creating groupList...");
System.out.println("No groups currently exist.");
}
catch(Exception e)
{
System.out.println("Error reading from GroupList file");
System.exit(-1);
}
//Autosave Daemon. Saves lists every 5 minutes
AutoSave aSave = new AutoSave(this);
aSave.setDaemon(true);
aSave.start();
//This block listens for connections and creates threads on new connections
try
{
final ServerSocket serverSock = new ServerSocket(port);
System.out.printf("%s up and running\n", this.getClass().getName());
Socket sock = null;
GroupThread thread = null;
while(true)
{
sock = serverSock.accept();
thread = new GroupThread(sock, this, authDB);
thread.start();
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
//This thread saves the user list
class ShutDownListener extends Thread
{
public GroupServer my_gs;
public ShutDownListener (GroupServer _gs) {
my_gs = _gs;
}
public void run()
{
System.out.println("Shutting down server");
ObjectOutputStream outStream;
ObjectOutputStream groupOut;
try
{
outStream = new ObjectOutputStream(new FileOutputStream("UserList.bin"));
outStream.writeObject(my_gs.userList);
groupOut = new ObjectOutputStream(new FileOutputStream("GroupList.bin"));
groupOut.writeObject(my_gs.groupList);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
class AutoSave extends Thread
{
public GroupServer my_gs;
public AutoSave (GroupServer _gs) {
my_gs = _gs;
}
public void run()
{
do
{
try
{
Thread.sleep(300000); //Save group and user lists every 5 minutes
System.out.println("Autosave group and user lists...");
ObjectOutputStream outStream;
ObjectOutputStream groupOut;
try
{
outStream = new ObjectOutputStream(new FileOutputStream("UserList.bin"));
outStream.writeObject(my_gs.userList);
groupOut = new ObjectOutputStream(new FileOutputStream("GroupList.bin"));
groupOut.writeObject(my_gs.groupList);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
catch(Exception e)
{
System.out.println("Autosave Interrupted");
}
}while(true);
}
}
| true |
1200d10d8a1f886761253a2c0e56c36ca2f27992 | Java | karthikbhat19/Xplorify | /Xplorify/app/src/main/java/com/example/xplorify/Splash.java | UTF-8 | 1,665 | 2.015625 | 2 | [] | no_license | package com.example.xplorify;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
public class Splash extends Activity {
LinearLayout LL;
ConstraintLayout CL;
Animation downtoup, uptodown;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
LL = findViewById(R.id.top_splash);
CL = findViewById(R.id.bot_splash);
uptodown = AnimationUtils.loadAnimation(this,R.anim.uptodown);
downtoup = AnimationUtils.loadAnimation(this,R.anim.downtoup);
LL.setAnimation(uptodown);
CL.setAnimation(downtoup);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Bundle lanim = ActivityOptions.makeCustomAnimation(getApplicationContext(),R.anim.come_into_left,R.anim.go_out_left).toBundle();
Intent l = new Intent(Splash.this,Login.class);
startActivity(l,lanim);
Splash.this.finish();
}
},2000);
}
}
| true |
54b02eec783b2193e692a1779355f071040689f0 | Java | aharshbe/NewsHag | /NewsHag/app/src/main/java/badassapps/aaron/newshag/NavDDetailView.java | UTF-8 | 4,485 | 2.21875 | 2 | [] | no_license | //package badassapps.aaron.newshag;
//
//import android.content.ContentValues;
//import android.content.Intent;
//import android.database.sqlite.SQLiteDatabase;
//import android.graphics.drawable.Drawable;
//import android.support.v7.app.AppCompatActivity;
//import android.os.Bundle;
//import android.text.method.ScrollingMovementMethod;
//import android.view.Menu;
//import android.view.MenuInflater;
//import android.view.MenuItem;
//import android.view.View;
//import android.widget.Button;
//import android.widget.ImageView;
//import android.widget.RelativeLayout;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import com.squareup.picasso.Picasso;
//
//public class NavDDetailView extends AppCompatActivity {
//
// TextView body, title;
// ImageView image;
// private String detailID;
// private String detailURL;
// Button button;
//
//
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_nav_ddetail_view);
//
// String detailTitle = getIntent().getStringExtra("title");
// String detailAbstract = getIntent().getStringExtra("abstract");
// String detailThumb = getIntent().getStringExtra("thumbnail");
// detailURL = getIntent().getStringExtra("url");
// detailID = getIntent().getStringExtra("id");
//
// body = (TextView) findViewById(R.id.body);
// title = (TextView) findViewById(R.id.title);
// image = (ImageView) findViewById(R.id.image);
// button = (Button) findViewById(R.id.button);
// title.setMovementMethod(new ScrollingMovementMethod());
// body.setMovementMethod(new ScrollingMovementMethod());
//
//
// body.setMovementMethod(new ScrollingMovementMethod());
//
// body.setText(detailAbstract);
// title.setText(detailTitle);
//
// if (detailThumb != null && !detailThumb.equals("")) {
// Picasso.with(NavDDetailView.this).load(detailThumb).into(image);
// }
//
//
// }
//
// public void clickingReadOn(View view) {
// Intent intent = new Intent(NavDDetailView.this, WebViewForTop10.class);
// intent.putExtra("url", detailURL);
// startActivity(intent);
// }
//
// public void clickingFavsToAdd(MenuItem item) {
//
//
// Toast.makeText(NavDDetailView.this, "Added the story to your favorites!", Toast.LENGTH_SHORT).show();
// insertFavorite();
//
// }
//
//
// public void clickingShare(MenuItem item) {
// Intent sharingIntent = new Intent(Intent.ACTION_SEND);
// sharingIntent.setType("text/plain");
// sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, getIntent().getStringExtra("url"));
// startActivity(Intent.createChooser(sharingIntent, getString(R.string.send_intent_title)));
//
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater inflater = getMenuInflater();
// inflater.inflate(R.menu.shared_icon, menu);
// inflater.inflate(R.menu.making_fav, menu);
// return true;
// }
//
// public void insertFavorite() {
//
// //Create our db object
// NewsDBOpenHelper helpMe = new NewsDBOpenHelper(this, "favorites", null, 1);
//
// //Insert values using writable db
// SQLiteDatabase db = helpMe.getWritableDatabase();
//
// //Receive our values from our class and pass them through here!
// ContentValues cv = new ContentValues();
//
// cv.put(NewsDBOpenHelper.COL_FAV, "1");
// cv.put(NewsDBOpenHelper.COL_TITLE,getIntent().getStringExtra("title") );
// cv.put(NewsDBOpenHelper.COL_URL, detailURL);
// cv.put(NewsDBOpenHelper.COL_THUMBNAIL, getIntent().getStringExtra("thumbnail"));
// cv.put(NewsDBOpenHelper.COL_ABSTRACT, getIntent().getStringExtra("abstract"));
//
// String id = detailID; //is the id
//
// long insertColumn = db.insert(NewsDBOpenHelper.FAVS_HAG_TABLE, null,cv);
// long insertColumnValue = db.update(NewsDBOpenHelper.FAVS_HAG_TABLE, cv, NewsDBOpenHelper.COL_ID + " = ?", new String[]{id});
// db.close();
//// Toast.makeText(NavDDetailView.this, "Insert into columnID " + insertColumn, Toast.LENGTH_SHORT).show();
//// Toast.makeText(NavDDetailView.this, "Inserted data into columnID " + insertColumnValue, Toast.LENGTH_SHORT).show();
//
// }
//
//
//
//}
//
//
//
| true |
d836545f48f2c1f6f3a2d67d44d974c2609a877b | Java | notmyown/de.nmo.eclipse | /de.nmo.eclipse.ui.games/src/de/nmo/eclipse/ui/games/KonamiCode.java | UTF-8 | 2,449 | 2.078125 | 2 | [] | no_license | package de.nmo.eclipse.ui.games;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IStartup;
/**
*
*
* @author Bergen, Marco (I-EA-25, extern)
* @since 03.08.2017
*/
public class KonamiCode extends PropertyTester implements IStartup {
static boolean konami = false;
String typed = "";
final static String code = "Up;Up;Down;Down;Left;Right;Left;Right;B;A;";
@Override
public void earlyStartup() {
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run() {
Display display = Display.getDefault();
display.addFilter(SWT.KeyDown, new Listener()
{
@Override
public void handleEvent(Event event) {
if (konami) {
return;
}
event.doit = false;
switch (event.keyCode) {
case 16777219: {
KonamiCode.this.typed += "Left;";
break;
}
case 16777220: {
KonamiCode.this.typed += "Right;";
break;
}
case 16777217: {
KonamiCode.this.typed += "Up;";
break;
}
case 16777218: {
KonamiCode.this.typed += "Down;";
break;
}
case 97: {
KonamiCode.this.typed += "A;";
break;
}
case 98: {
KonamiCode.this.typed += "B;";
break;
}
default: {
KonamiCode.this.typed = "";
break;
}
}
if (code.equals(KonamiCode.this.typed)) {
konami = true;
System.setProperty("de.nmo.eclipse.ui.games.systemTest", "konami");
MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "NMO Games",
"Sie haben erfolgreich NMO Games freigeschaltet. Nutzen sie das 'NMO Games' Menu.");
}
}
});
}
});
}
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
return konami;
}
}
| true |
4b56d5ce169134ddb870041b9e69032c0e871d60 | Java | AT-03/coding | /src/main/java/org/fundacionjala/coding/Ruber/EANValidator.java | UTF-8 | 1,239 | 3.375 | 3 | [] | no_license | package org.fundacionjala.coding.Ruber;
/**
* Created by Ruber Cuellar on 2/21/2017.
*/
public final class EANValidator {
private static final int PAR = 1;
private static final int IMPAR = 3;
private static final int DIVISOR = 10;
/**
* Constructor.
*/
private EANValidator() {
}
/**
* Validate the number if is valid.
* @param num the number to validate
* @return boolean
*/
public static boolean validate(final String num) {
int suma = 0;
int[] numbers = convertArray(num);
for (int i = 0; i < numbers.length - 1; i++) {
suma += i % 2 == 0 ? numbers[i] * PAR : numbers[i] * IMPAR;
}
suma = suma % DIVISOR == 0 ? 0 : DIVISOR - (suma % DIVISOR);
return suma == numbers[numbers.length - 1];
}
/**
* This method convert a String into array of numbers.
* @param num The string to convert
* @return int[] with numbers
*/
public static int[] convertArray(final String num) {
int[] numbers = new int[num.length()];
for (int i = 0; i < num.length(); i++) {
numbers[i] = Integer.parseInt(String.valueOf(num.charAt(i)));
}
return numbers;
}
}
| true |
d60b37c5511742a5dfdc1a7c9e8d2e12d91687ad | Java | Kadphol/basic-java-test | /GetEmployee/src/main/java/Employee.java | UTF-8 | 1,430 | 2.8125 | 3 | [] | no_license | public class Employee {
private int employeeId;
private int threadId;
private short id;
private short albumId;
private String title;
private String url;
private String thumbnailUrl;
public Employee() { }
public Employee(int employeeId, int threadId, short id, short albumId, String title, String url, String thumbnailUrl) {
this.employeeId = employeeId;
this.threadId = threadId;
this.id = id;
this.albumId = albumId;
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
public int getEmployeeId() { return employeeId; }
public void setEmployeeId(int employeeId) { this.employeeId = employeeId; }
public short getId() { return id; }
public void setId(short id) { this.id = id; }
public short getAlbumId() { return albumId; }
public void setAlbumId(short albumId) { this.albumId = albumId; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public String getThumbnailUrl() { return thumbnailUrl; }
public int getThreadId() { return threadId; }
public void setThreadId(int threadId) { this.threadId = threadId; }
public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; }
}
| true |
7175d7dc4d1fbe0226631e96736de96142d179d8 | Java | TheScarastic/redfin_b5 | /SystemUIGoogle/sources/com/android/systemui/shared/system/ActivityManagerWrapper.java | UTF-8 | 2,232 | 2.09375 | 2 | [] | no_license | package com.android.systemui.shared.system;
import android.app.ActivityManager;
import android.app.ActivityTaskManager;
import android.content.pm.UserInfo;
import android.os.RemoteException;
import android.util.Log;
import java.util.List;
/* loaded from: classes.dex */
public class ActivityManagerWrapper {
private static final ActivityManagerWrapper sInstance = new ActivityManagerWrapper();
private final ActivityTaskManager mAtm = ActivityTaskManager.getInstance();
private ActivityManagerWrapper() {
}
public static ActivityManagerWrapper getInstance() {
return sInstance;
}
public int getCurrentUserId() {
try {
UserInfo currentUser = ActivityManager.getService().getCurrentUser();
if (currentUser != null) {
return currentUser.id;
}
return 0;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
public ActivityManager.RunningTaskInfo getRunningTask() {
return getRunningTask(false);
}
public ActivityManager.RunningTaskInfo getRunningTask(boolean z) {
List tasks = this.mAtm.getTasks(1, z);
if (tasks.isEmpty()) {
return null;
}
return (ActivityManager.RunningTaskInfo) tasks.get(0);
}
public void closeSystemWindows(String str) {
try {
ActivityManager.getService().closeSystemDialogs(str);
} catch (RemoteException e) {
Log.w("ActivityManagerWrapper", "Failed to close system windows", e);
}
}
public boolean isScreenPinningActive() {
try {
return ActivityTaskManager.getService().getLockTaskModeState() == 2;
} catch (RemoteException unused) {
return false;
}
}
public boolean isLockTaskKioskModeActive() {
try {
return ActivityTaskManager.getService().getLockTaskModeState() == 1;
} catch (RemoteException unused) {
return false;
}
}
public static boolean isHomeTask(ActivityManager.RunningTaskInfo runningTaskInfo) {
return runningTaskInfo.configuration.windowConfiguration.getActivityType() == 2;
}
}
| true |
1c3e60426624243d17df0829a19fdd445febd0f6 | Java | KristianHjelmsmarkKEA/Motorhome | /src/main/java/com/example/demo/Service/PriceService.java | UTF-8 | 1,009 | 2.171875 | 2 | [] | no_license | package com.example.demo.Service;
import com.example.demo.Model.Price;
import com.example.demo.Repository.PriceRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PriceService {
@Autowired
PriceRepo priceRepo;
public List<Price> fetchAll() {
return priceRepo.fetchAll();
}
public void addPrice(Price price) {
priceRepo.addPrice(price);
}
public Price findFeeID(int feeID) {
return priceRepo.findFeeID(feeID);
}
public void updateFeeInformation(int feeID, Price p) {
priceRepo.updateFeeInformation(feeID, p);
}
public List<Price> fetchItemsFromCategoryNum(int categoryNumber) {
return priceRepo.fetchItemsFromCategoryNum(categoryNumber);
}
public List<Price> removeCategoryPrice(List<Price> listToRemove, int category) {
return priceRepo.removeCategoryPrice(listToRemove, category);
}
} | true |
3c2795a0af441b5bcd428e38118492d2ec82fc40 | Java | 1RG/Random-pixel-render | /src/lt/rg/rpr/view/AlertWindow.java | UTF-8 | 902 | 2.75 | 3 | [] | no_license | package lt.rg.rpr.view;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class AlertWindow {
static public String INFORMATION = "i";
static public String WARNING = "w";
static public String ERROR = "e";
static public void showInfo(String header, String text, String status) {
Alert alert = new Alert(null);
switch (status) {
case "i":
alert.setAlertType(AlertType.INFORMATION);
alert.setTitle("Information");
break;
case "w":
alert.setAlertType(AlertType.WARNING);
alert.setTitle("Warning");
break;
case "e" :
alert.setAlertType(AlertType.ERROR);
alert.setTitle("Error");
break;
default:
alert.setAlertType(AlertType.ERROR);
alert.setTitle("System error");
break;
}
alert.setHeaderText(header);
alert.setContentText(text);
alert.showAndWait();
}
}
| true |
f7449ad0974f5dc5027ef13fcbcd9644b30ffcde | Java | dngjs1/java_8_ex | /src/com/woohun/a3/MemberMain.java | UTF-8 | 268 | 2.703125 | 3 | [] | no_license | package com.woohun.a3;
public class MemberMain {
public static void main(String[] args) {
/*Member m = new Member();
m.info();
Member m2 = new Member();
m2.info();*/
Point p = new Point();
p.hap(10, 15);
p.hap(10, 15.1f);
p.hap(10.2f, 14.1f);
}
} | true |
259bc9744cb3242312a2eb0a6d8a04897706287f | Java | zuoerlost/fendany | /demo/src/main/java/com/fendany/utils/ws/WebSocketClientDemo.java | UTF-8 | 4,218 | 2.34375 | 2 | [] | no_license | package com.fendany.utils.ws;
import com.neovisionaries.ws.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* Created by moilions on 2017/2/23.
*/
//@Component
public class WebSocketClientDemo implements InitializingBean {
private final static Logger LOGGER = LoggerFactory.getLogger(WebSocketClientDemo.class);
@Override
public void afterPropertiesSet() throws Exception {
LOGGER.info(" 【WS】【Client】:ready to connection server ");
WebSocket ws = new WebSocketFactory().createSocket("ws://localhost:9999/ws/abc/123");
ws.connect();
ws.addListener(new WebSocketListener() {
@Override
public void onStateChanged(WebSocket websocket, WebSocketState newState) throws Exception {
}
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
System.out.println("______________-----onConnected----_____________");
}
@Override
public void onConnectError(WebSocket websocket, WebSocketException cause) throws Exception {
System.out.println("______________-----onConnectError----_____________");
}
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
}
@Override
public void onFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onContinuationFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onTextFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onBinaryFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onCloseFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onPingFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onPongFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onTextMessage(WebSocket websocket, String text) throws Exception {
}
@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception {
}
@Override
public void onFrameSent(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onFrameUnsent(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onError(WebSocket websocket, WebSocketException cause) throws Exception {
}
@Override
public void onFrameError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame) throws Exception {
}
@Override
public void onMessageError(WebSocket websocket, WebSocketException cause, List<WebSocketFrame> frames) throws Exception {
}
@Override
public void onTextMessageError(WebSocket websocket, WebSocketException cause, byte[] data) throws Exception {
}
@Override
public void onSendError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame) throws Exception {
}
@Override
public void onUnexpectedError(WebSocket websocket, WebSocketException cause) throws Exception {
}
@Override
public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception {
}
});
}
}
| true |
b7f40ab27f821e3aa1ff338b46431f09757cb4a1 | Java | zhangji92/workspace | /wangfeng/Wangfeng0530/app/src/main/java/com/example/administrator/wangfeng0530/Wang0531.java | UTF-8 | 721 | 2.28125 | 2 | [] | no_license | package com.example.administrator.wangfeng0530;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Wang0531 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wang0531);
Intent intent=getIntent();//获取一个intent
String str=intent.getStringExtra("price");//获取intent中的内容
TextView textView=(TextView)findViewById(R.id.text_View);//获取xml中TextView中的id
textView.setText("显示:"+str);//将获取的内容放到xml压面上
}
}
| true |
f9da6c802e6d180d07a03eca842b545cafc8eef9 | Java | dennohdee/hrm_android | /app/src/main/java/com/example/hrm/UserRoomDatabase.java | UTF-8 | 800 | 2.234375 | 2 | [] | no_license | package com.example.hrm;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Entity;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(entities = UserRoom.class, exportSchema = false,version = 1)
public abstract class UserRoomDatabase extends RoomDatabase {
private static final String DB_NAME = "user_db";
private static UserRoomDatabase instance;
public static synchronized UserRoomDatabase getInstance(Context context){
if(instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(), UserRoomDatabase.class, DB_NAME)
.fallbackToDestructiveMigration()
.build();
}
return instance;
}
public UserRoomDao userRoomDao;
}
| true |
863ab601beb26d408bb059a612389989f6b3ce25 | Java | nkutsche/net.sqf.utils.process | /src/net/sqf/utils/process/queues/Task.java | UTF-8 | 2,443 | 2.734375 | 3 | [] | no_license | package net.sqf.utils.process.queues;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import javax.swing.SwingWorker;
import net.sqf.utils.process.queues.listeners.QueueListener;
public abstract class Task<IOType> extends SwingWorker<IOType, IOType> implements PropertyChangeListener {
private final String description;
private IOType input = null;
private ArrayList<QueueListener<IOType>> startListener = new ArrayList<QueueListener<IOType>>();
private ArrayList<QueueListener<IOType>> endListener = new ArrayList<QueueListener<IOType>>();
private final ArrayList<QueueListener<IOType>> cancelListener = new ArrayList<QueueListener<IOType>>();
public Task(String description){
this.description = description;
this.addPropertyChangeListener(this);
}
public void start(IOType input) {
this.input = input;
processStartListener();
this.execute();
}
@Override
protected IOType doInBackground() throws Exception{
try {
IOType output = process(this.input);
this.setProgress(100);
return output;
} catch (Exception e) {
this.cancel(e);
throw e;
}
}
@Override
protected void done() {
// TODO Auto-generated method stub
super.done();
}
public abstract IOType process(IOType input) throws Exception;
public boolean isFinished() {
return this.getState().equals(SwingWorker.StateValue.DONE);
}
@Override
public String toString() {
return this.description;
}
protected void cancel(Exception e){
for (QueueListener<IOType> lis : this.cancelListener) {
lis.processCancel(this, e);
}
this.cancel(true);
}
public void addCancelListener(QueueListener<IOType> listener){
this.cancelListener.add(listener);
}
public void addEndListener(QueueListener<IOType> listener) {
this.endListener.add(listener);
}
private void processEndListener() {
for (QueueListener<IOType> lis : this.endListener) {
lis.processEnd(this);
}
}
public void addStartListener(QueueListener<IOType> listener) {
this.startListener.add(listener);
}
private void processStartListener() {
for (QueueListener<IOType> lis : this.startListener) {
lis.processStart(this);
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("state".equals(evt.getPropertyName())
&& SwingWorker.StateValue.DONE == evt.getNewValue()) {
processEndListener();
}
}
}
| true |
a612643cbc808771b4be4b0123e1fe97f910ca5b | Java | pwaba/TestApp | /app/src/main/java/com/example/peter/testapp/MainActivity.java | UTF-8 | 1,750 | 2.078125 | 2 | [] | no_license | package com.example.peter.testapp;
import android.app.Activity;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.example.peter.testapp.users.User;
import com.example.peter.testapp.users.UserHandler;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
public class MainActivity extends Activity {
private UserHandler userHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.userHandler = new UserHandler(getApplicationContext());
}
public void onLoginClick(View view) {
setContentView(R.layout.login_page);
}
public void onLoginClick2(View view) {
Button b1, b2;
EditText ed1, ed2;
b1 = (Button) findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText) findViewById(R.id.editText2);
b2 = (Button) findViewById(R.id.button2);
if (this.userHandler.checkUser(ed1.getText().toString(), ed2.getText().toString())) {
Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_SHORT).show();
setContentView(R.layout.overview_main);
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
}
}
| true |
9188b5704f101d858003686ef61a147096a63828 | Java | joe-tong/shiro | /src/main/java/com/werner/ping/service/Impl/IPrivilegeServiceImpl.java | UTF-8 | 1,342 | 2.109375 | 2 | [] | no_license | package com.werner.ping.service.Impl;
import com.werner.ping.bean.Privilege;
import com.werner.ping.mapper.PrivilegeMapper;
import com.werner.ping.service.IPrivilegeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author 童平平
* @Title: prilivilegeDemo
* @Package com.werner.ping.service.Impl
* @Description: TODO(用一句话描述该文件做什么)
* @date 2017.11.23 19:48
*/
@Service("privilegeService")
public class IPrivilegeServiceImpl implements IPrivilegeService{
@Resource
PrivilegeMapper privilegeMapper;
@Override
public List<String> selectAllUrl() {
List<String> allUrl = privilegeMapper.selectAllUrl();
return allUrl;
}
public List<Privilege> findPriByLoginname(String loginname){
if(loginname == null ||loginname.equals("")){
return null;
}
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole("超级管理员")){
return privilegeMapper.selectAll();
}
List<Privilege> privilegeList = privilegeMapper.selectPriByLoginname(loginname);
return privilegeList;
}
}
| true |
d1ab78d3ab3b5a054a3f477b950ed3d768e89152 | Java | andrelgirao22/truffle-api | /src/main/java/br/com/alg/trufflesapi/resources/StateResouce.java | UTF-8 | 980 | 2.21875 | 2 | [] | no_license | package br.com.alg.trufflesapi.resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import br.com.alg.trufflesapi.model.City;
import br.com.alg.trufflesapi.model.State;
import br.com.alg.trufflesapi.services.StateService;
@RestController
public class StateResouce {
@Autowired
private StateService service;
@GetMapping("/state")
public ResponseEntity<List<State>> listItem() {
return ResponseEntity.status(HttpStatus.OK).body(service.listAll());
}
@GetMapping("/city/{uf}")
public ResponseEntity<List<City>> listCities(@PathVariable("uf") String uf) {
return ResponseEntity.status(HttpStatus.OK).body(this.service.findCitiesByUf(uf));
}
}
| true |
db9b29eb2e114d4b0491d848e320513ae6aea02d | Java | zubedooo/JDBCHibernate | /hibernate-eclipse-postgresqlAnno/src/main/java/com/cms/deloitte/model/CardDetail.java | UTF-8 | 994 | 2.125 | 2 | [] | no_license | package com.cms.deloitte.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "CardDetail")
public class CardDetail {
@Id
@GeneratedValue
@Column
private int cardId;
@Column
private String bankName;
@ManyToOne
@JoinColumn(name = "customerId")
private AmazonCustomer amazonCustomer;
public int getCardId() {
return cardId;
}
public void setCardId(int cardId) {
this.cardId = cardId;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public AmazonCustomer getAmazonCustomer() {
return amazonCustomer;
}
public void setAmazonCustomer(AmazonCustomer amazonCustomer) {
this.amazonCustomer = amazonCustomer;
}
}
| true |
28844d0f03b2e3c1cc04f53302010fd681c4d877 | Java | pbartoszek/countmeup | /src/main/java/com/countmeup/controller/ResultsController.java | UTF-8 | 712 | 2.046875 | 2 | [] | no_license | package com.countmeup.controller;
import com.countmeup.domain.ResultService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class ResultsController {
private final ResultService resultService;
public ResultsController(ResultService resultService) {
this.resultService = resultService;
}
@GetMapping(value = "results",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Long> getResults() {
return resultService.getResults();
}
}
| true |
fda5b3325e7b989f86539daa7571073933f05628 | Java | jtap60/com.estr | /src/com/estrongs/android/pop/spfs/CreateSiteFileObject.java | UTF-8 | 408 | 1.65625 | 2 | [] | no_license | package com.estrongs.android.pop.spfs;
import com.estrongs.fs.impl.r.b;
import com.estrongs.fs.w;
public class CreateSiteFileObject
extends b
{
public CreateSiteFileObject(String paramString)
{
super("SP://" + w.K.c(), w.K, paramString);
}
}
/* Location:
* Qualified Name: com.estrongs.android.pop.spfs.CreateSiteFileObject
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
a8b16de58ce68ebaa93716b5635c2624c3671cc7 | Java | lopotun/TQuickFix | /src/main/java/net/kem/tquickfix/builder/QFMessageMapperBuilder.java | UTF-8 | 6,637 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package net.kem.tquickfix.builder;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: EvgenyK
* Date: 10/30/14
* Time: 2:43 PM
* Generates QF Component class file.
*/
public class QFMessageMapperBuilder {
private static final StringBuilder PUT_STATEMENTS = new StringBuilder(16384);
private static final String PUT_TEMPLATE = "\t\t\tMESSAGE_TYPE_TO_PARSE_METHOD.put(\"%s\", %s.class.getMethod(\"parse\", List.class, MutableInt.class, QFBuilderConfig.class));%n";
private static final String TEMPLATE_MESSAGE_MAPPER = "package " + QFBuilder.getSoucesPackage() + "$VER;\n" +
"\n" +
"import net.kem.tquickfix.MessageMapper;\n" +
"import net.kem.tquickfix.builder.QFBuilderConfig;\n" +
"import " + QFBuilder.getSoucesPackage() + "$VER.message.*;\n" +
"\n" +
"import org.apache.commons.lang3.mutable.MutableInt;\n" +
"\n" +
"import java.lang.reflect.Method;\n" +
"import java.util.HashMap;\n" +
"import java.util.List;\n" +
"import java.util.Map;\n" +
"\n" +
"/**\n" +
" * Autogenerated utility class that maps QF message type to QF message's \"parse\" method.\n" +
" */\n" +
"public class QFMessageMapper implements MessageMapper {\n" +
"\tprivate static final QFMessageMapper INSTANCE = new QFMessageMapper();\n" +
"\tprivate static final Map<String, Method> MESSAGE_TYPE_TO_PARSE_METHOD = new HashMap<String, Method>();\n" +
"\n" +
"\tstatic {\n" +
"\t\ttry {\n" +
"$MESSAGE_TYPE_TO_PARSE_METHOD" +
"\t\t} catch(NoSuchMethodException e) {\n" +
"\t\t\te.printStackTrace();\n" +
"\t\t}\n" +
"\t}\n" +
"\n" +
"\tpublic static QFMessageMapper getInstance() {\n" +
"\t\treturn INSTANCE;\n" +
"\t}\n" +
"\n" +
"\tpublic Method getMessageByType(String msgType) {\n" +
"\t\treturn MESSAGE_TYPE_TO_PARSE_METHOD.get(msgType);\n" +
"\t}\n" +
"}";
private static final Map<CharSequence, CharSequence> VERSION_TO_BEGIN_STRING_VALUE = new HashMap<>(10);
static {
VERSION_TO_BEGIN_STRING_VALUE.put("vfixt11", "FIXT.1.1");
VERSION_TO_BEGIN_STRING_VALUE.put("v50sp2", "FIX.5.0SP2");
VERSION_TO_BEGIN_STRING_VALUE.put("v50sp1", "FIX.5.0SP1");
VERSION_TO_BEGIN_STRING_VALUE.put("v50", "FIX.5.0");
VERSION_TO_BEGIN_STRING_VALUE.put("v44", "FIX.4.4");
VERSION_TO_BEGIN_STRING_VALUE.put("v40", "FIX.4.0");
}
private static final String TEMPLATE_QF_MESSAGE = "package " + QFBuilder.getSoucesPackage()+ "$VER.message;\n" +
"\n" +
"import net.kem.tquickfix.blocks.QFCommonMessage;\n" +
"import net.kem.tquickfix.blocks.QFField;\n" +
"import net.kem.tquickfix.builder.QFBuilderConfig;\n" +
"import "+ QFBuilder.getSoucesPackage() + "$VER.component.StandardHeaderComponent;\n" +
"import "+ QFBuilder.getSoucesPackage() + "$VER.component.StandardTrailerComponent;\n" +
"import "+ QFBuilder.getSoucesPackage() + "$VER.field.BeginString;\n" +
"import "+ QFBuilder.getSoucesPackage() + "$VER.field.CheckSum;\n" +
"import "+ QFBuilder.getSoucesPackage() + "$VER.field.MsgType;\n" +
"\n" +
"/**\n" +
" * Abstract presentation of FIX message element.\n" +
" */\n" +
"public abstract class QFMessage extends QFCommonMessage {\n" +
"\tprotected StandardHeaderComponent standardHeader;\n" +
"\tprotected StandardTrailerComponent standardTrailer;\n" +
"\n" +
"\tprotected QFMessage(String name, String type) {\n" +
"\t\tthis(name, type, false, null);\n" +
"\t}\n" +
" protected QFMessage(String name, String type, QFBuilderConfig config) {\n" +
"\t\tthis(name, type, false, config);\n" +
"\t}\n" +
"\n" +
"\tprotected QFMessage(String name, String type, boolean createHeaderTrailer) {\n" +
"\t\tthis(name, type, createHeaderTrailer, null);\n" +
"\t}\n" +
"\n" +
"\tprotected QFMessage(String name, String type, boolean createHeaderTrailer, QFBuilderConfig config) {\n" +
"\t\tsuper(name, type, config);\n" +
"\n" +
"\t\tif(createHeaderTrailer) {\n" +
"\t\t\tstandardHeader = new StandardHeaderComponent(config);\n" +
"\t\t\tstandardHeader.setBeginString(BeginString.getInstance(\"$BEGIN_STRING_VALUE\"));\n" +
"\t\t\tstandardHeader.setMsgType(MsgType.getInstance(type, QFField.Validation.FULL));\n" +
"\n" +
"\t\t\tstandardTrailer = new StandardTrailerComponent(config);\n" +
"\t\t\tstandardTrailer.setCheckSum(CheckSum.getInstance(\"000\"));\n" +
"\t\t}\n" +
"\t}\n" +
"\n" +
"\tpublic StandardHeaderComponent getStandardHeaderComponent() {\n" +
"\t\treturn standardHeader;\n" +
"\t}\n" +
"\n" +
"\tpublic void setStandardHeaderComponent(StandardHeaderComponent header) {\n" +
"\t\tthis.standardHeader = header;\n" +
"\t}\n" +
"\n" +
"\tpublic StandardTrailerComponent getStandardTrailerComponent() {\n" +
"\t\treturn standardTrailer;\n" +
"\t}\n" +
"\n" +
"\tpublic void setStandardTrailerComponent(StandardTrailerComponent trailer) {\n" +
"\t\tthis.standardTrailer = trailer;\n" +
"\t}\n" +
"}";
public static void addMessageMapping(String msgName, String msgType) {
PUT_STATEMENTS.append(String.format(PUT_TEMPLATE, msgType, msgName+"Message"));
}
public static void clearMessageMapping() {
PUT_STATEMENTS.setLength(0);
}
public static String buildTypeToMessageMapping() {
return TEMPLATE_MESSAGE_MAPPER.replace("$VER", QFBuilder.qfVersion).replace("$MESSAGE_TYPE_TO_PARSE_METHOD", PUT_STATEMENTS);
}
public static String buildQFMessage(CharSequence qfVersion) {
return TEMPLATE_QF_MESSAGE.replace("$VER", QFBuilder.qfVersion).replace("$MESSAGE_TYPE_TO_PARSE_METHOD", PUT_STATEMENTS).replace("$BEGIN_STRING_VALUE", VERSION_TO_BEGIN_STRING_VALUE.get(qfVersion));
}
} | true |
ea856d3882c62650bd600bf3dc55811863441b8f | Java | LudweNyobo88/ReversePolishNotation1 | /src/RPN.java | UTF-8 | 4,124 | 3.703125 | 4 | [] | no_license | import java.util.Scanner;
class StackNode
{
/*Stacks constructor with parameters*/
public StackNode(double data, StackNode underneath) {
/*calling the function of all stacks parameters*/
this.data = data;
this.underneath = underneath;
}
//Declaration of the StackNode constructor parameters
public StackNode underneath;
public double data;
}
public class RPN {
public void into(double new_data)
{
StackNode new_node = new StackNode(new_data, top);
top = new_node;
}
public double outof( )
{
double top_data = top.data;
top = top.underneath;
return top_data;
}
//RPN calculator method to act on a given command
public RPN(String command)
{
top = null;
this.command = command;/*calling the command parameter*/
}
public double get( ) //Getter method
{
double a, b;
int j;
for(int i = 0; i < command.length( ); i++)
{
// if it's a digit
if(Character.isDigit(command.charAt(i)))
{
double number;
// get a string of the number
String temp = "";
for(j = 0; (j < 100) && (Character.isDigit(command.charAt(i)) || (command.charAt(i) == '.')); j++, i++)
{
temp = temp + String.valueOf(command.charAt(i));
}
// convert to double and add to the stack conditions
number = Double.parseDouble(temp);
into(number);
}
else if(command.charAt(i) == '+') {/*adds top two elements in the stack, and replaces them in the stack with the answer.*/
b = outof( );
a = outof( );
into(a + b);
}
else if(command.charAt(i) == '-') {/*subtracts the top two elements in the stack, and replaces them in the stack with the answer.*/
b = outof( );
a = outof( );
into(a - b);
}
else if(command.charAt(i) == '*') {/*multiplies the top two elements in the stack, and replaces them in the stack with the answer*/
b = outof( );
a = outof( );
into(a * b);
}
else if(command.charAt(i) == '/') {/*divides the top two elements in the stack, and replaces them in the stack with the answer*/
b = outof( );
a = outof( );
into(a / b);
}
else if(command.charAt(i) == '^') {/*exponentiation operation were x y^ would be x to the yth power (x^y).*/
b = outof( );
a = outof( );
into(Math.pow(a, b));
}
else if(command.charAt(i) != ' ') {
throw new IllegalArgumentException( );
}
}
double val = outof( );
return val; /*returning the value*/
}
//Declaration of the variables
private String command;
private StackNode top;
/* main method */
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
while(true)
{
System.out.println("Enter RPN expression or \"quit\".");/*Input display*/
String line = in.nextLine( );
if(line.equals("quit")) /*Condition for quiting the calculator*/
{
in.close();
break;
} else {
RPN calc = new RPN(line);
System.out.printf("Answer is %f\n" , calc.get( ));/*Output/answer display*/
}
}
}
}
| true |
37b169568e5f4abe7fae1724cabe720db81bf3ed | Java | JanDurry/StudentFitnessTracker | /app/src/main/java/android/mi/ur/studentfitnesstracker/Database/SessionDatabaseAdapter.java | UTF-8 | 8,342 | 2.421875 | 2 | [] | no_license | package android.mi.ur.studentfitnesstracker.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.mi.ur.studentfitnesstracker.Constants.Constants;
import android.mi.ur.studentfitnesstracker.Objects.SessionItem;
import android.util.Log;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
/**
* Created by JanDurry on 24.02.2018.
*/
public class SessionDatabaseAdapter {
private SessionDBOpenHelper dbHelper;
private SQLiteDatabase db;
public SessionDatabaseAdapter(Context context) {
dbHelper = new SessionDBOpenHelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
public void open() throws SQLException {
try {
db = dbHelper.getWritableDatabase();
} catch (SQLException e) {
db = dbHelper.getReadableDatabase();
Log.e(Constants.DB_TAG, e.toString());
}
}
public void close() {
db.close();
}
public boolean checkIfUserDataExists() {
String count = "SELECT count(*) FROM " + Constants.DATABASE_TABLE_USER;
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0) {
return true;
}
return false;
}
public void updateUserData(int weight, int sessionGoal) {
String strFilter = "_id=1";
ContentValues args = new ContentValues();
args.put(Constants.KEY_WEIGHT, weight);
args.put(Constants.KEY_GOAL, sessionGoal);
Date currentTime = Calendar.getInstance().getTime();
args.put(Constants.KEY_GOAL_DATE, currentTime.toString());
db.update(Constants.DATABASE_TABLE_USER, args, strFilter, null);
}
public void updateUserGoal(int sessionGoal, String date, String goalDate) {
String strFilter = "_id=1";
ContentValues args = new ContentValues();
args.put(Constants.KEY_DATE, date);
args.put(Constants.KEY_GOAL, sessionGoal);
args.put(Constants.KEY_GOAL_DATE, goalDate);
db.update(Constants.DATABASE_TABLE_USER, args, strFilter, null);
}
public int getUserWeight() {
int weight = Constants.DEFAULT_WEIGHT;
Cursor cursor = db.query(Constants.DATABASE_TABLE_USER, new String[] { Constants.KEY_ID,
Constants.KEY_WEIGHT, Constants.KEY_GOAL}, null, null, null, null, null);
if (cursor.moveToFirst()) {
weight = cursor.getInt(Constants.COLUMN_WEIGHT_INDEX);
}
return weight;
}
public String getUserGoalDate() {
String date = Constants.DEFAULT_GOAL_DATE;
Cursor cursor = db.query(Constants.DATABASE_TABLE_USER, new String[] { Constants.KEY_ID,
Constants.KEY_WEIGHT, Constants.KEY_GOAL, Constants.KEY_DATE, Constants.KEY_GOAL_DATE}, null, null, null, null, null);
if (cursor.moveToFirst()) {
date = cursor.getString(Constants.COLUMN_GOAL_DATE_INDEX);
}
return date;
}
public int getUserGoal() {
int sessionGoal = Constants.DEFAULT_GOAL_KCAL;
Cursor cursor = db.query(Constants.DATABASE_TABLE_USER, new String[] { Constants.KEY_ID,
Constants.KEY_WEIGHT, Constants.KEY_GOAL}, null, null, null, null, null);
if (cursor.moveToFirst()) {
sessionGoal = cursor.getInt(Constants.COLUMN_SESSION_GOAL_INDEX);
}
return sessionGoal;
}
/* public int getTotalkCal() {
int totalkCal = Constants.DEFAULT_TOTAL_KCAL;
Cursor cursor = db.query(Constants.DATABASE_TABLE, new String[] { Constants.KEY_TOTAL_KCAL},
null, null, null, null, null);
if (cursor.moveToFirst()) {
totalkCal = cursor.getInt(Constants.COLUMN_TOTAL_KCAL_INDEX);
}
return totalkCal;
}*/
public long insertUserData(int weight, int sessionGoal, String date, String goalDate) {
ContentValues userValues = new ContentValues();
userValues.put(Constants.KEY_WEIGHT, weight);
userValues.put(Constants.KEY_GOAL, sessionGoal);
userValues.put(Constants.KEY_DATE, date);
userValues.put(Constants.KEY_GOAL_DATE, goalDate);
return db.insert(Constants.DATABASE_TABLE_USER, null, userValues);
}
public long insertSessionItem(SessionItem session) {
ContentValues sessionValues = new ContentValues();
sessionValues.put(Constants.KEY_TYPE, session.getSessionType());
sessionValues.put(Constants.KEY_DISTANCE, session.getDistance());
sessionValues.put(Constants.KEY_DATE, session.getDate());
sessionValues.put(Constants.KEY_PACE, session.getPace());
sessionValues.put(Constants.KEY_KCAL, session.getkCal());
sessionValues.put(Constants.KEY_TIME, session.getTime());
return db.insert(Constants.DATABASE_TABLE, null, sessionValues);
}
/*public long resetTotalkCal() {
ContentValues totalkCalValue = new ContentValues();
totalkCalValue.put(Constants.KEY_TOTAL_KCAL, "0");
return db.insert(Constants.DATABASE_TABLE, null, totalkCalValue);
}*/
public void removeSessionItem(SessionItem session) {
String toDelete = Constants.KEY_DATE + "=?";
String[] deleteArguments = new String[]{session.getDate()};
db.delete(Constants.DATABASE_TABLE, toDelete, deleteArguments);
}
public ArrayList<SessionItem> getAllSessionItems() {
ArrayList<SessionItem> sessions = new ArrayList<SessionItem>();
Cursor cursor = db.query(Constants.DATABASE_TABLE, new String[] { Constants.KEY_ID,
Constants.KEY_TYPE, Constants.KEY_DISTANCE, Constants.KEY_DATE, Constants.KEY_PACE,
Constants.KEY_KCAL, Constants.KEY_TIME }, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String type = cursor.getString(Constants.COLUMN_TYPE_INDEX);
int distance = cursor.getInt(Constants.COLUMN_DISTANCE_INDEX);
String date = cursor.getString(Constants.COLUMN_DATE_INDEX);
String pace = cursor.getString(Constants.COLUMN_PACE_INDEX);
double kcal = cursor.getDouble(Constants.COLUMN_KCAL_INDEX);
String time = cursor.getString(Constants.COLUMN_TIME_INDEX);
sessions.add(new SessionItem(type, distance, time, kcal, pace, date));
} while (cursor.moveToNext());
}
return sessions;
}
//** private class to create database tables **/
private class SessionDBOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_CREATE = "create table " + Constants.DATABASE_TABLE
+ " (" + Constants.KEY_ID + " integer primary key autoincrement, "
+ Constants.KEY_TYPE + " text not null, "
+ Constants.KEY_DISTANCE + " integer not null, "
+ Constants.KEY_DATE + " text, "
+ Constants.KEY_GOAL_DATE + " text, "
+ Constants.KEY_PACE + " text not null, "
+ Constants.KEY_KCAL + " double not null, "
+ Constants.KEY_TIME + " text not null);";
private static final String DATABASE_CREATE_USER = "create table " + Constants.DATABASE_TABLE_USER
+ " (" + Constants.KEY_ID + " integer primary key autoincrement, "
+ Constants.KEY_WEIGHT + " int not null, "
+ Constants.KEY_GOAL + " int not null, "
+ Constants.KEY_DATE + " String, "
+ Constants.KEY_GOAL_DATE + " String);";
public SessionDBOpenHelper(Context c, String dbname,
SQLiteDatabase.CursorFactory factory, int version) {
super(c, dbname, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE_USER);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
| true |
3939b003db62ddaf209a18f5d61256dd0e76173f | Java | HuyaAuto/jsoagger-fx | /jsoagger-jfxcore-engine/src/main/java/io/github/jsoagger/jfxcore/engine/controller/main/layout/CardViewStructure.java | UTF-8 | 2,542 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | /*-
* ========================LICENSE_START=================================
* JSoagger
* %%
* Copyright (C) 2019 JSOAGGER
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package io.github.jsoagger.jfxcore.engine.controller.main.layout;
import io.github.jsoagger.jfxcore.engine.controller.main.RootStructureController;
import javafx.beans.property.ObjectProperty;
import javafx.scene.layout.Pane;
/**
* @author Ramilafananana VONJISOA
* @mailto yvonjisoa@nexitia.com
* @date 2019
*/
public class CardViewStructure extends ViewStructure implements IViewStructure {
/**
* Constructor
*/
public CardViewStructure() {}
/**
* @{inheritedDoc}
*/
@Override
public void selectTab(int tabIndex) {}
/**
* @{inheritedDoc}
*/
@Override
public void removeTab(String tabId) {}
/**
* @{inheritedDoc}
*/
@Override
public void removeTab(int tabIndex) {}
/**
* @{inheritedDoc}
*/
@Override
public void selectTab(String tabId) {}
/**
* @{inheritedDoc}
*/
@Override
public void add(RootStructureController rootStructure) {}
/**
* @{inheritedDoc}
*/
@Override
public void remove(RootStructureController rootStructure) {}
/**
* @{inheritedDoc}
*/
@Override
public void closeAllTabs() {}
/**
* @{inheritedDoc}
*/
@Override
public ObjectProperty<ViewStructureStatus> statusProperty() {
return null;
}
/**
* @{inheritedDoc}
*/
@Override
public ViewStructureStatus getStatus() {
return null;
}
/**
* @{inheritedDoc}
*/
@Override
public void setStatus(ViewStructureStatus status) {}
/**
* @{inheritedDoc}
*/
@Override
public Pane getRootViewStructure() {
return null;
}
/**
* @{inheritedDoc}
*/
@Override
public Pane getRootViewStructureHeaderArea() {
return null;
}
/**
* @{inheritedDoc}
*/
@Override
public Pane getRootViewStructureContentArea() {
return null;
}
}
| true |
5d344c01ea77c8fc07864e0fe0960ef04bbfb436 | Java | nareshreddy0789/QAwork | /pageobjects/src/main/java/com/apple/carnival/ui/HomePage.java | UTF-8 | 1,393 | 2.1875 | 2 | [] | no_license | package com.apple.carnival.ui;
import org.json.JSONObject;
import com.apple.carnival.qa.parser.JsonParserUtil;
import com.apple.carnival.ui.utilities.ElementLocatorUtility;
public class HomePage extends CarnivalUI {
private String jsonCreateRequestLink = "CreateRequestLink";
private String jsonOverViewOfHosts = "OverViewOfHosts";
private String jsonLogout = "LogOut";
private String jsonLocatorFile = "src/main/resources/locators/HomePage.JSON";
private static JSONObject root=null;
public HomePage(){
if(root == null)
root = JsonParserUtil.parseJsonFile(jsonLocatorFile);
}
public void getCreateRequestPage(){
carnivalWebDriver.findElement(ElementLocatorUtility.getWebDriverLocator(root,jsonCreateRequestLink)).click();
}
public void getOverViewOfHostsPage(){
carnivalWebDriver.findElement(ElementLocatorUtility.getWebDriverLocator(root,jsonOverViewOfHosts)).click();
}
public void logout() {
carnivalWebDriver.findElement(ElementLocatorUtility.getWebDriverLocator(root,jsonLogout)).click();
}
public void getInstallBuildPage() {
carnivalWebDriver.findElement(ElementLocatorUtility.getWebDriverLocator(root,"InstallBuild")).click();
}
public void getEnvironmentInfoPage() throws InterruptedException {
carnivalWebDriver.findElement(ElementLocatorUtility.getWebDriverLocator(root,"EnvironmentInfoLink")).click();
Thread.sleep(3000);
}
}
| true |
46132faf1bfd80c5333dd962aeb7a78c58f5f482 | Java | RafRunner/CheckOut | /src/bancoDeDados/ProdutoDAO.java | ISO-8859-1 | 4,021 | 3.046875 | 3 | [] | no_license | package bancoDeDados;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import dominio.Produto;
import dominio.Promocao;
public class ProdutoDAO {
private static final String SELECT_PRODUTO = "SELECT NOME, VALOR_UNITARIO FROM produtos WHERE IDENTIFICADOR = ?";
private static final String GET_PRODUTOS = "SELECT NOME, VALOR_UNITARIO, IDENTIFICADOR FROM produtos";
private static final String INSERT_PRODUTO = "INSERT INTO produtos (NOME, VALOR_UNITARIO, IDENTIFICADOR)"
+ "VALUES (?, ?, ?)";
private static final String UPDATE_PRODUTO = "UPDATE produtos SET VALOR_UNITARIO = ? WHERE IDENTIFICADOR = ?";
private static final String DELETE_PRODUTO = "DELETE FROM produtos WHERE IDENTIFICADOR = ?";
public static Produto getProduto(int identificador)
{
Produto produto = null;
try (Connection conexao = FabricaConexao.getConection();
PreparedStatement consulta = conexao.prepareStatement(SELECT_PRODUTO)){
consulta.setInt(1, identificador);
ResultSet resultado = consulta.executeQuery();
if(resultado.next()) {
String nome = resultado.getString("NOME");
BigDecimal valorUnitario = resultado.getBigDecimal("VALOR_UNITARIO");
produto = new Produto(identificador, nome, valorUnitario, new ArrayList<Promocao>());
ArrayList<Promocao> promocoes = PromocaoDAO.getPromocoes(produto);
produto.setPromocoes(promocoes);
}
else {
System.out.println("Produto no encontrado!");
}
}
catch(Exception e) {
e.printStackTrace();
}
return produto;
}
public static ArrayList<Produto> getProdutos()
{
ArrayList<Produto> produtos = new ArrayList<Produto>();
try (Connection conexao = FabricaConexao.getConection();
PreparedStatement consulta = conexao.prepareStatement(GET_PRODUTOS)){
ResultSet resultado = consulta.executeQuery();
while (resultado.next()) {
String nome = resultado.getString("NOME");
BigDecimal valorUnitario = resultado.getBigDecimal("VALOR_UNITARIO");
int identificador = resultado.getInt("IDENTIFICADOR");
Produto produto = new Produto(identificador, nome, valorUnitario, new ArrayList<Promocao>());
ArrayList<Promocao> promocoes = PromocaoDAO.getPromocoes(produto);
produto.setPromocoes(promocoes);
produtos.add(produto);
}
}
catch(Exception e) {
e.printStackTrace();
}
return produtos;
}
public static void inserirProduto(Produto produto)
{
try (Connection conexao = FabricaConexao.getConection();
PreparedStatement insercao = conexao.prepareStatement(INSERT_PRODUTO)){
insercao.setString(1, produto.getNome());
insercao.setBigDecimal(2, produto.getValor());
insercao.setInt(3, produto.getId());
insercao.executeUpdate();
}
catch(SQLException e1) {
System.out.println("Esse item j existe no Banco de dados! (id = " + produto.getId() + ", nome = " + produto.getNome()
+ ")\nPara atualizar seu valor, use:\n"
+ "ProdutoDAO.alterarProduto(Produto produto, BigDecimal novoValor)\n");
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void alterarProduto(Produto produto, BigDecimal novoValor)
{
try (Connection conexao = FabricaConexao.getConection();
PreparedStatement alteracao = conexao.prepareStatement(UPDATE_PRODUTO)){
alteracao.setBigDecimal(1, novoValor);
alteracao.setInt(2, produto.getId());
alteracao.execute();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void removerProduto(Produto produto)
{
try (Connection conexao = FabricaConexao.getConection();
PreparedStatement remocao = conexao.prepareStatement(DELETE_PRODUTO)){
remocao.setInt(1, produto.getId());
remocao.executeUpdate();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
| true |
8625d1390b6ce3322a100e0b68de39a90298d944 | Java | qinannmj/FireFly | /src/main/java/cn/com/sparkle/firefly/net/client/syncwaitstrategy/AbstractWaitStrategy.java | UTF-8 | 1,095 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | package cn.com.sparkle.firefly.net.client.syncwaitstrategy;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import cn.com.sparkle.firefly.net.netlayer.PaxosSession;
public abstract class AbstractWaitStrategy implements WaitStrategy {
private ReentrantLock lock = new ReentrantLock();
private AtomicInteger count = new AtomicInteger(0);
private Condition fullConfition = lock.newCondition();
@Override
public void fireStrategy(PaxosSession session) throws InterruptedException {
int c = count.incrementAndGet();
if (c >= 4) {
try {
lock.lock();
if (count.get() >= 4) {
fireStrategy(session, fullConfition);
}
} finally {
lock.unlock();
}
}
}
@Override
public void finishMessageSend() {
int c = count.decrementAndGet();
if (c > 4) {
try {
lock.lock();
fullConfition.notify();
} finally {
lock.unlock();
}
}
}
public abstract void fireStrategy(PaxosSession session, Condition fullCondition) throws InterruptedException;
}
| true |
f745952bc26f6ac90fc230936c5cc432c1b5cbf6 | Java | hj458377603/AndroidDNF | /lol/src/com/test/utils/adapters/LazyAdapter.java | WINDOWS-1252 | 2,226 | 2.109375 | 2 | [] | no_license | package com.test.utils.adapters;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.test.entity.news.NewsInfo;
import com.test.lol.R;
import com.test.utils.volley.VolleyApplication;
public class LazyAdapter extends BaseAdapter{
private Activity activity;
private List<NewsInfo> data;
private static LayoutInflater inflater = null;
public LazyAdapter(Activity a, List<NewsInfo> d,
PullToRefreshListView listView) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.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) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.news_item, null);
TextView title = (TextView) vi.findViewById(R.id.title); //
final NetworkImageView imageView = (NetworkImageView) vi
.findViewById(R.id.pic); // ͼ
NewsInfo news = data.get(position);
title.setText(news.title);
Log.d("getView", "position:" + position);
// ImageLoader imageLoader = new ImageLoader(mQueue, new ImageCache() {
// @Override
// public void putBitmap(String url, Bitmap bitmap) {
// }
//
// @Override
// public Bitmap getBitmap(String url) {
// return null;
// }
// });
ImageLoader imageLoader = VolleyApplication.getInstance()
.getImageLoader();
imageView.setDefaultImageResId(R.drawable.default_img);
imageView.setErrorImageResId(R.drawable.ic_launcher);
imageView.setImageUrl(news.pic_url, imageLoader);
return vi;
}
}
| true |
6d61f457c60e5c18d4aa6ae1ab32785933b89dfa | Java | ffakenz/DAS | /project/workspace/gobierno/web_portal/src/test/java/ar/edu/ubp/das/src/concesionarias/RegistrarConcesionariaInteractorTest.java | UTF-8 | 2,575 | 2.0625 | 2 | [] | no_license | package ar.edu.ubp.das.src.concesionarias;
import ar.edu.ubp.das.mvc.action.DynaActionForm;
import ar.edu.ubp.das.mvc.config.DatasourceConfig;
import ar.edu.ubp.das.src.concesionarias.daos.MSConcesionariasDao;
import ar.edu.ubp.das.src.core.InteractorResponse;
import ar.edu.ubp.das.src.core.ResponseForward;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import util.TestDB;
import java.sql.SQLException;
import static org.junit.Assert.*;
public class RegistrarConcesionariaInteractorTest {
MSConcesionariasDao msConcesionariasDao;
RegistrarConcesionariaInteractor registrarConcesionariaInteractor;
@Before
public void setup() throws SQLException {
TestDB.getInstance().cleanDB();
TestDB.getInstance().setUpDB();
final DatasourceConfig dataSourceConfig = TestDB.getInstance().getDataSourceConfig();
msConcesionariasDao = new MSConcesionariasDao();
msConcesionariasDao.setDatasource(dataSourceConfig);
registrarConcesionariaInteractor = new RegistrarConcesionariaInteractor(msConcesionariasDao);
}
@Test
public void test12_Register_concesionaria_ok() throws SQLException {
final DynaActionForm concesionariaForm = new DynaActionForm();
concesionariaForm.setItem("nombre", "concesionaria-test-1");
concesionariaForm.setItem("direccion", "Direccion test 123");
concesionariaForm.setItem("cuit", "cuit-test-123");
concesionariaForm.setItem("tel", "tel-test-123");
concesionariaForm.setItem("email", "test@test.com");
// Insert the concesionaria
final InteractorResponse<Boolean> result = registrarConcesionariaInteractor.execute(concesionariaForm);
assertEquals(ResponseForward.SUCCESS, result.getResponse());
assertTrue(result.getResult());
}
@Ignore
public void test12_Register_concesionaria_fail() throws SQLException {
final DynaActionForm concesionariaForm = new DynaActionForm();
concesionariaForm.setItem("nombre", "concesionaria-test-1");
concesionariaForm.setItem("direccion", "Direccion test 123");
concesionariaForm.setItem("cuit", "cuit-test-123");
concesionariaForm.setItem("tel", "tel-test-123");
// concesionariaForm.setItem("email", "test@test.com");
// Insert the concesionaria
final InteractorResponse<Boolean> result = registrarConcesionariaInteractor.execute(concesionariaForm);
assertEquals(ResponseForward.WARNING, result.getResponse());
assertFalse(result.getResult());
}
}
| true |
4b50e2af94e07ed69c5f8d9bf33c8310d472acab | Java | chrisyao19/LeetCode | /Hash/290/equals, same-value-different-obj problem.java | UTF-8 | 1,318 | 3.71875 | 4 | [] | no_license | public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] tmp = str.split(" ");
if(pattern.length()!=tmp.length) return false;
Map map = new HashMap();
for(Integer i=0; i<pattern.length();i++) { //using integer, no autoboxing-smae-value-different-object anymore.
// if(!map.containsKey(pattern.charAt(i))) {
// if(map.containsValue(tmp[i])) return false;
// map.put(pattern.charAt(i), tmp[i]);
// } else {
// if(!map.get(pattern.charAt(i)).equals(tmp[i])) return false;
// }
if(map.put(pattern.charAt(i),i)!=map.put(tmp[i],i)) return false;
}
return true;
}
}
// // These two have the same value
// new String("test").equals("test") // --> true
// // ... but they are not the same object
// new String("test") == "test" // --> false
// // ... neither are these
// new String("test") == new String("test") // --> false
// // ... but these are because literals are interned by
// // the compiler and thus refer to the same object
// "test" == "test" // --> true
// // ... but you should really just call Objects.equals()
// Objects.equals("test", new String("test")) // --> true
// Objects.equals(null, "test") // --> false | true |
f708c98eba7ce1abc5570f2b5e367eed9f19f81f | Java | joseman1991/Ecuaciones_No_Lineales | /src/main/PanelFalsaPosicion.java | UTF-8 | 15,952 | 2.0625 | 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 main;
import javax.swing.JOptionPane;
import org.nfunk.jep.JEP;
/**
*
* @author JOSE
*/
public class PanelFalsaPosicion extends javax.swing.JPanel {
/**
* Creates new form PanelBisección
*/
public PanelFalsaPosicion() {
initComponents();
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtFuncion = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtA = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtB = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtprecision = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtIteraciones = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
lb_raiz = new javax.swing.JLabel();
lb_iteraciones = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null}
},
new String [] {
"i", "a", "b", "Xi", "f(a)", "f(b)", "f(x)", "ξ "
}
));
jScrollPane1.setViewportView(jTable1);
jLabel1.setFont(new java.awt.Font("Andalus", 1, 24)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("SOLUCIÓN DE ECUACIÓN NO LINEAL POR EL MÉTODO DE FALSA POSICIÓN");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Función"));
jLabel2.setText("Función:");
jLabel3.setText("Intervalo A:");
jLabel4.setText("Intervalo B:");
jLabel5.setText("Precisión:");
jLabel6.setText("Iteracciones:");
jButton1.setText("Calcular");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));
jLabel7.setText("Raiz:");
lb_raiz.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lb_iteraciones.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel10.setText("Iteraciones alcanzadas");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(lb_iteraciones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lb_raiz, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(10, 10, 10))))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(lb_raiz, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lb_iteraciones, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jLabel6))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtIteraciones, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtprecision, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtFuncion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(txtA, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtB, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(29, 29, 29)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtFuncion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(txtB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtprecision, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtIteraciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
JEP j = new JEP();
j.addStandardConstants();
j.addStandardFunctions();
String def = txtFuncion.getText();
j.parseExpression(txtA.getText());// pasamos a convertr la expresion ingresada en la casilla A
double a = j.getValue();
j.parseExpression(txtB.getText());// pasamos a convertr la expresion ingresada en la casilla B
double b = j.getValue();
j.parseExpression(txtprecision.getText());// pasamos a convertr la expresion ingresada en la casilla de tolerancia
double precision = j.getValue();
Funcion f = new Funcion(def);
MetodoFalsaPosicion mb = new MetodoFalsaPosicion(jTable1);
int i = Integer.parseInt(txtIteraciones.getText());
double raiz = mb.obtenerRaiz(f, a, b, precision, i);
lb_iteraciones.setText(mb.getIteraciones() + "");
lb_raiz.setText(raiz + "");
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "ERROR EN LA LECTURA DE DATOS", "Mensaje de error", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JTable jTable1;
private javax.swing.JLabel lb_iteraciones;
private javax.swing.JLabel lb_raiz;
private javax.swing.JTextField txtA;
private javax.swing.JTextField txtB;
private javax.swing.JTextField txtFuncion;
private javax.swing.JTextField txtIteraciones;
private javax.swing.JTextField txtprecision;
// End of variables declaration//GEN-END:variables
}
| true |
a6f047141e3757b606e1fb715116afa8d4a7de8c | Java | ivan9105/MVC | /src/main/java/com/springapp/mvc/integration/weather/WeatherClient.java | UTF-8 | 1,600 | 2.296875 | 2 | [] | no_license | package com.springapp.mvc.integration.weather;
import com.springapp.mvc.integration.weather.schema.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.core.SoapActionCallback;
/**
* Created by ���� on 01.09.2015.
*/
public class WeatherClient extends WebServiceGatewaySupport{
private static Log log = LogFactory.getLog(WeatherClient.class);
private static ObjectFactory factory;
static {
factory = new ObjectFactory();
}
public GetCitiesByCountryResponse getCitiesByCountry(String countryNameLat) {
GetCitiesByCountry request = factory.createGetCitiesByCountry();
request.setCountryName(countryNameLat);
log.debug(String.format("Request forecast for: %s", countryNameLat));
return (GetCitiesByCountryResponse) getWebServiceTemplate().
marshalSendAndReceive(request, new SoapActionCallback("http://www.webserviceX.NET/GetCitiesByCountry"));
}
public GetWeatherResponse getWeatherByCity(String cityName, String countryNameLat) {
GetWeather request = factory.createGetWeather();
request.setCityName(cityName);
request.setCountryName(countryNameLat);
log.debug(String.format("Request forecat for: %s, %s", countryNameLat, cityName));
return (GetWeatherResponse) getWebServiceTemplate()
.marshalSendAndReceive(request, new SoapActionCallback("http://www.webserviceX.NET/GetWeather"));
}
}
| true |
27137b05338071652894208a8a139cd5d57257ed | Java | FitnessEasy/comfybus | /ComfyBus/app/src/main/java/com/example/duytungdao/comfybus/remind/JSONDISTANCEObjects/JSONobjectStart.java | UTF-8 | 256 | 1.570313 | 2 | [] | no_license | package com.example.duytungdao.comfybus.remind.JSONDISTANCEObjects;
import org.json.JSONObject;
/**
* Created by duy tung dao on 10/30/2016.
*/
public class JSONobjectStart {
public String address;
public JSONobjectStart(JSONObject input){
}
}
| true |